From 802ef4b0e7ba15337b4ae445c394cae43c98e557 Mon Sep 17 00:00:00 2001 From: Nisheet Jain Date: Thu, 1 Oct 2015 21:46:16 -0700 Subject: [PATCH 1/6] Fixing typedef tslint rule for remotebuild package --- src/gulpmain.ts | 2 +- src/remotebuild/lib/cli.ts | 4 +- src/remotebuild/lib/commands.ts | 9 +- src/remotebuild/lib/darwin/darwinCerts.ts | 99 +++++++++---------- src/remotebuild/lib/darwin/darwinSpecifics.ts | 4 +- src/remotebuild/lib/help.ts | 2 +- src/remotebuild/lib/remoteBuildConf.ts | 4 +- src/remotebuild/lib/server.ts | 28 +++--- src/remotebuild/resources/en/resources.json | 15 ++- src/remotebuild/test/darwinCerts.ts | 30 +++--- src/remotebuild/test/server.ts | 42 ++++---- .../test/testServerModuleFactory.ts | 3 +- src/tslint.json | 2 +- src/typings/buildConfig.d.ts | 8 ++ src/typings/remotebuild.d.ts | 5 + src/typings/remotebuildTask.d.ts | 14 +++ 16 files changed, 155 insertions(+), 116 deletions(-) create mode 100644 src/typings/remotebuildTask.d.ts diff --git a/src/gulpmain.ts b/src/gulpmain.ts index 4be9b156..f169185c 100644 --- a/src/gulpmain.ts +++ b/src/gulpmain.ts @@ -23,7 +23,7 @@ import gulpUtils = require ("../tools/GulpUtils"); // we don't want to take dependency on Logger here /* tslint:disable:no-var-requires */ -// var require needed to require package json +// var require needed to require build_config.json var buildConfig: BuildConfig.IBuildConfig = require("../../src/build_config.json"); /* tslint:enable:no-var-requires */ var tacoModules: string[] = ["taco-utils", "taco-kits", "taco-dependency-installer", "taco-cli", "remotebuild", "taco-remote", "taco-remote-lib"]; diff --git a/src/remotebuild/lib/cli.ts b/src/remotebuild/lib/cli.ts index 084cd9e5..3390ff0a 100644 --- a/src/remotebuild/lib/cli.ts +++ b/src/remotebuild/lib/cli.ts @@ -46,7 +46,7 @@ class CliHelper { }) .then(function (): Q.Promise { var command: string = nconf.get("_")[0] || "start"; - var task = Commands.tasks[command]; + var task: RemoteBuild.IRemoteBuildTask = Commands.tasks[command]; if (!task) { Logger.logError(resources.getString("UnknownCommand", command)); @@ -102,5 +102,5 @@ class CliHelper { } } -var cli = CliHelper.cli; +var cli: () => void = CliHelper.cli; export = cli; diff --git a/src/remotebuild/lib/commands.ts b/src/remotebuild/lib/commands.ts index ec8a8e38..8791a765 100644 --- a/src/remotebuild/lib/commands.ts +++ b/src/remotebuild/lib/commands.ts @@ -9,7 +9,9 @@ /// /// /// +/// /// + "use strict"; import Q = require ("q"); @@ -20,12 +22,9 @@ import server = require ("./server"); import utils = require ("taco-utils"); import Logger = utils.Logger; -interface IRemoteBuildTask { - execute(config: RemoteBuildConf, cliArguments?: string[]): Q.Promise; -} class Commands { - public static tasks: { [key: string]: IRemoteBuildTask } = { + public static tasks: { [key: string]: RemoteBuild.IRemoteBuildTask } = { start: { execute: function (config: RemoteBuildConf, cliArguments?: string[]): Q.Promise { return server.start(config); @@ -42,7 +41,7 @@ class Commands { }, certificates: { execute: function (config: RemoteBuildConf, cliArguments: string[]): Q.Promise { - var subCommand = cliArguments[1]; + var subCommand: string = cliArguments[1]; switch (subCommand) { case "generate": return server.generateClientCert(config); diff --git a/src/remotebuild/lib/darwin/darwinCerts.ts b/src/remotebuild/lib/darwin/darwinCerts.ts index 68e1eef1..db399d58 100644 --- a/src/remotebuild/lib/darwin/darwinCerts.ts +++ b/src/remotebuild/lib/darwin/darwinCerts.ts @@ -28,11 +28,10 @@ import tacoUtils = require ("taco-utils"); import utils = tacoUtils.UtilHelper; import logger = tacoUtils.Logger; -var exec = child_process.exec; class Certs { - private static debug = false; - private static CERT_DEFAULTS = { + private static debug: boolean = false; + private static CERT_DEFAULTS: any = { days: 1825, // 5 years country: "US", ca_cn: os.hostname().substring(0, 50) + ".RB.CA", // Note: these cn entries have a maximum length of 64 bytes. If a hostname contains unicode characters, then os.hostname will return an ascii mis-encoding which is still one byte per character. @@ -43,15 +42,15 @@ class Certs { private static certStore: HostSpecifics.ICertStore = null; public static resetServerCert(conf: RemoteBuildConf, yesOrNoHandler?: Certs.ICliHandler): Q.Promise { - var certsDir = path.join(conf.serverDir, "certs"); + var certsDir: string = path.join(conf.serverDir, "certs"); if (!fs.existsSync(certsDir)) { return Certs.initializeServerCerts(conf); } - var shouldProceedDeferred = Q.defer(); + var shouldProceedDeferred: Q.Deferred = Q.defer(); yesOrNoHandler = yesOrNoHandler || readline.createInterface({ input: process.stdin, output: process.stdout }); - var answerCallback = function (answer: string): void { + var answerCallback: (answer: string) => void = function (answer: string): void { answer = answer.toLowerCase(); if (resources.getString("OSXResetServerCertResponseYes").split("\n").indexOf(answer) !== -1) { yesOrNoHandler.close(); @@ -76,11 +75,11 @@ class Certs { } public static generateClientCert(conf: RemoteBuildConf): Q.Promise { - var certsDir = path.join(conf.serverDir, "certs"); - var caKeyPath = path.join(certsDir, "ca-key.pem"); - var caCertPath = path.join(certsDir, "ca-cert.pem"); + var certsDir: string = path.join(conf.serverDir, "certs"); + var caKeyPath: string = path.join(certsDir, "ca-key.pem"); + var caCertPath: string = path.join(certsDir, "ca-cert.pem"); if (!fs.existsSync(caKeyPath) || !fs.existsSync(caCertPath)) { - var error = resources.getString("CAFilesNotFound", caKeyPath, caCertPath); + var error: string = resources.getString("CAFilesNotFound", caKeyPath, caCertPath); return Q(0).thenReject(error); } @@ -96,8 +95,8 @@ class Certs { } public static initializeServerCerts(conf: RemoteBuildConf): Q.Promise { - var certsDir = path.join(conf.serverDir, "certs"); - var certPaths = { + var certsDir: string = path.join(conf.serverDir, "certs"); + var certPaths: any = { certsDir: certsDir, caKeyPath: path.join(certsDir, "ca-key.pem"), caCertPath: path.join(certsDir, "ca-cert.pem"), @@ -106,7 +105,7 @@ class Certs { newCerts: false }; - var certsExist = fs.existsSync(certPaths.caCertPath) && fs.existsSync(certPaths.serverKeyPath) && fs.existsSync(certPaths.serverCertPath); + var certsExist: boolean = fs.existsSync(certPaths.caCertPath) && fs.existsSync(certPaths.serverKeyPath) && fs.existsSync(certPaths.serverCertPath); certPaths.newCerts = !certsExist; var promise: Q.Promise; if (certsExist) { @@ -129,7 +128,7 @@ class Certs { utils.createDirectoryIfNecessary(certsDir); fs.chmodSync(certsDir, 448); // 0700, user read/write/executable, no other permissions - var options = Certs.certOptionsFromConf(conf); + var options: Certs.ICertOptions = Certs.certOptionsFromConf(conf); return Certs.makeSelfSigningCACert(certPaths.caKeyPath, certPaths.caCertPath, options). then(function (): Q.Promise { return Certs.makeSelfSignedCert(certPaths.caKeyPath, certPaths.caCertPath, certPaths.serverKeyPath, certPaths.serverCertPath, options, conf); @@ -160,7 +159,7 @@ class Certs { public static isExpired(certPath: string): Q.Promise { return Certs.displayCert(certPath, ["dates"]). then(function (output: { stdout: string; stderr: string }): boolean { - var notAfter = new Date(output.stdout.substring(output.stdout.indexOf("notAfter=") + 9, output.stdout.length - 1)); + var notAfter: Date = new Date(output.stdout.substring(output.stdout.indexOf("notAfter=") + 9, output.stdout.length - 1)); return (notAfter.getTime() < new Date().getTime()); }); } @@ -168,7 +167,7 @@ class Certs { // display fields an array of any of these: 'subject', 'issuer', 'dates', etc. (see https://www.openssl.org/docs/apps/x509.html) public static displayCert(certPath: string, displayFields: string[]): Q.Promise<{ stdout: string; stderr: string }> { // openssl x509 -noout -in selfsigned-cert.pem -subject -issuer -dates - var args = "x509 -noout -in " + certPath; + var args: string = "x509 -noout -in " + certPath; (displayFields || []).forEach(function (f: string): void { args += " -" + f; }); @@ -176,7 +175,7 @@ class Certs { } public static removeAllCertsSync(conf: RemoteBuildConf): void { - var certsDir = path.join(conf.serverDir, "certs"); + var certsDir: string = path.join(conf.serverDir, "certs"); if (fs.existsSync(certsDir)) { rimraf.sync(certsDir); } @@ -184,15 +183,15 @@ class Certs { public static downloadClientCerts(conf: RemoteBuildConf, pinString: string): string { Certs.purgeExpiredPinBasedClientCertsSync(conf); - var clientCertsDir = path.join(conf.serverDir, "certs", "client"); + var clientCertsDir: string = path.join(conf.serverDir, "certs", "client"); - var pin = parseInt(pinString, 10); + var pin: number = parseInt(pinString, 10); if (isNaN(pin)) { throw { code: 400, id: "InvalidPin" }; } - var pinDir = path.join(clientCertsDir, "" + pin); - var pfx = path.join(pinDir, "client.pfx"); + var pinDir: string = path.join(clientCertsDir, "" + pin); + var pfx: string = path.join(pinDir, "client.pfx"); if (!fs.existsSync(pfx)) { throw { code: 404, id: "ClientCertNotFoundForPIN" }; } @@ -201,20 +200,20 @@ class Certs { } public static invalidatePIN(conf: RemoteBuildConf, pinString: string): void { - var pinDir = path.join(conf.serverDir, "certs", "client", "" + parseInt(pinString, 10)); + var pinDir: string = path.join(conf.serverDir, "certs", "client", "" + parseInt(pinString, 10)); rimraf(pinDir, utils.emptyMethod); } public static purgeExpiredPinBasedClientCertsSync(conf: RemoteBuildConf): void { - var clientCertsDir = path.join(conf.serverDir, "certs", "client"); + var clientCertsDir: string = path.join(conf.serverDir, "certs", "client"); if (!fs.existsSync(clientCertsDir)) { return; } - var pinTimeoutInMinutes = conf.pinTimeout; - var expiredIfOlderThan = new Date().getTime() - (pinTimeoutInMinutes * 60 * 1000); + var pinTimeoutInMinutes: number = conf.pinTimeout; + var expiredIfOlderThan: number = new Date().getTime() - (pinTimeoutInMinutes * 60 * 1000); fs.readdirSync(clientCertsDir).forEach(function (f: string): void { - var pfx = path.join(clientCertsDir, f, "client.pfx"); + var pfx: string = path.join(clientCertsDir, f, "client.pfx"); if (fs.existsSync(pfx) && fs.statSync(pfx).mtime.getTime() < expiredIfOlderThan) { rimraf.sync(path.join(clientCertsDir, f)); } @@ -225,9 +224,9 @@ class Certs { // Exported for tests public static makeSelfSigningCACert(caKeyPath: string, caCertPath: string, options?: Certs.ICertOptions): Q.Promise<{ stdout: string; stderr: string }> { options = options || {}; - var days = options.days || Certs.CERT_DEFAULTS.days; - var country = options.country || Certs.CERT_DEFAULTS.country; - var cn = Certs.CERT_DEFAULTS.ca_cn; + var days: number = options.days || Certs.CERT_DEFAULTS.days; + var country: string = options.country || Certs.CERT_DEFAULTS.country; + var cn: string = Certs.CERT_DEFAULTS.ca_cn; return Certs.openSslPromise("req -newkey rsa:4096 -x509 -days " + days + " -nodes -subj /C=" + country + "/CN=" + cn + " -keyout " + caKeyPath + " -out " + caCertPath); } @@ -235,11 +234,11 @@ class Certs { // Exported for tests public static makeSelfSignedCert(caKeyPath: string, caCertPath: string, outKeyPath: string, outCertPath: string, options: Certs.ICertOptions, conf: RemoteBuildConf): Q.Promise { options = options || {}; - var csrPath = path.join(path.dirname(outCertPath), "CSR-" + path.basename(outCertPath)); - var days = options.days || Certs.CERT_DEFAULTS.days; - var cn = options.cn || Certs.CERT_DEFAULTS.client_cn; + var csrPath: string = path.join(path.dirname(outCertPath), "CSR-" + path.basename(outCertPath)); + var days: number = options.days || Certs.CERT_DEFAULTS.days; + var cn: string = options.cn || Certs.CERT_DEFAULTS.client_cn; - var cnfPath = path.join(conf.serverDir, "certs", "openssl.cnf"); + var cnfPath: string = path.join(conf.serverDir, "certs", "openssl.cnf"); Certs.writeConfigFile(cnfPath, conf); return Certs.openSslPromise("genrsa -out " + outKeyPath + " 1024"). @@ -260,9 +259,9 @@ class Certs { } private static openSslPromise(args: string): Q.Promise<{ stdout: string; stderr: string }> { - var deferred = Q.defer<{ stdout: string; stderr: string }>(); + var deferred: Q.Deferred<{ stdout: string; stderr: string }> = Q.defer<{ stdout: string; stderr: string }>(); - exec("openssl " + args, function (error: Error, stdout: Buffer, stderr: Buffer): void { + child_process.exec("openssl " + args, function (error: Error, stdout: Buffer, stderr: Buffer): void { if (Certs.debug) { logger.log("exec openssl " + args); logger.log(util.format("stdout: %s", stdout)); @@ -292,14 +291,14 @@ class Certs { } private static writeConfigFile(cnfPath: string, conf: RemoteBuildConf): void { - var net = os.networkInterfaces(); - var cnf = "[req]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n[req_distinguished_name]\nC_default = US\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nsubjectAltName = @alt_names\n[alt_names]\n"; + var net: any = os.networkInterfaces(); + var cnf: string = "[req]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n[req_distinguished_name]\nC_default = US\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nsubjectAltName = @alt_names\n[alt_names]\n"; var hostname: string = conf.hostname; cnf += util.format("DNS.1 = %s\n", hostname); - var ipCount = 1; - Object.keys(net).forEach(function(key: string){ - for (var i = 0; i < net[key].length; i++) { + var ipCount: number = 1; + Object.keys(net).forEach(function(key: string): void{ + for (var i: number = 0; i < net[key].length; i++) { if (net[key][i].address && !net[key][i].internal) { cnf += util.format("IP.%d = %s\n", ipCount, net[key][i].address); ipCount++; @@ -313,14 +312,14 @@ class Certs { private static makeClientPinAndSslCert(caKeyPath: string, caCertPath: string, certsDir: string, options: Certs.ICertOptions, conf: RemoteBuildConf): Q.Promise { options = options || {}; options.cn = Certs.CERT_DEFAULTS.client_cn; - var clientCertsPath = path.join(certsDir, "client"); + var clientCertsPath: string = path.join(certsDir, "client"); utils.createDirectoryIfNecessary(clientCertsPath); // 6 digit random pin (Math.random excludes 1.0) - var pin = 100000 + Math.floor(Math.random() * 900000); - var pinDir = path.join(clientCertsPath, "" + pin); - var pfxPath = path.join(pinDir, "client.pfx"); - var clientKeyPath = path.join(pinDir, "client-key.pem"); - var clientCertPath = path.join(pinDir, "client-cert.pem"); + var pin: number = 100000 + Math.floor(Math.random() * 900000); + var pinDir: string = path.join(clientCertsPath, "" + pin); + var pfxPath: string = path.join(pinDir, "client.pfx"); + var clientKeyPath: string = path.join(pinDir, "client-key.pem"); + var clientCertPath: string = path.join(pinDir, "client-cert.pem"); utils.createDirectoryIfNecessary(pinDir); return Certs.makeSelfSignedCert(caKeyPath, caCertPath, clientKeyPath, clientCertPath, options, conf). @@ -336,15 +335,15 @@ class Certs { private static makePfx(caCertPath: string, keyPath: string, certPath: string, outPfxPath: string, options?: Certs.ICertOptions): Q.Promise<{ stdout: string; stderr: string }> { options = options || {}; - var name = Certs.CERT_DEFAULTS.pfx_name; + var name: string = Certs.CERT_DEFAULTS.pfx_name; return Certs.openSslPromise("pkcs12 -export -in " + certPath + " -inkey " + keyPath + " -certfile " + caCertPath + " -out " + outPfxPath + " -name \'" + name + "\' -password pass:"); } private static printSetupInstructionsToConsole(conf: RemoteBuildConf, pin: number): void { - var host = conf.hostname; - var port = conf.port; - var pinTimeoutInMinutes = conf.pinTimeout; + var host: string = conf.hostname; + var port: number = conf.port; + var pinTimeoutInMinutes: number = conf.pinTimeout; logger.log(resources.getString("OSXCertSetupInformation", host, port, pin)); if (pinTimeoutInMinutes) { logger.log(resources.getString("OSXCertSetupPinTimeout", pinTimeoutInMinutes)); diff --git a/src/remotebuild/lib/darwin/darwinSpecifics.ts b/src/remotebuild/lib/darwin/darwinSpecifics.ts index 7f9617ef..87765766 100644 --- a/src/remotebuild/lib/darwin/darwinSpecifics.ts +++ b/src/remotebuild/lib/darwin/darwinSpecifics.ts @@ -96,8 +96,8 @@ class DarwinSpecifics implements HostSpecifics.IHostSpecifics { if (conf.secure) { conf.set("suppressSetupMessage", true); return certs.generateClientCert(conf).then(function (pin: number): NodeJSHttp.Agent { - var pfxPath = path.join(conf.serverDir, "certs", "client", pin.toString(), "client.pfx"); - var cert = fs.readFileSync(pfxPath); + var pfxPath: string = path.join(conf.serverDir, "certs", "client", pin.toString(), "client.pfx"); + var cert: Buffer = fs.readFileSync(pfxPath); fs.unlinkSync(pfxPath); // TODO: Remove the casting once we've get some complete/up-to-date .d.ts files. See https://github.com/Microsoft/TACO/issues/18 return new https.Agent( {strictSSL: true, pfx: cert }); diff --git a/src/remotebuild/lib/help.ts b/src/remotebuild/lib/help.ts index 5bc726bb..23dc6070 100644 --- a/src/remotebuild/lib/help.ts +++ b/src/remotebuild/lib/help.ts @@ -50,7 +50,7 @@ class Help extends HelpCommandBase { return baseRun(data); } - var moduleConfig = self.remotebuildConf.moduleConfig(topic); + var moduleConfig: RemoteBuild.IServerModuleConfiguration = self.remotebuildConf.moduleConfig(topic); if (moduleConfig) { try { var mod: RemoteBuild.IServerModuleFactory = require(moduleConfig.requirePath || topic); diff --git a/src/remotebuild/lib/remoteBuildConf.ts b/src/remotebuild/lib/remoteBuildConf.ts index aa23dda5..12501fa5 100644 --- a/src/remotebuild/lib/remoteBuildConf.ts +++ b/src/remotebuild/lib/remoteBuildConf.ts @@ -58,7 +58,7 @@ class RemoteBuildConf implements RemoteBuild.IRemoteBuildConfiguration { // To support the simple case of "my home directory" I'm doing the replacement here // We only want to expand if the directory starts with ~/ not in cases such as /foo/~ // Ideally we would also cope with the case of ~user/ but that is harder to find and probably less common - var serverDir = conf.get("serverDir"); + var serverDir: string = conf.get("serverDir"); conf.set("serverDir", serverDir.replace(/^~(?=\/|^)/, process.env.HOME)); } @@ -70,7 +70,7 @@ class RemoteBuildConf implements RemoteBuild.IRemoteBuildConfiguration { throw new Error(resources.getString("InvalidPortSpecified", this.port)); } - var serverMods = this.remoteBuildConf.modules; + var serverMods: RemoteBuildConf.IModulesConf = this.remoteBuildConf.modules; if (typeof (serverMods) !== "object" || Object.keys(serverMods).length === 0) { this.usingDefaultModulesConfig = true; if (isUnitTest) { diff --git a/src/remotebuild/lib/server.ts b/src/remotebuild/lib/server.ts index cfca1ab3..41862750 100644 --- a/src/remotebuild/lib/server.ts +++ b/src/remotebuild/lib/server.ts @@ -48,11 +48,11 @@ class Server { private static shutdown: () => void; public static start(conf: RemoteBuildConf): Q.Promise { - var app = express(); + var app: Express.Express = express(); app.use(expressLogger("dev")); app.use(errorhandler()); - var serverDir = conf.serverDir; + var serverDir: string = conf.serverDir; UtilHelper.createDirectoryIfNecessary(serverDir); app.get("/", function (req: express.Request, res: express.Response): void { @@ -84,7 +84,7 @@ class Server { process.removeListener("SIGTERM", Server.shutdown); process.removeListener("SIGINT", Server.shutdown); if (Server.serverInstance) { - var tempInstance = Server.serverInstance; + var tempInstance: { close(callback?: Function): void } = Server.serverInstance; Server.serverInstance = null; tempInstance.close(callback); } else if (callback) { @@ -161,7 +161,7 @@ class Server { Logger.logWarning(resources.getString("NoServerModulesSelected")); } - var onlyAuthorizedClientRequest = function (req: express.Request, res: express.Response, next: Function): void { + var onlyAuthorizedClientRequest: (req: express.Request, res: express.Response, next: Function) => void = function (req: express.Request, res: express.Response, next: Function): void { if (!( req).client.authorized) { res.status(401).send(resources.getStringForLanguage(req, "UnauthorizedClientRequest")); } else { @@ -170,7 +170,7 @@ class Server { }; return Server.eachServerModule(conf, function (modGen: RemoteBuild.IServerModuleFactory, mod: string, moduleConfig: RemoteBuild.IServerModuleConfiguration): Q.Promise { return modGen.create(conf, moduleConfig, serverCapabilities).then(function (serverMod: RemoteBuild.IServerModule): void { - var modRouter = serverMod.getRouter(); + var modRouter: Express.Router = serverMod.getRouter(); // These routes are fully secured through client cert verification: if (conf.secure) { app.all("/" + moduleConfig.mountPath, onlyAuthorizedClientRequest); @@ -183,10 +183,10 @@ class Server { } private static eachServerModule(conf: RemoteBuildConf, eachFunc: (modGen: RemoteBuild.IServerModuleFactory, mod: string, modConfig: { mountPath: string }) => Q.Promise): Q.Promise { - var serverMods = conf.modules; + var serverMods: string[] = conf.modules; return serverMods.reduce>(function (promise: Q.Promise, mod: string): Q.Promise { try { - var requirePath = conf.moduleConfig(mod).requirePath || mod; + var requirePath: string = conf.moduleConfig(mod).requirePath || mod; var modGen: RemoteBuild.IServerModuleFactory = require(requirePath); } catch (e) { Logger.logError(resources.getString("UnableToLoadModule", mod)); @@ -206,7 +206,7 @@ class Server { private static startupPlainHttpServer(conf: RemoteBuildConf, app: express.Application): Q.Promise { return Q(http.createServer(app)). then(function (svr: http.Server): Q.Promise { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); svr.on("error", function (err: any): void { deferred.reject(Server.friendlyServerListenError(err, conf)); }); @@ -222,7 +222,7 @@ class Server { } private static startupHttpsServer(conf: RemoteBuildConf, app: express.Application): Q.Promise { - var generatedNewCerts = false; + var generatedNewCerts: boolean = false; var generatedClientPin: number; return HostSpecifics.hostSpecifics.getServerCerts(). then(function (certStore: HostSpecifics.ICertStore): Q.Promise { @@ -238,7 +238,7 @@ class Server { return Q(certStore); }). then(function (certStore: HostSpecifics.ICertStore): https.Server { - var sslSettings = { + var sslSettings: any = { key: certStore.getKey(), cert: certStore.getCert(), ca: certStore.getCA(), @@ -248,7 +248,7 @@ class Server { return https.createServer(sslSettings, app); }). then(function (svr: https.Server): Q.Promise { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); svr.on("error", function (err: any): void { if (generatedNewCerts) { HostSpecifics.hostSpecifics.removeAllCertsSync(conf); @@ -315,10 +315,10 @@ class Server { private static getModuleMount(req: express.Request, res: express.Response): void { var mod: string = req.params.module; - var modConfig = Server.serverConf.moduleConfig(mod); + var modConfig: RemoteBuild.IServerModuleConfiguration = Server.serverConf.moduleConfig(mod); if (mod && modConfig && modConfig.mountPath ) { - var mountLocation = modConfig.mountPath; - var contentLocation = util.format("%s://%s:%d/%s", req.protocol, req.hostname, Server.serverConf.port, mountLocation); + var mountLocation: string = modConfig.mountPath; + var contentLocation: string = util.format("%s://%s:%d/%s", req.protocol, req.hostname, Server.serverConf.port, mountLocation); res.set({ "Content-Location": contentLocation }); diff --git a/src/remotebuild/resources/en/resources.json b/src/remotebuild/resources/en/resources.json index e0b69783..b93eabf2 100644 --- a/src/remotebuild/resources/en/resources.json +++ b/src/remotebuild/resources/en/resources.json @@ -78,7 +78,20 @@ "_RemoteBuildNotes1.comment": "Text shown in notes section providing additional notes when user invokes 'remotebuild help start'", "RemoteBuildNotes2": "Command line options override configuration file values", "_RemoteBuildNotes2.comment": "Text shown in notes section providing additional notes when user invokes 'remotebuild help start'", - "OSXCertSetupInformation": "Use the following information in Visual Studio under Tools, Options, Tools for Apache Cordova, Remote Agent Configuration to use this agent:

Enable remote iOS processing: True
Host: {0}
Port: {1}
Secure mode: True
Security PIN: {2}

Alternately to use TACO run 'taco remote add ' to configure TACO to use this build server for the chosen platform, specifying
Host: {0}
Port: {1}
PIN: {2}", + "OSXCertSetupInformation": [ + "Use the following information in Visual Studio under Tools, Options, Tools for Apache Cordova, Remote Agent Configuration to use this agent:", + "", + "Enable remote iOS processing: True", + "Host: {0}", + "Port: {1}", + "Secure mode: True", + "Security PIN: {2}", + "", + "Alternately to use the taco-cli run 'taco remote add ' to configure the taco CLI to use this build server for the chosen platform, specifying", + "Host: {0}", + "Port: {1}", + "PIN: {2}" + ], "_OSXCertSetupInformation.comment": "{0} is the host name or IP address of the machine, {1} is the port number that the server is running on, {2} is the 6 digit generated PIN", "OSXCertSetupNoPinTimeout": "The security PIN is for one-time use. To generate additional PINs, use the following command:", "_OSXCertSetupNoPinTimeout.comment": "Message printed to console explaining how to generate new PINs. The following line is a console command to generate the certificates", diff --git a/src/remotebuild/test/darwinCerts.ts b/src/remotebuild/test/darwinCerts.ts index 7f2c9b29..d716c157 100644 --- a/src/remotebuild/test/darwinCerts.ts +++ b/src/remotebuild/test/darwinCerts.ts @@ -17,7 +17,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import fs = require ("fs"); @@ -33,15 +33,15 @@ import RemoteBuildConf = require ("../lib/remoteBuildConf"); import resources = require ("../resources/resourceManager"); import utils = require ("taco-utils"); -var serverDir = path.join(os.tmpdir(), "remotebuild", "certs"); -var certsDir = path.join(serverDir, "certs"); -var clientCertsDir = path.join(certsDir, "client"); -var caKeyPath = path.join(certsDir, "ca-key.pem"); -var caCertPath = path.join(certsDir, "ca-cert.pem"); +var serverDir: string = path.join(os.tmpdir(), "remotebuild", "certs"); +var certsDir: string = path.join(serverDir, "certs"); +var clientCertsDir: string = path.join(certsDir, "client"); +var caKeyPath: string = path.join(certsDir, "ca-key.pem"); +var caCertPath: string = path.join(certsDir, "ca-cert.pem"); // Tests for lib/darwin/darwinCerts.js functionality // Since the certs use openSSL to work with certificates, we restrict these tests to the mac where openSSL should exist. -var macOnly = os.platform() === "darwin" ? describe : describe.skip; +var macOnly: (description: string, spec: () => void) => void = os.platform() === "darwin" ? describe : describe.skip; macOnly("Certs", function (): void { after(function (): void { nconf.overrides({}); @@ -116,7 +116,7 @@ macOnly("Certs", function (): void { // Tests that resetting server certificates queries the user and respects a "no" response it("ResetServerCertNo", function (done: MochaDone): void { - var noHandler = { + var noHandler: any = { closed: false, question: function (question: string, answerCallback: (answer: string) => void): void { answerCallback("n"); @@ -145,7 +145,7 @@ macOnly("Certs", function (): void { // Tests that resetting server certificates will create new certificates after a "yes" response it("ResetServerCertYes", function (done: MochaDone): void { - var yesHandler = { + var yesHandler: any = { closed: false, question: function (question: string, answerCallback: (answer: string) => void): void { answerCallback("y"); @@ -175,7 +175,7 @@ macOnly("Certs", function (): void { // Test that client certificates are purged if they are older than the timeout, and are not purged if they are younger it("PurgeExpiredPinBasedClientCertsSync", function (done: MochaDone): void { var createdPin: number; - var config = conf({ serverDir: serverDir }); + var config: RemoteBuildConf = conf({ serverDir: serverDir }); certs.initializeServerCerts(config). then(function (): Q.Promise { return certs.generateClientCert(conf({ serverDir: serverDir, suppressSetupMessage: true })); @@ -220,8 +220,8 @@ macOnly("Certs", function (): void { // Test that we can make a self signed certificate from the CA certificate it("MakeSelfSignedCert", function (done: MochaDone): void { - var outKeyPath = path.join(serverDir, "selfsigned-key.pem"); - var outCertPath = path.join(serverDir, "selfsigned-cert.pem"); + var outKeyPath: string = path.join(serverDir, "selfsigned-key.pem"); + var outCertPath: string = path.join(serverDir, "selfsigned-cert.pem"); certs.makeSelfSigningCACert(caKeyPath, caCertPath). then(function (): Q.Promise { @@ -240,9 +240,9 @@ macOnly("Certs", function (): void { then(function (): Q.Promise { return certs.displayCert(outCertPath, ["dates"]). then(function (output: { stdout: string }): void { - var notBefore = new Date(output.stdout.substring(output.stdout.indexOf("notBefore=") + 10, output.stdout.indexOf(os.EOL))); - var notAfter = new Date(output.stdout.substring(output.stdout.indexOf("notAfter=") + 9, output.stdout.length - 1)); - var diffSeconds = (notAfter.getTime() - notBefore.getTime()) / 1000; + var notBefore: Date = new Date(output.stdout.substring(output.stdout.indexOf("notBefore=") + 10, output.stdout.indexOf(os.EOL))); + var notAfter: Date = new Date(output.stdout.substring(output.stdout.indexOf("notAfter=") + 9, output.stdout.length - 1)); + var diffSeconds: number = (notAfter.getTime() - notBefore.getTime()) / 1000; should.assert(diffSeconds === (60 * 60 * 24 * 365 * 5), "Cert should expire in 5 years"); }); }).done(function (): void { diff --git a/src/remotebuild/test/server.ts b/src/remotebuild/test/server.ts index bceb7309..8453d026 100644 --- a/src/remotebuild/test/server.ts +++ b/src/remotebuild/test/server.ts @@ -14,7 +14,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import fs = require ("fs"); @@ -33,11 +33,11 @@ import server = require ("../lib/server"); import tacoUtils = require ("taco-utils"); import testServerModuleFactory = require ("./testServerModuleFactory"); -var serverDir = path.join(os.tmpdir(), "remotebuild", "server"); -var certsDir = path.join(serverDir, "certs"); -var clientCertsDir = path.join(certsDir, "client"); +var serverDir: string = path.join(os.tmpdir(), "remotebuild", "server"); +var certsDir: string = path.join(serverDir, "certs"); +var clientCertsDir: string = path.join(certsDir, "client"); -var darwinOnlyTest = os.platform() === "darwin" ? it : it.skip; +var darwinOnlyTest: (expectation: string, assertion?: (done: MochaDone) => void) => void = os.platform() === "darwin" ? it : it.skip; describe("server", function (): void { before(function (): void { @@ -69,7 +69,7 @@ describe("server", function (): void { fs.existsSync(serverDir).should.be.true; fs.existsSync(certsDir).should.be.false; }).then(function (): Q.Promise<{}> { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); request.get("http://localhost:3000", function (error: any, response: any, body: any): void { response.statusCode.should.equal(200); deferred.resolve({}); @@ -79,11 +79,11 @@ describe("server", function (): void { }); it("should fail gracefully if the port is taken", function (done: MochaDone): void { - var dummyServer = net.createServer(function (c: net.Socket): void { + var dummyServer: NodeJSNet.Server = net.createServer(function (c: net.Socket): void { // Don't care about connections, we just want to use up a port }); - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); dummyServer.listen(3000, function (): void { deferred.resolve({}); }); @@ -122,7 +122,7 @@ describe("server", function (): void { fs.existsSync(path.join(certsDir, "ca-key.pem")).should.be.ok; fs.existsSync(path.join(certsDir, "ca-cert.pem")).should.be.ok; }).then(function (): Q.Promise<{}> { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); // Disabling strict SSL for unit testing request.get({ url: "https://localhost:3000", strictSSL: false }, function (error: any, response: any, body: any): void { response.statusCode.should.equal(200); @@ -136,27 +136,27 @@ describe("server", function (): void { this.timeout(10000); // Certificates can take ages to generate apparently // TODO: Remove the casting once we've get some complete/up-to-date .d.ts files. See https://github.com/Microsoft/TACO/issues/18 nconf.overrides( { serverDir: serverDir, port: 3000, secure: true, lang: "en", pinTimeout: 10 }); - var config = new RemoteBuildConf(nconf, true); + var config: RemoteBuildConf = new RemoteBuildConf(nconf, true); HostSpecifics.hostSpecifics.initialize(config).then(function (): Q.Promise { return server.start(config); }).then(function (): void { fs.existsSync(clientCertsDir).should.be.ok; }).then(function (): Q.Promise { - var pins = fs.readdirSync(clientCertsDir); + var pins: string[] = fs.readdirSync(clientCertsDir); pins.length.should.equal(1); - var downloadedPin = pins[0]; - var clientPfxSize = fs.statSync(path.join(clientCertsDir, downloadedPin, "client.pfx")).size; + var downloadedPin: string = pins[0]; + var clientPfxSize: number = fs.statSync(path.join(clientCertsDir, downloadedPin, "client.pfx")).size; clientPfxSize.should.be.greaterThan(0); - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); // turn off strict SSL for unit testing - var downloadedCertPath = path.join(serverDir, "downloaded-client.pfx"); - var downloadRequest = request.get({ url: "https://localhost:3000/certs/" + downloadedPin, strictSSL: false }); - var writeStream = fs.createWriteStream(downloadedCertPath); + var downloadedCertPath: string = path.join(serverDir, "downloaded-client.pfx"); + var downloadRequest: request.Request = request.get({ url: "https://localhost:3000/certs/" + downloadedPin, strictSSL: false }); + var writeStream: fs.WriteStream = fs.createWriteStream(downloadedCertPath); downloadRequest.pipe(writeStream); downloadRequest.on("error", done); writeStream.on("finish", function (): void { - var downloadedPfxSize = fs.statSync(downloadedCertPath).size; + var downloadedPfxSize: number = fs.statSync(downloadedCertPath).size; if (downloadedPfxSize !== clientPfxSize) { done(new Error("Download size does not match!")); } @@ -165,7 +165,7 @@ describe("server", function (): void { }); return deferred.promise; }).then(function (downloadedPin: string): Q.Promise<{}> { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); request.get({ url: "https://localhost:3000/certs/" + downloadedPin, strictSSL: false }, function (error: any, response: any, body: any): void { response.statusCode.should.equal(404); deferred.resolve({}); @@ -175,7 +175,7 @@ describe("server", function (): void { }); it("should load server modules and serve requests from there", function (mocha: MochaDone): void { - var modPath = path.join("..", "test", "testServerModuleFactory"); // path is relative to lib/server.js since that's where the require is invoked + var modPath: string = path.join("..", "test", "testServerModuleFactory"); // path is relative to lib/server.js since that's where the require is invoked var testModules: { [key: string]: any } = {}; testModules["testServerModuleFactory"] = { mountPath: "testRoute", requirePath: modPath }; @@ -184,7 +184,7 @@ describe("server", function (): void { server.start(new RemoteBuildConf(nconf, true)).then(function (): void { testServerModuleFactory.TestServerModule.modConfig.mountPath.should.equal("testRoute"); }).then(function (): Q.Promise { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); request.get("http://localhost:3000/testRoute/foo", function (error: any, response: any, body: any): void { response.statusCode.should.equal(200); deferred.resolve({}); diff --git a/src/remotebuild/test/testServerModuleFactory.ts b/src/remotebuild/test/testServerModuleFactory.ts index 9e40ec1d..88986cfe 100644 --- a/src/remotebuild/test/testServerModuleFactory.ts +++ b/src/remotebuild/test/testServerModuleFactory.ts @@ -1,5 +1,6 @@ /// /// +/// import express = require ("express"); import Q = require ("q"); @@ -18,7 +19,7 @@ module TestServerModuleFactory { public static modConfig: RemoteBuild.IServerModuleConfiguration = null; public getRouter(): Express.Router { - var router = express.Router(); + var router: Express.Router = express.Router(); router.all("*", function (req: Express.Request, res: Express.Response): void { TestServerModule.lastReq = req; res.sendStatus(200); diff --git a/src/tslint.json b/src/tslint.json index f3292f12..c0ef18f1 100644 --- a/src/tslint.json +++ b/src/tslint.json @@ -64,7 +64,7 @@ "semicolon": true, "sort-object-literal-keys": false, "triple-equals": [true, "allow-null-check"], - "typedef": [false, + "typedef": [true, "call-signature", "parameter", "property-declaration", diff --git a/src/typings/buildConfig.d.ts b/src/typings/buildConfig.d.ts index da6f1ad4..d139615d 100644 --- a/src/typings/buildConfig.d.ts +++ b/src/typings/buildConfig.d.ts @@ -1,3 +1,11 @@ +/** + ******************************************************* + * * + * Copyright (C) Microsoft. All rights reserved. * + * * + ******************************************************* + */ + declare module BuildConfig { export interface IBuildConfig { src: string; diff --git a/src/typings/remotebuild.d.ts b/src/typings/remotebuild.d.ts index ff7f2a34..95783ce3 100644 --- a/src/typings/remotebuild.d.ts +++ b/src/typings/remotebuild.d.ts @@ -46,6 +46,11 @@ declare module RemoteBuild { printHelp(remoteBuildConf: IRemoteBuildConfiguration, moduleConfig: IServerModuleConfiguration): void; getConfig(remoteBuildConf: IRemoteBuildConfiguration, moduleConfig: IServerModuleConfiguration): IServerModuleConfiguration; } + + interface IRemoteBuildTask { + execute(config: IRemoteBuildConfiguration , cliArguments?: string[]): Q.Promise; + } + interface IServerModule { getRouter(): Express.Router; shutdown(): void; diff --git a/src/typings/remotebuildTask.d.ts b/src/typings/remotebuildTask.d.ts new file mode 100644 index 00000000..8d4ae609 --- /dev/null +++ b/src/typings/remotebuildTask.d.ts @@ -0,0 +1,14 @@ +/** + ******************************************************* + * * + * Copyright (C) Microsoft. All rights reserved. * + * * + ******************************************************* + */ + +/// +/// + +interface IRemoteBuildTask { + execute(config: RemoteBuild.IRemoteBuildConfiguration, cliArguments?: string[]): Q.Promise; +} From f3b854736f1b4ed971d6564e655b5703c52e409d Mon Sep 17 00:00:00 2001 From: Nisheet Jain Date: Sat, 3 Oct 2015 21:48:30 -0700 Subject: [PATCH 2/6] Fixing tslint typedef issues for taco-cli --- src/taco-cli/cli/build.ts | 25 ++-- src/taco-cli/cli/create.ts | 90 +++++------ src/taco-cli/cli/docs.ts | 2 +- src/taco-cli/cli/emulate.ts | 16 +- src/taco-cli/cli/installReqs.ts | 6 +- src/taco-cli/cli/kit.ts | 32 ++-- src/taco-cli/cli/logo.ts | 12 +- src/taco-cli/cli/platform.ts | 12 +- src/taco-cli/cli/plugin.ts | 10 +- src/taco-cli/cli/remote.ts | 32 ++-- .../remoteBuild/connectionSecurityHelper.ts | 20 +-- .../remoteBuild/remoteBuildClientHelper.ts | 140 +++++++++--------- src/taco-cli/cli/run.ts | 18 +-- src/taco-cli/cli/taco.ts | 2 +- src/taco-cli/cli/templates.ts | 2 +- .../cli/utils/buildTelemetryHelper.ts | 33 +++-- .../cli/utils/checkForNewerVersion.ts | 28 ++-- src/taco-cli/cli/utils/cordovaHelper.ts | 12 +- src/taco-cli/cli/utils/cordovaWrapper.ts | 8 +- .../cli/utils/platformPluginCommandBase.ts | 6 +- src/taco-cli/cli/utils/projectHelper.ts | 22 +-- src/taco-cli/cli/utils/settings.ts | 12 +- src/taco-cli/cli/utils/templateManager.ts | 20 +-- src/taco-cli/test/build.ts | 62 ++++---- src/taco-cli/test/buildAndRunTelemetry.ts | 77 +++++----- src/taco-cli/test/checkForNewerVersion.ts | 63 ++++---- src/taco-cli/test/cordovaWrapper.ts | 6 +- src/taco-cli/test/create.ts | 64 ++++---- src/taco-cli/test/emulate.ts | 16 +- src/taco-cli/test/help.ts | 14 +- src/taco-cli/test/kit.ts | 18 +-- src/taco-cli/test/meta.ts | 8 +- src/taco-cli/test/platformPlugin.ts | 42 +++--- src/taco-cli/test/remote.ts | 53 +++---- src/taco-cli/test/run.ts | 46 +++--- src/taco-cli/test/settings.ts | 6 +- src/taco-cli/test/templateManager.ts | 14 +- src/taco-cli/test/templates.ts | 14 +- src/taco-cli/test/utils/MockCordova.ts | 8 +- src/taco-cli/test/utils/memoryStream.ts | 6 +- src/taco-cli/test/utils/serverMock.ts | 12 +- src/typings/telemetryHelper.d.ts | 2 +- 42 files changed, 552 insertions(+), 539 deletions(-) diff --git a/src/taco-cli/cli/build.ts b/src/taco-cli/cli/build.ts index 481be201..5d448927 100644 --- a/src/taco-cli/cli/build.ts +++ b/src/taco-cli/cli/build.ts @@ -35,7 +35,6 @@ import tacoUtility = require ("taco-utils"); import commands = tacoUtility.Commands; import logger = tacoUtility.Logger; import UtilHelper = tacoUtility.UtilHelper; - import ICommandTelemetryProperties = tacoUtility.ICommandTelemetryProperties; /** @@ -47,7 +46,7 @@ class Build extends commands.TacoCommandBase { /* * Exposed for testing purposes: when we talk to a mocked server we don't want 5s delays between pings */ - public static remoteBuild = RemoteBuildClientHelper; + public static remoteBuild: any = RemoteBuildClientHelper; private static KNOWN_OPTIONS: Nopt.CommandData = { local: Boolean, @@ -70,11 +69,11 @@ class Build extends commands.TacoCommandBase { } private static cleanPlatform(platform: Settings.IPlatformWithLocation, commandData: commands.ICommandData): Q.Promise { - var promise = Q({}); + var promise: Q.Promise = Q({}); switch (platform.location) { case Settings.BuildLocationType.Local: // To clean locally, try and run the clean script - var cleanScriptPath = path.join("platforms", platform.platform, "cordova", "clean"); + var cleanScriptPath: string = path.join("platforms", platform.platform, "cordova", "clean"); if (fs.existsSync(cleanScriptPath)) { promise = promise.then(function (): Q.Promise { return Q.denodeify(UtilHelper.loggedExec)(cleanScriptPath).fail(function (err: any): void { @@ -91,12 +90,12 @@ class Build extends commands.TacoCommandBase { commandData.options["release"] = commandData.options["debug"] = true; } - var remotePlatform = path.resolve(".", "remote", platform.platform); - var configurations = ["release", "debug"]; + var remotePlatform: string = path.resolve(".", "remote", platform.platform); + var configurations: string[] = ["release", "debug"]; promise = configurations.reduce(function (soFar: Q.Promise, configuration: string): Q.Promise { return soFar.then(function (): void { if (commandData.options[configuration]) { - var remotePlatformConfig = path.join(remotePlatform, configuration); + var remotePlatformConfig: string = path.join(remotePlatform, configuration); if (fs.existsSync(remotePlatformConfig)) { logger.log(resources.getString("CleaningRemoteResources", platform.platform, configuration)); rimraf.sync(remotePlatformConfig); @@ -114,16 +113,16 @@ class Build extends commands.TacoCommandBase { } private static buildRemotePlatform(platform: string, commandData: commands.ICommandData, telemetryProperties: ICommandTelemetryProperties): Q.Promise { - var configuration = commandData.options["release"] ? "release" : "debug"; - var buildTarget = commandData.options["target"] || (commandData.options["device"] ? "device" : commandData.options["emulator"] ? "emulator" : ""); + var configuration: string = commandData.options["release"] ? "release" : "debug"; + var buildTarget: string = commandData.options["target"] || (commandData.options["device"] ? "device" : commandData.options["emulator"] ? "emulator" : ""); return Q.all([Settings.loadSettings(), CordovaWrapper.getCordovaVersion()]).spread((settings: Settings.ISettings, cordovaVersion: string) => { - var language = settings.language || "en"; - var remoteConfig = settings.remotePlatforms && settings.remotePlatforms[platform]; + var language: string = settings.language || "en"; + var remoteConfig: Settings.IRemoteConnectionInfo = settings.remotePlatforms && settings.remotePlatforms[platform]; if (!remoteConfig) { throw errorHelper.get(TacoErrorCodes.CommandRemotePlatformNotKnown, platform); } - var buildSettings = new RemoteBuildSettings({ + var buildSettings: RemoteBuildSettings = new RemoteBuildSettings({ projectSourceDir: path.resolve("."), buildServerInfo: remoteConfig, buildCommand: "build", @@ -190,7 +189,7 @@ class Build extends commands.TacoCommandBase { } public parseArgs(args: string[]): commands.ICommandData { - var parsedOptions = tacoUtility.ArgsHelper.parseArguments(Build.KNOWN_OPTIONS, Build.SHORT_HANDS, args, 0); + var parsedOptions: commands.ICommandData = tacoUtility.ArgsHelper.parseArguments(Build.KNOWN_OPTIONS, Build.SHORT_HANDS, args, 0); // Raise errors for invalid command line parameters if (parsedOptions.options["remote"] && parsedOptions.options["local"]) { diff --git a/src/taco-cli/cli/create.ts b/src/taco-cli/cli/create.ts index 339b57a3..1c69205a 100644 --- a/src/taco-cli/cli/create.ts +++ b/src/taco-cli/cli/create.ts @@ -78,23 +78,23 @@ class Create extends commands.TacoCommandBase { return Q.reject(err); } - var self = this; + var self: Create = this; var templateDisplayName: string; return this.createProject() - .then(function (templateUsed: string): Q.Promise { + .then(function(templateUsed: string): Q.Promise { templateDisplayName = templateUsed; - var kitProject = self.isKitProject(); + var kitProject: boolean = self.isKitProject(); var valueToSerialize: string = kitProject ? self.commandParameters.data.options["kit"] : self.commandParameters.data.options["cordova"]; return projectHelper.createTacoJsonFile(self.commandParameters.cordovaParameters.projectPath, kitProject, valueToSerialize); }) - .then(function (): Q.Promise { + .then(function(): Q.Promise { self.finalize(templateDisplayName); return Q.resolve({}); - }).then(function (): Q.Promise { + }).then(function(): Q.Promise { return self.generateTelemetryProperties(); }); } @@ -112,8 +112,8 @@ class Create extends commands.TacoCommandBase { private generateTelemetryProperties(): Q.Promise { var telemetryProperties: ICommandTelemetryProperties = {}; telemetryProperties["cliVersion"] = telemetryHelper.telemetryProperty(require("../package.json").version); - var self = this; - return kitHelper.getDefaultKit().then(function (defaultKitId: string): Q.Promise { + var self: Create = this; + return kitHelper.getDefaultKit().then(function(defaultKitId: string): Q.Promise { if (self.isKitProject()) { telemetryProperties["kit"] = telemetryHelper.telemetryProperty(self.commandParameters.data.options["kit"] || defaultKitId); telemetryProperties["template"] = telemetryHelper.telemetryProperty(self.commandParameters.data.options["template"] || "blank"); @@ -181,7 +181,7 @@ class Create extends commands.TacoCommandBase { * Creates the Kit or CLI project */ private createProject(): Q.Promise { - var self = this; + var self: Create = this; var cordovaCli: string = this.commandParameters.data.options["cordova"]; var mustUseTemplate: boolean = this.isKitProject() && !this.commandParameters.cordovaParameters.copyFrom && !this.commandParameters.cordovaParameters.linkTo; var kitId: string = this.commandParameters.data.options["kit"]; @@ -190,41 +190,41 @@ class Create extends commands.TacoCommandBase { // Create the project if (!this.isKitProject()) { return this.printStatusMessage() - .then(function (): Q.Promise { + .then(function(): Q.Promise { // Use the CLI version specified as an argument to create the project "command.create.status.cliProject return cordovaWrapper.create(cordovaCli, self.commandParameters.cordovaParameters); }); } else { - return kitHelper.getValidCordovaCli(kitId).then(function (cordovaCliToUse: string): void { + return kitHelper.getValidCordovaCli(kitId).then(function(cordovaCliToUse: string): void { cordovaCli = cordovaCliToUse; }) - .then(function (): Q.Promise { - return self.printStatusMessage(); - }) - .then(function (): Q.Promise { - if (kitId) { - return kitHelper.getKitInfo(kitId); - } else { - return Q.resolve(null); - } - }) - .then(function (kitInfo: TacoKits.IKitInfo): Q.Promise { - if (kitInfo && !!kitInfo.deprecated) { - // Warn the user - logger.log(resources.getString("CommandCreateWarningDeprecatedKit", kitId)); - } - - if (mustUseTemplate) { - var templates: templateManager = new templateManager(kitHelper); - - return templates.createKitProjectWithTemplate(kitId, templateId, cordovaCli, self.commandParameters.cordovaParameters) - .then(function (templateDisplayName: string): Q.Promise { - return Q.resolve(templateDisplayName); - }); - } else { - return cordovaWrapper.create(cordovaCli, self.commandParameters.cordovaParameters); - } - }); + .then(function(): Q.Promise { + return self.printStatusMessage(); + }) + .then(function(): Q.Promise { + if (kitId) { + return kitHelper.getKitInfo(kitId); + } else { + return Q.resolve(null); + } + }) + .then(function(kitInfo: TacoKits.IKitInfo): Q.Promise { + if (kitInfo && !!kitInfo.deprecated) { + // Warn the user + logger.log(resources.getString("CommandCreateWarningDeprecatedKit", kitId)); + } + + if (mustUseTemplate) { + var templates: templateManager = new templateManager(kitHelper); + + return templates.createKitProjectWithTemplate(kitId, templateId, cordovaCli, self.commandParameters.cordovaParameters) + .then(function(templateDisplayName: string): Q.Promise { + return Q.resolve(templateDisplayName); + }); + } else { + return cordovaWrapper.create(cordovaCli, self.commandParameters.cordovaParameters); + } + }); } } @@ -232,8 +232,8 @@ class Create extends commands.TacoCommandBase { * Prints the project creation status message */ private printStatusMessage(): Q.Promise { - var self = this; - var cordovaParameters = this.commandParameters.cordovaParameters; + var self: Create = this; + var cordovaParameters: Cordova.ICordovaCreateParameters = this.commandParameters.cordovaParameters; var projectPath: string = cordovaParameters.projectPath ? path.resolve(cordovaParameters.projectPath) : "''"; if (!this.isKitProject()) { @@ -243,7 +243,7 @@ class Create extends commands.TacoCommandBase { var kitIdArg: string = this.commandParameters.data.options["kit"]; return (kitIdArg ? Q(kitIdArg) : kitHelper.getDefaultKit()) .then((kitId: string) => kitHelper.getKitInfo(kitId) - .then(kitInfo => self.printNewProjectTable("CommandCreateStatusTableKitVersionDescription", + .then((kitInfo: TacoKits.IKitInfo) => self.printNewProjectTable("CommandCreateStatusTableKitVersionDescription", kit.getKitTitle(kitId, kitInfo)))); } } @@ -254,13 +254,13 @@ class Create extends commands.TacoCommandBase { } private printNewProjectTable(kitOrCordovaStringResource: string, kitOrCordovaVersion: string): void { - var cordovaParameters = this.commandParameters.cordovaParameters; + var cordovaParameters: Cordova.ICordovaCreateParameters = this.commandParameters.cordovaParameters; var projectFullPath: string = path.resolve(this.commandParameters.cordovaParameters.projectPath); logger.log(resources.getString("CommandCreateStatusCreatingNewProject")); - var indentation = 6; // We leave some empty space on the left before the text/table starts - var nameDescriptionPairs = [ + var indentation: number = 6; // We leave some empty space on the left before the text/table starts + var nameDescriptionPairs: INameDescription[] = [ { name: resources.getString("CommandCreateStatusTableNameDescription"), description: cordovaParameters.appName }, { name: resources.getString("CommandCreateStatusTableIDDescription"), description: cordovaParameters.appId }, { name: resources.getString("CommandCreateStatusTableLocationDescription"), description: projectFullPath }, @@ -300,11 +300,11 @@ class Create extends commands.TacoCommandBase { "HowToUseCommandSetupRemote", "HowToUseCommandBuildPlatform", "HowToUseCommandEmulatePlatform", - "HowToUseCommandRunPlatform"].map(msg => resources.getString(msg, projectFullPath))); + "HowToUseCommandRunPlatform"].map((msg: string) => resources.getString(msg, projectFullPath))); ["", "HowToUseCommandHelp", - "HowToUseCommandDocs"].forEach(msg => logger.log(resources.getString(msg))); + "HowToUseCommandDocs"].forEach((msg: string) => logger.log(resources.getString(msg))); } private isKitProject(): boolean { diff --git a/src/taco-cli/cli/docs.ts b/src/taco-cli/cli/docs.ts index 548825ee..194c4a5a 100644 --- a/src/taco-cli/cli/docs.ts +++ b/src/taco-cli/cli/docs.ts @@ -29,7 +29,7 @@ class Documentation extends commands.TacoCommandBase { public run(data: commands.ICommandData): Q.Promise { // This implementation is based on "npm docs": https://github.com/npm/npm/blob/master/lib/docs.js - var link = resources.getString("TacoDocumentationLink"); + var link: string = resources.getString("TacoDocumentationLink"); opener(link); return Q.resolve({}); } diff --git a/src/taco-cli/cli/emulate.ts b/src/taco-cli/cli/emulate.ts index 9ab4b9f6..42ab3faa 100644 --- a/src/taco-cli/cli/emulate.ts +++ b/src/taco-cli/cli/emulate.ts @@ -63,17 +63,17 @@ class Emulate extends commands.TacoCommandBase { private static runRemotePlatform(platform: string, commandData: commands.ICommandData, telemetryProperties: ICommandTelemetryProperties): Q.Promise { return Q.all([Settings.loadSettings(), CordovaWrapper.getCordovaVersion()]).spread(function (settings: Settings.ISettings, cordovaVersion: string): Q.Promise { - var configuration = commandData.options["release"] ? "release" : "debug"; - var buildTarget = commandData.options["target"] || ""; - var language = settings.language || "en"; - var remoteConfig = settings.remotePlatforms && settings.remotePlatforms[platform]; + var configuration: string = commandData.options["release"] ? "release" : "debug"; + var buildTarget: string = commandData.options["target"] || ""; + var language: string = settings.language || "en"; + var remoteConfig: Settings.IRemoteConnectionInfo = settings.remotePlatforms && settings.remotePlatforms[platform]; if (!remoteConfig) { throw errorHelper.get(TacoErrorCodes.CommandRemotePlatformNotKnown, platform); } - var buildInfoPath = path.resolve(".", "remote", platform, configuration, "buildInfo.json"); + var buildInfoPath: string = path.resolve(".", "remote", platform, configuration, "buildInfo.json"); var buildInfoPromise: Q.Promise; - var buildSettings = new RemoteBuildSettings({ + var buildSettings: RemoteBuildSettings = new RemoteBuildSettings({ projectSourceDir: path.resolve("."), buildServerInfo: remoteConfig, buildCommand: "build", @@ -89,7 +89,7 @@ class Emulate extends commands.TacoCommandBase { buildInfoPromise = RemoteBuildClientHelper.checkForBuildOnServer(buildSettings, buildInfoPath).then(function (buildInfo: BuildInfo): BuildInfo { if (!buildInfo) { // No info for the remote build: User must build first - var buildCommandToRun = "taco build" + ([commandData.options["remote"] ? " --remote" : ""].concat(commandData.remain).join(" ")); + var buildCommandToRun: string = "taco build" + ([commandData.options["remote"] ? " --remote" : ""].concat(commandData.remain).join(" ")); throw errorHelper.get(TacoErrorCodes.NoRemoteBuildIdFound, buildCommandToRun); } else { return buildInfo; @@ -162,7 +162,7 @@ class Emulate extends commands.TacoCommandBase { } public parseArgs(args: string[]): commands.ICommandData { - var parsedOptions = tacoUtility.ArgsHelper.parseArguments(Emulate.KNOWN_OPTIONS, Emulate.SHORT_HANDS, args, 0); + var parsedOptions: commands.ICommandData = tacoUtility.ArgsHelper.parseArguments(Emulate.KNOWN_OPTIONS, Emulate.SHORT_HANDS, args, 0); // Raise errors for invalid command line parameters if (parsedOptions.options["remote"] && parsedOptions.options["local"]) { diff --git a/src/taco-cli/cli/installReqs.ts b/src/taco-cli/cli/installReqs.ts index 635a0312..bf7970e2 100644 --- a/src/taco-cli/cli/installReqs.ts +++ b/src/taco-cli/cli/installReqs.ts @@ -201,8 +201,8 @@ class InstallReqs extends commands.TacoCommandBase { } public run(data: commands.ICommandData): Q.Promise { - return tacoUtils.TelemetryHelper.generate("InstallReqs", telemetry => { - var self = this; + return tacoUtils.TelemetryHelper.generate("InstallReqs", (telemetry: tacoUtils.TelemetryGenerator): Q.Promise => { + var self: InstallReqs = this; var parsed: commands.ICommandData = null; try { @@ -257,7 +257,7 @@ class InstallReqs extends commands.TacoCommandBase { return cordovaWrapper.requirements(requestedPlatforms) .then(function (result: any): Q.Promise { - var sessionId = tacoUtils.Telemetry.isOptedIn ? + var sessionId: string = tacoUtils.Telemetry.isOptedIn ? tacoUtils.Telemetry.getSessionId() : // Valid session ID to publish telemetry "null"; // Null session ID to not publish telemetry var installer: DependencyInstaller = new DependencyInstaller(sessionId); diff --git a/src/taco-cli/cli/kit.ts b/src/taco-cli/cli/kit.ts index d8c8a416..5ff3c7e9 100644 --- a/src/taco-cli/cli/kit.ts +++ b/src/taco-cli/cli/kit.ts @@ -71,7 +71,7 @@ class Kit extends commands.TacoCommandBase { */ public static promptUser(prompt: string): Q.Promise { var deferred: Q.Deferred = Q.defer(); - var yesOrNoHandler = readline.createInterface({ input: process.stdin, output: process.stdout }); + var yesOrNoHandler: readline.ReadLine = readline.createInterface({ input: process.stdin, output: process.stdout }); yesOrNoHandler.question(prompt, function (answer: string): void { yesOrNoHandler.close(); @@ -171,7 +171,7 @@ class Kit extends commands.TacoCommandBase { return kitHelper.getKitMetadata().then(function (meta: TacoKits.ITacoKitMetadata): Q.Promise { return Q.all(Object.keys(meta.kits).map(function (kitId: string): Q.Promise { return kitHelper.getKitInfo(kitId).then(function (kitInfo: TacoKits.IKitInfo): Q.Promise { - var kitNameDescription = { + var kitNameDescription: INameDescription = { name: util.format("%s", kitId), description: Kit.getKitDescription(kitInfo) }; @@ -356,7 +356,7 @@ class Kit extends commands.TacoCommandBase { */ private static printKit(kitId: string): Q.Promise { return kitHelper.getKitInfo(kitId).then(function (kitInfo: TacoKits.IKitInfo): void { - var indent = LoggerHelper.getDescriptionColumnIndent(Kit.getLongestPlatformPluginLength(kitInfo.platforms ? Object.keys(kitInfo.platforms) : null, kitInfo.plugins ? Object.keys(kitInfo.plugins) : null)); + var indent: number = LoggerHelper.getDescriptionColumnIndent(Kit.getLongestPlatformPluginLength(kitInfo.platforms ? Object.keys(kitInfo.platforms) : null, kitInfo.plugins ? Object.keys(kitInfo.plugins) : null)); Kit.printKitNameAndDescription(kitId, kitInfo); Kit.printCordovaCliVersion(kitInfo); Kit.printPlatformOverrideInfo(kitInfo, indent); @@ -369,7 +369,7 @@ class Kit extends commands.TacoCommandBase { * Pretty prints the current Kit/Cordova CLI info */ private static getCurrentKitInfo(): Q.Promise { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); return projectHelper.getProjectInfo().then(function (projectInfo: projectHelper.IProjectInfo): Q.Promise { deferred.resolve(projectInfo.tacoKitId); return deferred.promise; @@ -401,7 +401,7 @@ class Kit extends commands.TacoCommandBase { } var downloadOptions: Cordova.ICordovaDownloadOptions = { searchpath: "", noregistry: false, usegit: false, cli_variables: {}, browserify: "", link: "", save: true, shrinkwrap: false }; - var command = (componentType === ProjectComponentType.Platform) ? "platform" : "plugin"; + var command: string = (componentType === ProjectComponentType.Platform) ? "platform" : "plugin"; // Remove all the updatable plugins and re-add them return Kit.invokeComponentCommandSilent(command, "remove", Object.keys(components), downloadOptions) @@ -436,7 +436,7 @@ class Kit extends commands.TacoCommandBase { assert(componentType === ProjectComponentType.Platform || componentType === ProjectComponentType.Plugin); var componentUpdates: IDictionary = {}; return kitHelper.getKitInfo(kitId).then(function (kitInfo: TacoKits.IKitInfo): Q.Promise { - var componentOverrides = (componentType === ProjectComponentType.Platform) ? kitInfo.platforms : kitInfo.plugins; + var componentOverrides: any = (componentType === ProjectComponentType.Platform) ? kitInfo.platforms : kitInfo.plugins; if (!installedComponentInfo) { return Q.resolve({}); } @@ -475,7 +475,7 @@ class Kit extends commands.TacoCommandBase { */ private static printProjectUpdateInfo(id: string, installedPlatformVersions: IDictionary, installedPluginVersions: IDictionary, platformVersionUpdates: IDictionary = null, pluginVersionUpdates: IDictionary = null): void { - var indent = LoggerHelper.getDescriptionColumnIndent(Kit.getLongestPlatformPluginLength(installedPlatformVersions ? Object.keys(installedPlatformVersions) : null, installedPluginVersions ? Object.keys(installedPluginVersions) : null)); + var indent: number = LoggerHelper.getDescriptionColumnIndent(Kit.getLongestPlatformPluginLength(installedPlatformVersions ? Object.keys(installedPlatformVersions) : null, installedPluginVersions ? Object.keys(installedPluginVersions) : null)); var platformsRequireUpdate: boolean = Kit.projectComponentNeedsUpdate(installedPlatformVersions, platformVersionUpdates); var pluginsRequireUpdate: boolean = Kit.projectComponentNeedsUpdate(installedPluginVersions, pluginVersionUpdates); @@ -518,7 +518,7 @@ class Kit extends commands.TacoCommandBase { private static printUpdateInfo(indent: number, installedComponentInfo: IDictionary, componentUpdateInfo: IDictionary = null, componentType: ProjectComponentType = ProjectComponentType.Platform): void { assert(installedComponentInfo); - var suffix = componentType === ProjectComponentType.Platform ? resources.getString("CommandKitSelectKitPlatformVersion") : resources.getString("CommandKitSelectKitPluginVersion"); + var suffix: string = componentType === ProjectComponentType.Platform ? resources.getString("CommandKitSelectKitPlatformVersion") : resources.getString("CommandKitSelectKitPluginVersion"); if (componentUpdateInfo) { LoggerHelper.logNameDescriptionTable( Object.keys(componentUpdateInfo).map(function (componentName: string): INameDescription { @@ -547,8 +547,8 @@ class Kit extends commands.TacoCommandBase { if (nonUpdatablePlugins) { var updatablePlugins: IDictionary = {}; - Object.keys(pluginVersions).filter(pluginName => nonUpdatablePlugins.indexOf(pluginName) === -1) - .forEach(pluginName => updatablePlugins[pluginName] = pluginVersions[pluginName]); + Object.keys(pluginVersions).filter((pluginName: string) => nonUpdatablePlugins.indexOf(pluginName) === -1) + .forEach((pluginName: string) => updatablePlugins[pluginName] = pluginVersions[pluginName]); return updatablePlugins; } else { @@ -574,7 +574,7 @@ class Kit extends commands.TacoCommandBase { * Returns the CLI version that was used to create the project */ private static getCliversion(projectInfo: projectHelper.IProjectInfo): Q.Promise { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); if (projectInfo.cordovaCliVersion.length === 0) { cordovaWrapper.getGlobalCordovaVersion().then(function (globalCordovaVersion: string): void { deferred.resolve(globalCordovaVersion); @@ -625,14 +625,14 @@ class Kit extends commands.TacoCommandBase { * Validates whether the version string passed is a valid Cordova version */ private static validateCliVersion(version: string): Q.Promise { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); if (!semver.valid(version)) { return Q.reject(errorHelper.get(TacoErrorCodes.ErrorInvalidVersion, version, "cordova")); } - var npmCommand = process.platform === "win32" ? "npm.cmd" : "npm"; - var npmProcess = child_process.spawn(npmCommand, ["view", "cordova", "versions"]); + var npmCommand: string = process.platform === "win32" ? "npm.cmd" : "npm"; + var npmProcess: child_process.ChildProcess = child_process.spawn(npmCommand, ["view", "cordova", "versions"]); npmProcess.on("error", function (error: Error): void { throw errorHelper.get(TacoErrorCodes.ErrorReadingPackageVersions, "cordova"); }); @@ -662,7 +662,7 @@ class Kit extends commands.TacoCommandBase { .then(function (): Q.Promise { return Q.all([projectHelper.getInstalledPlatformVersions(projectPath), projectHelper.getInstalledPluginVersions(projectPath), projectHelper.getNonUpdatablePlugins(projectPath), projectHelper.createTacoJsonFile(projectPath, false, newCliVersion)]) .spread(function (platformVersions: IDictionary, pluginVersions: IDictionary, nonUpdatablePlugins: string[]): Q.Promise { - var pluginsToUpdate = Kit.filterUpdatablePluginVerions(pluginVersions, nonUpdatablePlugins); + var pluginsToUpdate: IDictionary = Kit.filterUpdatablePluginVerions(pluginVersions, nonUpdatablePlugins); return Kit.getCliversion(projectInfo) .then(function (currentCliVersion: string): Q.Promise { Kit.printCliProjectUpdateInfo(currentCliVersion, newCliVersion, platformVersions, pluginsToUpdate); @@ -758,7 +758,7 @@ class Kit extends commands.TacoCommandBase { /* tslint:enable:member-ordering */ public parseArgs(args: string[]): commands.ICommandData { - var parsedOptions = tacoUtility.ArgsHelper.parseArguments(Kit.KNOWN_OPTIONS, Kit.SHORT_HANDS, args, 0); + var parsedOptions: commands.ICommandData = tacoUtility.ArgsHelper.parseArguments(Kit.KNOWN_OPTIONS, Kit.SHORT_HANDS, args, 0); // Raise errors for invalid command line parameter combinations if (parsedOptions.options.hasOwnProperty("json") && parsedOptions.options.hasOwnProperty("cordova")) { diff --git a/src/taco-cli/cli/logo.ts b/src/taco-cli/cli/logo.ts index 7318ac58..500475a1 100644 --- a/src/taco-cli/cli/logo.ts +++ b/src/taco-cli/cli/logo.ts @@ -11,7 +11,7 @@ /* tslint:disable:no-var-requires */ // var require needed to require package json -var version = require("../package.json").version; +var version: string = require("../package.json").version; /* tslint:enable:no-var-requires */ function logoColorFunction(s: string): string { @@ -29,14 +29,14 @@ console.log(logoColorFunction(" _____________________________")); console.log(logoColorFunction(" ___ __/_ |__ ____/_ __ \\")); console.log(logoColorFunction(" __ / _ /| |_ / _ / / /")); console.log(logoColorFunction(" _ / _ ___ |/ /___ / /_/ /")); -var lastLine = /* align */ " /_/ /_/ |_|\\____/ \\____/ CLI v" + version; +var lastLine: string = /* */ " /_/ /_/ |_|\\____/ \\____/ CLI v" + version; console.log(logoColorFunction(lastLine)); console.log(); -var len = lastLine.length; -var line = new Array(len + 1).join("-"); -var title = "Tools for Apache Cordova"; -var spaces = Math.floor((len - title.length) / 2); +var len: number = lastLine.length; +var line: string = new Array(len + 1).join("-"); +var title: string = "Tools for Apache Cordova"; +var spaces: number = Math.floor((len - title.length) / 2); console.log(logoColorFunction(line)); console.log(logoColorFunction(new Array(spaces + 1).join(" ") + title)); diff --git a/src/taco-cli/cli/platform.ts b/src/taco-cli/cli/platform.ts index a020b93d..b161db51 100644 --- a/src/taco-cli/cli/platform.ts +++ b/src/taco-cli/cli/platform.ts @@ -44,9 +44,9 @@ class Platform extends commandBase.PlatformPluginCommandBase { public checkForKitOverrides(projectInfo: projectHelper.IProjectInfo): Q.Promise { var targets: string[] = []; var platformInfoToPersist: Cordova.ICordovaPlatformPluginInfo[] = []; - var self = this; + var self: Platform = this; - var subCommand = this.cordovaCommandParams.subCommand; + var subCommand: string = this.cordovaCommandParams.subCommand; if (subCommand !== "add") { return Q({}); } @@ -68,7 +68,7 @@ class Platform extends commandBase.PlatformPluginCommandBase { platformInfoToPersist.push(platformInfo); } - var target = platformInfo.spec.length > 0 ? platformName + "@" + platformInfo.spec : platformName; + var target: string = platformInfo.spec.length > 0 ? platformName + "@" + platformInfo.spec : platformName; targets.push(target); }); } else { @@ -90,7 +90,7 @@ class Platform extends commandBase.PlatformPluginCommandBase { * Checks if the platform has a version specification in config.xml of the cordova project */ public configXmlHasVersionOverride(platformName: string, projectInfo: projectHelper.IProjectInfo): Q.Promise { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); cordovaHelper.getEngineVersionSpec(platformName, projectInfo.configXmlPath, projectInfo.cordovaCliVersion).then(function (versionSpec: string): void { deferred.resolve(versionSpec !== ""); }); @@ -168,11 +168,11 @@ class Platform extends commandBase.PlatformPluginCommandBase { "HowToUseCommandSetupRemote", "HowToUseCommandBuildPlatform", "HowToUseCommandEmulatePlatform", - "HowToUseCommandRunPlatform"].map(msg => resources.getString(msg))); + "HowToUseCommandRunPlatform"].map((msg: string) => resources.getString(msg))); ["", "HowToUseCommandHelp", - "HowToUseCommandDocs"].forEach(msg => logger.log(resources.getString(msg))); + "HowToUseCommandDocs"].forEach((msg: string) => logger.log(resources.getString(msg))); } break; diff --git a/src/taco-cli/cli/plugin.ts b/src/taco-cli/cli/plugin.ts index 564671ec..7f325d32 100644 --- a/src/taco-cli/cli/plugin.ts +++ b/src/taco-cli/cli/plugin.ts @@ -44,10 +44,10 @@ class Plugin extends commandBase.PlatformPluginCommandBase { */ public checkForKitOverrides(projectInfo: projectHelper.IProjectInfo): Q.Promise { var targets: string[] = []; - var self = this; + var self: Plugin = this; var pluginInfoToPersist: Cordova.ICordovaPlatformPluginInfo[] = []; - var subCommand = this.cordovaCommandParams.subCommand; + var subCommand: string = this.cordovaCommandParams.subCommand; if (subCommand !== "add") { return Q({}); } @@ -102,7 +102,7 @@ class Plugin extends commandBase.PlatformPluginCommandBase { * Checks if the plugin has a version specification in config.xml of the cordova project */ public configXmlHasVersionOverride(pluginName: string, projectInfo: projectHelper.IProjectInfo): Q.Promise { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); cordovaHelper.getPluginVersionSpec(pluginName, projectInfo.configXmlPath, projectInfo.cordovaCliVersion).then(function (versionSpec: string): void { deferred.resolve(versionSpec !== ""); }); @@ -188,11 +188,11 @@ class Plugin extends commandBase.PlatformPluginCommandBase { "HowToUseCommandSetupRemote", "HowToUseCommandBuildPlatform", "HowToUseCommandEmulatePlatform", - "HowToUseCommandRunPlatform"].map(msg => resources.getString(msg))); + "HowToUseCommandRunPlatform"].map((msg: string) => resources.getString(msg))); ["", "HowToUseCommandHelp", - "HowToUseCommandDocs"].forEach(msg => logger.log(resources.getString(msg))); + "HowToUseCommandDocs"].forEach((msg: string) => logger.log(resources.getString(msg))); } break; diff --git a/src/taco-cli/cli/remote.ts b/src/taco-cli/cli/remote.ts index f6a2c59f..8a7ce9cb 100644 --- a/src/taco-cli/cli/remote.ts +++ b/src/taco-cli/cli/remote.ts @@ -100,7 +100,7 @@ class Remote extends commands.TacoCommandBase { * Generates the telemetry properties for the remote operation */ private static generateTelemetryProperties(subCommand: string, platform?: string, isSecure?: boolean): Q.Promise { - var self = this; + return projectHelper.getCurrentProjectTelemetryProperties().then(function (telemetryProperties: ICommandTelemetryProperties): Q.Promise { telemetryProperties["subCommand"] = telemetryHelper.telemetryProperty(subCommand); @@ -146,9 +146,9 @@ class Remote extends commands.TacoCommandBase { // No settings or the settings were corrupted: start from scratch return {}; }).then(function (settings: Settings.ISettings): void { - var platforms = Object.keys(settings.remotePlatforms || {}).map(function (platform: string): INameDescription { - var remote = settings.remotePlatforms && settings.remotePlatforms[platform]; - var url = util.format("[%s] %s://%s:%d/%s", + var platforms: INameDescription [] = Object.keys(settings.remotePlatforms || {}).map(function (platform: string): INameDescription { + var remote: Settings.IRemoteConnectionInfo = settings.remotePlatforms && settings.remotePlatforms[platform]; + var url: string = util.format("[%s] %s://%s:%d/%s", remote.secure ? resources.getString("CommandRemoteListSecured") : resources.getString("CommandRemoteListNotSecured"), remote.secure ? "https" : "http", remote.host, @@ -160,7 +160,7 @@ class Remote extends commands.TacoCommandBase { if (platforms && platforms.length > 0) { logger.log(resources.getString("CommandRemoteListPrelude")); logger.logLine(); - var header = { name: resources.getString("CommandRemoteListPlatformHeader"), description: resources.getString("CommandRemoteListDescriptionHeader") }; + var header: INameDescription = { name: resources.getString("CommandRemoteListPlatformHeader"), description: resources.getString("CommandRemoteListDescriptionHeader") }; loggerHelper.logNameDescriptionTableWithHeader(header, platforms, null, null, " "); } else { logger.log(resources.getString("CommandRemoteListNoPlatforms")); @@ -196,11 +196,11 @@ class Remote extends commands.TacoCommandBase { loggerHelper.logList([ "HowToUseCommandBuildPlatform", "HowToUseCommandEmulatePlatform", - "HowToUseCommandRunPlatform"].map(msg => resources.getString(msg))); + "HowToUseCommandRunPlatform"].map((msg: string) => resources.getString(msg))); ["", "HowToUseCommandHelp", - "HowToUseCommandDocs"].forEach(msg => logger.log(resources.getString(msg))); + "HowToUseCommandDocs"].forEach((msg: string) => logger.log(resources.getString(msg))); }); }).then(function (): Q.Promise { return Remote.generateTelemetryProperties("add", platform, remoteInfo.secure); @@ -208,11 +208,11 @@ class Remote extends commands.TacoCommandBase { } private static queryUserForRemoteConfig(): Q.Promise<{ host: string; port: number; pin: number }> { - var hostPromise = Q.defer<{ host: string }>(); - var portPromise = Q.defer<{ host: string; port: number }>(); - var pinPromise = Q.defer<{ host: string; port: number; pin: number }>(); + var hostPromise: Q.Deferred<{ host: string }> = Q.defer<{ host: string }>(); + var portPromise: Q.Deferred<{ host: string; port: number }> = Q.defer<{ host: string; port: number }>(); + var pinPromise: Q.Deferred<{ host: string; port: number; pin: number }> = Q.defer<{ host: string; port: number; pin: number }>(); - var cliSession = Remote.cliSession ? Remote.cliSession : readline.createInterface({ input: process.stdin, output: process.stdout }); + var cliSession: IcliSession = Remote.cliSession ? Remote.cliSession : readline.createInterface({ input: process.stdin, output: process.stdout }); // Query the user for the host, port, and PIN, but don't keep asking questions if they input a known-invalid argument cliSession.question(resources.getString("CommandRemoteQueryHost"), function (hostAnswer: string): void { @@ -257,8 +257,8 @@ class Remote extends commands.TacoCommandBase { private static acquireCertificateIfRequired(hostPortAndPin: { host: string; port: number; pin: number }): Q.Promise<{ host: string; port: number; certName?: string; secure: boolean }> { if (hostPortAndPin.pin) { // Secure connection: try to acquire a cert and store it in the windows cert store - var certificateUrl = util.format("https://%s:%d/certs/%d", hostPortAndPin.host, hostPortAndPin.port, hostPortAndPin.pin); - var deferred = Q.defer(); + var certificateUrl: string = util.format("https://%s:%d/certs/%d", hostPortAndPin.host, hostPortAndPin.port, hostPortAndPin.pin); + var deferred: Q.Deferred = Q.defer(); // Note: we set strictSSL to be false here because we don't yet know who the server is. We are vulnerable to a MITM attack in this first instance here request.get({ uri: certificateUrl, strictSSL: false, encoding: null, timeout: Remote.HTTP_TIMEOUT_IN_MS }, function (error: any, response: any, body: Buffer): void { if (error) { @@ -286,7 +286,7 @@ class Remote extends commands.TacoCommandBase { } private static findRemoteMountPath(hostPortAndCert: { host: string; port: number; certName?: string; secure: boolean }): Q.Promise { - var mountDiscoveryUrl = util.format("http%s://%s:%d/modules/%s", hostPortAndCert.certName ? "s" : "", hostPortAndCert.host, hostPortAndCert.port, "taco-remote"); + var mountDiscoveryUrl: string = util.format("http%s://%s:%d/modules/%s", hostPortAndCert.certName ? "s" : "", hostPortAndCert.host, hostPortAndCert.port, "taco-remote"); return ConnectionSecurityHelper.getAgent(hostPortAndCert).then(function (agent: https.Agent): Q.Promise { // TODO: Remove the casting once we've get some complete/up-to-date .d.ts files. See https://github.com/Microsoft/TACO/issues/18 var options: request.Options = { @@ -295,7 +295,7 @@ class Remote extends commands.TacoCommandBase { timeout: Remote.HTTP_TIMEOUT_IN_MS }; - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); request.get(options, function (error: any, response: any, body: any): void { if (error) { deferred.reject(Remote.getFriendlyHttpError(error, hostPortAndCert.host, hostPortAndCert.port, mountDiscoveryUrl, !!hostPortAndCert.certName)); @@ -377,7 +377,7 @@ class Remote extends commands.TacoCommandBase { } public parseArgs(args: string[]): commands.ICommandData { - var parsedOptions = tacoUtility.ArgsHelper.parseArguments(Remote.KNOWN_OPTIONS, Remote.SHORT_HANDS, args, 0); + var parsedOptions: commands.ICommandData = tacoUtility.ArgsHelper.parseArguments(Remote.KNOWN_OPTIONS, Remote.SHORT_HANDS, args, 0); return parsedOptions; } diff --git a/src/taco-cli/cli/remoteBuild/connectionSecurityHelper.ts b/src/taco-cli/cli/remoteBuild/connectionSecurityHelper.ts index d2a11db3..ba487d28 100644 --- a/src/taco-cli/cli/remoteBuild/connectionSecurityHelper.ts +++ b/src/taco-cli/cli/remoteBuild/connectionSecurityHelper.ts @@ -31,13 +31,13 @@ class ConnectionSecurityHelper { return Q(null); } - var bufferDeferred = Q.defer(); + var bufferDeferred: Q.Deferred = Q.defer(); switch (os.platform()) { case "win32": - var certScriptPath = path.resolve(__dirname, "win32", "certificates.ps1"); + var certScriptPath: string = path.resolve(__dirname, "win32", "certificates.ps1"); // Note: On windows 7, powershell -file will still attempt to use input from stdin as commands. If we do not close stdin then the process will not exit - var certLoadProcess = child_process.spawn("powershell", ["-executionpolicy", "unrestricted", "-file", certScriptPath, "get", connectionInfo.certName], { stdio: ["ignore", "pipe", "inherit"] }); - var output = ""; + var certLoadProcess: NodeJSChildProcess.ChildProcess = child_process.spawn("powershell", ["-executionpolicy", "unrestricted", "-file", certScriptPath, "get", connectionInfo.certName], { stdio: ["ignore", "pipe", "inherit"] }); + var output: string = ""; certLoadProcess.stdout.on("data", function (data: any): void { output += data.toString(); }); @@ -59,7 +59,7 @@ class ConnectionSecurityHelper { break; case "linux": case "darwin": - var certPath = path.resolve(UtilHelper.tacoHome, "certs", encodeURIComponent(connectionInfo.host), "cert.pfx"); + var certPath: string = path.resolve(UtilHelper.tacoHome, "certs", encodeURIComponent(connectionInfo.host), "cert.pfx"); fs.readFile(certPath, bufferDeferred.makeNodeResolver()); break; default: @@ -79,14 +79,14 @@ class ConnectionSecurityHelper { * and return a promise for the name of the certificate that can be used to retrieve it later */ public static saveCertificate(certificateData: Buffer, host: string): Q.Promise { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); switch (os.platform()) { case "win32": - var base64Certificate = certificateData.toString("base64"); + var base64Certificate: string = certificateData.toString("base64"); // Save the certificate in the user's certificate store via a powershell script - var certScriptPath = path.resolve(__dirname, "win32", "certificates.ps1"); - var certSaveProcess = child_process.spawn("powershell", ["-executionpolicy", "unrestricted", "-file", certScriptPath, "set"]); + var certScriptPath: string = path.resolve(__dirname, "win32", "certificates.ps1"); + var certSaveProcess: NodeJSChildProcess.ChildProcess = child_process.spawn("powershell", ["-executionpolicy", "unrestricted", "-file", certScriptPath, "set"]); var output: string = ""; certSaveProcess.stdin.write(base64Certificate); @@ -112,7 +112,7 @@ class ConnectionSecurityHelper { break; case "linux": case "darwin": - var certPath = path.resolve(UtilHelper.tacoHome, "certs", encodeURIComponent(host)); + var certPath: string = path.resolve(UtilHelper.tacoHome, "certs", encodeURIComponent(host)); UtilHelper.createDirectoryIfNecessary(certPath); // The folder should only be accessible to the specific user fs.chmod(certPath, "0700", function (err: NodeJS.ErrnoException): void { diff --git a/src/taco-cli/cli/remoteBuild/remoteBuildClientHelper.ts b/src/taco-cli/cli/remoteBuild/remoteBuildClientHelper.ts index 32412545..28d1be01 100644 --- a/src/taco-cli/cli/remoteBuild/remoteBuildClientHelper.ts +++ b/src/taco-cli/cli/remoteBuild/remoteBuildClientHelper.ts @@ -44,10 +44,10 @@ import Logger = tacoUtils.Logger; import GlobalConfig = tacoUtils.TacoGlobalConfig; import NewlineNormalizerStream = tacoUtils.NewlineNormalizerStream; import UtilHelper = tacoUtils.UtilHelper; - import ICommandTelemetryProperties = tacoUtils.ICommandTelemetryProperties; +import ITelemetryPropertyInfo = tacoUtils.ITelemetryPropertyInfo; -var telemetryProperty = tacoUtils.TelemetryHelper.telemetryProperty; +var telemetryProperty: (propertyValue: any, isPii?: boolean) => ITelemetryPropertyInfo = tacoUtils.TelemetryHelper.telemetryProperty; class RemoteBuildClientHelper { public static PING_INTERVAL: number = 5000; @@ -57,13 +57,13 @@ class RemoteBuildClientHelper { */ public static build(settings: BuildSettings, telemetryProperties: ICommandTelemetryProperties): Q.Promise { var outputBuildDir: string = settings.platformConfigurationBldDir; - var buildInfoFilePath = settings.buildInfoFilePath; + var buildInfoFilePath: string = settings.buildInfoFilePath; if (!RemoteBuildClientHelper.isValidBuildServerUrl(settings.buildServerUrl)) { throw errorHelper.get(TacoErrorCodes.InvalidRemoteBuildUrl, settings.buildServerUrl); } - var changeTimeFile = path.join(settings.platformConfigurationBldDir, "lastChangeTime.json"); + var changeTimeFile: string = path.join(settings.platformConfigurationBldDir, "lastChangeTime.json"); var lastChangeTime: { [file: string]: number } = {}; var promise: Q.Promise = RemoteBuildClientHelper.checkForBuildOnServer(settings, buildInfoFilePath) @@ -79,7 +79,7 @@ class RemoteBuildClientHelper { } } - var platformJsonFile = path.join(settings.projectSourceDir, "plugins", util.format("remote_%s.json", settings.platform)); + var platformJsonFile: string = path.join(settings.projectSourceDir, "plugins", util.format("remote_%s.json", settings.platform)); if (fs.existsSync(platformJsonFile)) { fs.unlinkSync(platformJsonFile); } @@ -136,8 +136,8 @@ class RemoteBuildClientHelper { } public static run(buildInfo: BuildInfo, serverSettings: Settings.IRemoteConnectionInfo): Q.Promise { - var buildUrlBase = Settings.getRemoteServerUrl(serverSettings) + "/build/" + buildInfo.buildNumber; - var httpSettings = { language: buildInfo.buildLang, agent: ConnectionSecurityHelper.getAgent(serverSettings) }; + var buildUrlBase: string = Settings.getRemoteServerUrl(serverSettings) + "/build/" + buildInfo.buildNumber; + var httpSettings: { language: string; agent: Q.Promise } = { language: buildInfo.buildLang, agent: ConnectionSecurityHelper.getAgent(serverSettings) }; return RemoteBuildClientHelper.httpOptions(buildUrlBase + "/deploy", httpSettings).then(RemoteBuildClientHelper.promiseForHttpGet) .then(function (): Q.Promise<{ response: any; body: string }> { @@ -148,8 +148,8 @@ class RemoteBuildClientHelper { } public static emulate(buildInfo: BuildInfo, serverSettings: Settings.IRemoteConnectionInfo, target: string): Q.Promise { - var buildUrlBase = Settings.getRemoteServerUrl(serverSettings) + "/build/" + buildInfo.buildNumber; - var httpSettings = { language: buildInfo.buildLang, agent: ConnectionSecurityHelper.getAgent(serverSettings) }; + var buildUrlBase: string = Settings.getRemoteServerUrl(serverSettings) + "/build/" + buildInfo.buildNumber; + var httpSettings: { language: string; agent: Q.Promise } = { language: buildInfo.buildLang, agent: ConnectionSecurityHelper.getAgent(serverSettings) }; return RemoteBuildClientHelper.httpOptions(buildUrlBase + "/emulate?" + querystring.stringify({ target: target }), httpSettings).then(RemoteBuildClientHelper.promiseForHttpGet) .then(function (responseAndBody: { response: any; body: string }): BuildInfo { return BuildInfo.createNewBuildInfoFromDataObject(JSON.parse(responseAndBody.body)); @@ -157,8 +157,8 @@ class RemoteBuildClientHelper { } public static debug(buildInfo: BuildInfo, serverSettings: Settings.IRemoteConnectionInfo): Q.Promise { - var buildUrlBase = Settings.getRemoteServerUrl(serverSettings) + "/build/" + buildInfo.buildNumber; - var httpSettings = { language: buildInfo.buildLang, agent: ConnectionSecurityHelper.getAgent(serverSettings) }; + var buildUrlBase: string = Settings.getRemoteServerUrl(serverSettings) + "/build/" + buildInfo.buildNumber; + var httpSettings: { language: string; agent: Q.Promise } = { language: buildInfo.buildLang, agent: ConnectionSecurityHelper.getAgent(serverSettings) }; return RemoteBuildClientHelper.httpOptions(buildUrlBase + "/debug", httpSettings).then(RemoteBuildClientHelper.promiseForHttpGet).then(function (responseAndBody: { response: any; body: string }): BuildInfo { return BuildInfo.createNewBuildInfoFromDataObject(JSON.parse(responseAndBody.body)); }); @@ -168,7 +168,7 @@ class RemoteBuildClientHelper { * Try to find whether the server has a previous build of this project */ public static checkForBuildOnServer(settings: BuildSettings, buildInfoFilePath: string): Q.Promise { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); // If we don't have a buildInfo.json file then we cannot query the server. if (!fs.existsSync(buildInfoFilePath)) { @@ -187,8 +187,8 @@ class RemoteBuildClientHelper { var buildNumber: number = buildInfo.buildNumber; - var serverUrl = settings.buildServerUrl; - var buildUrl = serverUrl + "/build/" + buildNumber; + var serverUrl: string = settings.buildServerUrl; + var buildUrl: string = serverUrl + "/build/" + buildNumber; // If we do have a buildInfo.json, check whether the server still has that build number around return RemoteBuildClientHelper.httpOptions(buildUrl, settings).then(function (requestOptions: request.Options): Q.Promise { @@ -257,11 +257,11 @@ class RemoteBuildClientHelper { */ private static appAsTgzStream(settings: BuildSettings, lastChangeTime: { [file: string]: number }, changeTimeFile: string, telemetryProperties: ICommandTelemetryProperties): Q.Promise { - var platform = settings.platform; - var projectSourceDir = settings.projectSourceDir; - var changeListFile = path.join(projectSourceDir, "changeList.json"); + var platform: string = settings.platform; + var projectSourceDir: string = settings.projectSourceDir; + var changeListFile: string = path.join(projectSourceDir, "changeList.json"); var newChangeTime: { [file: string]: number } = {}; - var isIncremental = false; + var isIncremental: boolean = false; try { var json: { [file: string]: number } = JSON.parse( fs.readFileSync(changeTimeFile)); Object.keys(json).forEach(function (file: string): void { @@ -276,11 +276,11 @@ class RemoteBuildClientHelper { var upToDateFiles: string[] = []; - var filterForChanges = function (reader: fstream.Reader, props: any): boolean { - var shouldInclude = RemoteBuildClientHelper.filterForRemote(settings, reader, lastChangeTime); - var appRelPath = path.relative(settings.projectSourceDir, reader.path); + var filterForChanges: (reader: fstream.Reader, props: any) => boolean = function (reader: fstream.Reader, props: any): boolean { + var shouldInclude: boolean = RemoteBuildClientHelper.filterForRemote(settings, reader, lastChangeTime); + var appRelPath: string = path.relative(settings.projectSourceDir, reader.path); if (shouldInclude) { - var newmtime = reader.props.mtime.getTime(); + var newmtime: number = reader.props.mtime.getTime(); if (reader.props.type === "Directory" || !lastChangeTime[appRelPath] || lastChangeTime[appRelPath] !== newmtime) { // If this is a directory, or a new file, or a file that has changed since we last looked, then include it newChangeTime[appRelPath] = newmtime; @@ -297,11 +297,11 @@ class RemoteBuildClientHelper { return false; }; - var property = telemetryProperty(0, /*isPii*/ false); + var property: ITelemetryPropertyInfo = telemetryProperty(0, /*isPii*/ false); telemetryProperties["remoteBuild." + platform + ".filesChangedCount"] = property; - var filterForTar = (reader: fstream.Reader, props: any) => { - var appRelPath = path.relative(settings.projectSourceDir, reader.path); - var wasModifiedRecently = appRelPath === "changeList.json" || appRelPath in newChangeTime; + var filterForTar: (reader: fstream.Reader, props: any) => void = (reader: fstream.Reader, props: any) => { + var appRelPath: string = path.relative(settings.projectSourceDir, reader.path); + var wasModifiedRecently: boolean = appRelPath === "changeList.json" || appRelPath in newChangeTime; if (wasModifiedRecently && reader.props.type !== "Directory") { property.value++; // We found another file that was modified } @@ -309,13 +309,13 @@ class RemoteBuildClientHelper { return wasModifiedRecently; }; - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); // TODO: Remove the casting once we've get some complete/up-to-date .d.ts files. See https://github.com/Microsoft/TACO/issues/18 - var firstPassReader = new fstream.Reader( { path: projectSourceDir, type: "Directory", filter: filterForChanges }); + var firstPassReader: fstream.Reader = new fstream.Reader( { path: projectSourceDir, type: "Directory", filter: filterForChanges }); firstPassReader.on("close", function (): void { // We have now determined which files are new and which files are old. Construct changeList.json - var previousFiles = Object.keys(lastChangeTime); + var previousFiles: string[] = Object.keys(lastChangeTime); var changeList: { deletedFiles: string[] } = { deletedFiles: previousFiles.filter(function (file: string): boolean { @@ -343,10 +343,10 @@ class RemoteBuildClientHelper { return deferred.promise.then(() => { // TODO: Remove the casting once we've get some complete/up-to-date .d.ts files. See https://github.com/Microsoft/TACO/issues/18 - var projectSourceDirReader = new fstream.Reader( { path: projectSourceDir, type: "Directory", filter: filterForTar }); - var tarProducingStream = CountStream.count(projectSourceDirReader.pipe(tar.Pack()), + var projectSourceDirReader: fstream.Reader = new fstream.Reader( { path: projectSourceDir, type: "Directory", filter: filterForTar }); + var tarProducingStream: NodeJS.ReadableStream = CountStream.count(projectSourceDirReader.pipe(tar.Pack()), (sz: number) => telemetryProperties["remotebuild." + platform + ".projectSizeInBytes"] = telemetryProperty(sz, /*isPii*/ false)); - var tgzProducingStream = CountStream.count(tarProducingStream.pipe(zlib.createGzip()), + var tgzProducingStream: NodeJS.ReadableStream = CountStream.count(tarProducingStream.pipe(zlib.createGzip()), (sz: number) => telemetryProperties["remotebuild." + platform + ".gzipedProjectSizeInBytes"] = telemetryProperty(sz, /*isPii*/ false)); return tgzProducingStream; }); @@ -357,9 +357,9 @@ class RemoteBuildClientHelper { * We want to include all changed user data, and exclude all irrelevant metadata or data for different platforms */ private static filterForRemote(settings: BuildSettings, reader: fstream.Reader, lastChangeTime: { [file: string]: number }): boolean { - var appRelPath = path.relative(settings.projectSourceDir, reader.path); + var appRelPath: string = path.relative(settings.projectSourceDir, reader.path); - var exclusions = [ + var exclusions: string[] = [ "remote", // the /remote folder is for local tracking of remote builds, no need to send it to the remote server "platforms" // The /platforms folder is for locally installed platforms, and thus irrelevant to remote builds ]; @@ -370,7 +370,7 @@ class RemoteBuildClientHelper { // We want to exclude /merges/ if x is not the current platform // Similarly for the others here - var otherPlatformExclusions = [ + var otherPlatformExclusions: string[] = [ "merges", path.join("res", "screens"), path.join("res", "icons"), @@ -378,9 +378,9 @@ class RemoteBuildClientHelper { path.join("res", "native") ]; - var shouldBeExcluded = function (exclusion: string): boolean { + var shouldBeExcluded: (exclusion: string) => boolean = function (exclusion: string): boolean { // If we are looking at \ and basename is not the platform, then it should be excluded - var checkFullPath = path.join(exclusion, reader.basename); + var checkFullPath: string = path.join(exclusion, reader.basename); return reader.basename !== settings.platform && !!appRelPath.match(new RegExp("^" + checkFullPath + "$")); }; @@ -389,7 +389,7 @@ class RemoteBuildClientHelper { } if (settings.incrementalBuild && appRelPath) { - var stat = fs.statSync(reader.path); + var stat: fs.Stats = fs.statSync(reader.path); if (stat.isDirectory()) { // Consider all directories, since their contents may be modified return true; @@ -418,7 +418,7 @@ class RemoteBuildClientHelper { var cfg: string = settings.configuration ? settings.configuration.toLowerCase() : "release"; var cliVersion: string = require("../../package.json").version; - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); var params: { [idx: string]: string } = { command: "build", vcordova: vcordova, @@ -445,7 +445,7 @@ class RemoteBuildClientHelper { params["buildNumber"] = settings.incrementalBuild.toString(); } - var buildUrl = serverUrl + "/build/tasks?" + querystring.stringify(params); + var buildUrl: string = serverUrl + "/build/tasks?" + querystring.stringify(params); Logger.log(resources.getString("SubmittingRemoteBuild", buildUrl)); appAsTgzStream.on("error", function (error: any): void { @@ -484,7 +484,7 @@ class RemoteBuildClientHelper { * Status progression: uploaded -> extracted -> building -> [complete|invalid|error] -> downloaded [if a device targeted build] */ private static pollForBuildComplete(settings: BuildSettings, buildingUrl: string, interval: number, attempts: number, logOffset?: number): Q.Promise { - var thisAttempt = attempts + 1; + var thisAttempt: number = attempts + 1; Logger.log(resources.getString("CheckingRemoteBuildStatus", (new Date()).toLocaleTimeString(), buildingUrl, thisAttempt)); return RemoteBuildClientHelper.httpOptions(buildingUrl, settings).then(RemoteBuildClientHelper.promiseForHttpGet) @@ -493,7 +493,7 @@ class RemoteBuildClientHelper { throw errorHelper.get(TacoErrorCodes.RemoteBuildStatusPollFailed, responseAndBody.response.statusCode, responseAndBody.body); } - var buildInfo = BuildInfo.createNewBuildInfoFromDataObject(JSON.parse(responseAndBody.body)); + var buildInfo: BuildInfo = BuildInfo.createNewBuildInfoFromDataObject(JSON.parse(responseAndBody.body)); Logger.log(buildInfo.status + " - " + buildInfo.message); buildInfo["logOffset"] = logOffset || 0; if (buildInfo.status === BuildInfo.COMPLETE) { @@ -521,12 +521,12 @@ class RemoteBuildClientHelper { return Q({}); } - var queueUrl = settings.buildServerUrl + "/build/tasks"; + var queueUrl: string = settings.buildServerUrl + "/build/tasks"; return RemoteBuildClientHelper.httpOptions(queueUrl, settings).then(RemoteBuildClientHelper.promiseForHttpGet) .then(function (responseAndBody: { response: any; body: string }): Q.Promise { try { var serverInfo: TacoRemote.IServerInfo = JSON.parse(responseAndBody.body); - var queueIndex = serverInfo.queuedBuilds.map((bi: BuildInfo) => bi.buildNumber === buildInfo.buildNumber).indexOf(true); + var queueIndex: number = serverInfo.queuedBuilds.map((bi: BuildInfo) => bi.buildNumber === buildInfo.buildNumber).indexOf(true); if (queueIndex >= 0) { Logger.log(resources.getString("RemoteBuildQueued", queueIndex + 1)); @@ -542,25 +542,25 @@ class RemoteBuildClientHelper { * Download the finished log of a build, regardless of whether it succeeded or failed */ private static logBuildOutput(buildInfo: BuildInfo, settings: BuildSettings): Q.Promise { - var serverUrl = settings.buildServerUrl; - var deferred = Q.defer(); + var serverUrl: string = settings.buildServerUrl; + var deferred: Q.Deferred = Q.defer(); var offset: number = buildInfo["logOffset"] || 0; - var logFlags = offset > 0 ? "r+" : "w"; - var buildNumber = buildInfo.buildNumber; - var downloadUrl = util.format("%s/build/tasks/%d/log?offset=%d", serverUrl, buildNumber, offset); + var logFlags: string = offset > 0 ? "r+" : "w"; + var buildNumber: number = buildInfo.buildNumber; + var downloadUrl: string = util.format("%s/build/tasks/%d/log?offset=%d", serverUrl, buildNumber, offset); return RemoteBuildClientHelper.httpOptions(downloadUrl, settings).then(request).then(function (req: request.Request): Q.Promise { - var logPath = path.join(settings.platformConfigurationBldDir, "build.log"); + var logPath: string = path.join(settings.platformConfigurationBldDir, "build.log"); UtilHelper.createDirectoryIfNecessary(settings.platformConfigurationBldDir); - var endOfFile = 0; + var endOfFile: number = 0; if (offset > 0 && fs.existsSync(logPath)) { - var logFileStat = fs.statSync(logPath); + var logFileStat: fs.Stats = fs.statSync(logPath); endOfFile = logFileStat.size; } // TODO: Remove the casting once we've get some complete/up-to-date .d.ts files. See https://github.com/Microsoft/TACO/issues/18 - var logStream = fs.createWriteStream(logPath, { start: endOfFile, flags: logFlags }); - var countStream = new CountStream(); - var newlineNormalizerStream = new NewlineNormalizerStream(); + var logStream: fs.WriteStream = fs.createWriteStream(logPath, { start: endOfFile, flags: logFlags }); + var countStream: CountStream = new CountStream(); + var newlineNormalizerStream: NewlineNormalizerStream = new NewlineNormalizerStream(); logStream.on("finish", function (): void { Logger.log(resources.getString("BuildLogWrittenTo", logPath)); }); @@ -577,12 +577,12 @@ class RemoteBuildClientHelper { * This file is used by vs-mda/vs-tac, but it is also good for checking what plugins are actually installed remotely. */ private static downloadRemotePluginFile(buildInfo: BuildInfo, settings: BuildSettings, toDir: string): Q.Promise { - var serverUrl = settings.buildServerUrl; - var deferred = Q.defer(); - var buildNumber = buildInfo.buildNumber; - var downloadUrl = util.format("%s/files/%d/cordovaApp/plugins/%s.json", serverUrl, buildNumber, settings.platform); + var serverUrl: string = settings.buildServerUrl; + var deferred: Q.Deferred = Q.defer(); + var buildNumber: number = buildInfo.buildNumber; + var downloadUrl: string = util.format("%s/files/%d/cordovaApp/plugins/%s.json", serverUrl, buildNumber, settings.platform); UtilHelper.createDirectoryIfNecessary(toDir); - var remotePluginStream = fs.createWriteStream(path.join(toDir, util.format("remote_%s.json", settings.platform))); + var remotePluginStream: fs.WriteStream = fs.createWriteStream(path.join(toDir, util.format("remote_%s.json", settings.platform))); remotePluginStream.on("finish", function (): void { deferred.resolve(buildInfo); }); @@ -595,16 +595,16 @@ class RemoteBuildClientHelper { * Download a completed build from the remote server as a zip */ private static downloadBuild(buildInfo: BuildInfo, settings: BuildSettings, toDir: string): Q.Promise { - var serverUrl = settings.buildServerUrl; + var serverUrl: string = settings.buildServerUrl; UtilHelper.createDirectoryIfNecessary(toDir); - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); - var buildNumber = buildInfo.buildNumber; - var downloadUrl = serverUrl + "/build/" + buildNumber + "/download"; + var buildNumber: number = buildInfo.buildNumber; + var downloadUrl: string = serverUrl + "/build/" + buildNumber + "/download"; Logger.log(resources.getString("DownloadingRemoteBuild", downloadUrl, toDir)); - var zipFile = path.join(toDir, buildNumber + ".zip"); - var outZip = fs.createWriteStream(zipFile); + var zipFile: string = path.join(toDir, buildNumber + ".zip"); + var outZip: fs.WriteStream = fs.createWriteStream(zipFile); outZip.on("error", function (error: any): void { deferred.reject(errorHelper.wrap(TacoErrorCodes.ErrorDownloadingRemoteBuild, error, toDir)); }); @@ -623,10 +623,10 @@ class RemoteBuildClientHelper { private static unzipBuildFiles(zipFile: string, toDir: string): Q.Promise<{}> { Logger.log(resources.getString("ExtractingRemoteBuild", toDir)); UtilHelper.createDirectoryIfNecessary(toDir); - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); try { - var zip = new AdmZip(zipFile); + var zip: AdmZip = new AdmZip(zipFile); zip.extractAllTo(toDir, true); Logger.log(resources.getString("DoneExtractingRemoteBuild", toDir)); fs.unlink(zipFile, function (err: NodeJS.ErrnoException): void { @@ -647,7 +647,7 @@ class RemoteBuildClientHelper { * perform a HTTP GET request and return a promise which is resolved with the response or rejected with an error */ private static promiseForHttpGet(urlOptions: request.Options): Q.Promise<{ response: any; body: string }> { - var deferred = Q.defer<{ response: any; body: string }>(); + var deferred: Q.Deferred<{ response: any; body: string }> = Q.defer<{ response: any; body: string }>(); request.get(urlOptions, function (error: any, response: any, body: any): void { if (error) { deferred.reject(errorHelper.wrap(TacoErrorCodes.ErrorHttpGet, error, urlOptions.url)); @@ -655,7 +655,7 @@ class RemoteBuildClientHelper { if (response.statusCode !== 200 && response.statusCode !== 202) { // see if the response is JSON with a message try { - var bodyJson = JSON.parse(response.body); + var bodyJson: any = JSON.parse(response.body); if (bodyJson.message) { deferred.reject(errorHelper.get(TacoErrorCodes.HttpGetFailed, response.statusCode, bodyJson.message)); return; diff --git a/src/taco-cli/cli/run.ts b/src/taco-cli/cli/run.ts index 196f731a..9c9e166d 100755 --- a/src/taco-cli/cli/run.ts +++ b/src/taco-cli/cli/run.ts @@ -75,18 +75,18 @@ class Run extends commands.TacoCommandBase { private static runRemotePlatform(platform: string, commandData: commands.ICommandData, telemetryProperties: ICommandTelemetryProperties): Q.Promise { return Q.all([Settings.loadSettings(), CordovaWrapper.getCordovaVersion()]).spread(function (settings: Settings.ISettings, cordovaVersion: string): Q.Promise { - var configuration = commandData.options["release"] ? "release" : "debug"; - var buildTarget = commandData.options["target"] || (commandData.options["device"] ? "device" : ""); - var language = settings.language || "en"; - var remoteConfig = settings.remotePlatforms && settings.remotePlatforms[platform]; + var configuration: string = commandData.options["release"] ? "release" : "debug"; + var buildTarget: string = commandData.options["target"] || (commandData.options["device"] ? "device" : ""); + var language: string = settings.language || "en"; + var remoteConfig: Settings.IRemoteConnectionInfo = settings.remotePlatforms && settings.remotePlatforms[platform]; if (!remoteConfig) { throw errorHelper.get(TacoErrorCodes.CommandRemotePlatformNotKnown, platform); } - var buildOptions = commandData.remain.filter(function (opt: string): boolean { return opt.indexOf("--") === 0; }); - var buildInfoPath = path.resolve(".", "remote", platform, configuration, "buildInfo.json"); + var buildOptions: string[] = commandData.remain.filter(function (opt: string): boolean { return opt.indexOf("--") === 0; }); + var buildInfoPath: string = path.resolve(".", "remote", platform, configuration, "buildInfo.json"); var buildInfoPromise: Q.Promise; - var buildSettings = new RemoteBuildSettings({ + var buildSettings: RemoteBuildSettings = new RemoteBuildSettings({ projectSourceDir: path.resolve("."), buildServerInfo: remoteConfig, buildCommand: "build", @@ -103,7 +103,7 @@ class Run extends commands.TacoCommandBase { buildInfoPromise = RemoteBuildClientHelper.checkForBuildOnServer(buildSettings, buildInfoPath).then(function (buildInfo: BuildInfo): BuildInfo { if (!buildInfo) { // No info for the remote build: User must build first - var buildCommandToRun = "taco build" + ([commandData.options["remote"] ? " --remote" : ""].concat(commandData.remain).join(" ")); + var buildCommandToRun: string = "taco build" + ([commandData.options["remote"] ? " --remote" : ""].concat(commandData.remain).join(" ")); throw errorHelper.get(TacoErrorCodes.NoRemoteBuildIdFound, buildCommandToRun); } else { return buildInfo; @@ -212,7 +212,7 @@ class Run extends commands.TacoCommandBase { } public parseArgs(args: string[]): commands.ICommandData { - var parsedOptions = tacoUtility.ArgsHelper.parseArguments(Run.KNOWN_OPTIONS, Run.SHORT_HANDS, args, 0); + var parsedOptions: commands.ICommandData = tacoUtility.ArgsHelper.parseArguments(Run.KNOWN_OPTIONS, Run.SHORT_HANDS, args, 0); // Raise errors for invalid command line parameters if (parsedOptions.options["remote"] && parsedOptions.options["local"]) { diff --git a/src/taco-cli/cli/taco.ts b/src/taco-cli/cli/taco.ts index 74cfdeb2..e626c865 100644 --- a/src/taco-cli/cli/taco.ts +++ b/src/taco-cli/cli/taco.ts @@ -123,7 +123,7 @@ class Taco { } else { logger.logWarning(resources.getString("TacoCommandPassthrough")); - var routeToCordovaEvent = new telemetry.TelemetryEvent(telemetry.appName + "/routedcommand"); + var routeToCordovaEvent: telemetry.TelemetryEvent = new telemetry.TelemetryEvent(telemetry.appName + "/routedcommand"); telemetryHelper.addTelemetryEventProperty(routeToCordovaEvent, "argument", parsedArgs.args, true); return cordovaWrapper.cli(parsedArgs.args).then(function (output: any): any { routeToCordovaEvent.properties["success"] = "true"; diff --git a/src/taco-cli/cli/templates.ts b/src/taco-cli/cli/templates.ts index e9c87921..1b8a894b 100644 --- a/src/taco-cli/cli/templates.ts +++ b/src/taco-cli/cli/templates.ts @@ -34,7 +34,7 @@ class Templates extends commands.TacoCommandBase { public info: commands.ICommandInfo; public run(data: commands.ICommandData): Q.Promise { - var self = this; + var self: Templates = this; return this.getTemplatesToPrint() .then(function (templateList: templateManager.ITemplateList): void { diff --git a/src/taco-cli/cli/utils/buildTelemetryHelper.ts b/src/taco-cli/cli/utils/buildTelemetryHelper.ts index e73b1935..f0d4efc0 100644 --- a/src/taco-cli/cli/utils/buildTelemetryHelper.ts +++ b/src/taco-cli/cli/utils/buildTelemetryHelper.ts @@ -13,31 +13,31 @@ import Q = require ("q"); import commands = tacoUtility.Commands; import ICommandTelemetryProperties = tacoUtility.ICommandTelemetryProperties; -var telemetryProperty = tacoUtility.TelemetryHelper.telemetryProperty; +var telemetryProperty: (propertyValue: any, isPii?: boolean) => tacoUtility.ITelemetryPropertyInfo = tacoUtility.TelemetryHelper.telemetryProperty; class BuildTelemetryHelper { // We don't use CordovaHelper.getSupportedPlatforms() because we need to validate this even if // cordova is not installed, and the white list is a good enough solution, so we just use it for all cases - private static knownPlatforms = ["android", "ios", "amazon-fireos", "blackberry10", "browser", "firefoxos", + private static knownPlatforms: string[] = ["android", "ios", "amazon-fireos", "blackberry10", "browser", "firefoxos", "windows", "windows8", "wp8", "www"]; - private static buildAndRunNonPiiOptions = ["clean", "local", "remote", "debuginfo", "nobuild", "device", "emulator", "target", "debug", "release"]; + private static buildAndRunNonPiiOptions: string[] = ["clean", "local", "remote", "debuginfo", "nobuild", "device", "emulator", "target", "debug", "release"]; public static storePlatforms(telemetryProperties: ICommandTelemetryProperties, modifier: string, platforms: Settings.IPlatformWithLocation[], settings: Settings.ISettings): void { - var baseName = "platforms." + modifier + "."; - var remoteBaseName = baseName + "remote"; + var baseName: string = "platforms." + modifier + "."; + var remoteBaseName: string = baseName + "remote"; if (platforms.length > 0) { this.encodePlatforms(telemetryProperties, baseName + "local", this.extractPlatformsList(platforms, Settings.BuildLocationType.Local)); } - var remotePlatforms = this.extractPlatformsList(platforms, Settings.BuildLocationType.Remote); + var remotePlatforms: string[] = this.extractPlatformsList(platforms, Settings.BuildLocationType.Remote); if (remotePlatforms.length > 0) { this.encodePlatforms(telemetryProperties, remoteBaseName, remotePlatforms); } - remotePlatforms.forEach(platform => { + remotePlatforms.forEach((platform: string) => { if (settings.remotePlatforms && settings.remotePlatforms[platform]) { telemetryProperties["platforms.remote." + platform + ".is_secure"] = telemetryProperty(settings.remotePlatforms[platform].secure, /*isPii*/ false); } @@ -46,11 +46,11 @@ class BuildTelemetryHelper { public static addCommandLineBasedPropertiesForBuildAndRun(telemetryProperties: ICommandTelemetryProperties, knownOptions: Nopt.CommandData, commandData: commands.ICommandData): Q.Promise { - return Settings.loadSettingsOrReturnEmpty().then(settings => { - var properties = tacoUtility.TelemetryHelper.addPropertiesFromOptions(telemetryProperties, knownOptions, commandData.options, this.buildAndRunNonPiiOptions); + return Settings.loadSettingsOrReturnEmpty().then((settings: Settings.ISettings) => { + var properties: tacoUtility.ICommandTelemetryProperties = tacoUtility.TelemetryHelper.addPropertiesFromOptions(telemetryProperties, knownOptions, commandData.options, this.buildAndRunNonPiiOptions); return Settings.determinePlatformsFromOptions(commandData).then((platforms: Settings.IPlatformWithLocation[]) => { - var requestedPlatforms = Settings.parseRequestedPlatforms(commandData); - var requestedUsedPlatforms = platforms.filter((platform: Settings.IPlatformWithLocation): boolean => requestedPlatforms.indexOf(platform.platform) !== -1); + var requestedPlatforms: string[] = Settings.parseRequestedPlatforms(commandData); + var requestedUsedPlatforms: Settings.IPlatformWithLocation[] = platforms.filter((platform: Settings.IPlatformWithLocation): boolean => requestedPlatforms.indexOf(platform.platform) !== -1); this.storePlatforms(properties, "requestedViaCommandLine", requestedUsedPlatforms, settings); return properties; }); @@ -58,22 +58,23 @@ class BuildTelemetryHelper { } public static getIsPlatformPii(): { (platform: string): boolean } { - return platform => this.knownPlatforms.indexOf(platform.toLocaleLowerCase()) < 0; + return (platform: string) => this.knownPlatforms.indexOf(platform.toLocaleLowerCase()) < 0; } /* * Encode platform with pii or npii as required */ private static encodePlatforms(telemetryProperties: ICommandTelemetryProperties, baseName: string, platforms: string[]): void { - var platformIndex = 1; // This is a one-based index - platforms.forEach(platform => { + var platformIndex: number = 1; // This is a one-based index + platforms.forEach((platform: string) => { telemetryProperties[baseName + platformIndex++] = telemetryProperty(platform, BuildTelemetryHelper.getIsPlatformPii()(platform)); }); } private static extractPlatformsList(platforms: Settings.IPlatformWithLocation[], buildLocationType: Settings.BuildLocationType): string[] { - var filteredPlatforms = platforms.filter(platform => platform.location === buildLocationType); - return filteredPlatforms.map(platform => platform.platform); + return platforms + .filter((platform: Settings.IPlatformWithLocation) => platform.location === buildLocationType) + .map((platform: Settings.IPlatformWithLocation) => platform.platform); } } diff --git a/src/taco-cli/cli/utils/checkForNewerVersion.ts b/src/taco-cli/cli/utils/checkForNewerVersion.ts index 079a7dab..2b681e29 100644 --- a/src/taco-cli/cli/utils/checkForNewerVersion.ts +++ b/src/taco-cli/cli/utils/checkForNewerVersion.ts @@ -21,11 +21,11 @@ import semver = require ("semver"); import logger = tacoUtility.Logger; class CheckForNewerVersion { - private millisecondsInAnHour = 60 * 60 * 1000; - private maximumCheckIntervalInHours = 4; + private millisecondsInAnHour: number = 60 * 60 * 1000; + private maximumCheckIntervalInHours: number = 4; private tacoCliNpmRepositoryUrl: string; private packageFilePath: string; - private millisecondsUntilTimeout = 5 * 1000; /* We want this to be high, as to have time to get the response back, + private millisecondsUntilTimeout: number = 5 * 1000; /* We want this to be high, as to have time to get the response back, but not very high, because we'll be blocking the user console if this takes too long */ constructor(tacoCliNpmRepositoryUrl: string = "http://registry.npmjs.org/taco-cli/latest", packageFilePath: string = "../../package.json") { @@ -43,10 +43,10 @@ class CheckForNewerVersion { */ return this.isCheckForUpdateNeeded() // 1. - .then(isCheckForUpdateNeeded => { + .then((isCheckForUpdateNeeded: boolean) => { if (isCheckForUpdateNeeded) { // 2. return this.getLatestVersion() // 3. - .then(latestVersion => this.printVersionWarningIfNeccesary(latestVersion)) // 4. + .then((latestVersion: string) => this.printVersionWarningIfNeccesary(latestVersion)) // 4. .then(() => this.updateLastTimeCheckWasDone()); // 5. } else { return Q.resolve(isCheckForUpdateNeeded); @@ -63,12 +63,12 @@ class CheckForNewerVersion { } private isCheckForUpdateNeeded(): Q.Promise { - var self = this; - return settingsManager.loadSettings().then(settings => { - var currentDate = new Date(); + var self: CheckForNewerVersion = this; + return settingsManager.loadSettings().then((settings: settingsManager.ISettings) => { + var currentDate: Date = new Date(); if (settings.lastCheckForNewerVersionTimestamp) { - var millisecondSinceLastCheck = currentDate.getTime() - new Date(settings.lastCheckForNewerVersionTimestamp).getTime(); - var isCheckForUpdateNeeded = millisecondSinceLastCheck > self.maximumCheckIntervalInHours * self.millisecondsInAnHour; + var millisecondSinceLastCheck: number = currentDate.getTime() - new Date(settings.lastCheckForNewerVersionTimestamp).getTime(); + var isCheckForUpdateNeeded: boolean = millisecondSinceLastCheck > self.maximumCheckIntervalInHours * self.millisecondsInAnHour; // FOR DEBUGGING: The next line is only used while debugging this feature // logger.log("Last Check Time" + lastCheckTime + "Current date = " + currentDate + ", Last checked date = " + settings.lastCheckForNewerVersionTimestamp); return isCheckForUpdateNeeded; @@ -80,12 +80,12 @@ class CheckForNewerVersion { } private getLatestVersion(): Q.Promise { - var deferredLatestVersion = Q.defer(); - var proxy = process.env.PROXY || process.env.http_proxy || null; + var deferredLatestVersion: Q.Deferred = Q.defer(); + var proxy: string = process.env.PROXY || process.env.http_proxy || null; request({ url: this.tacoCliNpmRepositoryUrl, json: true, proxy: proxy, timeout: this.millisecondsUntilTimeout }, (error: any, response: any, body: any) => { try { if (!error && response.statusCode === 200 && body.version) { // 200 is the 200 OK HTTP Code. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html - var latestVersion = body.version; + var latestVersion: string = body.version; deferredLatestVersion.resolve(latestVersion); } else { deferredLatestVersion.reject("error = " + error + ", status code = " + (response ? response.statusCode : "none") + ", body = " + body); @@ -112,7 +112,7 @@ class CheckForNewerVersion { } private updateLastTimeCheckWasDone(): Q.Promise { - return settingsManager.updateSettings(settings => settings.lastCheckForNewerVersionTimestamp = Date.now()); + return settingsManager.updateSettings((settings: settingsManager.ISettings) => settings.lastCheckForNewerVersionTimestamp = Date.now()); } } diff --git a/src/taco-cli/cli/utils/cordovaHelper.ts b/src/taco-cli/cli/utils/cordovaHelper.ts index 08fa21b4..9194889f 100644 --- a/src/taco-cli/cli/utils/cordovaHelper.ts +++ b/src/taco-cli/cli/utils/cordovaHelper.ts @@ -25,7 +25,7 @@ import packageLoader = tacoUtility.TacoPackageLoader; class CordovaHelper { private static CORDOVA_NPM_PACKAGE_NAME: string = "cordova"; // Cordova's known parameters - private static CORDOVA_BOOLEAN_PARAMETERS = + private static CORDOVA_BOOLEAN_PARAMETERS: any = { verbose: Boolean, version: Boolean, @@ -44,7 +44,7 @@ class CordovaHelper { nobuild: Boolean, list: Boolean }; - private static CORDOVA_VALUE_PARAMETERS = + private static CORDOVA_VALUE_PARAMETERS: any = { "copy-from": String, "link-to": path, @@ -94,7 +94,7 @@ class CordovaHelper { } // If the user specified custom www assets, adjust the cordovaConfig - var customWww = parameters.copyFrom || parameters.linkTo; + var customWww: string = parameters.copyFrom || parameters.linkTo; if (customWww) { if (customWww.indexOf("http") === 0) { @@ -292,8 +292,8 @@ class CordovaHelper { cordova.on("log", console.log); } - var dom = domain.create(); - var deferred = Q.defer(); + var dom: domain.Domain = domain.create(); + var deferred: Q.Deferred = Q.defer(); dom.on("error", function (err: any): void { deferred.reject(errorHelper.wrap(TacoErrorCodes.CordovaCommandUnhandledException, err)); @@ -332,7 +332,7 @@ class CordovaHelper { // calling into platform code should be dealing with this based // on the parsed args object. var downstreamArgs: string[] = []; - var argNames = ["debug", "release", "device", "emulator", "nobuild", "list"]; + var argNames: string[] = ["debug", "release", "device", "emulator", "nobuild", "list"]; argNames.forEach(function (flag: string): void { if (commandData.options[flag]) { downstreamArgs.push("--" + flag); diff --git a/src/taco-cli/cli/utils/cordovaWrapper.ts b/src/taco-cli/cli/utils/cordovaWrapper.ts index c3d3d0e6..e1b4ed10 100644 --- a/src/taco-cli/cli/utils/cordovaWrapper.ts +++ b/src/taco-cli/cli/utils/cordovaWrapper.ts @@ -37,15 +37,15 @@ class CordovaWrapper { private static CORDOVA_CHECK_REQS_MIN_VERSION: string = "5.1.1"; public static cli(args: string[], captureOutput: boolean = false): Q.Promise { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); var output: string = ""; var errorOutput: string = ""; var options: child_process.IExecOptions = captureOutput ? { stdio: "pipe" } : { stdio: "inherit" }; - var proc = child_process.spawn(CordovaWrapper.cordovaCommandName, args, options); + var proc: child_process.ChildProcess = child_process.spawn(CordovaWrapper.cordovaCommandName, args, options); proc.on("error", function (err: any): void { // ENOENT error thrown if no Cordova.cmd is found - var tacoError = (err.code === "ENOENT") ? + var tacoError: tacoUtility.TacoError = (err.code === "ENOENT") ? errorHelper.get(TacoErrorCodes.CordovaCmdNotFound) : errorHelper.wrap(TacoErrorCodes.CordovaCommandFailedWithError, err, args.join(" ")); deferred.reject(tacoError); @@ -68,7 +68,7 @@ class CordovaWrapper { if (captureOutput && output && args[0] === "requirements" && code === 1 && errorOutput && errorOutput.indexOf("Some of requirements check failed") !== -1) { deferred.resolve(output); } else { - var tacoError = errorOutput ? + var tacoError: tacoUtility.TacoError = errorOutput ? errorHelper.wrap(TacoErrorCodes.CordovaCommandFailedWithError, new Error(errorOutput), args.join(" ")) : errorHelper.get(TacoErrorCodes.CordovaCommandFailed, code, args.join(" ")); deferred.reject(tacoError); diff --git a/src/taco-cli/cli/utils/platformPluginCommandBase.ts b/src/taco-cli/cli/utils/platformPluginCommandBase.ts index bb133069..f82b56a8 100644 --- a/src/taco-cli/cli/utils/platformPluginCommandBase.ts +++ b/src/taco-cli/cli/utils/platformPluginCommandBase.ts @@ -125,7 +125,7 @@ export class PlatformPluginCommandBase extends commands.TacoCommandBase { return Q.reject(err); } - var self = this; + var self: PlatformPluginCommandBase = this; var projectInfo: projectHelper.IProjectInfo; var specsToPersist: Cordova.ICordovaPlatformPluginInfo[] = []; return projectHelper.getProjectInfo().then(function (info: projectHelper.IProjectInfo): Q.Promise { @@ -165,7 +165,7 @@ export class PlatformPluginCommandBase extends commands.TacoCommandBase { * Generates the telemetry properties for the platform/plugin operation */ private generateTelemetryProperties(): Q.Promise { - var self = this; + var self: PlatformPluginCommandBase = this; return projectHelper.getCurrentProjectTelemetryProperties().then(function (telemetryProperties: ICommandTelemetryProperties): Q.Promise { var numericSuffix: number = 1; telemetryProperties["subCommand"] = telemetryHelper.telemetryProperty(self.cordovaCommandParams.subCommand); @@ -213,7 +213,7 @@ export class PlatformPluginCommandBase extends commands.TacoCommandBase { // Sanitize the --variable option flags if (variables) { - var self = this; + var self: PlatformPluginCommandBase = this; variables.forEach(function (variable: string): void { var keyval: any[] = variable.split("="); var key: string = keyval[0].toUpperCase(); diff --git a/src/taco-cli/cli/utils/projectHelper.ts b/src/taco-cli/cli/utils/projectHelper.ts index bbc08aa2..134b8ac4 100644 --- a/src/taco-cli/cli/utils/projectHelper.ts +++ b/src/taco-cli/cli/utils/projectHelper.ts @@ -109,7 +109,7 @@ class ProjectHelper { * If we can't find a taco.json then it will not change directory */ public static cdToProjectRoot(): void { - var tacoRoot = ProjectHelper.getProjectRoot(); + var tacoRoot: string = ProjectHelper.getProjectRoot(); if (tacoRoot) { process.chdir(tacoRoot); // Cordova checks for process.env.PWD before checkign process.cwd, and process.env.PWD is not changed by process.chdir() @@ -138,8 +138,8 @@ class ProjectHelper { } var tacoJson: ProjectHelper.ITacoJsonMetadata; - var tacoJsonFilePath = path.join(projectPath, ProjectHelper.TACO_JSON_FILENAME); - var configFilePath = path.join(projectPath, ProjectHelper.CONFIG_XML_FILENAME); + var tacoJsonFilePath: string = path.join(projectPath, ProjectHelper.TACO_JSON_FILENAME); + var configFilePath: string = path.join(projectPath, ProjectHelper.CONFIG_XML_FILENAME); if (ProjectHelper.cachedProjectInfo) { if (tacoJsonFilePath === ProjectHelper.cachedProjectFilePath) { @@ -190,7 +190,7 @@ class ProjectHelper { public static getInstalledComponents(projectDir: string, componentDirName: string): Q.Promise { var components: string[] = []; projectDir = projectDir || ProjectHelper.getProjectRoot(); - var componentDir = path.join(projectDir, componentDirName); + var componentDir: string = path.join(projectDir, componentDirName); if (!fs.existsSync(componentDir)) { return Q.resolve(components); } @@ -207,20 +207,20 @@ class ProjectHelper { */ public static getInstalledPlatformVersions(projectDir: string): Q.Promise { projectDir = projectDir || ProjectHelper.getProjectRoot(); - var onWindows = process.platform === "win32"; - var deferred = Q.defer(); + var onWindows: boolean = process.platform === "win32"; + var deferred: Q.Deferred = Q.defer(); var platformVersions: cordovaHelper.IDictionary = {}; return ProjectHelper.getInstalledComponents(projectDir, "platforms") .then(function (platformsInstalled: string[]): Q.Promise { return Q.all(platformsInstalled.map(function (platform: string): Q.Promise { - var deferredProcPromise = Q.defer(); + var deferredProcPromise: Q.Deferred = Q.defer(); var cmdName: string = "version"; if (onWindows) { cmdName = cmdName + ".bat"; } var cmdPath: string = path.join(projectDir, "platforms", platform, "cordova", cmdName); - var versionProc = child_process.spawn(cmdPath); + var versionProc: child_process.ChildProcess = child_process.spawn(cmdPath); versionProc.stdout.on("data", function (data: any): void { var version: string = data.toString(); platformVersions[platform] = version.trim(); @@ -244,9 +244,9 @@ class ProjectHelper { .then(function (pluginsInstalled: string[]): Q.Promise { pluginsInstalled.forEach(function (plugin: string): void { // Ignore plugins without a package.json - var pluginPackgeJson = path.join(projectDir, "plugins", plugin, "package.json"); + var pluginPackgeJson: string = path.join(projectDir, "plugins", plugin, "package.json"); if (fs.existsSync(pluginPackgeJson)) { - var pluginInfo = require(pluginPackgeJson); + var pluginInfo: any = require(pluginPackgeJson); if (pluginInfo) { pluginVersions[plugin] = pluginInfo["version"]; } @@ -292,7 +292,7 @@ class ProjectHelper { // JsonSerializer class in the taco-utils does the necessary formatting // This is important as VS expects the JSON file to be in the standard JSON format var jsonSerializer: tacoUtility.JsonSerializer = new tacoUtility.JsonSerializer(); - var formattedTacoJson = jsonSerializer.serialize(jsonData); + var formattedTacoJson: any = jsonSerializer.serialize(jsonData); fs.writeFile(tacoJsonPath, formattedTacoJson, function (err: NodeJS.ErrnoException): void { if (err) { diff --git a/src/taco-cli/cli/utils/settings.ts b/src/taco-cli/cli/utils/settings.ts index df5fd0ba..42929627 100755 --- a/src/taco-cli/cli/utils/settings.ts +++ b/src/taco-cli/cli/utils/settings.ts @@ -33,7 +33,7 @@ import utils = tacoUtils.UtilHelper; */ class Settings { private static settings: Settings.ISettings = null; - private static SETTINGS_FILENAME = "TacoSettings.json"; + private static SETTINGS_FILENAME: string = "TacoSettings.json"; public static get settingsFile(): string { return path.join(utils.tacoHome, Settings.SETTINGS_FILENAME); @@ -86,8 +86,8 @@ class Settings { CordovaHelper.getSupportedPlatforms(), Settings.determinePlatformsFromOptions(options) ]).spread(function (supportedPlatforms: CordovaHelper.IDictionary, platforms: Settings.IPlatformWithLocation[]): Settings.IPlatformWithLocation[] { - var filteredPlatforms = platforms.filter(function (platform: Settings.IPlatformWithLocation): boolean { - var supported = !supportedPlatforms || platform.platform in supportedPlatforms || platform.location === Settings.BuildLocationType.Remote; + var filteredPlatforms: Settings.IPlatformWithLocation [] = platforms.filter(function (platform: Settings.IPlatformWithLocation): boolean { + var supported: boolean = !supportedPlatforms || platform.platform in supportedPlatforms || platform.location === Settings.BuildLocationType.Remote; if (!supported) { logger.logWarning(resources.getString("CommandUnsupportedPlatformIgnored", platform.platform)); } @@ -124,7 +124,7 @@ class Settings { throw error; } }) - .then(settings => { + .then((settings: Settings.ISettings) => { updateFunction(settings); return this.saveSettings(settings); }); @@ -150,7 +150,7 @@ class Settings { * taco build --local browser -- ios ==> 'browser' */ public static parseRequestedPlatforms(options: commands.ICommandData): string[] { - var optionsToIgnore = options.original.indexOf("--") === -1 ? [] : options.original.slice(options.original.indexOf("--")); + var optionsToIgnore: string[] = options.original.indexOf("--") === -1 ? [] : options.original.slice(options.original.indexOf("--")); return options.remain.filter(function (platform: string): boolean { return optionsToIgnore.indexOf(platform) === -1; }); } @@ -188,7 +188,7 @@ class Settings { return { location: Settings.BuildLocationType.Local, platform: platform }; })); }).then((platforms: Settings.IPlatformWithLocation[]) => { - var requestedPlatforms = Settings.parseRequestedPlatforms(options); + var requestedPlatforms: string[] = Settings.parseRequestedPlatforms(options); if (requestedPlatforms.length > 0) { // Filter down to user-requested platforms if appropriate diff --git a/src/taco-cli/cli/utils/templateManager.ts b/src/taco-cli/cli/utils/templateManager.ts index a77d9ab8..8d3171df 100644 --- a/src/taco-cli/cli/utils/templateManager.ts +++ b/src/taco-cli/cli/utils/templateManager.ts @@ -15,7 +15,7 @@ "use strict"; -import admZip = require ("adm-zip"); +import AdmZip = require ("adm-zip"); import childProcess = require ("child_process"); import crypto = require ("crypto"); import fs = require ("fs"); @@ -96,7 +96,7 @@ class TemplateManager { "\\$projectname\\$": appName }; - Object.keys(tokens).forEach(function(token: string){ + Object.keys(tokens).forEach(function(token: string): void { replaceParams.regex = token; replaceParams.replacement = tokens[token]; replace(replaceParams); @@ -116,7 +116,7 @@ class TemplateManager { * @return {Q.Promise} A Q promise that is resolved with the template's display name if there are no errors */ public createKitProjectWithTemplate(kitId: string, templateId: string, cordovaCliVersion: string, cordovaParameters: Cordova.ICordovaCreateParameters): Q.Promise { - var self = this; + var self: TemplateManager = this; var templateSrcPath: string = null; templateId = templateId ? templateId : TemplateManager.DEFAULT_TEMPLATE_ID; @@ -156,7 +156,7 @@ class TemplateManager { } // If we reach this point, we are in case 1) (see above comment), so we need to perform a recursive copy - var filterFunc = function (itemPath: string): boolean { + var filterFunc: (itemPath: string) => boolean = function (itemPath: string): boolean { // Return true if the item path is not in our list of git files to ignore return TemplateManager.GIT_FILE_LIST.indexOf(path.basename(itemPath)) === -1; }; @@ -199,7 +199,7 @@ class TemplateManager { .then(function (kitOverride: TacoKits.IKitTemplatesOverrideInfo): Q.Promise { return Q.resolve({ kitId: kitOverride.kitId, - templates: kitOverride.templates.map(t => new TemplateDescriptor(t)) + templates: kitOverride.templates.map((t: TacoKits.ITemplateOverrideInfo) => new TemplateDescriptor(t)) }); }); } @@ -214,7 +214,7 @@ class TemplateManager { .then(function (results: TacoKits.ITemplateOverrideInfo[]): Q.Promise { return Q.resolve({ kitId: "", - templates: results.map(templateInfo => new TemplateDescriptor(templateInfo)) + templates: results.map((templateInfo: TacoKits.ITemplateOverrideInfo) => new TemplateDescriptor(templateInfo)) }); }); } @@ -230,7 +230,7 @@ class TemplateManager { public getTemplateEntriesCount(kitId: string, templateId: string): Q.Promise { return this.kitHelper.getTemplateOverrideInfo(kitId, templateId) .then(function (templateOverrideInfo: TacoKits.ITemplateOverrideInfo): number { - var templateZip = new admZip(templateOverrideInfo.templateInfo.url); + var templateZip: AdmZip = new AdmZip(templateOverrideInfo.templateInfo.url); return templateZip.getEntries().length - 1; // We substract 1, because the returned count includes the root folder of the template }); @@ -301,11 +301,11 @@ class TemplateManager { } private acquireFromTacoKits(templateId: string, kitId: string): Q.Promise { - var self = this; + var self: TemplateManager = this; return this.kitHelper.getTemplateOverrideInfo(kitId, templateId) .then(function (templateOverrideForKit: TacoKits.ITemplateOverrideInfo): Q.Promise { - var templateInfo = templateOverrideForKit.templateInfo; + var templateInfo: TacoKits.ITemplateInfo = templateOverrideForKit.templateInfo; self.templateName = templateInfo.name; @@ -327,7 +327,7 @@ class TemplateManager { wrench.mkdirSyncRecursive(cachedTemplateKitPath, 511); // 511 decimal is 0777 octal // Extract the template archive to the cache - var templateZip = new admZip(templateInfo.url); + var templateZip: AdmZip = new AdmZip(templateInfo.url); templateZip.extractAllTo(cachedTemplateKitPath); } diff --git a/src/taco-cli/test/build.ts b/src/taco-cli/test/build.ts index f29d3691..675a70db 100644 --- a/src/taco-cli/test/build.ts +++ b/src/taco-cli/test/build.ts @@ -15,7 +15,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import AdmZip = require ("adm-zip"); @@ -46,22 +46,22 @@ import BuildInfo = TacoUtility.BuildInfo; import Command = buildAndRunTelemetry.Command; import utils = TacoUtility.UtilHelper; -var build = new buildMod(); -var create = new createMod(); +var build: buildMod = new buildMod(); +var create: createMod = new createMod(); describe("taco build", function (): void { var testHttpServer: http.Server; - var tacoHome = path.join(os.tmpdir(), "taco-cli", "build"); + var tacoHome: string = path.join(os.tmpdir(), "taco-cli", "build"); var originalCwd: string; var vcordova: string = "4.0.0"; - var projectPath = path.join(tacoHome, "example"); + var projectPath: string = path.join(tacoHome, "example"); function createCleanProject(): Q.Promise { // Create a dummy test project with no platforms added utils.createDirectoryIfNecessary(tacoHome); process.chdir(tacoHome); return Q.denodeify(del)("example").then(function (): Q.Promise { - var args = ["example", "--cordova", vcordova]; + var args: string[] = ["example", "--cordova", vcordova]; return create.run({ options: {}, original: args, @@ -72,7 +72,7 @@ describe("taco build", function (): void { }); } - var remoteServerConfiguration = { host: "localhost", port: 3000, secure: false, mountPoint: "cordova" }; + var remoteServerConfiguration: any = { host: "localhost", port: 3000, secure: false, mountPoint: "cordova" }; before(function (mocha: MochaDone): void { originalCwd = process.cwd(); // Set up mocked out resources @@ -83,7 +83,7 @@ describe("taco build", function (): void { kitHelper.kitPackagePromise = null; // Create a mocked out remote server so we can specify how it reacts testHttpServer = http.createServer(); - var port = 3000; + var port: number = 3000; testHttpServer.listen(port); // Reduce the delay when polling for a change in status @@ -114,8 +114,8 @@ describe("taco build", function (): void { del("example", mocha); }); - var buildRun = function (args: string[]): Q.Promise { - var command = new buildMod(); + var buildRun: (args: string[]) => Q.Promise = function (args: string[]): Q.Promise { + var command: buildMod = new buildMod(); return command.run({ options: {}, original: args, @@ -124,12 +124,12 @@ describe("taco build", function (): void { }; it("should make the correct sequence of calls for 'taco build --remote test'", function (mocha: MochaDone): void { - var buildArguments = ["--remote", "test"]; - var configuration = "debug"; - var buildNumber = 12340; + var buildArguments: string [] = ["--remote", "test"]; + var configuration: string = "debug"; + var buildNumber: number = 12340; // Mock out the server on the other side - var sequence = [ + var sequence: any = [ { expectedUrl: "/cordova/build/tasks?" + querystring.stringify({ command: "build", @@ -210,7 +210,7 @@ describe("taco build", function (): void { waitForPayload: false }, ]; - var serverFunction = ServerMock.generateServerFunction(mocha, sequence); + var serverFunction: (request: http.ServerRequest, response: http.ServerResponse) => void = ServerMock.generateServerFunction(mocha, sequence); testHttpServer.on("request", serverFunction); Q(buildArguments).then(buildRun).finally(function (): void { @@ -223,12 +223,12 @@ describe("taco build", function (): void { }); it("should report an error if the remote build fails", function (mocha: MochaDone): void { - var buildArguments = ["--remote", "test"]; - var configuration = "debug"; - var buildNumber = 12341; + var buildArguments: string[] = ["--remote", "test"]; + var configuration: string = "debug"; + var buildNumber: number = 12341; // Mock out the server on the other side - var sequence = [ + var sequence: any = [ { expectedUrl: "/cordova/build/tasks?" + querystring.stringify({ command: "build", @@ -298,7 +298,7 @@ describe("taco build", function (): void { } ]; - var serverFunction = ServerMock.generateServerFunction(mocha, sequence); + var serverFunction: (request: http.ServerRequest, response: http.ServerResponse) => void = ServerMock.generateServerFunction(mocha, sequence); testHttpServer.on("request", serverFunction); Q(buildArguments).then(buildRun).finally(function (): void { @@ -311,11 +311,11 @@ describe("taco build", function (): void { }); it("should attempt incremental builds where possible", function (mocha: MochaDone): void { - var buildArguments = ["--remote", "test"]; - var configuration = "debug"; - var buildNumber = 12342; + var buildArguments: string[] = ["--remote", "test"]; + var configuration: string = "debug"; + var buildNumber: number = 12342; - var buildInfoDir = path.join("remote", "test", configuration); + var buildInfoDir: string = path.join("remote", "test", configuration); utils.createDirectoryIfNecessary(buildInfoDir); fs.writeFileSync(path.join(buildInfoDir, "buildInfo.json"), JSON.stringify(new BuildInfo({ status: BuildInfo.COMPLETE, @@ -324,7 +324,7 @@ describe("taco build", function (): void { // Mock out the server on the other side // Since this test is only whether we attempt incremental builds, we'll let the build fail to make the test shorter - var sequence = [ + var sequence: any = [ { expectedUrl: "/cordova/build/" + buildNumber, head: { @@ -377,7 +377,7 @@ describe("taco build", function (): void { } ]; - var serverFunction = ServerMock.generateServerFunction(mocha, sequence); + var serverFunction: (request: http.ServerRequest, response: http.ServerResponse) => void = ServerMock.generateServerFunction(mocha, sequence); testHttpServer.on("request", serverFunction); Q(buildArguments).then(buildRun).finally(function (): void { @@ -390,13 +390,13 @@ describe("taco build", function (): void { }); it("should make the correct sequence of calls for 'taco build --remote test --device'", function (mocha: MochaDone): void { - var buildArguments = ["--remote", "test", "--device"]; - var configuration = "debug"; - var buildNumber = 12340; + var buildArguments: string[] = ["--remote", "test", "--device"]; + var configuration: string = "debug"; + var buildNumber: number = 12340; var testZipFile: string = path.resolve(__dirname, "resources", "empty.zip"); // Mock out the server on the other side - var sequence = [ + var sequence: any = [ { expectedUrl: "/cordova/build/tasks?" + querystring.stringify({ command: "build", @@ -488,7 +488,7 @@ describe("taco build", function (): void { fileToSend: testZipFile }, ]; - var serverFunction = ServerMock.generateServerFunction(mocha, sequence); + var serverFunction: (request: http.ServerRequest, response: http.ServerResponse) => void = ServerMock.generateServerFunction(mocha, sequence); testHttpServer.on("request", serverFunction); Q(buildArguments).then(buildRun).finally(function (): void { diff --git a/src/taco-cli/test/buildAndRunTelemetry.ts b/src/taco-cli/test/buildAndRunTelemetry.ts index febf09b0..a13a81c4 100644 --- a/src/taco-cli/test/buildAndRunTelemetry.ts +++ b/src/taco-cli/test/buildAndRunTelemetry.ts @@ -14,7 +14,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import AdmZip = require ("adm-zip"); @@ -43,8 +43,8 @@ import TacoUtility = require ("taco-utils"); import BuildInfo = TacoUtility.BuildInfo; import utils = TacoUtility.UtilHelper; -var build = new buildMod(); -var create = new createMod(); +var build: buildMod = new buildMod(); +var create: createMod = new createMod(); interface IExpectedRequest { expectedUrl: string; @@ -88,20 +88,20 @@ module BuildAndRunTelemetryTests { } export function createBuildAndRunTelemetryTests(runCommand: { (args: string[]): Q.Promise }, command: Command): void { - var tacoHome = path.join(os.tmpdir(), "taco-cli", commandSwitch("build", "run", "emulate")); - var projectPath = path.join(tacoHome, "example"); + var tacoHome: string = path.join(os.tmpdir(), "taco-cli", commandSwitch("build", "run", "emulate")); + var projectPath: string = path.join(tacoHome, "example"); var testIosHttpServer: http.Server; var testAndroidHttpServer: http.Server; - var iosPort = 3001; - var androidPort = 3002; + var iosPort: number = 3001; + var androidPort: number = 3002; var cordova: Cordova.ICordova = mockCordova.MockCordova510.default; var vcordova: string = "4.0.0"; - var buildNumber = 12341; - var isNotEmulate = command !== Command.Emulate; + var buildNumber: number = 12341; + var isNotEmulate: boolean = command !== Command.Emulate; var customLoader: TacoUtility.ITacoPackageLoader = { - lazyRequire: (packageName: string, packageId: string, logLevel?: TacoUtility.InstallLogLevel) => { + lazyRequire: (packageName: string, packageId: string, logLevel?: TacoUtility.InstallLogLevel): any => { return Q(cordova); } }; @@ -134,7 +134,7 @@ module BuildAndRunTelemetryTests { }; function generateCompleteBuildSequence(platform: string, port: number, isIncrementalTest: boolean): any { - var configuration = "debug"; + var configuration: string = "debug"; // Mock out the server on the other side var queryOptions: { [key: string]: string } = { @@ -145,9 +145,9 @@ module BuildAndRunTelemetryTests { platform: platform }; - var zip = new AdmZip(); + var zip: AdmZip = new AdmZip(); zip.addFile("test.txt", new Buffer("test file"), "comment"); - var zippedAppBuffer = zip.toBuffer(); + var zippedAppBuffer: Buffer = zip.toBuffer(); var nonIncrementalBuildStart: IExpectedRequest[] = [{ expectedUrl: "/cordova/build/tasks?" + querystring.stringify(queryOptions), @@ -225,11 +225,11 @@ module BuildAndRunTelemetryTests { } ]; - var buildSequence = (isIncrementalTest ? incrementalBuildStart : nonIncrementalBuildStart).concat(remainingBuildSequence); + var buildSequence: any = (isIncrementalTest ? incrementalBuildStart : nonIncrementalBuildStart).concat(remainingBuildSequence); if (command !== Command.Build) { - var target = isIncrementalTest ? "ipad 2" : ""; - var runSequence = [{ + var target: string = isIncrementalTest ? "ipad 2" : ""; + var runSequence: any = [{ expectedUrl: "/cordova/build/" + buildNumber + "/emulate?" + querystring.stringify({ target: target }), head: { "Content-Type": "application/json" }, statusCode: 200, @@ -243,11 +243,11 @@ module BuildAndRunTelemetryTests { } function configureRemoteServer(done: MochaDone, isIncrementalTest: boolean): Q.Promise { - var iosSequence = generateCompleteBuildSequence("ios", iosPort, isIncrementalTest); - var androidSequence = generateCompleteBuildSequence("android", androidPort, isIncrementalTest); + var iosSequence: any = generateCompleteBuildSequence("ios", iosPort, isIncrementalTest); + var androidSequence: any = generateCompleteBuildSequence("android", androidPort, isIncrementalTest); - var iosServerFunction = ServerMock.generateServerFunction(done, iosSequence); - var androidServerFunction = ServerMock.generateServerFunction(done, androidSequence); + var iosServerFunction: (request: http.ServerRequest, response: http.ServerResponse) => void = ServerMock.generateServerFunction(done, iosSequence); + var androidServerFunction: (request: http.ServerRequest, response: http.ServerResponse) => void = ServerMock.generateServerFunction(done, androidSequence); testIosHttpServer.on("request", iosServerFunction); if (!isIncrementalTest) { @@ -262,16 +262,17 @@ module BuildAndRunTelemetryTests { return Settings.saveSettings({ remotePlatforms: platforms }); } - var expectedGzipedSizeAbsoluteError = 60; /* This is how much the gzip size changes because of the different + var expectedGzipedSizeAbsoluteError: number = 60; /* This is how much the gzip size changes because of the different compression rate of different file modification dates, etc... */ // We use this function to validate that the gzip size is near the expected ratio (non-deterministic changes in dates or other // numbers might change the compression ratio, so it's difficult to predict the exact size), and then replace the number with // the expected size, so we can compare it by eql with the expected full telemetry properties - function validateGzipedSize(telemetryProperties: TacoUtility.ICommandTelemetryProperties, platform: string, expectedGzippedSize: number): void { - var keyName = "remotebuild." + platform + ".gzipedProjectSizeInBytes"; + function validateGzipedSize(telemetryProperties: TacoUtility.ICommandTelemetryProperties, + platform: string, expectedGzippedSize: number): void { + var keyName: string = "remotebuild." + platform + ".gzipedProjectSizeInBytes"; if (expectedGzippedSize !== -1) { - var value = telemetryProperties[keyName].value; + var value: string = telemetryProperties[keyName].value; value.should.be.above(expectedGzipedSizeAbsoluteError - expectedGzippedSize); value.should.be.below(expectedGzipedSizeAbsoluteError + expectedGzippedSize); telemetryProperties[keyName].value = String(expectedGzippedSize); @@ -314,7 +315,7 @@ module BuildAndRunTelemetryTests { } it("1. android local clean release emulator", (done: MochaDone) => { - var args = ["--local", "--release", "android"]; + var args: string[] = ["--local", "--release", "android"]; var expected: TacoUtility.ICommandTelemetryProperties = { "options.local": { isPii: false, value: "true" }, @@ -335,23 +336,23 @@ module BuildAndRunTelemetryTests { expected["platforms.actuallyBuilt.local1"] = { isPii: false, value: "android" }; } - runCommand(args).then(telemetryProperties => { + runCommand(args).then((telemetryProperties: TacoUtility.ICommandTelemetryProperties) => { telemetryShouldEqual(telemetryProperties, expected); }).done(() => done(), done); }); function mockProjectWithIncrementalBuild(): void { // We write an empty changes file, and a build info file so we'll get an incremental build - var changeTimeFileDirectory = path.join(projectPath, "remote", "ios", "debug"); + var changeTimeFileDirectory: string = path.join(projectPath, "remote", "ios", "debug"); utils.createDirectoryIfNecessary(changeTimeFileDirectory); - var changeTimeFile = path.join(changeTimeFileDirectory, "lastChangeTime.json"); - var buildInfoFile = path.join(changeTimeFileDirectory, "buildInfo.json"); + var changeTimeFile: string = path.join(changeTimeFileDirectory, "lastChangeTime.json"); + var buildInfoFile: string = path.join(changeTimeFileDirectory, "buildInfo.json"); fs.writeFileSync(changeTimeFile, "{}"); fs.writeFileSync(buildInfoFile, "{\"buildNumber\": " + buildNumber + "}"); } it("2. ios remote debug target non_secure_server incremental", (done: MochaDone) => { - var args = ["--remote", "--debug", "--target=ipad 2", "ios"]; + var args: string[] = ["--remote", "--debug", "--target=ipad 2", "ios"]; var expected: TacoUtility.ICommandTelemetryProperties = { "options.remote": { isPii: false, value: "true" }, @@ -374,13 +375,13 @@ module BuildAndRunTelemetryTests { testIosHttpServer.removeAllListeners("request"); testAndroidHttpServer.removeAllListeners("request"); }) - .then(telemetryProperties => { + .then((telemetryProperties: TacoUtility.ICommandTelemetryProperties) => { telemetryShouldEqual(telemetryProperties, expected, 28382); }).done(() => done(), done); }); it("3. android ios unsecure_server not_incremental", (done: MochaDone) => { - var args = ["android", "ios"]; + var args: string[] = ["android", "ios"]; var expected: TacoUtility.ICommandTelemetryProperties = { "platforms.actuallyBuilt.remote1": { isPii: false, value: "android" }, "platforms.actuallyBuilt.remote2": { isPii: false, value: "ios" }, @@ -405,7 +406,7 @@ module BuildAndRunTelemetryTests { testIosHttpServer.removeAllListeners("request"); testAndroidHttpServer.removeAllListeners("request"); }) - .then(telemetryProperties => telemetryShouldEqual(telemetryProperties, expected, 28379, 28379)) + .then((telemetryProperties: TacoUtility.ICommandTelemetryProperties) => telemetryShouldEqual(telemetryProperties, expected, 28379, 28379)) .done(() => done(), done); }); @@ -427,12 +428,12 @@ module BuildAndRunTelemetryTests { } runCommand(args) - .then(telemetryProperties => telemetryShouldEqual(telemetryProperties, expected)) + .then((telemetryProperties: TacoUtility.ICommandTelemetryProperties) => telemetryShouldEqual(telemetryProperties, expected)) .then(() => done(), done); }); it("5. --uknown_option unknown_platform", (done: MochaDone) => { - var args = ["--uknown_option=unknown_value", "unknown_platform"]; + var args: string[] = ["--uknown_option=unknown_value", "unknown_platform"]; var expected: TacoUtility.ICommandTelemetryProperties = { "platforms.requestedViaCommandLine.local1": { isPii: true, value: "unknown_platform" }, "platforms.actuallyBuilt.local1": { isPii: true, value: "unknown_platform" }, @@ -441,7 +442,7 @@ module BuildAndRunTelemetryTests { "unknownOption1.value": { isPii: true, value: "unknown_value" } }; - runCommand(args).then(telemetryProperties => { + runCommand(args).then((telemetryProperties: TacoUtility.ICommandTelemetryProperties) => { telemetryShouldEqual(telemetryProperties, expected); }).done(() => done(), done); }); @@ -449,7 +450,7 @@ module BuildAndRunTelemetryTests { if ((command !== Command.Build)) { it("6. nobuild debuginfo", (done: MochaDone) => { utils.createDirectoryIfNecessary(path.join(projectPath, "platforms", "android")); - var args = ["--nobuild", "--debuginfo", "android"]; + var args: string[] = ["--nobuild", "--debuginfo", "android"]; var expected: TacoUtility.ICommandTelemetryProperties = { "options.nobuild": { isPii: false, value: "true" }, "options.debuginfo": { isPii: false, value: "true" }, @@ -459,7 +460,7 @@ module BuildAndRunTelemetryTests { }; runCommand(args) - .then(telemetryProperties => telemetryShouldEqual(telemetryProperties, expected)) + .then((telemetryProperties: TacoUtility.ICommandTelemetryProperties) => telemetryShouldEqual(telemetryProperties, expected)) .then(() => done(), done); }); } diff --git a/src/taco-cli/test/checkForNewerVersion.ts b/src/taco-cli/test/checkForNewerVersion.ts index b1ac821b..72a4d4a9 100644 --- a/src/taco-cli/test/checkForNewerVersion.ts +++ b/src/taco-cli/test/checkForNewerVersion.ts @@ -40,12 +40,13 @@ enum MessageExpectation { } describe("Check for newer version", function (): void { - var tacoHome = path.join(os.tmpdir(), "taco-cli", "check-for-new-version"); + var tacoHome: string = path.join(os.tmpdir(), "taco-cli", "check-for-new-version"); // Use a dummy home location so we don't trash any real configurations process.env["TACO_HOME"] = tacoHome; - - var stdoutWrite = process.stdout.write; // We save the original implementation, so we can restore it later + // because of function overloading assigning "(buffer: string, cb?: Function) => boolean" as the type for + // stdoutWrite just doesn't work + var stdoutWrite: any = process.stdout.write; // We save the original implementation, so we can restore it later var memoryStdout: ms.MemoryStream; var expectedRequestAndResponse: { expectedUrl: string; statusCode: number; head: any; response: any; waitForPayload?: boolean, responseDelay?: number }; @@ -54,10 +55,10 @@ describe("Check for newer version", function (): void { this.timeout(15000); var tacoCliLatestInformation: any; - var fakeServer = "http://localhost:8080"; - var repositoryPath = "/taco-cli/latest"; - var repositoryInFakeServerPath = fakeServer + repositoryPath; - var packageFilePath = path.join(utils.tacoHome, "package.json"); + var fakeServer: string = "http://localhost:8080"; + var repositoryPath: string = "/taco-cli/latest"; + var repositoryInFakeServerPath: string = fakeServer + repositoryPath; + var packageFilePath: string = path.join(utils.tacoHome, "package.json"); before(() => { // Set up mocked out resources @@ -173,20 +174,20 @@ describe("Check for newer version", function (): void { }); function simulateBeforeExit(): void { - var listeners = process.listeners("beforeExit"); + var listeners: Function[] = process.listeners("beforeExit"); listeners.length.should.eql(1, "There should be only a single listener for the beforeExit event"); process.removeListener("beforeExit", listeners[0]); listeners[0](); } function launchFakeNPMServer(done: MochaDone): Q.Promise { - var serverIsListening = Q.defer(); + var serverIsListening: Q.Deferred = Q.defer(); // Port for the web server - const PORT = 8080; + const PORT: number = 8080; // Create the server - var server = http.createServer(ServerMock.generateServerFunction(done, [expectedRequestAndResponse])); + var server: http.Server = http.createServer(ServerMock.generateServerFunction(done, [expectedRequestAndResponse])); server.listen(PORT); // If there is any error, we reject the promise @@ -203,16 +204,16 @@ describe("Check for newer version", function (): void { } function testCheckForNewerVersion(messageExpectation: MessageExpectation, done: MochaDone): void { - var timeBeforeTest = Date.now(); + var timeBeforeTest: number = Date.now(); var fakeNPMServer: http.Server; launchFakeNPMServer(done) - .then(server => fakeNPMServer = server) + .then((server: http.Server) => fakeNPMServer = server) .then(() => new CheckForNewerVersion(repositoryInFakeServerPath, packageFilePath) .showOnExit() - .fail(error => TacoUtility.UtilHelper.emptyMethod(error))) + .fail((error: Error) => TacoUtility.UtilHelper.emptyMethod(error))) .then(() => { // CheckForNewerVersion doesn't print anything synchronically. It prints it on the beforeExit event - var actual = memoryStdout.contentsAsText(); + var actual: string = memoryStdout.contentsAsText(); should(actual).be.empty; if (messageExpectation === MessageExpectation.WillBeShown) { @@ -220,8 +221,8 @@ describe("Check for newer version", function (): void { actual = memoryStdout.contentsAsText(); actual.should.be.equal("NewerTacoCLIVersionAvailable\n", "The output of the console should match what we expected"); - return Settings.loadSettings().then(settings => { - var lastCheck = new Date(settings.lastCheckForNewerVersionTimestamp).getTime(); + return Settings.loadSettings().then((settings: Settings.ISettings) => { + var lastCheck: number = new Date(settings.lastCheckForNewerVersionTimestamp).getTime(); lastCheck.should.be.greaterThan(timeBeforeTest, "The last check for newer version timestamp: " + lastCheck + " should be updated after each attempt to check for a newer version and thus be greater than " + timeBeforeTest); done(); @@ -238,10 +239,10 @@ describe("Check for newer version", function (): void { } function setCheckedTimestampToHoursAgo(howManyHoursAgo: number): Q.Promise { - var someHoursAgo = new Date(); + var someHoursAgo: Date = new Date(); someHoursAgo.setHours(someHoursAgo.getHours() - howManyHoursAgo); - var lastCheckForNewerVersionTimestamp = someHoursAgo.getTime(); - return Settings.updateSettings(settings => settings.lastCheckForNewerVersionTimestamp = lastCheckForNewerVersionTimestamp).then(() => lastCheckForNewerVersionTimestamp); + var lastCheckForNewerVersionTimestamp: number = someHoursAgo.getTime(); + return Settings.updateSettings((settings: Settings.ISettings) => settings.lastCheckForNewerVersionTimestamp = lastCheckForNewerVersionTimestamp).then(() => lastCheckForNewerVersionTimestamp); } function setLatestReleasedVersion(version: string): void { @@ -249,25 +250,25 @@ describe("Check for newer version", function (): void { expectedRequestAndResponse.response = JSON.stringify(tacoCliLatestInformation); } - it("shows message when there is an update available and it's the first time we've ever checked", done => { + it("shows message when there is an update available and it's the first time we've ever checked", (done: MochaDone) => { this.timeout(10000); testCheckForNewerVersion(MessageExpectation.WillBeShown, done); }); - it("doesn't run the check if we've checked 3 hours ago", done => { + it("doesn't run the check if we've checked 3 hours ago", (done: MochaDone) => { this.timeout(10000); var lastCheckForNewerVersionTimestamp: number; setCheckedTimestampToHoursAgo(3) - .then(storedNumber => lastCheckForNewerVersionTimestamp = storedNumber) + .then((storedNumber: number) => lastCheckForNewerVersionTimestamp = storedNumber) .then(() => new CheckForNewerVersion(repositoryInFakeServerPath, packageFilePath).showOnExit().fail(utils.emptyMethod)) .done(() => { - var listeners = process.listeners("beforeExit"); + var listeners: Function[] = process.listeners("beforeExit"); listeners.length.should.eql(0, "There should be no listeners for the beforeExit event"); var actual: string = memoryStdout.contentsAsText(); should(actual).be.empty; - return Settings.loadSettings().then(settings => { + return Settings.loadSettings().then((settings: Settings.ISettings) => { settings.lastCheckForNewerVersionTimestamp.should.be.equal(lastCheckForNewerVersionTimestamp, "The last checked time shouldn't had changed expected: " + lastCheckForNewerVersionTimestamp + " actual: " + settings.lastCheckForNewerVersionTimestamp.should); done(); @@ -275,35 +276,35 @@ describe("Check for newer version", function (): void { }); }); - it("does run the check if we've checked 5 hours ago", done => { + it("does run the check if we've checked 5 hours ago", (done: MochaDone) => { this.timeout(10000); setCheckedTimestampToHoursAgo(5) .done(() => testCheckForNewerVersion(MessageExpectation.WillBeShown, done)); }); - it("doesn't show a message when there is not an update available", done => { + it("doesn't show a message when there is not an update available", (done: MochaDone) => { this.timeout(10000); setLatestReleasedVersion("1.0.0"); testCheckForNewerVersion(MessageExpectation.WontBeShown, done); }); - it("doesn't show any errors if the http request times out", done => { + it("doesn't show any errors if the http request times out", (done: MochaDone) => { this.timeout(15000); expectedRequestAndResponse.responseDelay = 10 * 1000; // 10 seconds testCheckForNewerVersion(MessageExpectation.WontBeShown, done); }); - it("doesn't show any errors if the http request fails with 4xx", done => { + it("doesn't show any errors if the http request fails with 4xx", (done: MochaDone) => { this.timeout(10000); expectedRequestAndResponse.statusCode = 401; testCheckForNewerVersion(MessageExpectation.WontBeShown, done); }); - it("doesn't show any errors if the http request fails", done => { + it("doesn't show any errors if the http request fails", (done: MochaDone) => { this.timeout(10000); expectedRequestAndResponse.statusCode = 500; @@ -311,7 +312,7 @@ describe("Check for newer version", function (): void { testCheckForNewerVersion(MessageExpectation.WontBeShown, done); }); - it("works if the settings file is empty", done => { + it("works if the settings file is empty", (done: MochaDone) => { this.timeout(10000); // Create an empty settings file diff --git a/src/taco-cli/test/cordovaWrapper.ts b/src/taco-cli/test/cordovaWrapper.ts index 567d8f08..6bcdfb1b 100755 --- a/src/taco-cli/test/cordovaWrapper.ts +++ b/src/taco-cli/test/cordovaWrapper.ts @@ -26,7 +26,7 @@ describe("cordovaWrapper", () => { var functionsCalled: { [index: string]: boolean } = {}; before((): void => { // Set up tests with mocked out Cordova implementation - var cordova = mockCordova.MockCordova510.default; + var cordova: mockCordova.MockCordova510 = mockCordova.MockCordova510.default; cordova.raw.build = (): Q.Promise => { functionsCalled["build"] = true; throw new Error("Build Error thrown synchronously"); @@ -41,7 +41,7 @@ describe("cordovaWrapper", () => { }; cordova.raw.emulate = (): Q.Promise => { functionsCalled["emulate"] = true; - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); setTimeout(() => { throw new Error("Emulate Error thrown asynchronously"); }, 1); @@ -49,7 +49,7 @@ describe("cordovaWrapper", () => { }; TacoPackageLoader.mockForTests = { - lazyRequire: (packageName: string, packageId: string, logLevel?: TacoUtility.InstallLogLevel) => { + lazyRequire: (packageName: string, packageId: string, logLevel?: TacoUtility.InstallLogLevel): any => { if (packageName !== "cordova") { return Q.reject(new Error("Expected to load cordova package")); } diff --git a/src/taco-cli/test/create.ts b/src/taco-cli/test/create.ts index 6b8e7bfd..2a27e8da 100644 --- a/src/taco-cli/test/create.ts +++ b/src/taco-cli/test/create.ts @@ -18,12 +18,12 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ /* tslint:disable:no-var-requires */ // Special case to allow using color package with index signature for style rules -var colors = require("colors/safe"); +var colors: any = require("colors/safe"); /* tslint:enable:no-var-requires */ import fs = require ("fs"); @@ -170,7 +170,7 @@ describe("taco create", function (): void { } function runScenarioWithExpectedFileCount(scenario: number, expectedFileCount: number, tacoJsonFileContents?: IKeyValuePair): Q.Promise { - var create = new Create(); + var create: Create = new Create(); return create.run(makeICommandData(scenario, successScenarios)) .then(function (): void { @@ -195,7 +195,7 @@ describe("taco create", function (): void { } function runFailureScenario(scenario: number, expectedErrorCode?: T): Q.Promise { - var create = new Create(); + var create: Create = new Create(); return create.run(makeICommandData(scenario, failureScenarios)) .then(function (): Q.Promise { @@ -306,7 +306,7 @@ describe("taco create", function (): void { // copy-from custom assets: 2 files and 1 folder // Kit 5.1.1-Kit: Cordova adds 2 files and 4 folders - var totalEntries = 9 + tacoFileCount; + var totalEntries: number = 9 + tacoFileCount; runScenarioWithExpectedFileCount(scenario, totalEntries, expectedKitTacoJsonKeyValues["5.1.1-Kit"]).then(done, done); }); @@ -316,7 +316,7 @@ describe("taco create", function (): void { // CLI 4.2.0 + default Cordova project // TACO: adds 1 file - var totalEntries = cordovaDefaultProjectFileCount + tacoFileCount; + var totalEntries: number = cordovaDefaultProjectFileCount + tacoFileCount; runScenarioWithExpectedFileCount(scenario, totalEntries, expectedCliTacoJsonKeyValues["4.3.0"]).then(done, done); }); @@ -440,7 +440,9 @@ describe("taco create", function (): void { }); describe("Onboarding experience", () => { - var stdoutWrite = process.stdout.write; // We save the original implementation, so we can restore it later + // because of function overloading assigning "(buffer: string, cb?: Function) => boolean" as the type for + // stdoutWrite just doesn't work + var stdoutWrite: any = process.stdout.write; // We save the original implementation, so we can restore it later var memoryStdout: ms.MemoryStream; beforeEach(() => { @@ -453,8 +455,8 @@ describe("taco create", function (): void { process.stdout.write = stdoutWrite; }); - var tenSpaces = " "; - var tenMinuses = "----------"; + var tenSpaces: string = " "; + var tenMinuses: string = "----------"; function testCreateForArguments(createCommandLineArguments: string[], expectedMessages: string[], alternativeExpectedMessages: string[], @@ -467,11 +469,11 @@ describe("taco create", function (): void { original: createCommandLineArguments, remain: createCommandLineArguments.slice() }; - var create = new Create(); + var create: Create = new Create(); create.run(commandData).done(() => { - var expected = expectedMessages.join("\n"); + var expected : string = expectedMessages.join("\n"); - var actual = colors.strip(memoryStdout.contentsAsText()); // We don't want to compare the colors + var actual: string = colors.strip(memoryStdout.contentsAsText()); // We don't want to compare the colors actual = actual.replace(/ {10,}/g, tenSpaces); // We don't want to count spaces when we have a lot of them, so we replace it with 10 actual = actual.replace(/-{10,}/g, tenMinuses); // We don't want to count -----s when we have a lot of them, so we replace it with 10 (They also depend dynamically on the path length) actual = actual.replace(/ +$/gm, ""); // We also don't want trailing spaces @@ -490,7 +492,7 @@ describe("taco create", function (): void { }); } - var downloadingDependenciesOutput = ["", + var downloadingDependenciesOutput: string[] = ["", "PackageLoaderDownloadingMessage", "", "PackageLoaderDownloadCompletedMessage"]; @@ -498,9 +500,9 @@ describe("taco create", function (): void { it("prints the onboarding experience when using a kit", function (done: MochaDone): void { this.timeout(60000); // installing the node packages during create can take a long time - var projectPath = getProjectPath("onboarding-experience", 1); + var projectPath: string = getProjectPath("onboarding-experience", 1); - var firstPart = [ + var firstPart: string[] = [ "CommandCreateStatusCreatingNewProject", " ----------", " CommandCreateStatusTableNameDescription ..... HelloTaco", @@ -509,7 +511,7 @@ describe("taco create", function (): void { " CommandCreateStatusTableKitVersionDescription ..... 4.3.1-Kit", " ----------"]; - var lastPart = [ + var lastPart: string[] = [ "CommandCreateSuccessProjectTemplate", "OnboardingExperienceTitle", " * HowToUseChangeToProjectFolder", @@ -533,9 +535,9 @@ describe("taco create", function (): void { it("prints the onboarding experience when not using a kit", function (done: MochaDone): void { this.timeout(60000); // installing the node packages during create can take a long time - var projectPath = getProjectPath("onboarding-experience", 2); + var projectPath: string = getProjectPath("onboarding-experience", 2); - var firstPart = [ + var firstPart: string[] = [ "CommandCreateStatusCreatingNewProject", " ----------", " CommandCreateStatusTableNameDescription ..... HelloTaco", @@ -544,7 +546,7 @@ describe("taco create", function (): void { " CommandCreateStatusTableCordovaCLIVersionDescription ..... 5.1.1", " ----------"]; - var lastPart = [ + var lastPart: string[] = [ "CommandCreateSuccessProjectCLI", "OnboardingExperienceTitle", " * HowToUseChangeToProjectFolder", @@ -569,9 +571,9 @@ describe("taco create", function (): void { it("it adds (Deprecated) to a deprecated kit", function (done: MochaDone): void { this.timeout(60000); // installing the node packages during create can take a long time - var projectPath = getProjectPath("onboarding-experience", 3); + var projectPath: string = getProjectPath("onboarding-experience", 3); - var firstPart = [ + var firstPart: string[] = [ "CommandCreateStatusCreatingNewProject", " ----------", " CommandCreateStatusTableNameDescription ..... HelloTaco", @@ -580,7 +582,7 @@ describe("taco create", function (): void { " CommandCreateStatusTableKitVersionDescription ..... 4.3.0-Kit (CommandKitListDeprecatedKit)", " ----------"]; - var lastPart = [ + var lastPart: string[] = [ "CommandCreateWarningDeprecatedKit", "CommandCreateSuccessProjectTemplate", "OnboardingExperienceTitle", @@ -603,10 +605,10 @@ describe("taco create", function (): void { }); it("it adds (Default) to a default kit", function (done: MochaDone): void { - var projectPath = getProjectPath("onboarding-experience", 4); + var projectPath: string = getProjectPath("onboarding-experience", 4); this.timeout(60000); // installing the node packages during create can take a long time - kitHelper.getDefaultKit().done(defaultKitId => { - var firstPart = [ + kitHelper.getDefaultKit().done((defaultKitId: string) => { + var firstPart: string[] = [ "CommandCreateStatusCreatingNewProject", " ----------", " CommandCreateStatusTableNameDescription ..... HelloTaco", @@ -615,7 +617,7 @@ describe("taco create", function (): void { " CommandCreateStatusTableKitVersionDescription ..... " + defaultKitId + " (CommandKitListDefaultKit)", " ----------"]; - var lastPart = [ + var lastPart: string[] = [ "CommandCreateSuccessProjectTemplate", "OnboardingExperienceTitle", " * HowToUseChangeToProjectFolder", @@ -639,10 +641,10 @@ describe("taco create", function (): void { }); describe("Telemetry properties", () => { - var cliVersion = require("../package.json").version; + var cliVersion: string = require("../package.json").version; function createProjectAndVerifyTelemetryProps(args: string[], expectedProperties: TacoUtility.ICommandTelemetryProperties, done: MochaDone): void { - var create = new Create(); + var create: Create = new Create(); var commandData: tacoUtils.Commands.ICommandData = { options: {}, original: args, @@ -659,7 +661,7 @@ describe("taco create", function (): void { it("Returns the expected telemetry properties for a kit project created with the Blank template", function (done: MochaDone): void { this.timeout(60000); // installing the node packages during create can take a long time - var projectPath = getProjectPath("Telemetry properties for Create command", 1); + var projectPath: string = getProjectPath("Telemetry properties for Create command", 1); var expected: TacoUtility.ICommandTelemetryProperties = { cliVersion: { isPii: false, value: cliVersion }, @@ -673,7 +675,7 @@ describe("taco create", function (): void { it("Returns the expected telemetry properties for a kit project created with TypeScript template", function (done: MochaDone): void { this.timeout(60000); // installing the node packages during create can take a long time - var projectPath = getProjectPath("Telemetry properties for Create command", 2); + var projectPath: string = getProjectPath("Telemetry properties for Create command", 2); var expected: TacoUtility.ICommandTelemetryProperties = { cliVersion: { isPii: false, value: cliVersion }, @@ -689,7 +691,7 @@ describe("taco create", function (): void { it("Returns the expected telemetry properties for a CLI project", function (done: MochaDone): void { this.timeout(60000); // installing the node packages during create can take a long time - var projectPath = getProjectPath("Telemetry properties for Create command", 3); + var projectPath: string = getProjectPath("Telemetry properties for Create command", 3); var expected: TacoUtility.ICommandTelemetryProperties = { cliVersion: { isPii: false, value: cliVersion }, diff --git a/src/taco-cli/test/emulate.ts b/src/taco-cli/test/emulate.ts index 2ec561a5..2817d065 100644 --- a/src/taco-cli/test/emulate.ts +++ b/src/taco-cli/test/emulate.ts @@ -15,7 +15,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import del = require ("del"); @@ -40,20 +40,20 @@ import BuildInfo = TacoUtility.BuildInfo; import Command = buildAndRunTelemetry.Command; import utils = TacoUtility.UtilHelper; -var create = new createMod(); +var create: createMod = new createMod(); describe("taco emulate", function (): void { var testHttpServer: http.Server; - var tacoHome = path.join(os.tmpdir(), "taco-cli", "emulate"); + var tacoHome: string = path.join(os.tmpdir(), "taco-cli", "emulate"); var originalCwd: string; - var vcordova = "4.0.0"; + var vcordova: string = "4.0.0"; function createCleanProject(): Q.Promise { // Create a dummy test project with no platforms added utils.createDirectoryIfNecessary(tacoHome); process.chdir(tacoHome); return Q.denodeify(del)("example").then(function (): Q.Promise { - var args = ["example", "--cordova", vcordova]; + var args: string[] = ["example", "--cordova", vcordova]; return create.run({ options: {}, original: args, @@ -75,7 +75,7 @@ describe("taco emulate", function (): void { kitHelper.kitPackagePromise = null; // Create a mocked out remote server so we can specify how it reacts testHttpServer = http.createServer(); - var port = 3000; + var port: number = 3000; testHttpServer.listen(port); // Configure a dummy platform "test" to use the mocked out remote server in insecure mode RemoteMock.saveConfig("test", { host: "localhost", port: 3000, secure: false, mountPoint: "cordova" }).done(function (): void { @@ -107,8 +107,8 @@ describe("taco emulate", function (): void { del("example", mocha); }); - var emulateRun = function (args: string[]): Q.Promise { - var emulate = new emulateMod(); + var emulateRun: (args: string[]) => Q.Promise = function (args: string[]): Q.Promise { + var emulate: emulateMod = new emulateMod(); return emulate.run({ options: {}, original: args, diff --git a/src/taco-cli/test/help.ts b/src/taco-cli/test/help.ts index 9e5b2cfd..033e0a57 100644 --- a/src/taco-cli/test/help.ts +++ b/src/taco-cli/test/help.ts @@ -15,12 +15,12 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ /* tslint:disable:no-var-requires */ // Special case to allow using color package with index signature for style rules -var colors = require("colors/safe"); +var colors: any = require("colors/safe"); /* tslint:enable:no-var-requires */ import tacoUtils = require ("taco-utils"); @@ -30,8 +30,10 @@ import ms = require ("./utils/memoryStream"); import commands = tacoUtils.Commands.ICommandData; describe("help for a command", function (): void { - var help = new Help(); - var stdoutWrite = process.stdout.write; // We save the original implementation, so we can restore it later + var help: Help = new Help(); + // because of function overloading assigning "(buffer: string, cb?: Function) => boolean" as the type for + // stdoutWrite just doesn't work + var stdoutWrite: any = process.stdout.write; // We save the original implementation, so we can restore it later var memoryStdout: ms.MemoryStream; var previous: boolean; @@ -47,8 +49,8 @@ describe("help for a command", function (): void { function testHelpForCommand(command: string, expectedLines: string[], done: MochaDone): void { helpRun(command).done(() => { - var expected = expectedLines.join("\n"); - var actual = colors.strip(memoryStdout.contentsAsText()); // The colors add extra characters + var expected: string = expectedLines.join("\n"); + var actual: string = colors.strip(memoryStdout.contentsAsText()); // The colors add extra characters actual = actual.replace(/ (\.+) ?\n +/gm, " $1 "); // We undo the word-wrapping actual = actual.replace(/ +$/gm, ""); // Remove useless spaces at the end of a line actual.should.be.equal(expected); diff --git a/src/taco-cli/test/kit.ts b/src/taco-cli/test/kit.ts index f7e68d25..59b20696 100644 --- a/src/taco-cli/test/kit.ts +++ b/src/taco-cli/test/kit.ts @@ -16,7 +16,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import del = require ("del"); @@ -46,7 +46,7 @@ describe("Kit", function (): void { this.timeout(20000); function kitRun(args: string[] = []): Q.Promise { - var kit = new kitMod(); + var kit: kitMod = new kitMod(); var data: commands = { options: {}, original: args, @@ -65,7 +65,7 @@ describe("Kit", function (): void { var originalCwd: string; function createProject(args: string[], projectDir: string): Q.Promise { - var create = new createMod(); + var create: createMod = new createMod(); // Create a dummy test project with no platforms added utils.createDirectoryIfNecessary(tacoHome); process.chdir(tacoHome); @@ -128,7 +128,7 @@ describe("Kit", function (): void { it("'taco kit' should not throw any error", function (done: MochaDone): void { kitRun() .done((telemetryParameters: TacoUtility.ICommandTelemetryProperties) => { - var expected = { subCommand: { isPii: false, value: "list" } }; + var expected: any = { subCommand: { isPii: false, value: "list" } }; telemetryParameters.should.be.eql(expected); done(); }, function (err: tacoUtils.TacoError): void { @@ -139,7 +139,7 @@ describe("Kit", function (): void { it("'taco kit list' should not throw any error", function (done: MochaDone): void { kitRun(["list"]) .done((telemetryParameters: TacoUtility.ICommandTelemetryProperties) => { - var expected = { subCommand: { isPii: false, value: "list" } }; + var expected: any = { subCommand: { isPii: false, value: "list" } }; telemetryParameters.should.be.eql(expected); done(); }, function (err: tacoUtils.TacoError): void { @@ -150,7 +150,7 @@ describe("Kit", function (): void { it("'taco kit list --kit {kit-ID}' should not throw any error", function (done: MochaDone): void { kitRun(["list", "--kit", "5.1.1-Kit"]) .done((telemetryParameters: TacoUtility.ICommandTelemetryProperties) => { - var expected = { + var expected: any = { subCommand: { isPii: false, value: "list" }, "options.kit": { isPii: false, value: "5.1.1-Kit" } }; @@ -165,7 +165,7 @@ describe("Kit", function (): void { kitRun(["list", "--json", tempJson]) .done((telemetryParameters: TacoUtility.ICommandTelemetryProperties) => { fs.existsSync(tempJson).should.be.true; - var expected = { + var expected: any = { subCommand: { isPii: false, value: "list" }, "options.json": { isPii: true, value: tempJson } }; @@ -202,7 +202,7 @@ describe("Kit", function (): void { it("'taco kit select --cordova {CLI-VERSION}' should execute with no errors", function (done: MochaDone): void { runKitCommandAndVerifyTacoJsonContents(["select", "--cordova", "5.1.1"], tacoJsonPath, expectedCliTacoJsonKeyValues) .then((telemetryParameters: TacoUtility.ICommandTelemetryProperties) => { - var expected = { + var expected: any = { subCommand: { isPii: false, value: "select" }, "options.cordova": { isPii: false, value: "5.1.1" } }; @@ -238,7 +238,7 @@ describe("Kit", function (): void { it("'taco kit select --kit {kit-ID}' should execute with no errors", function (done: MochaDone): void { runKitCommandAndVerifyTacoJsonContents(["select", "--kit", "5.1.1-Kit"], tacoJsonPath, expectedKitTacoJsonKeyValues) .then((telemetryParameters: TacoUtility.ICommandTelemetryProperties) => { - var expected = { + var expected: any = { subCommand: { isPii: false, value: "select" }, "options.kit": { isPii: false, value: "5.1.1-Kit" } }; diff --git a/src/taco-cli/test/meta.ts b/src/taco-cli/test/meta.ts index 691f2d23..994bf8d7 100644 --- a/src/taco-cli/test/meta.ts +++ b/src/taco-cli/test/meta.ts @@ -45,10 +45,10 @@ interface ICommandInfo { describe("taco meta command tests: ", function (): void { // Command list - var commandsJsonPath = path.resolve(__dirname, "..", "cli", "commands.json"); + var commandsJsonPath: string = path.resolve(__dirname, "..", "cli", "commands.json"); fs.existsSync(commandsJsonPath).should.be.true; - var commands = require(commandsJsonPath); + var commands: any = require(commandsJsonPath); should(commands).not.be.empty; // Options we are interested in testing @@ -56,7 +56,7 @@ describe("taco meta command tests: ", function (): void { var tacoInvalidArgs: string[][] = [["/?"], ["?"]]; function runHelp(command: string): Q.Promise { - var help = new Help(); + var help: Help = new Help(); // Construct CommandData and pass it as argument var original: string[] = []; @@ -75,7 +75,7 @@ describe("taco meta command tests: ", function (): void { }; function runVersion(): Q.Promise { - var version = new Version(); + var version: Version = new Version(); var commandData: tacoUtils.Commands.ICommandData = { options: {}, diff --git a/src/taco-cli/test/platformPlugin.ts b/src/taco-cli/test/platformPlugin.ts index 3532ac0e..d72e9c7d 100644 --- a/src/taco-cli/test/platformPlugin.ts +++ b/src/taco-cli/test/platformPlugin.ts @@ -15,7 +15,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import child_process = require ("child_process"); @@ -40,15 +40,15 @@ import ms = require ("./utils/memoryStream"); import utils = TacoUtility.UtilHelper; -var platformCommand = new Platform(); -var pluginCommand = new Plugin(); -var createCommand = new Create(); +var platformCommand: Platform = new Platform(); +var pluginCommand: Plugin = new Plugin(); +var createCommand: Create = new Create(); var testKitId: string = "5.1.1-Kit"; /* tslint:disable:no-var-requires */ // var require needed to require package json -var cliVersion = require("../package.json").version; +var cliVersion: string = require("../package.json").version; /* tslint:enable:no-var-requires */ interface IComponentVersionMap { @@ -244,7 +244,7 @@ var cliPluginOperations: ICommandAndResult[] = [ ]; describe("taco platform for kit", function(): void { - var tacoHome = path.join(os.tmpdir(), "taco-cli", "platformPlugin"); + var tacoHome: string = path.join(os.tmpdir(), "taco-cli", "platformPlugin"); var cliProjectDir: string = "cliProject"; var kitProjectDir: string = "kitProject"; var originalCwd: string; @@ -292,7 +292,7 @@ describe("taco platform for kit", function(): void { } function getInstalledPlatforms(platformsExpected: IComponentVersionMap, projectPath: string): string[] { - var platformsDir = path.join(projectPath, "platforms"); + var platformsDir: string = path.join(projectPath, "platforms"); if (!fs.existsSync(platformsDir)) { return []; } @@ -304,8 +304,8 @@ describe("taco platform for kit", function(): void { function checkPlatformVersions(platformsExpected: IComponentVersionMap, projectPath: string): Q.Promise { var platformsInstalled: string[] = getInstalledPlatforms(platformsExpected, projectPath); - var onWindows = process.platform === "win32"; - var deferred = Q.defer(); + var onWindows: boolean = process.platform === "win32"; + var deferred: Q.Deferred = Q.defer(); return Q.all(platformsInstalled.map(function(platform: string): Q.Promise { var cmdName: string = "version"; if (onWindows) { @@ -313,7 +313,7 @@ describe("taco platform for kit", function(): void { } var cmdPath: string = path.join(projectPath, "platforms", platform, "cordova", cmdName); - var versionProc = child_process.spawn(cmdPath); + var versionProc: child_process.ChildProcess = child_process.spawn(cmdPath); versionProc.stdout.on("data", function(data: any): void { var version: string = data.toString(); if (!path) { @@ -334,8 +334,8 @@ describe("taco platform for kit", function(): void { } function getInstalledPluginVersion(plugin: string, projectPath: string): string { - var pluginPackgeJson = path.join(projectPath, "plugins", plugin, "package.json"); - var pluginInfo = require(pluginPackgeJson); + var pluginPackgeJson: string = path.join(projectPath, "plugins", plugin, "package.json"); + var pluginInfo: any = require(pluginPackgeJson); if (pluginInfo) { return pluginInfo["version"]; } @@ -344,7 +344,7 @@ describe("taco platform for kit", function(): void { } function checkPluginVersions(pluginsExpected: IComponentVersionMap, projectPath: string): void { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); Object.keys(pluginsExpected).forEach(function(plugin: string): void { var versionInstalled: string = getInstalledPluginVersion(plugin, projectPath); versionInstalled.trim().should.be.equal(pluginsExpected[plugin]); @@ -352,7 +352,7 @@ describe("taco platform for kit", function(): void { } function sleep(milliseconds: number): Q.Promise { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); setTimeout(deferred.resolve, milliseconds); return deferred.promise; }; @@ -497,7 +497,9 @@ describe("taco platform for kit", function(): void { }); describe("Onboarding experience", () => { - var stdoutWrite = process.stdout.write; // We save the original implementation, so we can restore it later + // because of function overloading assigning "(buffer: string, cb?: Function) => boolean" as the type for + // stdoutWrite just doesn't work + var stdoutWrite: any = process.stdout.write; // We save the original implementation, so we can restore it later var memoryStdout: ms.MemoryStream; beforeEach(function(done: MochaDone): void { @@ -526,7 +528,7 @@ describe("taco platform for kit", function(): void { // all those messages don't get printed, but if we only run the onboarding tests, they are the first // tests to run, so they do get printed. We accept both options and we validate we got one of them commandRun(platformCommandLineArguments).done(() => { - var actual = memoryStdout.contentsAsText(); + var actual: string = memoryStdout.contentsAsText(); if (scenarioArguments.every((msg: string) => actual.indexOf(msg) >= 0) || alternativeScenarioArguments.every((msg: string) => actual.indexOf(msg) >= 0)) { done(); @@ -541,8 +543,8 @@ describe("taco platform for kit", function(): void { it("prints the onboarding experience when adding a platform", function(done: MochaDone): void { this.timeout(10000); // Instaling the android platform can take several seconds. Setting the timeout on the test-suit is not working - var firstPart = ["CommandPlatformStatusAdding"]; - var lastPart = [ + var firstPart: string[] = ["CommandPlatformStatusAdding"]; + var lastPart: string[] = [ "CommandPlatformStatusAdded", "OnboardingExperienceTitle", " * HowToUseCommandInstallReqsPlugin", @@ -564,10 +566,10 @@ describe("taco platform for kit", function(): void { it("prints the onboarding experience when adding a plugin", function(done: MochaDone): void { this.timeout(10000); // Instaling the android platform can take several seconds. Setting the timeout on the test-suit is not working - var firstPart = [ + var firstPart: string[] = [ "CommandPluginTestedPlatforms", "CommandPluginStatusAdding"]; - var lastPart = [ + var lastPart: string[] = [ "CommandPluginWithIdStatusAdded", "OnboardingExperienceTitle", " * HowToUseCommandInstallReqsPlugin", diff --git a/src/taco-cli/test/remote.ts b/src/taco-cli/test/remote.ts index 5cb3d947..a361c74b 100755 --- a/src/taco-cli/test/remote.ts +++ b/src/taco-cli/test/remote.ts @@ -13,7 +13,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import fs = require ("fs"); @@ -36,11 +36,11 @@ import ms = require ("./utils/memoryStream"); import utils = TacoUtility.UtilHelper; -var remote = new RemoteMod(); +var remote: RemoteMod = new RemoteMod(); describe("taco remote", function(): void { - var testHome = path.join(os.tmpdir(), "taco-cli", "setup"); - var tacoSettingsFile = path.join(testHome, "TacoSettings.json"); + var testHome: string = path.join(os.tmpdir(), "taco-cli", "setup"); + var tacoSettingsFile: string = path.join(testHome, "TacoSettings.json"); before(function(): void { utils.createDirectoryIfNecessary(testHome); process.env["TACO_HOME"] = testHome; @@ -73,20 +73,20 @@ describe("taco remote", function(): void { remote.canHandleArgs(makeICommandData([])).should.be.true; }); - var remoteRun = function(args: string[]): Q.Promise { + var remoteRun: (args: string[]) => Q.Promise = function(args: string[]): Q.Promise { return remote.run(makeICommandData(args)); }; it("should save in the expected format", function(mocha: MochaDone): void { - var questionsAsked = 0; - var sessionClosed = false; - var desiredState = { + var questionsAsked: number = 0; + var sessionClosed: boolean = false; + var desiredState: any = { host: "localhost", port: 3000, pin: "", mountPoint: "testMountPoint" }; - var expectedSequence = [ + var expectedSequence: any = [ { expectedUrl: "/modules/taco-remote", head: { @@ -96,10 +96,10 @@ describe("taco remote", function(): void { response: desiredState.mountPoint } ]; - var mockServer = http.createServer(); - var serverFunction = ServerMock.generateServerFunction(mocha, expectedSequence); + var mockServer: http.Server = http.createServer(); + var serverFunction: (request: http.ServerRequest, response: http.ServerResponse) => void = ServerMock.generateServerFunction(mocha, expectedSequence); - var cliVersion = require("../package.json").version; + var cliVersion: string = require("../package.json").version; var expectedTelemetryProperties: TacoUtility.ICommandTelemetryProperties = { subCommand: { isPii: false, value: "add" }, platform: { isPii: false, value: "ios" }, @@ -154,14 +154,14 @@ describe("taco remote", function(): void { it("should be able to configure secure connections", function(mocha: MochaDone): void { this.timeout(20000); - var mockServer = ServerMock.createSecureTestServer(); - var desiredState = { + var mockServer: https.Server = ServerMock.createSecureTestServer(); + var desiredState: any = { host: "localhost", port: 3000, pin: "123456", mountPoint: "cordova" }; - var expectedSequence = [ + var expectedSequence: any = [ { expectedUrl: "/certs/" + desiredState.pin, head: { @@ -187,7 +187,8 @@ describe("taco remote", function(): void { response: "success" } ]; - var serverFunction = ServerMock.generateServerFunction(mocha, expectedSequence); + + var serverFunction: (request: http.ServerRequest, response: http.ServerResponse) => void = ServerMock.generateServerFunction(mocha, expectedSequence); mockServer.listen(desiredState.port); mockServer.on("request", serverFunction); @@ -211,7 +212,7 @@ describe("taco remote", function(): void { agent: agent }; - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); request.get(options, function(err: any, response: any, body: any): void { if (err) { mocha(err); @@ -229,7 +230,9 @@ describe("taco remote", function(): void { }); describe("Onboarding experience", function(): void { - var stdoutWrite = process.stdout.write; // We save the original implementation, so we can restore it later + // because of function overloading assigning "(buffer: string, cb?: Function) => boolean" as the type for + // stdoutWrite just doesn't work + var stdoutWrite: any = process.stdout.write; // We save the original implementation, so we can restore it later var memoryStdout: ms.MemoryStream; beforeEach(() => { @@ -246,13 +249,13 @@ describe("taco remote", function(): void { // retrieve the contents from the memory stream it("prints the onboarding experience when adding a new remote", function(done: MochaDone): void { this.timeout(5000); - var desiredState = { + var desiredState: any = { host: "localhost", port: 3000, pin: "", mountPoint: "testMountPoint" }; - var expectedSequence = [ + var expectedSequence: any = [ { expectedUrl: "/modules/taco-remote", head: { @@ -263,8 +266,8 @@ describe("taco remote", function(): void { } ]; - var mockServer = http.createServer(); - var serverFunction = ServerMock.generateServerFunction(done, expectedSequence); + var mockServer: http.Server = http.createServer(); + var serverFunction: (request: http.ServerRequest, response: http.ServerResponse) => void = ServerMock.generateServerFunction(done, expectedSequence); mockServer.listen(desiredState.port); mockServer.on("request", serverFunction); @@ -272,7 +275,7 @@ describe("taco remote", function(): void { remoteRun(["add", "ios"]).finally(function(): void { mockServer.close(); }).done(() => { - var messages = ["CommandRemoteHeader", + var messages: string[] = ["CommandRemoteHeader", "CommandRemoteSettingsStored", "OnboardingExperienceTitle", " * HowToUseCommandBuildPlatform", @@ -282,8 +285,8 @@ describe("taco remote", function(): void { "HowToUseCommandHelp", "HowToUseCommandDocs", ""]; // Get the expected console output - var expected = messages.join("\n"); - var actual = memoryStdout.contentsAsText(); + var expected: string = messages.join("\n"); + var actual: string = memoryStdout.contentsAsText(); actual.should.be.equal(expected); done(); }, done); diff --git a/src/taco-cli/test/run.ts b/src/taco-cli/test/run.ts index 81f82765..43a067d7 100755 --- a/src/taco-cli/test/run.ts +++ b/src/taco-cli/test/run.ts @@ -15,7 +15,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import del = require ("del"); @@ -40,21 +40,21 @@ import BuildInfo = TacoUtility.BuildInfo; import Command = buildAndRunTelemetry.Command; import utils = TacoUtility.UtilHelper; -var create = new createMod(); +var create: createMod = new createMod(); describe("taco run", function (): void { this.timeout(20000); // The remote tests sometimes take some time to run var testHttpServer: http.Server; - var tacoHome = path.join(os.tmpdir(), "taco-cli", "run"); + var tacoHome: string = path.join(os.tmpdir(), "taco-cli", "run"); var originalCwd: string; - var vcordova = "4.0.0"; + var vcordova: string = "4.0.0"; function createCleanProject(): Q.Promise { // Create a dummy test project with no platforms added utils.createDirectoryIfNecessary(tacoHome); process.chdir(tacoHome); return Q.denodeify(del)("example").then(function (): Q.Promise { - var args = ["example", "--cordova", vcordova]; + var args: string[] = ["example", "--cordova", vcordova]; return create.run({ options: {}, original: args, @@ -76,7 +76,7 @@ describe("taco run", function (): void { kitHelper.kitPackagePromise = null; // Create a mocked out remote server so we can specify how it reacts testHttpServer = http.createServer(); - var port = 3000; + var port: number = 3000; testHttpServer.listen(port); // Configure a dummy platform "test" to use the mocked out remote server in insecure mode RemoteMock.saveConfig("test", { host: "localhost", port: 3000, secure: false, mountPoint: "cordova" }).done(function (): void { @@ -108,8 +108,8 @@ describe("taco run", function (): void { del("example", mocha); }); - var runRun = function (args: string[]): Q.Promise { - var run = new runMod(); + var runRun: (args: string[]) => Q.Promise = function (args: string[]): Q.Promise { + var run: runMod = new runMod(); return run.run({ options: {}, original: args, @@ -118,22 +118,22 @@ describe("taco run", function (): void { }; it("should make the correct sequence of calls for 'taco run --remote test --device'", function (mocha: MochaDone): void { - var runArguments = ["--remote", "test", "--device", "--nobuild"]; - var configuration = "debug"; - var buildNumber = 12343; + var runArguments: string[] = ["--remote", "test", "--device", "--nobuild"]; + var configuration: string = "debug"; + var buildNumber: number = 12343; - var buildInfo = { + var buildInfo: any = { buildNumber: buildNumber, status: BuildInfo.COMPLETE, buildLang: "en" }; - var buildInfoPath = path.resolve(".", "remote", "test", configuration); + var buildInfoPath: string = path.resolve(".", "remote", "test", configuration); utils.createDirectoryIfNecessary(buildInfoPath); fs.writeFileSync(path.join(buildInfoPath, "buildInfo.json"), JSON.stringify(buildInfo)); // Mock out the server on the other side - var sequence = [ + var sequence: any = [ { expectedUrl: "/cordova/build/" + buildNumber, head: { @@ -170,7 +170,7 @@ describe("taco run", function (): void { waitForPayload: false } ]; - var serverFunction = ServerMock.generateServerFunction(mocha, sequence); + var serverFunction: (request: http.ServerRequest, response: http.ServerResponse) => void = ServerMock.generateServerFunction(mocha, sequence); testHttpServer.on("request", serverFunction); Q(runArguments).then(runRun).finally(function (): void { @@ -183,23 +183,23 @@ describe("taco run", function (): void { }); it("should make the correct sequence of calls for 'taco run --remote test --emulator", function (mocha: MochaDone): void { - var target = "iphone 5"; - var runArguments = ["--remote", "test", "--emulator", "--target", target, "--nobuild"]; - var configuration = "debug"; - var buildNumber = 12344; + var target: string = "iphone 5"; + var runArguments: string[] = ["--remote", "test", "--emulator", "--target", target, "--nobuild"]; + var configuration: string = "debug"; + var buildNumber: number = 12344; - var buildInfo = { + var buildInfo: any = { buildNumber: buildNumber, status: BuildInfo.COMPLETE, buildLang: "en" }; - var buildInfoPath = path.resolve(".", "remote", "test", configuration); + var buildInfoPath: string = path.resolve(".", "remote", "test", configuration); utils.createDirectoryIfNecessary(buildInfoPath); fs.writeFileSync(path.join(buildInfoPath, "buildInfo.json"), JSON.stringify(buildInfo)); // Mock out the server on the other side - var sequence = [ + var sequence: any = [ { expectedUrl: "/cordova/build/" + buildNumber, head: { @@ -225,7 +225,7 @@ describe("taco run", function (): void { } ]; - var serverFunction = ServerMock.generateServerFunction(mocha, sequence); + var serverFunction: (request: http.ServerRequest, response: http.ServerResponse) => void = ServerMock.generateServerFunction(mocha, sequence); testHttpServer.on("request", serverFunction); Q(runArguments).then(runRun).finally(function (): void { diff --git a/src/taco-cli/test/settings.ts b/src/taco-cli/test/settings.ts index 1f2e83a0..573e60e9 100644 --- a/src/taco-cli/test/settings.ts +++ b/src/taco-cli/test/settings.ts @@ -14,7 +14,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import del = require ("del"); @@ -33,10 +33,10 @@ import TacoUtility = require ("taco-utils"); import utils = TacoUtility.UtilHelper; -var create = new createMod(); +var create: createMod = new createMod(); describe("taco settings", function (): void { - var tacoHome = path.join(os.tmpdir(), "taco-cli", "settings"); + var tacoHome: string = path.join(os.tmpdir(), "taco-cli", "settings"); var originalCwd: string; before(function (mocha: MochaDone): void { diff --git a/src/taco-cli/test/templateManager.ts b/src/taco-cli/test/templateManager.ts index 1d9d453d..88d847fa 100644 --- a/src/taco-cli/test/templateManager.ts +++ b/src/taco-cli/test/templateManager.ts @@ -18,7 +18,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import archiver = require ("archiver"); @@ -247,12 +247,12 @@ describe("TemplateManager", function (): void { ]; function verifyFileContent(filePath: string): void { - var lr = new wrench.LineReader(filePath); - var lineNumber = 0; + var lr: wrench.LineReader = new wrench.LineReader(filePath); + var lineNumber: number = 0; while (lr.hasNextLine()) { var currentLine: string = lr.getNextLine().trim(); - var correctLine = replacedLines[lineNumber]; + var correctLine: string = replacedLines[lineNumber]; if (currentLine !== correctLine) { fs.closeSync(lr.fd); @@ -267,7 +267,7 @@ describe("TemplateManager", function (): void { it("should correctly replace all tokens in all files, recursively", function (done: MochaDone): void { // Copy template items to a new folder - var testProjectPath = path.join(runFolder, "testProject"); + var testProjectPath: string = path.join(runFolder, "testProject"); wrench.mkdirSyncRecursive(testProjectPath, 511); // 511 decimal is 0777 octal utils.copyRecursive(testTemplateSrc, testProjectPath) @@ -296,7 +296,7 @@ describe("TemplateManager", function (): void { var templates: templateManager = new templateManager(mockKitHelper, templateCache); // Build the expected result - var expectedResult = { + var expectedResult: any = { kitId: testKitId, templates: [ { @@ -332,7 +332,7 @@ describe("TemplateManager", function (): void { var templates: templateManager = new templateManager(mockKitHelper, templateCache); // Build the expected result - var expectedResult = { + var expectedResult: any = { kitId: "", templates: [ { diff --git a/src/taco-cli/test/templates.ts b/src/taco-cli/test/templates.ts index 22be4dab..a0212120 100644 --- a/src/taco-cli/test/templates.ts +++ b/src/taco-cli/test/templates.ts @@ -16,12 +16,12 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ /* tslint:disable:no-var-requires */ // Special case to allow using color package with index signature for style rules -var colors = require("colors/safe"); +var colors: any = require("colors/safe"); /* tslint:enable:no-var-requires */ import tacoUtils = require ("taco-utils"); @@ -34,7 +34,7 @@ describe("templates", function (): void { this.timeout(20000); function templatesRun(): Q.Promise { - var templates = new Templates(); + var templates: Templates = new Templates(); var data: commands = { options: {}, original: [], @@ -59,7 +59,9 @@ describe("templates", function (): void { }); describe("Onboarding experience", function (): void { - var stdoutWrite = process.stdout.write; // We save the original implementation, so we can restore it later + // because of function overloading assigning "(buffer: string, cb?: Function) => boolean" as the type for + // stdoutWrite just doesn't work + var stdoutWrite: any = process.stdout.write; // We save the original implementation, so we can restore it later var memoryStdout: ms.MemoryStream; beforeEach(() => { @@ -74,7 +76,7 @@ describe("templates", function (): void { it("templates prints the onboarding experience", function (done: MochaDone): void { templatesRun().done(() => { - var expected = [ + var expected: any = [ "CommandTemplatesHeader", "", " blank ............... BlankTemplateName", @@ -82,7 +84,7 @@ describe("templates", function (): void { "", "HowToUseCreateProjectWithTemplate", ""].join("\n"); - var actual = colors.strip(memoryStdout.contentsAsText()); // The colors add extra characters + var actual: string = colors.strip(memoryStdout.contentsAsText()); // The colors add extra characters actual.should.be.equal(expected); done(); }, done); diff --git a/src/taco-cli/test/utils/MockCordova.ts b/src/taco-cli/test/utils/MockCordova.ts index 8f7bbd06..13fc0a53 100644 --- a/src/taco-cli/test/utils/MockCordova.ts +++ b/src/taco-cli/test/utils/MockCordova.ts @@ -37,7 +37,7 @@ module MockCordova { /* tslint:enable no-arg */ // Next line hacks, gets the name of the method that was called from the stack trace (e.g.: MockCordovaRaw510.build) - var methodName = ( new Error()).stack.split("\n")[2].replace(/^ +at ([A-z0-9]+\.[A-z0-9]+) \(.*/, "$1"); + var methodName: string = ( new Error()).stack.split("\n")[2].replace(/^ +at ([A-z0-9]+\.[A-z0-9]+) \(.*/, "$1"); throw new MethodNotImplementedException(caller, methodName, "The cordova method " + methodName + " was called during a test. You need to provide a custom implementation"); @@ -49,18 +49,18 @@ module MockCordova { export class MockCordova510 implements Cordova.ICordova510 { - public raw = new MockCordovaRaw510(); + public raw: MockCordovaRaw510 = new MockCordovaRaw510(); private events: { [event: string]: any[] } = {}; public static get default(): MockCordova510 { - var t = new MockCordova510(); + var t: MockCordova510 = new MockCordova510(); t.on = (event: string, func: Function) => { t.events[event] = (t.events[event] || []); t.events[event].push(func); }; t.off = (event: string, func: Function) => { - var idx = t.events[event] && t.events[event].indexOf(func); + var idx: number = t.events[event] && t.events[event].indexOf(func); if (idx) { t.events[event].splice(idx); }; diff --git a/src/taco-cli/test/utils/memoryStream.ts b/src/taco-cli/test/utils/memoryStream.ts index d42ebf92..e9811637 100644 --- a/src/taco-cli/test/utils/memoryStream.ts +++ b/src/taco-cli/test/utils/memoryStream.ts @@ -50,13 +50,13 @@ import utils = tacoUtils.UtilHelper; export class MemoryStream extends stream.Writable { private stdoutWrite: { (data: any, encoding: string, callback: Function): void }; - private shouldAlsoPrintToRealStdout = true; // We turn this on for debugging purposes, on the tests, possible on the build server + private shouldAlsoPrintToRealStdout: boolean = true; // We turn this on for debugging purposes, on the tests, possible on the build server private fullBuffer: Buffer = new Buffer(""); public _write(data: Buffer, encoding: string, callback: Function): void; public _write(data: string, encoding: string, callback: Function): void; public _write(data: any, encoding: string, callback: Function): void { - var buffer = Buffer.isBuffer(data) ? data : new Buffer(data, encoding); + var buffer: Buffer = Buffer.isBuffer(data) ? data : new Buffer(data, encoding); this.fullBuffer = Buffer.concat([this.fullBuffer, buffer]); if (this.shouldAlsoPrintToRealStdout) { this.stdoutWrite.call(process.stdout, data, encoding, utils.emptyMethod); @@ -67,7 +67,7 @@ export class MemoryStream extends stream.Writable { } public contentsAsText(): string { - var rawContents = this.fullBuffer.toString("utf-8"); + var rawContents: string = this.fullBuffer.toString("utf-8"); return rawContents.replace(/\r\n/g, "\n"); // We normalize the line endings } diff --git a/src/taco-cli/test/utils/serverMock.ts b/src/taco-cli/test/utils/serverMock.ts index 19084561..f85a1f5e 100644 --- a/src/taco-cli/test/utils/serverMock.ts +++ b/src/taco-cli/test/utils/serverMock.ts @@ -9,7 +9,7 @@ class ServerMock { * Create a https server using the certificates in test/resources/certs/ */ public static createSecureTestServer(): https.Server { - var testCertsFolder = path.resolve(__dirname, "..", "resources", "certs"); + var testCertsFolder: string = path.resolve(__dirname, "..", "resources", "certs"); var sslSettings: https.ServerOptions = { key: fs.readFileSync(path.join(testCertsFolder, "server-key.pem")), cert: fs.readFileSync(path.join(testCertsFolder, "server-cert.pem")), @@ -26,21 +26,21 @@ class ServerMock { */ public static generateServerFunction(onErr: (err: Error) => void, sequence: { expectedUrl: string; statusCode: number; head: any; response: any; waitForPayload?: boolean; responseDelay?: number; fileToSend?: string }[]): (request: http.ServerRequest, response: http.ServerResponse) => void { - var sequenceIndex = 0; + var sequenceIndex: number = 0; return function (request: http.ServerRequest, response: http.ServerResponse): void { if (sequenceIndex < sequence.length) { - var data = sequence[sequenceIndex]; + var data: any = sequence[sequenceIndex]; ++sequenceIndex; if (request.url !== data.expectedUrl) { onErr(new Error("Expected request to " + data.expectedUrl + " got " + request.url)); } else { - var sendResponse = function (): void { + var sendResponse: () => void = function (): void { setTimeout(() => { response.writeHead(data.statusCode, data.head); if (data.fileToSend) { - var reader = fs.createReadStream(data.fileToSend); + var reader: fs.ReadStream = fs.createReadStream(data.fileToSend); reader.pipe(response); - reader.on("end", function () { + reader.on("end", function (): void { response.end(); }); } else { diff --git a/src/typings/telemetryHelper.d.ts b/src/typings/telemetryHelper.d.ts index d017e495..146d56a5 100644 --- a/src/typings/telemetryHelper.d.ts +++ b/src/typings/telemetryHelper.d.ts @@ -10,7 +10,7 @@ /// declare module TacoUtility { - interface ITelemetryPropertyInfo { + interface ITelemetryPropertyInfo { value: any; isPii: boolean; } From 7a2b83276a82ed07ad5cfedef4d25b51d86fddbf Mon Sep 17 00:00:00 2001 From: Nisheet Jain Date: Sun, 4 Oct 2015 02:34:24 -0700 Subject: [PATCH 3/6] Fixing tslint typedef issues for taco-dependency-installer,taco-kits,taco-remote,taco-remote-lib,taco-remote-multiplexer,taco-utils --- .../dependencyInstaller.ts | 24 +++---- .../elevatedInstaller.ts | 6 +- .../installerRunner.ts | 16 ++--- .../installers/androidSdkInstaller.ts | 16 ++--- .../installers/installerBase.ts | 4 +- .../installers/javaJdkInstaller.ts | 9 ++- .../test/dependencyDataWrapper.ts | 2 +- .../test/dependencyInstaller.ts | 2 +- .../test/installerRunner.ts | 2 +- .../test/installerUtils.ts | 2 +- .../utils/dependencyDataWrapper.ts | 2 +- .../utils/installerUtils.ts | 8 +-- src/taco-kits/tacoKits.ts | 10 +-- src/taco-kits/test/tacoKits.ts | 14 ++-- src/taco-remote-lib/common/builder.ts | 28 ++++---- src/taco-remote-lib/ios/ios.ts | 28 ++++---- src/taco-remote-lib/ios/iosAppRunnerHelper.ts | 64 +++++++++---------- src/taco-remote-lib/ios/iosBuild.ts | 48 +++++++------- src/taco-remote-lib/ios/iosEmulateHelper.ts | 10 +-- src/taco-remote-lib/ios/plist.ts | 18 +++--- src/taco-remote-lib/tacoRemoteLib.ts | 18 +++--- src/taco-remote-lib/test/iosAppRunner.ts | 30 ++++----- src/taco-remote-lib/test/plist.ts | 16 ++--- .../tacoRemoteMultiplexer.ts | 2 +- src/taco-remote/lib/buildManager.ts | 58 ++++++++--------- src/taco-remote/lib/buildRetention.ts | 20 +++--- .../lib/darwin/darwinDependenciesHelper.ts | 18 +++--- src/taco-remote/lib/requestRedirector.ts | 4 +- src/taco-remote/lib/selftest.ts | 36 +++++------ src/taco-remote/lib/server.ts | 34 +++++----- src/taco-remote/lib/tacoRemoteConfig.ts | 6 +- src/taco-remote/test/build.ts | 14 ++-- src/taco-utils/buildInfo.ts | 26 ++++---- src/taco-utils/commands.ts | 12 ++-- src/taco-utils/cordovaConfig.ts | 10 +-- src/taco-utils/countStream.ts | 2 +- src/taco-utils/helpCommandBase.ts | 16 ++--- src/taco-utils/jsonSerializer.ts | 6 +- src/taco-utils/logFormatHelper.ts | 6 +- src/taco-utils/loggerHelper.ts | 16 ++--- src/taco-utils/newlineNormalizerStream.ts | 4 +- src/taco-utils/processLogger.ts | 4 +- src/taco-utils/resourceManager.ts | 14 ++-- src/taco-utils/resourceSet.ts | 10 +-- src/taco-utils/tacoPackageLoader.ts | 18 +++--- src/taco-utils/tacoUtils.ts | 46 ++++++------- src/taco-utils/telemetry.ts | 48 +++++++------- src/taco-utils/telemetryHelper.ts | 34 +++++----- src/taco-utils/test/cordovaConfig.ts | 6 +- src/taco-utils/test/packageLoader.ts | 10 +-- src/taco-utils/test/resources.ts | 60 ++++++++--------- src/taco-utils/test/utilHelper.ts | 2 +- src/taco-utils/utilHelper.ts | 18 +++--- 53 files changed, 469 insertions(+), 468 deletions(-) diff --git a/src/taco-dependency-installer/dependencyInstaller.ts b/src/taco-dependency-installer/dependencyInstaller.ts index 9619469d..ee99eb67 100644 --- a/src/taco-dependency-installer/dependencyInstaller.ts +++ b/src/taco-dependency-installer/dependencyInstaller.ts @@ -75,7 +75,7 @@ module TacoDependencyInstaller { } public run(requirementsResult: any): Q.Promise { - return tacoUtils.TelemetryHelper.generate("dependencyInstaller", telemetry => { + return tacoUtils.TelemetryHelper.generate("dependencyInstaller", (telemetry: tacoUtils.TelemetryGenerator) => { telemetry.add("requirements", requirementsResult, /*isPii*/ false); if (process.platform !== "win32" && process.platform !== "darwin") { @@ -104,7 +104,7 @@ module TacoDependencyInstaller { this.sortDependencies(); // Print a summary of what is about to be installed, Wait for user confirmation, then spawn the elevated process which will perform the installations - var self = this; + var self: DependencyInstaller = this; telemetry.step("promptUserBeforeInstall"); return this.promptUserBeforeInstall() @@ -130,7 +130,7 @@ module TacoDependencyInstaller { this.missingDependencies = []; // Process cordova results - var self = this; + var self: DependencyInstaller = this; dependencyIds.forEach(function (value: ICordovaRequirement): void { if (self.canInstallDependency(value)) { @@ -251,7 +251,7 @@ module TacoDependencyInstaller { } private displayUnsupportedWarning(): void { - var self = this; + var self: DependencyInstaller = this; if (this.unsupportedMissingDependencies.length > 0) { logger.logWarning(resources.getString("UnsupportedDependenciesHeader")); @@ -284,7 +284,7 @@ module TacoDependencyInstaller { } private sortDependencies(): void { - var self = this; + var self: DependencyInstaller = this; // Build a representation of the graph in a way that is understood by the toposort package var nodes: string[] = []; @@ -379,7 +379,7 @@ module TacoDependencyInstaller { try { // Create a JSON object wrapper around our array of missing dependencies - var jsonWrapper = { + var jsonWrapper: any = { dependencies: this.missingDependencies }; @@ -392,7 +392,7 @@ module TacoDependencyInstaller { } private prepareCommunications(): Q.Promise { - var self = this; + var self: DependencyInstaller = this; if (os.platform() === "win32") { // For Windows we need to prepare a local server to communicate with the elevated installer process @@ -409,7 +409,7 @@ module TacoDependencyInstaller { } private createServer(): void { - var self = this; + var self: DependencyInstaller = this; this.serverHandle = net.createServer(function (socket: net.Socket): void { self.socketHandle = socket; @@ -447,7 +447,7 @@ module TacoDependencyInstaller { } private promptUser(msg: string): void { - var self = this; + var self: DependencyInstaller = this; installerUtils.promptUser(msg) .then(function (answer: string): void { @@ -456,7 +456,7 @@ module TacoDependencyInstaller { } private connectServer(): Q.Promise { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); this.serverHandle.listen(DependencyInstaller.socketPath, function (): void { deferred.resolve({}); @@ -477,7 +477,7 @@ module TacoDependencyInstaller { } private spawnElevatedInstallerWin32(): Q.Promise { - var self = this; + var self: DependencyInstaller = this; // Set up the communication channels to talk with the elevated installer process return this.prepareCommunications() @@ -517,7 +517,7 @@ module TacoDependencyInstaller { } private spawnElevatedInstallerDarwin(): Q.Promise { - var self = this; + var self: DependencyInstaller = this; var deferred: Q.Deferred = Q.defer(); var elevatedInstallerScript: string = path.resolve(__dirname, "elevatedInstaller.js"); var command: string; diff --git a/src/taco-dependency-installer/elevatedInstaller.ts b/src/taco-dependency-installer/elevatedInstaller.ts index efbfe46a..b2736a74 100644 --- a/src/taco-dependency-installer/elevatedInstaller.ts +++ b/src/taco-dependency-installer/elevatedInstaller.ts @@ -108,8 +108,8 @@ class ElevatedInstaller { public run(): void { tacoUtils.Telemetry.init("TACO/dependencyInstaller", require("./package.json").version, this.parentSessionId !== "null"); tacoUtils.Telemetry.setSessionId(this.parentSessionId); - tacoUtils.TelemetryHelper.generate("ElevatedInstaller", telemetry => { - var self = this; + tacoUtils.TelemetryHelper.generate("ElevatedInstaller", (telemetry: tacoUtils.TelemetryGenerator) => { + var self: ElevatedInstaller = this; telemetry.step("prepareCommunications"); this.prepareCommunications() @@ -133,7 +133,7 @@ class ElevatedInstaller { } private prepareCommunications(): Q.Promise { - var self = this; + var self: ElevatedInstaller = this; switch (process.platform) { case "win32": diff --git a/src/taco-dependency-installer/installerRunner.ts b/src/taco-dependency-installer/installerRunner.ts index 2e803a1b..0d802ec2 100644 --- a/src/taco-dependency-installer/installerRunner.ts +++ b/src/taco-dependency-installer/installerRunner.ts @@ -49,8 +49,8 @@ class InstallerRunner { } public run(): Q.Promise { - return tacoUtils.TelemetryHelper.generate("InstallerRunner", telemetry => { - var self = this; + return tacoUtils.TelemetryHelper.generate("InstallerRunner", (telemetry: tacoUtils.TelemetryGenerator) => { + var self: InstallerRunner = this; return Q({}) .then(function (): void { telemetry.step("parseInstallConfig"); @@ -80,7 +80,7 @@ class InstallerRunner { } private parseInstallConfig(telemetry: tacoUtils.TelemetryGenerator): void { - var self = this; + var self: InstallerRunner = this; var parsedData: DependencyInstallerInterfaces.IInstallerConfig = null; if (!fs.existsSync(this.configFile)) { @@ -156,11 +156,11 @@ class InstallerRunner { }; // We want to know if the users like to change the default installation directory, or not, to improve the experience if neccesary - var defaultInstallDirectory = self.dependenciesDataWrapper.getInstallDirectory(value.id, value.version); + var defaultInstallDirectory: string = self.dependenciesDataWrapper.getInstallDirectory(value.id, value.version); if (defaultInstallDirectory && value.installDestination) { - var normalizedDefaultInstallDirectory = path.normalize(utilHelper.expandEnvironmentVariables(defaultInstallDirectory)); - var normalizedInstallDestination = path.normalize(value.installDestination); - var isDefault = normalizedDefaultInstallDirectory === normalizedInstallDestination; + var normalizedDefaultInstallDirectory: string = path.normalize(utilHelper.expandEnvironmentVariables(defaultInstallDirectory)); + var normalizedInstallDestination: string = path.normalize(value.installDestination); + var isDefault: boolean = normalizedDefaultInstallDirectory === normalizedInstallDestination; telemetry.add("installDestination.isDefault", isDefault, /*isPii*/ false); telemetry.add("installDestination.path", normalizedInstallDestination, /*isPii*/ true); } else { @@ -183,7 +183,7 @@ class InstallerRunner { } private runInstallers(): Q.Promise { - var self = this; + var self: InstallerRunner = this; return this.missingDependencies.reduce(function (previous: Q.Promise, value: IDependencyWrapper, currentIndex: number): Q.Promise { return previous diff --git a/src/taco-dependency-installer/installers/androidSdkInstaller.ts b/src/taco-dependency-installer/installers/androidSdkInstaller.ts index cffae7fa..4f3d81fe 100644 --- a/src/taco-dependency-installer/installers/androidSdkInstaller.ts +++ b/src/taco-dependency-installer/installers/androidSdkInstaller.ts @@ -14,7 +14,7 @@ "use strict"; -import admZip = require ("adm-zip"); +import AdmZip = require ("adm-zip"); import childProcess = require ("child_process"); import fs = require ("fs"); import os = require ("os"); @@ -35,7 +35,6 @@ import utilHelper = tacoUtils.UtilHelper; class AndroidSdkInstaller extends InstallerBase { private static ANDROID_HOME_NAME: string = "ANDROID_HOME"; - private static androidCommand = os.platform() === "win32" ? "android.bat" : "android"; private static ANDROID_PACKAGES: string[] = [ "tools", "platform-tools", @@ -49,6 +48,7 @@ class AndroidSdkInstaller extends InstallerBase { "android-22" ]; + private static androidCommand: string = os.platform() === "win32" ? "android.bat" : "android"; private installerArchive: string; private androidHomeValue: string; @@ -87,7 +87,7 @@ class AndroidSdkInstaller extends InstallerBase { } protected installDarwin(): Q.Promise { - var self = this; + var self: AndroidSdkInstaller = this; // Before we extract Android SDK, we need to save the first directory under the specified install path that doesn't exist. This directory and all those under it will be created // with root as the owner, so we will need to change the owner back to the current user after the extraction is complete. @@ -152,7 +152,7 @@ class AndroidSdkInstaller extends InstallerBase { } protected postInstallDarwin(): Q.Promise { - var self = this; + var self: AndroidSdkInstaller = this; return this.addExecutePermission() .then(function (): Q.Promise { @@ -187,7 +187,7 @@ class AndroidSdkInstaller extends InstallerBase { } // Extract the archive - var templateZip = new admZip(this.installerArchive); + var templateZip: AdmZip = new AdmZip(this.installerArchive); if (!fs.existsSync(this.installDestination)) { wrench.mkdirSyncRecursive(this.installDestination, 511); // 511 decimal is 0777 octal @@ -240,7 +240,7 @@ class AndroidSdkInstaller extends InstallerBase { private installAndroidPackages(): Q.Promise { // Install Android packages var deferred: Q.Deferred = Q.defer(); - var command = path.join(this.androidHomeValue, "tools", AndroidSdkInstaller.androidCommand); + var command: string = path.join(this.androidHomeValue, "tools", AndroidSdkInstaller.androidCommand); var args: string[] = [ "update", "sdk", @@ -262,7 +262,7 @@ class AndroidSdkInstaller extends InstallerBase { } cp.stdout.on("data", function (data: Buffer): void { - var stringData = data.toString(); + var stringData: string = data.toString(); if (/\[y\/n\]:/.test(stringData)) { // Accept license terms @@ -295,7 +295,7 @@ class AndroidSdkInstaller extends InstallerBase { } private postInstallDefault(): Q.Promise { - var self = this; + var self: AndroidSdkInstaller = this; return this.installAndroidPackages() .then(function (): Q.Promise { return self.killAdb(); diff --git a/src/taco-dependency-installer/installers/installerBase.ts b/src/taco-dependency-installer/installers/installerBase.ts index 4827bbe8..99e4e372 100644 --- a/src/taco-dependency-installer/installers/installerBase.ts +++ b/src/taco-dependency-installer/installers/installerBase.ts @@ -51,9 +51,9 @@ class InstallerBase { } public run(): Q.Promise { - var self = this; + var self: InstallerBase = this; return tacoUtils.TelemetryHelper.generate("Installer:" + this.id, - telemetry => { + (telemetry: tacoUtils.TelemetryGenerator) => { this.telemetry = telemetry; // So any method can access it return this.download() .then(function (): Q.Promise { diff --git a/src/taco-dependency-installer/installers/javaJdkInstaller.ts b/src/taco-dependency-installer/installers/javaJdkInstaller.ts index 5a717029..dfc34410 100644 --- a/src/taco-dependency-installer/installers/javaJdkInstaller.ts +++ b/src/taco-dependency-installer/installers/javaJdkInstaller.ts @@ -12,7 +12,6 @@ "use strict"; -import admZip = require ("adm-zip"); import childProcess = require ("child_process"); import os = require ("os"); import path = require ("path"); @@ -42,7 +41,7 @@ class JavaJdkInstaller extends InstallerBase { } protected installWin32(): Q.Promise { - var self = this; + var self: JavaJdkInstaller = this; var deferred: Q.Deferred = Q.defer(); // Make sure we have an install location @@ -94,7 +93,7 @@ class JavaJdkInstaller extends InstallerBase { } protected installDarwin(): Q.Promise { - var self = this; + var self: JavaJdkInstaller = this; return this.attachDmg() .then(function (): Q.Promise { @@ -106,7 +105,7 @@ class JavaJdkInstaller extends InstallerBase { } private attachDmg(): Q.Promise { - var self = this; + var self: JavaJdkInstaller = this; var deferred: Q.Deferred = Q.defer(); var command: string = "hdiutil attach " + this.installerDownloadPath; @@ -131,7 +130,7 @@ class JavaJdkInstaller extends InstallerBase { } private installPkg(): Q.Promise { - var self = this; + var self: JavaJdkInstaller = this; var deferred: Q.Deferred = Q.defer(); var pkgPath: string = path.join("/", "Volumes", this.darwinMountpointName, this.darwinMountpointName + ".pkg"); var commandLine: string = "installer -pkg \"" + pkgPath + "\" -target \"/\""; diff --git a/src/taco-dependency-installer/test/dependencyDataWrapper.ts b/src/taco-dependency-installer/test/dependencyDataWrapper.ts index db79e745..618bd315 100644 --- a/src/taco-dependency-installer/test/dependencyDataWrapper.ts +++ b/src/taco-dependency-installer/test/dependencyDataWrapper.ts @@ -15,7 +15,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import path = require ("path"); diff --git a/src/taco-dependency-installer/test/dependencyInstaller.ts b/src/taco-dependency-installer/test/dependencyInstaller.ts index 6842f426..99edc541 100644 --- a/src/taco-dependency-installer/test/dependencyInstaller.ts +++ b/src/taco-dependency-installer/test/dependencyInstaller.ts @@ -15,7 +15,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import fs = require ("fs"); diff --git a/src/taco-dependency-installer/test/installerRunner.ts b/src/taco-dependency-installer/test/installerRunner.ts index 4734b6f8..a6fe486c 100644 --- a/src/taco-dependency-installer/test/installerRunner.ts +++ b/src/taco-dependency-installer/test/installerRunner.ts @@ -16,7 +16,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import fs = require ("fs"); diff --git a/src/taco-dependency-installer/test/installerUtils.ts b/src/taco-dependency-installer/test/installerUtils.ts index 41734d87..19ee3a1d 100644 --- a/src/taco-dependency-installer/test/installerUtils.ts +++ b/src/taco-dependency-installer/test/installerUtils.ts @@ -14,7 +14,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import os = require ("os"); diff --git a/src/taco-dependency-installer/utils/dependencyDataWrapper.ts b/src/taco-dependency-installer/utils/dependencyDataWrapper.ts index ed79b675..5dc81f09 100644 --- a/src/taco-dependency-installer/utils/dependencyDataWrapper.ts +++ b/src/taco-dependency-installer/utils/dependencyDataWrapper.ts @@ -126,7 +126,7 @@ class DependencyDataWrapper { * platform if no platform is specified) or the "default" platform. Returns null if no such version ID exists. */ public getFirstValidVersion(id: string, platform: string = process.platform, architecture: string = os.arch()): string { - var self = this; + var self: DependencyDataWrapper = this; var validVersion: string; if (this.dependencyExists(id) && !!this.dependencies[id].versions) { diff --git a/src/taco-dependency-installer/utils/installerUtils.ts b/src/taco-dependency-installer/utils/installerUtils.ts index 7e83fb1c..0163b315 100644 --- a/src/taco-dependency-installer/utils/installerUtils.ts +++ b/src/taco-dependency-installer/utils/installerUtils.ts @@ -117,7 +117,7 @@ class InstallerUtils { */ public static promptUser(message: string): Q.Promise { var deferred: Q.Deferred = Q.defer(); - var rl = readline.createInterface({ + var rl: readline.ReadLine = readline.createInterface({ input: process.stdin, output: process.stdout }); @@ -174,8 +174,8 @@ class InstallerUtils { public static promptForEnvVariableOverwrite(name: string, socket: NodeJSNet.Socket): Q.Promise { var deferred: Q.Deferred = Q.defer(); - var dataListener = function (data: Buffer): void { - var stringData = data.toString(); + var dataListener: (data: Buffer) => void = function (data: Buffer): void { + var stringData: string = data.toString(); socket.removeListener("data", dataListener); deferred.resolve(stringData); @@ -267,7 +267,7 @@ class InstallerUtils { deferred.reject(new Error(resources.getString("FileNotFound"))); } - var fws = fs.createWriteStream(filePath); + var fws: fs.WriteStream = fs.createWriteStream(filePath); response.pipe(fws); fws.on("finish", function (): void { diff --git a/src/taco-kits/tacoKits.ts b/src/taco-kits/tacoKits.ts index 2fda6ecc..1480e7ed 100644 --- a/src/taco-kits/tacoKits.ts +++ b/src/taco-kits/tacoKits.ts @@ -197,7 +197,7 @@ module TacoKits { public getTemplatesForKit(inputKitId: string): Q.Promise { var kit: string = null; var templates: ITemplateMetadata = null; - var self = this; + var self: KitHelper = this; return this.getTemplateMetadata() .then(function (templateMetadata: ITemplateMetadata): Q.Promise { @@ -284,7 +284,7 @@ module TacoKits { var deferred: Q.Deferred = Q.defer(); var templates: ITemplateMetadata = null; var templateOverrideInfo: ITemplateOverrideInfo = null; - var self = this; + var self: KitHelper = this; return this.getTemplateMetadata() .then(function (templateMetadata: ITemplateMetadata): Q.Promise { @@ -394,7 +394,7 @@ module TacoKits { public getTemplateMetadata(): Q.Promise { var deferred: Q.Deferred = Q.defer(); return this.getKitMetadata().then(function (metadata: ITacoKitMetadata): Q.Promise { - var templates = metadata.templates; + var templates: ITemplateMetadata = metadata.templates; if (templates) { deferred.resolve(templates); } else { @@ -412,7 +412,7 @@ module TacoKits { */ public getCordovaCliForDefaultKit(): Q.Promise { var deferred: Q.Deferred = Q.defer(); - var self = this; + var self: KitHelper = this; return this.getDefaultKit().then(function (defaultKit: string): Q.Promise { return self.getCordovaCliForKit(defaultKit); }); @@ -465,7 +465,7 @@ module TacoKits { /* tslint:disable:variable-name */ // taco-kits error codes need to be accessed by other packages as TacoErrorCode // more like an enum. - export var TacoErrorCode = TacoErrorCodes; + export var TacoErrorCode: any = TacoErrorCodes; /* tslint:enable:variable-name */ } diff --git a/src/taco-kits/test/tacoKits.ts b/src/taco-kits/test/tacoKits.ts index 5f0306f7..bac43f2d 100644 --- a/src/taco-kits/test/tacoKits.ts +++ b/src/taco-kits/test/tacoKits.ts @@ -16,7 +16,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import mocha = require ("mocha"); @@ -58,7 +58,7 @@ describe("KitHelper", function (): void { } }; - var templateSrcPath = path.resolve(__dirname, "..", "templates", "default", "blank.zip"); + var templateSrcPath: string = path.resolve(__dirname, "..", "templates", "default", "blank.zip"); var testTemplateOverrideInfo: tacoKits.ITemplateOverrideInfo = { kitId: "default", templateInfo: { @@ -134,7 +134,7 @@ describe("KitHelper", function (): void { kitHelper.getKitInfo(testDeprecatedKitId) .then(function (kitInfo: TacoKits.IKitInfo): void { // Verify the returned kitInfo is correct - var stringifiedInfo = JSON.stringify(kitInfo); + var stringifiedInfo: string = JSON.stringify(kitInfo); stringifiedInfo.should.equal(JSON.stringify(testDeprecatedKitInfo)); done(); @@ -148,7 +148,7 @@ describe("KitHelper", function (): void { kitHelper.getKitInfo(testDefaultKitId) .then(function (kitInfo: TacoKits.IKitInfo): void { // Verify the returned kitInfo is correct - var stringifiedInfo = JSON.stringify(kitInfo); + var stringifiedInfo: string = JSON.stringify(kitInfo); stringifiedInfo.should.equal(JSON.stringify(testDefaultKitInfo)); done(); @@ -215,7 +215,7 @@ describe("KitHelper", function (): void { kitHelper.getTemplateOverrideInfo(testDefaultKitId, testDefaultTemplateId) .then(function (templateOverrideInfo: TacoKits.ITemplateOverrideInfo): void { // Verify the returned override info is correct - var stringifiedInfo = JSON.stringify(templateOverrideInfo); + var stringifiedInfo: string = JSON.stringify(templateOverrideInfo); stringifiedInfo.should.equal(JSON.stringify(testTemplateOverrideInfo)); done(); @@ -254,7 +254,7 @@ describe("KitHelper", function (): void { kitHelper.getTemplatesForKit(kitId) .then(function (kitOverride: TacoKits.IKitTemplatesOverrideInfo): void { // Verify the returned override info is correct - var stringifiedInfo = JSON.stringify(kitOverride); + var stringifiedInfo: string = JSON.stringify(kitOverride); stringifiedInfo.should.equal(JSON.stringify(expectedResult)); done(); @@ -291,7 +291,7 @@ describe("KitHelper", function (): void { kitHelper.getTemplatesForKit(kitId) .then(function (kitOverride: TacoKits.IKitTemplatesOverrideInfo): void { // Verify the returned override info is correct - var stringifiedInfo = JSON.stringify(kitOverride); + var stringifiedInfo: string = JSON.stringify(kitOverride); stringifiedInfo.should.equal(JSON.stringify(expectedResult)); done(); diff --git a/src/taco-remote-lib/common/builder.ts b/src/taco-remote-lib/common/builder.ts index 29906b83..4b31ccf8 100644 --- a/src/taco-remote-lib/common/builder.ts +++ b/src/taco-remote-lib/common/builder.ts @@ -63,8 +63,8 @@ class Builder { } public build(): Q.Promise { - var isDeviceBuild = this.currentBuild.options.indexOf("--device") !== -1; - var self = this; + var isDeviceBuild: boolean = this.currentBuild.options.indexOf("--device") !== -1; + var self: Builder = this; return Q.fcall(Builder.change_directory, self.currentBuild.appDir) .then(function (): Q.Promise { return self.update_plugins(); }) @@ -127,16 +127,16 @@ class Builder { } private update_plugins(): Q.Promise { - var remotePluginsPath = path.join("remote", "plugins"); - var self = this; + var remotePluginsPath: string = path.join("remote", "plugins"); + var self: Builder = this; if (!fs.existsSync(remotePluginsPath)) { return Q.resolve({}); } - var newAndModifiedPlugins = fs.readdirSync(remotePluginsPath).filter(function (entry: string): boolean { + var newAndModifiedPlugins: string[] = fs.readdirSync(remotePluginsPath).filter(function (entry: string): boolean { return fs.statSync(path.join(remotePluginsPath, entry)).isDirectory(); }); - var pluginNameRegex = new RegExp("plugins#([^#]*)#plugin.xml$".replace(/#/g, path.sep === "\\" ? "\\\\" : path.sep)); + var pluginNameRegex: RegExp = new RegExp("plugins#([^#]*)#plugin.xml$".replace(/#/g, path.sep === "\\" ? "\\\\" : path.sep)); var deletedPlugins: string[] = []; if (this.currentBuild.changeList && this.currentBuild.changeList.deletedFiles) { deletedPlugins = this.currentBuild.changeList.deletedFiles.map(function (file: string): string { @@ -150,7 +150,7 @@ class Builder { }); } - var deleteOldPlugins = deletedPlugins.reduce(function (soFar: Q.Promise, plugin: string): Q.Promise { + var deleteOldPlugins: Q.Promise = deletedPlugins.reduce(function (soFar: Q.Promise, plugin: string): Q.Promise { return soFar.then(function (): Q.Promise { if (fs.existsSync(path.join("plugins", plugin))) { return self.cordova.raw.plugin("remove", plugin).catch(function (err: any): void { @@ -168,7 +168,7 @@ class Builder { }, Q({})); var fetchJson: Cordova.IFetchJson = {}; - var fetchJsonPath = path.join(remotePluginsPath, "fetch.json"); + var fetchJsonPath: string = path.join(remotePluginsPath, "fetch.json"); if (fs.existsSync(fetchJsonPath)) { try { fetchJson = JSON.parse( fs.readFileSync(fetchJsonPath)); @@ -181,8 +181,8 @@ class Builder { return newAndModifiedPlugins.reduce(function (soFar: Q.Promise, plugin: string): Q.Promise { return soFar.then(function (): Q.Promise { - var newFolder = path.join(remotePluginsPath, plugin); - var installedFolder = path.join("plugins", plugin); + var newFolder: string = path.join(remotePluginsPath, plugin); + var installedFolder: string = path.join("plugins", plugin); if (fs.existsSync(installedFolder)) { // The plugin is already installed; overwrite it // Note that the plugin may have been installed by another plugin that depended on it; @@ -216,7 +216,7 @@ class Builder { } private prepareNativeOverrides(): Q.Promise { - var resFrom = path.join("res", "native", this.currentBuild.buildPlatform); + var resFrom: string = path.join("res", "native", this.currentBuild.buildPlatform); if (!fs.existsSync(resFrom)) { // If res -> native folder isn't here then it could be a project that was created when // the res -> cert folder still existed, so check for that location as well. @@ -224,7 +224,7 @@ class Builder { } if (fs.existsSync(resFrom)) { - var resTo = path.join("platforms", this.currentBuild.buildPlatform); + var resTo: string = path.join("platforms", this.currentBuild.buildPlatform); return UtilHelper.copyRecursive(resFrom, resTo); } @@ -233,8 +233,8 @@ class Builder { private compile_platform(): Q.Promise { Logger.log("cordova compile " + this.currentBuild.buildPlatform); - var configuration = (this.currentBuild.configuration === "debug") ? "--debug" : "--release"; - var opts = (this.currentBuild.options.length > 0) ? [this.currentBuild.options, configuration] : [configuration]; + var configuration: string = (this.currentBuild.configuration === "debug") ? "--debug" : "--release"; + var opts: string [] = (this.currentBuild.options.length > 0) ? [this.currentBuild.options, configuration] : [configuration]; return this.cordova.raw.compile({ platforms: [this.currentBuild.buildPlatform], options: opts }); } } diff --git a/src/taco-remote-lib/ios/ios.ts b/src/taco-remote-lib/ios/ios.ts index 6d9a7ebc..5d0c656c 100644 --- a/src/taco-remote-lib/ios/ios.ts +++ b/src/taco-remote-lib/ios/ios.ts @@ -20,7 +20,7 @@ import fs = require ("fs"); import net = require ("net"); import path = require ("path"); import util = require ("util"); -import packer = require ("zip-stream"); +import Packer = require ("zip-stream"); import iosAppRunner = require ("./iosAppRunnerHelper"); import resources = require ("../resources/resourceManager"); @@ -76,8 +76,8 @@ class IOSAgent implements ITargetPlatform { return; } - var proxyPort = this.nativeDebugProxyPort; - var cfg = utils.CordovaConfig.getCordovaConfig(buildInfo.appDir); + var proxyPort: number = this.nativeDebugProxyPort; + var cfg: utils.CordovaConfig = utils.CordovaConfig.getCordovaConfig(buildInfo.appDir); iosAppRunner.startDebugProxy(proxyPort) .then(function (nativeProxyProcess: child_process.ChildProcess): Q.Promise { return iosAppRunner.startApp(cfg.id(), proxyPort); @@ -93,18 +93,18 @@ class IOSAgent implements ITargetPlatform { } public downloadBuild(buildInfo: BuildInfo, req: Express.Request, res: Express.Response, callback: (err: any) => void): void { - var iosOutputDir = path.join(buildInfo.appDir, "platforms", "ios", "build", "device"); - var pathToPlistFile = path.join(iosOutputDir, buildInfo["appName"] + ".plist"); - var pathToIpaFile = path.join(iosOutputDir, buildInfo["appName"] + ".ipa"); + var iosOutputDir: string = path.join(buildInfo.appDir, "platforms", "ios", "build", "device"); + var pathToPlistFile: string = path.join(iosOutputDir, buildInfo["appName"] + ".plist"); + var pathToIpaFile: string = path.join(iosOutputDir, buildInfo["appName"] + ".ipa"); if (!fs.existsSync(pathToPlistFile) || !fs.existsSync(pathToIpaFile)) { - var msg = resources.getString("DownloadInvalid", pathToPlistFile, pathToIpaFile); + var msg: string = resources.getString("DownloadInvalid", pathToPlistFile, pathToIpaFile); Logger.log(msg); res.status(404).send(resources.getStringForLanguage(req, "DownloadInvalid", pathToPlistFile, pathToIpaFile)); callback(msg); return; } - var archive = new packer(); + var archive: Packer = new Packer(); archive.on("error", function (err: Error): void { Logger.logError(resources.getString("ArchivePackError", err.message)); callback(err); @@ -147,10 +147,10 @@ class IOSAgent implements ITargetPlatform { req.query.target = "iphone 5"; } - var cfg = utils.CordovaConfig.getCordovaConfig(buildInfo.appDir); + var cfg: utils.CordovaConfig = utils.CordovaConfig.getCordovaConfig(buildInfo.appDir); - var emulateProcess = child_process.fork(path.join(__dirname, "iosEmulateHelper.js"), [], { silent: true }); - var emulateLogger = new ProcessLogger(); + var emulateProcess: child_process.ChildProcess = child_process.fork(path.join(__dirname, "iosEmulateHelper.js"), [], { silent: true }); + var emulateLogger: ProcessLogger = new ProcessLogger(); emulateLogger.begin(buildInfo.buildDir, "emulate.log", buildInfo.buildLang, emulateProcess); emulateProcess.send({ appDir: buildInfo.appDir, appName: cfg.id(), target: req.query.target }, null); @@ -168,13 +168,13 @@ class IOSAgent implements ITargetPlatform { } public deployBuildToDevice(buildInfo: utils.BuildInfo, req: Express.Request, res: Express.Response): void { - var pathToIpaFile = path.join(buildInfo.appDir, "platforms", "ios", "build", "device", buildInfo["appName"] + ".ipa"); + var pathToIpaFile: string = path.join(buildInfo.appDir, "platforms", "ios", "build", "device", buildInfo["appName"] + ".ipa"); if (!fs.existsSync(pathToIpaFile)) { res.status(404).send(resources.getStringForLanguage(req, "BuildNotFound", req.params.id)); return; } - var ideviceinstaller = child_process.spawn("ideviceinstaller", ["-i", pathToIpaFile]); + var ideviceinstaller: child_process.ChildProcess = child_process.spawn("ideviceinstaller", ["-i", pathToIpaFile]); var stdout: string = ""; var stderr: string = ""; var errorMessage: string; @@ -216,7 +216,7 @@ class IOSAgent implements ITargetPlatform { this.webProxyInstance = null; } - var portRange = util.format("null:%d,:%d-%d", this.webDebugProxyDevicePort, this.webDebugProxyPortMin, this.webDebugProxyPortMax); + var portRange: string = util.format("null:%d,:%d-%d", this.webDebugProxyDevicePort, this.webDebugProxyPortMin, this.webDebugProxyPortMax); try { this.webProxyInstance = child_process.spawn("ios_webkit_debug_proxy", ["-c", portRange]); } catch (e) { diff --git a/src/taco-remote-lib/ios/iosAppRunnerHelper.ts b/src/taco-remote-lib/ios/iosAppRunnerHelper.ts index 68607dc8..7d88f099 100644 --- a/src/taco-remote-lib/ios/iosAppRunnerHelper.ts +++ b/src/taco-remote-lib/ios/iosAppRunnerHelper.ts @@ -23,7 +23,7 @@ import utils = require ("taco-utils"); import UtilHelper = utils.UtilHelper; var proxyInstance: child_process.ChildProcess = null; -var promiseExec = Q.denodeify(UtilHelper.loggedExec); +var promiseExec: (...args: any[]) => Q.Promise = Q.denodeify(UtilHelper.loggedExec); class IosAppRunnerHelper { public static startDebugProxy(proxyPort: number): Q.Promise { @@ -45,14 +45,14 @@ class IosAppRunnerHelper { // This exceeds the maximum stdout size that exec allows, so we redirect to a temp file. return promiseExec("ideviceinstaller -l -o xml > /tmp/$$.ideviceinstaller && echo /tmp/$$.ideviceinstaller").spread(function (stdout: string, stderr: string): string { // First find the path of the app on the device - var filename = stdout.trim(); + var filename: string = stdout.trim(); if (!/^\/tmp\/[0-9]+\.ideviceinstaller$/.test(filename)) { throw new Error("WrongInstalledAppsFile"); } var list: any[] = pl.parseFileSync(filename); fs.unlink(filename); - for (var i = 0; i < list.length; ++i) { + for (var i: number = 0; i < list.length; ++i) { if (list[i].CFBundleIdentifier === packageId) { var path: string = list[i].Path; return path; @@ -64,7 +64,7 @@ class IosAppRunnerHelper { } public static startAppViaDebugger(portNumber: number, packagePath: string): Q.Promise { - var encodedPath = IosAppRunnerHelper.encodePath(packagePath); + var encodedPath: string = IosAppRunnerHelper.encodePath(packagePath); // We need to send 3 messages to the proxy, waiting for responses between each message: // A(length of encoded path),0,(encoded path) @@ -72,14 +72,14 @@ class IosAppRunnerHelper { // c // We expect a '+' for each message sent, followed by a $OK#9a to indicate that everything has worked. // For more info, see http://www.opensource.apple.com/source/lldb/lldb-167.2/docs/lldb-gdb-remote.txt - var socket = new net.Socket(); - var initState = 0; + var socket: net.Socket = new net.Socket(); + var initState: number = 0; var endStatus: number = null; var endSignal: number = null; - var deferred1 = Q.defer(); - var deferred2 = Q.defer(); - var deferred3 = Q.defer(); + var deferred1: Q.Deferred = Q.defer(); + var deferred2: Q.Deferred = Q.defer(); + var deferred3: Q.Deferred = Q.defer(); socket.on("data", function (data: any): void { data = data.toString(); @@ -89,12 +89,12 @@ class IosAppRunnerHelper { socket.write("+"); if (data[1] === "W") { // The app process has exited, with hex status given by data[2-3] - var status = parseInt(data.substring(2, 4), 16); + var status: number = parseInt(data.substring(2, 4), 16); endStatus = status; socket.end(); } else if (data[1] === "X") { // The app rocess exited because of signal given by data[2-3] - var signal = parseInt(data.substring(2, 4), 16); + var signal: number = parseInt(data.substring(2, 4), 16); endSignal = signal; socket.end(); } else if (data.substring(1, 3) === "OK") { @@ -127,7 +127,7 @@ class IosAppRunnerHelper { socket.connect(portNumber, "localhost", function (): void { // set argument 0 to the (encoded) path of the app - var cmd = IosAppRunnerHelper.makeGdbCommand("A" + encodedPath.length + ",0," + encodedPath); + var cmd: string = IosAppRunnerHelper.makeGdbCommand("A" + encodedPath.length + ",0," + encodedPath); initState++; socket.write(cmd); setTimeout(function (): void { @@ -142,7 +142,7 @@ class IosAppRunnerHelper { return deferred1.promise.then(function (sock: net.Socket): Q.Promise { // Set the step and continue thread to any thread - var cmd = IosAppRunnerHelper.makeGdbCommand("Hc0"); + var cmd: string = IosAppRunnerHelper.makeGdbCommand("Hc0"); initState++; sock.write(cmd); setTimeout(function (): void { @@ -155,7 +155,7 @@ class IosAppRunnerHelper { return deferred2.promise; }).then(function (sock: net.Socket): Q.Promise { // Continue execution; actually start the app running. - var cmd = IosAppRunnerHelper.makeGdbCommand("c"); + var cmd: string = IosAppRunnerHelper.makeGdbCommand("c"); initState++; sock.write(cmd); setTimeout(function (): void { @@ -170,9 +170,9 @@ class IosAppRunnerHelper { public static encodePath(packagePath: string): string { // Encode the path by converting each character value to hex - var encodedPath = ""; - for (var i = 0; i < packagePath.length; ++i) { - var c = packagePath[i]; + var encodedPath: string = ""; + for (var i: number = 0; i < packagePath.length; ++i) { + var c: string = packagePath[i]; encodedPath += IosAppRunnerHelper.charToHex(c); } @@ -182,9 +182,9 @@ class IosAppRunnerHelper { private static mountDeveloperImage(): Q.Promise { return IosAppRunnerHelper.getDiskImage() .then(function (path: string): Q.Promise { - var imagemounter = child_process.spawn("ideviceimagemounter", [path]); - var deferred = Q.defer(); - var stdout = ""; + var imagemounter: child_process.ChildProcess = child_process.spawn("ideviceimagemounter", [path]); + var deferred: Q.Deferred = Q.defer(); + var stdout: string = ""; imagemounter.stdout.on("data", function (data: any): void { stdout += data.toString(); }); @@ -207,7 +207,7 @@ class IosAppRunnerHelper { private static getDiskImage(): Q.Promise { // Attempt to find the OS version of the iDevice, e.g. 7.1 - var versionInfo = promiseExec("ideviceinfo -s -k ProductVersion").spread(function (stdout: string, stderr: string): string { + var versionInfo: Q.Promise = promiseExec("ideviceinfo -s -k ProductVersion").spread(function (stdout: string, stderr: string): string { return stdout.trim().substring(0, 3); // Versions for DeveloperDiskImage seem to be X.Y, while some device versions are X.Y.Z // NOTE: This will almost certainly be wrong in the next few years, once we hit version 10.0 }, function (): string { @@ -215,19 +215,19 @@ class IosAppRunnerHelper { }); // Attempt to find the path where developer resources exist. - var pathInfo = promiseExec("xcrun -sdk iphoneos --show-sdk-platform-path").spread(function (stdout: string, stderr: string): string { - var sdkpath = stdout.trim(); + var pathInfo: Q.Promise = promiseExec("xcrun -sdk iphoneos --show-sdk-platform-path").spread(function (stdout: string, stderr: string): string { + var sdkpath: string = stdout.trim(); return sdkpath; }); // Attempt to find the developer disk image for the appropriate return Q.all([versionInfo, pathInfo]).spread(function (version: string, sdkpath: string): Q.Promise { - var find = child_process.spawn("find", [sdkpath, "-path", "*" + version + "*", "-name", "DeveloperDiskImage.dmg"]); - var deferred = Q.defer(); + var find: child_process.ChildProcess = child_process.spawn("find", [sdkpath, "-path", "*" + version + "*", "-name", "DeveloperDiskImage.dmg"]); + var deferred: Q.Deferred = Q.defer(); find.stdout.on("data", function (data: any): void { var dataStr: string = data.toString(); - var path = dataStr.split("\n")[0].trim(); + var path: string = dataStr.split("\n")[0].trim(); if (!path) { deferred.reject("FailedFindDeveloperDiskImage"); } else { @@ -243,8 +243,8 @@ class IosAppRunnerHelper { } private static charToHex(char: string): string { - var conversionTable = "0123456789ABCDEF"; - var charCode = char.charCodeAt(0); + var conversionTable: string = "0123456789ABCDEF"; + var charCode: number = char.charCodeAt(0); /* tslint:disable:no-bitwise */ // We do need some bitwise operations to convert the char to Hex @@ -253,9 +253,9 @@ class IosAppRunnerHelper { } private static makeGdbCommand(command: string): string { - var commandString = "$" + command + "#"; - var stringSum = 0; - for (var i = 0; i < command.length; i++) { + var commandString: string = "$" + command + "#"; + var stringSum: number = 0; + for (var i: number = 0; i < command.length; i++) { stringSum += command.charCodeAt(i); } @@ -263,7 +263,7 @@ class IosAppRunnerHelper { // We need some bitwise operations to calculate the checksum stringSum = stringSum & 0xFF; /* tslint:enable:no-bitwise */ - var checksum = stringSum.toString(16).toUpperCase(); + var checksum: string = stringSum.toString(16).toUpperCase(); if (checksum.length < 2) { checksum = "0" + checksum; } diff --git a/src/taco-remote-lib/ios/iosBuild.ts b/src/taco-remote-lib/ios/iosBuild.ts index 992d5e14..b003982d 100644 --- a/src/taco-remote-lib/ios/iosBuild.ts +++ b/src/taco-remote-lib/ios/iosBuild.ts @@ -32,7 +32,7 @@ import TacoPackageLoader = utils.TacoPackageLoader; import UtilHelper = utils.UtilHelper; process.on("message", function (buildRequest: { buildInfo: BuildInfo; language: string }): void { - var buildInfo = BuildInfo.createNewBuildInfoFromDataObject(buildRequest.buildInfo); + var buildInfo: BuildInfo = BuildInfo.createNewBuildInfoFromDataObject(buildRequest.buildInfo); process.env.TACO_LANG = buildRequest.language; if (IOSBuilder.running) { buildInfo.updateStatus(BuildInfo.ERROR, "BuildInvokedTwice"); @@ -46,7 +46,7 @@ process.on("message", function (buildRequest: { buildInfo: BuildInfo; language: buildInfo.updateStatus(BuildInfo.BUILDING, "AcquiringCordova"); process.send(buildInfo); TacoPackageLoader.lazyRequire("cordova", "cordova@" + cordovaVersion, buildInfo.logLevel).done(function (pkg: Cordova.ICordova): void { - var iosBuilder = new IOSBuilder(buildInfo, pkg); + var iosBuilder: IOSBuilder = new IOSBuilder(buildInfo, pkg); iosBuilder.build().done(function (resultBuildInfo: BuildInfo): void { process.send(resultBuildInfo); @@ -84,14 +84,14 @@ class IOSBuilder extends Builder { } protected package(): Q.Promise { - var deferred = Q.defer(); - var self = this; + var deferred: Q.Deferred = Q.defer(); + var self: IOSBuilder = this; // need quotes around ipa paths for xcrun exec to work if spaces in path - var appDirName = this.cfg.id() + ".app"; - var ipaFileName = this.currentBuild["appName"] + ".ipa"; - var pathToCordovaApp = UtilHelper.quotesAroundIfNecessary(path.join("platforms", "ios", "build", "device", appDirName)); - var fullPathToIpaFile = UtilHelper.quotesAroundIfNecessary(path.join(process.cwd(), "platforms", "ios", "build", "device", ipaFileName)); + var appDirName: string = this.cfg.id() + ".app"; + var ipaFileName: string = this.currentBuild["appName"] + ".ipa"; + var pathToCordovaApp: string = UtilHelper.quotesAroundIfNecessary(path.join("platforms", "ios", "build", "device", appDirName)); + var fullPathToIpaFile: string = UtilHelper.quotesAroundIfNecessary(path.join(process.cwd(), "platforms", "ios", "build", "device", ipaFileName)); child_process.exec("xcrun -v -sdk iphoneos PackageApplication " + pathToCordovaApp + " -o " + fullPathToIpaFile, {}, function (error: Error, stdout: Buffer, stderr: Buffer): void { @@ -100,8 +100,8 @@ class IOSBuilder extends Builder { if (error) { deferred.reject(error); } else { - var plistFileName = self.currentBuild["appName"] + ".plist"; - var fullPathToPlistFile = path.join(process.cwd(), "platforms", "ios", "build", "device", plistFileName); + var plistFileName: string = self.currentBuild["appName"] + ".plist"; + var fullPathToPlistFile: string = path.join(process.cwd(), "platforms", "ios", "build", "device", plistFileName); plist.createEnterprisePlist(self.cfg, fullPathToPlistFile); deferred.resolve({}); } @@ -112,19 +112,19 @@ class IOSBuilder extends Builder { // Public for unit tests public applyPreferencesToBuildConfig(config: CordovaConfig): Q.Promise { - var promise = Q({}); - var self = this; + var promise: Q.Promise = Q({}); + var self: IOSBuilder = this; - var preferences = config.preferences(); + var preferences: { [key: string]: string } = config.preferences(); // Always put the targeted device into the build config. // If a valid overriding device is not given, use 'universal' - var deviceToAdd = "1,2"; + var deviceToAdd: string = "1,2"; var validOverridingTargetDevices: any = {}; validOverridingTargetDevices["handset"] = "1"; validOverridingTargetDevices["tablet"] = "2"; - var targetDevice = preferences["target-device"]; + var targetDevice: string = preferences["target-device"]; if (targetDevice && validOverridingTargetDevices[targetDevice]) { deviceToAdd = validOverridingTargetDevices[targetDevice]; } @@ -133,7 +133,7 @@ class IOSBuilder extends Builder { return self.appendToBuildConfig("TARGETED_DEVICE_FAMILY = " + deviceToAdd); }); - var deploymentTarget = preferences["deployment-target"]; + var deploymentTarget: string = preferences["deployment-target"]; if (deploymentTarget) { promise = promise.then(function (): Q.Promise { return self.appendToBuildConfig("IPHONEOS_DEPLOYMENT_TARGET = " + deploymentTarget); @@ -149,9 +149,9 @@ class IOSBuilder extends Builder { } private appendToBuildConfig(data: string): Q.Promise { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); - var buildConfigDir = path.join("platforms", "ios", "cordova"); + var buildConfigDir: string = path.join("platforms", "ios", "cordova"); if (!fs.existsSync(buildConfigDir)) { deferred.reject(new Error(resources.getString("ErrorXcconfigDirNotFound"))); } else { @@ -168,7 +168,7 @@ class IOSBuilder extends Builder { } private updateAppPlistBuildNumber(): Q.Promise { - var appPlistFile = path.join("platforms", "ios", this.currentBuild["appName"], this.currentBuild["appName"] + "-Info.plist"); + var appPlistFile: string = path.join("platforms", "ios", this.currentBuild["appName"], this.currentBuild["appName"] + "-Info.plist"); plist.updateAppBundleVersion(appPlistFile, this.currentBuild.buildNumber); return Q({}); } @@ -177,13 +177,13 @@ class IOSBuilder extends Builder { // We want to make sure that the .app file is named according to the package Id // in order to avoid issues with unicode names and to allow us to identify which // application to attach to for debugging. - var deferred = Q.defer(); - var isDeviceBuild = this.currentBuild.options === "--device"; - var oldName = path.join("platforms", "ios", "build", isDeviceBuild ? "device" : "emulator", this.currentBuild["appName"] + ".app"); - var newName = path.join("platforms", "ios", "build", isDeviceBuild ? "device" : "emulator", this.cfg.id() + ".app"); + var deferred: Q.Deferred = Q.defer(); + var isDeviceBuild: boolean = this.currentBuild.options === "--device"; + var oldName: string = path.join("platforms", "ios", "build", isDeviceBuild ? "device" : "emulator", this.currentBuild["appName"] + ".app"); + var newName: string = path.join("platforms", "ios", "build", isDeviceBuild ? "device" : "emulator", this.cfg.id() + ".app"); if (oldName !== newName && fs.existsSync(oldName)) { - var clearOldData = Q.defer(); + var clearOldData: Q.Deferred = Q.defer(); if (fs.existsSync(newName)) { rimraf(newName, function (error: Error): void { if (error) { diff --git a/src/taco-remote-lib/ios/iosEmulateHelper.ts b/src/taco-remote-lib/ios/iosEmulateHelper.ts index 43da8b73..e60f77b6 100644 --- a/src/taco-remote-lib/ios/iosEmulateHelper.ts +++ b/src/taco-remote-lib/ios/iosEmulateHelper.ts @@ -61,9 +61,9 @@ class IOSEmulateHelper { } private static cordovaEmulate(emulateRequest: { appDir: string; appName: string; target: string }): Q.Promise<{}> { - var deferred = Q.defer(); - var emulatorAppPath = utils.quotesAroundIfNecessary(path.join(emulateRequest.appDir, "platforms", "ios", "build", "emulator", emulateRequest.appName + ".app")); - var emulatorProcess = utils.loggedExec(util.format("ios-sim launch %s %s --exit", emulatorAppPath, IOSEmulateHelper.iosSimTarget(emulateRequest.target)), {}, function (error: Error, stdout: Buffer, stderr: Buffer): void { + var deferred: Q.Deferred = Q.defer(); + var emulatorAppPath: string = utils.quotesAroundIfNecessary(path.join(emulateRequest.appDir, "platforms", "ios", "build", "emulator", emulateRequest.appName + ".app")); + var emulatorProcess: child_process.ChildProcess = utils.loggedExec(util.format("ios-sim launch %s %s --exit", emulatorAppPath, IOSEmulateHelper.iosSimTarget(emulateRequest.target)), {}, function (error: Error, stdout: Buffer, stderr: Buffer): void { if (error) { deferred.reject(error); } else { @@ -71,7 +71,7 @@ class IOSEmulateHelper { } }); // When run via SSH / without a GUI, ios-sim can hang indefinitely. A cold launch can take on the order of 5 seconds. - var emulatorTimeout = setTimeout(function (): void { + var emulatorTimeout: NodeJS.Timer = setTimeout(function (): void { emulatorProcess.kill(); deferred.reject({ status: "error", messageId: "EmulateFailedTimeout" }); }, 10000); @@ -83,7 +83,7 @@ class IOSEmulateHelper { private static iosSimTarget(emulateRequestTarget: string): string { emulateRequestTarget = emulateRequestTarget.toLowerCase(); - var iosSimTarget = IOSEmulateHelper.IOS_SIMULATOR_TARGETS[emulateRequestTarget] || "--family iphone --retina"; + var iosSimTarget: string = IOSEmulateHelper.IOS_SIMULATOR_TARGETS[emulateRequestTarget] || "--family iphone --retina"; return iosSimTarget; } } diff --git a/src/taco-remote-lib/ios/plist.ts b/src/taco-remote-lib/ios/plist.ts index e3e4cb6a..a1fe7869 100644 --- a/src/taco-remote-lib/ios/plist.ts +++ b/src/taco-remote-lib/ios/plist.ts @@ -19,26 +19,26 @@ import utils = require ("taco-utils"); module Plist { export function updateAppBundleVersion(pathToAppPlist: string, buildNumber: number): void { - var plistInfo = pl.parseFileSync(pathToAppPlist); - var version = plistInfo["CFBundleVersion"]; + var plistInfo: any = pl.parseFileSync(pathToAppPlist); + var version: string = plistInfo["CFBundleVersion"]; version = version ? version + "." + buildNumber : "" + buildNumber; plistInfo["CFBundleVersion"] = version; - var updatedPlistContents = pl.build(plistInfo); + var updatedPlistContents: string = pl.build(plistInfo); updatedPlistContents = updatedPlistContents.replace(/[\s\r\n]*<\/string>/g, ""); fs.writeFileSync(pathToAppPlist, updatedPlistContents, "utf-8"); } export function createEnterprisePlist(cordovaConfigOrPathToConfigXml: any, outFilePath: string): void { - var cfg = cordovaConfigOrPathToConfigXml; + var cfg: TacoUtility.CordovaConfig = cordovaConfigOrPathToConfigXml; if (typeof cordovaConfigOrPathToConfigXml === "string") { cfg = new utils.CordovaConfig(cordovaConfigOrPathToConfigXml); } - var id = cfg.id(); - var version = cfg.version(); - var name = cfg.name(); + var id: string = cfg.id(); + var version: string = cfg.version(); + var name: string = cfg.name(); - var plistContents = getTemplateContents(); + var plistContents: string = getTemplateContents(); plistContents = plistContents.replace("${BUNDLE_IDENTIFIER}", id); plistContents = plistContents.replace("${APPLICATION_VERSION}", version); plistContents = plistContents.replace("${DISPLAY_NAME}", name); @@ -49,7 +49,7 @@ module Plist { function getTemplateContents(): string { if (!templateContents) { - var templatePath = path.join(__dirname, "templates", "EnterpriseApp.plist"); + var templatePath: string = path.join(__dirname, "templates", "EnterpriseApp.plist"); templateContents = utils.UtilHelper.readFileContentsSync(templatePath, "utf-8"); } diff --git a/src/taco-remote-lib/tacoRemoteLib.ts b/src/taco-remote-lib/tacoRemoteLib.ts index 65755a8b..ad05cbb3 100644 --- a/src/taco-remote-lib/tacoRemoteLib.ts +++ b/src/taco-remote-lib/tacoRemoteLib.ts @@ -27,10 +27,10 @@ import resources = require ("./resources/resourceManager"); module TacoRemoteLib { var language: string; var platforms: ITargetPlatform[]; - var initialized = false; + var initialized: boolean = false; - var supportedBuildConfigurations = ["debug", "release"]; - var finalStatuses = [BuildInfo.COMPLETE, BuildInfo.ERROR]; + var supportedBuildConfigurations: string[] = ["debug", "release"]; + var finalStatuses: string[] = [BuildInfo.COMPLETE, BuildInfo.ERROR]; export var locResources: utils.ResourceManager = resources; @@ -182,14 +182,14 @@ module TacoRemoteLib { return; } - var cordovaAppError = validateCordovaApp(buildInfo, buildInfo.appDir); + var cordovaAppError: { id: string, args?: any[] } = validateCordovaApp(buildInfo, buildInfo.appDir); if (cordovaAppError) { buildInfo.updateStatus(BuildInfo.INVALID, cordovaAppError.id, cordovaAppError.args); callback(buildInfo); return; } - var cfg = utils.CordovaConfig.getCordovaConfig(buildInfo.appDir); + var cfg: utils.CordovaConfig = utils.CordovaConfig.getCordovaConfig(buildInfo.appDir); buildInfo["appName"] = cfg.name(); buildInfo.updateStatus(BuildInfo.BUILDING); @@ -198,7 +198,7 @@ module TacoRemoteLib { // have multiple builds in parallel by forking multiple child processes (with some max limit.) var buildProcess: child_process.ChildProcess; buildProcess = platform.createBuildProcess(); - var buildLogger = new ProcessLogger(); + var buildLogger: ProcessLogger = new ProcessLogger(); buildLogger.begin(buildInfo.buildDir, "build.log", buildInfo.buildLang, buildProcess); buildProcess.on("message", function (resultBuildInfo: BuildInfo): void { @@ -226,8 +226,8 @@ module TacoRemoteLib { } try { - var cfg = utils.CordovaConfig.getCordovaConfig(buildInfo.appDir); - var appName = cfg.name(); + var cfg: utils.CordovaConfig = utils.CordovaConfig.getCordovaConfig(buildInfo.appDir); + var appName: string = cfg.name(); if (!utils.UtilHelper.isValidCordovaAppName(appName)) { return { id: "InvalidCordovaAppUnsupportedAppName", args: [appName, utils.UtilHelper.invalidAppNameCharacters()] }; } @@ -243,7 +243,7 @@ module TacoRemoteLib { } function getPlatform(buildInfo: BuildInfo): ITargetPlatform { - for (var i = 0; i < platforms.length; ++i) { + for (var i: number = 0; i < platforms.length; ++i) { var platform: ITargetPlatform = platforms[i]; if (platform.canServiceRequest(buildInfo)) { return platform; diff --git a/src/taco-remote-lib/test/iosAppRunner.ts b/src/taco-remote-lib/test/iosAppRunner.ts index 3964d581..85e5abe8 100644 --- a/src/taco-remote-lib/test/iosAppRunner.ts +++ b/src/taco-remote-lib/test/iosAppRunner.ts @@ -14,7 +14,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import net = require ("net"); @@ -33,16 +33,16 @@ interface IMockDebuggerProxy extends net.Server { describe("Device functionality", function (): void { // Check that when the debugger behaves nicely, we do as well it("should complete the startup sequence when the debugger is well behaved", function (done: MochaDone): void { - var port = 12345; - var appPath = "/private/var/mobile/Applications/042F57CA-9717-4655-8349-532093FFCF44/BlankCordovaApp1.app"; + var port: number = 12345; + var appPath: string = "/private/var/mobile/Applications/042F57CA-9717-4655-8349-532093FFCF44/BlankCordovaApp1.app"; - var encodedAppPath = "2F707269766174652F7661722F6D6F62696C652F4170706C69636174696F6E732F30343246353743412D393731372D343635352D383334392D3533323039334646434634342F426C616E6B436F72646F7661417070312E617070"; + var encodedAppPath: string = "2F707269766174652F7661722F6D6F62696C652F4170706C69636174696F6E732F30343246353743412D393731372D343635352D383334392D3533323039334646434634342F426C616E6B436F72646F7661417070312E617070"; encodedAppPath.should.equal(runner.encodePath(appPath)); var mockDebuggerProxy: IMockDebuggerProxy = net.createServer(function (client: net.Socket): void { mockDebuggerProxy.close(); client.on("data", function (data: Buffer): void { - var dataString = data.toString(); + var dataString: string = data.toString(); if (mockDebuggerProxy.protocolState % 2 === 1) { // Every second message should be an acknowledgement of a send of ours dataString[0].should.equal("+"); @@ -58,15 +58,15 @@ describe("Device functionality", function (): void { switch (mockDebuggerProxy.protocolState) { case 0: expectedResponse = "A" + encodedAppPath.length + ",0," + encodedAppPath; - var checksum = 0; - for (var i = 0; i < expectedResponse.length; ++i) { + var checksum: number = 0; + for (var i: number = 0; i < expectedResponse.length; ++i) { checksum += expectedResponse.charCodeAt(i); }; /* tslint:disable:no-bitwise */ // Some bitwise operations needed to calculate the checksum here checksum = checksum & 0xFF; /* tslint:enable:no-bitwise */ - var checkstring = checksum.toString(16).toUpperCase(); + var checkstring: string = checksum.toString(16).toUpperCase(); if (checkstring.length === 1) { checkstring = "0" + checkstring; } @@ -110,16 +110,16 @@ describe("Device functionality", function (): void { // Check that when the debugger reports an error, we notice it it("should report an error if the debugger fails for some reason", function (done: MochaDone): void { - var port = 12345; - var appPath = "/private/var/mobile/Applications/042F57CA-9717-4655-8349-532093FFCF44/BlankCordovaApp1.app"; + var port: number = 12345; + var appPath: string = "/private/var/mobile/Applications/042F57CA-9717-4655-8349-532093FFCF44/BlankCordovaApp1.app"; - var encodedAppPath = "2F707269766174652F7661722F6D6F62696C652F4170706C69636174696F6E732F30343246353743412D393731372D343635352D383334392D3533323039334646434634342F426C616E6B436F72646F7661417070312E617070"; + var encodedAppPath: string = "2F707269766174652F7661722F6D6F62696C652F4170706C69636174696F6E732F30343246353743412D393731372D343635352D383334392D3533323039334646434634342F426C616E6B436F72646F7661417070312E617070"; encodedAppPath.should.equal(runner.encodePath(appPath)); var mockDebuggerProxy: IMockDebuggerProxy = net.createServer(function (client: net.Socket): void { mockDebuggerProxy.close(); client.on("data", function (data: Buffer): void { - var dataString = data.toString(); + var dataString: string = data.toString(); if (mockDebuggerProxy.protocolState % 2 === 1) { // Every second message should be an acknowledgement of a send of ours dataString[0].should.equal("+"); @@ -136,15 +136,15 @@ describe("Device functionality", function (): void { switch (mockDebuggerProxy.protocolState) { case 0: expectedResponse = "A" + encodedAppPath.length + ",0," + encodedAppPath; - var checksum = 0; - for (var i = 0; i < expectedResponse.length; ++i) { + var checksum: number = 0; + for (var i: number = 0; i < expectedResponse.length; ++i) { checksum += expectedResponse.charCodeAt(i); }; /* tslint:disable:no-bitwise */ // Some bit operations needed to calculate checksum checksum = checksum & 0xFF; /* tslint:enable:no-bitwise */ - var checkstring = checksum.toString(16).toUpperCase(); + var checkstring: string = checksum.toString(16).toUpperCase(); if (checkstring.length === 1) { checkstring = "0" + checkstring; } diff --git a/src/taco-remote-lib/test/plist.ts b/src/taco-remote-lib/test/plist.ts index dfa3ebfc..fc41a0ed 100644 --- a/src/taco-remote-lib/test/plist.ts +++ b/src/taco-remote-lib/test/plist.ts @@ -13,7 +13,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import fs = require ("fs"); @@ -27,7 +27,7 @@ import utils = require ("taco-utils"); import UtilHelper = utils.UtilHelper; describe("plist", function (): void { - var testDir = path.join(os.tmpdir(), "taco-remote-lib", "plist"); + var testDir: string = path.join(os.tmpdir(), "taco-remote-lib", "plist"); before(function (): void { UtilHelper.createDirectoryIfNecessary(path.join(testDir, "plist")); }); @@ -37,21 +37,21 @@ describe("plist", function (): void { }); it("should create plist files correctly", function (): void { - var outFile = path.join(testDir, "plist", "actualEnterpriseApp.plist"); + var outFile: string = path.join(testDir, "plist", "actualEnterpriseApp.plist"); plist.createEnterprisePlist(path.join(__dirname, "resources", "config.xml"), outFile); fs.existsSync(outFile).should.equal(true, "We just created it"); - var expectedContents = UtilHelper.readFileContentsSync(path.join(__dirname, "resources", "plist", "expectedEnterpriseApp.plist")); - var actualContents = UtilHelper.readFileContentsSync(outFile); + var expectedContents: string = UtilHelper.readFileContentsSync(path.join(__dirname, "resources", "plist", "expectedEnterpriseApp.plist")); + var actualContents: string = UtilHelper.readFileContentsSync(outFile); actualContents.should.equal(expectedContents); }); it("should update the App Bundle Version correctly", function (done: MochaDone): void { // make a copy of app.plist in the out directory since the function under test will modify it's contents - var appPlistFile = path.join(testDir, "plist", "cordovaApp.plist"); + var appPlistFile: string = path.join(testDir, "plist", "cordovaApp.plist"); UtilHelper.copyFile(path.join(__dirname, "resources", "plist", "cordovaApp.plist"), appPlistFile).then(function (): void { plist.updateAppBundleVersion(appPlistFile, 1234); // buildNumber 1234 - var expectedContents = UtilHelper.readFileContentsSync(path.join(__dirname, "resources", "plist", "expectedCordovaApp.plist")).replace(/\r\n/g, "\n"); - var actualContents = UtilHelper.readFileContentsSync(appPlistFile).replace(/\r\n/g, "\n"); + var expectedContents: string = UtilHelper.readFileContentsSync(path.join(__dirname, "resources", "plist", "expectedCordovaApp.plist")).replace(/\r\n/g, "\n"); + var actualContents: string = UtilHelper.readFileContentsSync(appPlistFile).replace(/\r\n/g, "\n"); actualContents.should.equal(expectedContents, "We should have updated the build number"); done(); }).done(); diff --git a/src/taco-remote-multiplexer/tacoRemoteMultiplexer.ts b/src/taco-remote-multiplexer/tacoRemoteMultiplexer.ts index 59dfc3b0..c58fb7dc 100644 --- a/src/taco-remote-multiplexer/tacoRemoteMultiplexer.ts +++ b/src/taco-remote-multiplexer/tacoRemoteMultiplexer.ts @@ -25,5 +25,5 @@ class TacoRemoteMultiplexer implements TacoRemoteMultiplexer.ITacoRemoteMultiple } }; -var tacoRemoteMultiplexer = new TacoRemoteMultiplexer(); +var tacoRemoteMultiplexer: TacoRemoteMultiplexer = new TacoRemoteMultiplexer(); export = tacoRemoteMultiplexer; diff --git a/src/taco-remote/lib/buildManager.ts b/src/taco-remote/lib/buildManager.ts index 56f15082..7bc8539b 100644 --- a/src/taco-remote/lib/buildManager.ts +++ b/src/taco-remote/lib/buildManager.ts @@ -61,7 +61,7 @@ class BuildManager { utils.UtilHelper.createDirectoryIfNecessary(this.baseBuildDir); this.maxBuildsInQueue = conf.maxBuildsInQueue; this.deleteBuildsOnShutdown = conf.deleteBuildsOnShutdown; - var allowsEmulate = conf.allowsEmulate; + var allowsEmulate: boolean = conf.allowsEmulate; try { this.requestRedirector = require(conf.get("redirector")); @@ -100,7 +100,7 @@ class BuildManager { this.buildMetrics.submitted++; if (this.queuedBuilds.length === this.maxBuildsInQueue) { - var message = resources.getString("BuildQueueFull", this.maxBuildsInQueue); + var message: string = resources.getString("BuildQueueFull", this.maxBuildsInQueue); var error: any = new Error(message); error.code = 503; throw error; @@ -114,7 +114,7 @@ class BuildManager { var buildPlatform: string = req.query.platform || "ios"; var logLevel: string = req.query.logLevel || null; - var self = this; + var self: BuildManager = this; return this.requestRedirector.getPackageToServeRequest(req).then(function (pkg: TacoRemoteLib.IRemoteLib): Q.Promise { pkg.init(self.serverConf); var errors: string[] = []; @@ -129,7 +129,7 @@ class BuildManager { buildNumber = ++self.nextBuildNumber; } - var buildDir = path.join(self.baseBuildDir, "" + buildNumber); + var buildDir: string = path.join(self.baseBuildDir, "" + buildNumber); if (!fs.existsSync(buildDir)) { fs.mkdirSync(buildDir); } @@ -137,7 +137,7 @@ class BuildManager { Logger.log(resources.getString("BuildManagerDirInit", buildDir)); // Pass the build query to the buildInfo, for package-specific config options - var params = req.query; + var params: any = req.query; params.status = BuildInfo.UPLOADING; params.buildCommand = buildCommand; params.buildPlatform = buildPlatform; @@ -147,14 +147,14 @@ class BuildManager { params.buildNumber = buildNumber; params.options = options; params.logLevel = logLevel; - var buildInfo = new BuildInfo(params); + var buildInfo: BuildInfo = new BuildInfo(params); // Associate the buildInfo object with the package used to service it, but without changing the JSON representation; Object.defineProperty(buildInfo, "pkg", { enumerable: false, writable: true, configurable: true }); buildInfo["pkg"] = pkg; self.builds[buildNumber] = buildInfo; - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); self.saveUploadedTgzFile(buildInfo, req, function (err: any, result: any): void { if (err) { deferred.reject(err); @@ -172,19 +172,19 @@ class BuildManager { } public downloadBuildLog(id: number, offset: number, res: express.Response): void { - var buildInfo = this.builds[id]; + var buildInfo: BuildInfo = this.builds[id]; if (!buildInfo) { res.end(); return; } - var buildLog = path.join(buildInfo.buildDir, "build.log"); + var buildLog: string = path.join(buildInfo.buildDir, "build.log"); if (!fs.existsSync(buildLog)) { res.end(); return; } - var logStream = fs.createReadStream(buildLog, { start: offset }); + var logStream: fs.ReadStream = fs.createReadStream(buildLog, { start: offset }); logStream.on("error", function (err: any): void { Logger.log(resources.getString("LogFileReadError")); Logger.log(err); @@ -204,7 +204,7 @@ class BuildManager { // Downloads the requested build. public downloadBuild(buildInfo: BuildInfo, req: express.Request, res: express.Response): void { - var self = this; + var self: BuildManager = this; if (!buildInfo["pkg"]) { res.status(404).send(resources.getStringForLanguage(req, "MalformedBuildInfo")); return; @@ -264,10 +264,10 @@ class BuildManager { } private saveUploadedTgzFile(buildInfo: BuildInfo, req: express.Request, callback: Function): void { - var self = this; + var self: BuildManager = this; Logger.log(resources.getString("UploadSaving", buildInfo.buildDir)); buildInfo.tgzFilePath = path.join(buildInfo.buildDir, "upload_" + buildInfo.buildNumber + ".tgz"); - var tgzFile = fs.createWriteStream(buildInfo.tgzFilePath); + var tgzFile: fs.WriteStream = fs.createWriteStream(buildInfo.tgzFilePath); req.pipe(tgzFile); tgzFile.on("finish", function (): void { buildInfo.updateStatus(BuildInfo.UPLOADED); @@ -283,8 +283,8 @@ class BuildManager { } private beginBuild(req: express.Request, buildInfo: BuildInfo): void { - var self = this; - var extractToDir = path.join(buildInfo.buildDir, "cordovaApp"); + var self: BuildManager = this; + var extractToDir: string = path.join(buildInfo.buildDir, "cordovaApp"); buildInfo.buildSuccessful = false; buildInfo.appDir = extractToDir; try { @@ -305,7 +305,7 @@ class BuildManager { return; } - var onError = function (err: Error): void { + var onError: (err: Error) => void = function (err: Error): void { buildInfo.updateStatus(BuildInfo.ERROR, resources.getStringForLanguage(req, "TgzExtractError", buildInfo.tgzFilePath, err.message)); Logger.log(resources.getString("TgzExtractError", buildInfo.tgzFilePath, err.message)); self.buildMetrics.failed++; @@ -315,40 +315,40 @@ class BuildManager { // extracting to unix, causing the extract to fail because the directory cannot be navigated. // Also, the tar module does not handle an 'error' event from it's underlying stream, so we have no way of catching errors like an unwritable // directory in the tar gracefully- they cause an uncaughtException and server shutdown. For safety sake we force 'rwx' for all on everything. - var tarFilter = function (who: Fstream.Writer): boolean { + var tarFilter: (who: Fstream.Writer) => boolean = function (who: Fstream.Writer): boolean { who.props.mode = 511; // "chmod 777" // Do not include the /plugins folder - var localPath = path.relative(extractToDir, who.props.path); + var localPath: string = path.relative(extractToDir, who.props.path); return !(localPath.split(path.sep)[0] === "plugins"); }; - var pluginsOnlyFilter = function (who: Fstream.Writer): boolean { + var pluginsOnlyFilter: (who: Fstream.Writer) => boolean = function (who: Fstream.Writer): boolean { who.props.mode = 511; // "chmod 0777" // Here we want to exclusively extract the contents of the /plugins folder, and we will put it in a separate location // Later in taco-remote-lib we will manually merge the plugins into the project to ensure they are added correctly. - var localPath = path.relative(extractToDir, who.props.path); + var localPath: string = path.relative(extractToDir, who.props.path); return !who.props.depth || (who.props.depth === 0 && who.props.Directory) || localPath.split(path.sep)[0] === "plugins"; }; - var extractDeferred = Q.defer(); - var extractPluginDeferred = Q.defer(); + var extractDeferred: Q.Deferred = Q.defer(); + var extractPluginDeferred: Q.Deferred = Q.defer(); // strip: 1 means take the top level directory name off when extracting (we want buildInfo.appDir to be the top level dir.) // TODO: Remove the casting once we've get some complete/up-to-date .d.ts files. See https://github.com/Microsoft/TACO/issues/18 - var tarExtractor = tar.Extract( { path: extractToDir, strip: 1, filter: tarFilter }); + var tarExtractor: tar.ExtractStream = tar.Extract( { path: extractToDir, strip: 1, filter: tarFilter }); tarExtractor.on("end", function (): void { self.removeDeletedFiles(buildInfo); extractDeferred.resolve({}); }); // TODO: Remove the casting once we've get some complete/up-to-date .d.ts files. See https://github.com/Microsoft/TACO/issues/18 - var pluginExtractor = tar.Extract( { path: path.join(extractToDir, "remote"), strip: 1, filter: pluginsOnlyFilter }); + var pluginExtractor: tar.ExtractStream = tar.Extract( { path: path.join(extractToDir, "remote"), strip: 1, filter: pluginsOnlyFilter }); pluginExtractor.on("end", function (): void { extractPluginDeferred.resolve({}); }); - var unzip = zlib.createGunzip(); - var tgzStream = fs.createReadStream(buildInfo.tgzFilePath); + var unzip: zlib.Gunzip = zlib.createGunzip(); + var tgzStream: fs.ReadStream = fs.createReadStream(buildInfo.tgzFilePath); tarExtractor.on("error", onError); pluginExtractor.on("error", onError); unzip.on("error", onError); @@ -365,7 +365,7 @@ class BuildManager { } private removeDeletedFiles(buildInfo: BuildInfo): void { - var changeListFile = path.join(buildInfo.appDir, "changeList.json"); + var changeListFile: string = path.join(buildInfo.appDir, "changeList.json"); if (fs.existsSync(changeListFile)) { buildInfo.changeList = JSON.parse(fs.readFileSync(changeListFile, { encoding: "utf-8" })); if (buildInfo.changeList) { @@ -386,7 +386,7 @@ class BuildManager { // build may change the current working directory to the app dir. To build multiple builds in parallel we will // need to fork out child processes. For now, limiting to one build at a time, and queuing up new builds that come in while a current build is in progress. private build(buildInfo: BuildInfo): void { - var self = this; + var self: BuildManager = this; if (self.currentBuild) { Logger.log(resources.getString("NewBuildQueued", buildInfo.buildNumber)); self.queuedBuilds.push(buildInfo); @@ -430,7 +430,7 @@ class BuildManager { private dequeueNextBuild(): void { Logger.log(resources.getString("BuildMovingOn")); this.currentBuild = null; - var nextBuild = this.queuedBuilds.shift(); + var nextBuild: BuildInfo = this.queuedBuilds.shift(); if (nextBuild) { this.build(nextBuild); } diff --git a/src/taco-remote/lib/buildRetention.ts b/src/taco-remote/lib/buildRetention.ts index e4c32a87..7d13deda 100644 --- a/src/taco-remote/lib/buildRetention.ts +++ b/src/taco-remote/lib/buildRetention.ts @@ -27,9 +27,9 @@ class BuildRetention { } private static deleteBuilds(builds: { [idx: string]: utils.BuildInfo }, toDelete: string[], sync?: boolean): void { - for (var i = 0; i < toDelete.length; ++i) { - var idx = toDelete[i]; - var buildInfo = builds[idx]; + for (var i: number = 0; i < toDelete.length; ++i) { + var idx: string = toDelete[i]; + var buildInfo: utils.BuildInfo = builds[idx]; Logger.log(resources.getString("BuildRetentionDelete", buildInfo.buildNumber, buildInfo.buildDir)); if (sync) { rimraf.sync(buildInfo.buildDir); @@ -50,16 +50,16 @@ class BuildRetention { } public purge(builds: { [idx: string]: utils.BuildInfo }): void { - var buildNumbers = Object.keys(builds); - var nBuildsToDelete = buildNumbers.length - this.maxBuildsToKeep; + var buildNumbers: string[] = Object.keys(builds); + var nBuildsToDelete: number = buildNumbers.length - this.maxBuildsToKeep; if (nBuildsToDelete <= 0) { return; } // eligible builds do not include those queued up or currently building. var eligibleBuilds: utils.BuildInfo[] = []; - for (var i = 0; i < buildNumbers.length; i++) { - var buildInfo = builds[buildNumbers[i]]; + for (var i: number = 0; i < buildNumbers.length; i++) { + var buildInfo: utils.BuildInfo = builds[buildNumbers[i]]; if (buildInfo.status === utils.BuildInfo.COMPLETE || buildInfo.status === utils.BuildInfo.DOWNLOADED || buildInfo.status === utils.BuildInfo.ERROR || buildInfo.status === utils.BuildInfo.EMULATED || buildInfo.status === utils.BuildInfo.INVALID) { @@ -68,14 +68,14 @@ class BuildRetention { }; // sort eligible builds by oldest first, then delete required number eligibleBuilds.sort(function (b1: utils.BuildInfo, b2: utils.BuildInfo): number { - var diff = b1.submissionTime - b2.submissionTime; + var diff: number = b1.submissionTime - b2.submissionTime; return (diff === 0) ? 0 : (diff > 0 ? +1 : -1); }); if (nBuildsToDelete > eligibleBuilds.length) { nBuildsToDelete = eligibleBuilds.length; } - var numbersToDelete = eligibleBuilds.slice(0, nBuildsToDelete).map(function (b: utils.BuildInfo): string { + var numbersToDelete: string[] = eligibleBuilds.slice(0, nBuildsToDelete).map(function (b: utils.BuildInfo): string { return b.buildNumber.toString(); }); Logger.log(resources.getString("BuildRetentionPreDelete", nBuildsToDelete)); @@ -83,7 +83,7 @@ class BuildRetention { } public deleteAllSync(builds: { [idx: string]: utils.BuildInfo }): void { - var buildNumbers = Object.keys(builds); + var buildNumbers: string[] = Object.keys(builds); BuildRetention.deleteBuilds(builds, buildNumbers, true); } } diff --git a/src/taco-remote/lib/darwin/darwinDependenciesHelper.ts b/src/taco-remote/lib/darwin/darwinDependenciesHelper.ts index 515258cc..9a822f3f 100644 --- a/src/taco-remote/lib/darwin/darwinDependenciesHelper.ts +++ b/src/taco-remote/lib/darwin/darwinDependenciesHelper.ts @@ -27,16 +27,16 @@ import UtilHelper = tacoUtils.UtilHelper; class DarwinDependenciesHelper { public static askInstallHomebrew(): Q.Promise { - var firstRunPath = path.join(UtilHelper.tacoHome, ".taco-remote"); - var isFirstRun = !fs.existsSync(firstRunPath); - var deferred = Q.defer(); + var firstRunPath: string = path.join(UtilHelper.tacoHome, ".taco-remote"); + var isFirstRun: boolean = !fs.existsSync(firstRunPath); + var deferred: Q.Deferred = Q.defer(); if (isFirstRun) { Logger.log(resources.getString("FirstRunDependencyConfiguration")); - var readlineInterface = readline.createInterface({ input: process.stdin, output: process.stdout }); - var deferred2 = Q.defer(); + var readlineInterface: readline.ReadLine = readline.createInterface({ input: process.stdin, output: process.stdout }); + var deferred2: Q.Deferred = Q.defer(); readlineInterface.question(resources.getString("HomebrewInstallationQuery"), function (response: string): void { readlineInterface.close(); - var shouldInstall = response === "" || response.trim().toLowerCase().indexOf(resources.getString("HomebrewInstallationQueryResponse")) === 0; + var shouldInstall: boolean = response === "" || response.trim().toLowerCase().indexOf(resources.getString("HomebrewInstallationQueryResponse")) === 0; if (shouldInstall) { DarwinDependenciesHelper.tryInstallHomebrew().then(DarwinDependenciesHelper.tryInstallPackages).then(function (): void { @@ -74,10 +74,10 @@ class DarwinDependenciesHelper { } private static tryInstallHomebrew(): Q.Promise { - var homebrewInstalled = Q.defer(); + var homebrewInstalled: Q.Deferred = Q.defer(); // We use spawn here rather than exec primarily so we can allow for user-interaction - var curlInstaller = child_process.spawn("curl", ["-fsSL", "https://raw.githubusercontent.com/Homebrew/install/master/install"]); - var installHomebrew = child_process.spawn("ruby", ["-"]); + var curlInstaller: child_process.ChildProcess = child_process.spawn("curl", ["-fsSL", "https://raw.githubusercontent.com/Homebrew/install/master/install"]); + var installHomebrew: child_process.ChildProcess = child_process.spawn("ruby", ["-"]); curlInstaller.stdout.on("data", function (data: any): void { installHomebrew.stdin.write(data); diff --git a/src/taco-remote/lib/requestRedirector.ts b/src/taco-remote/lib/requestRedirector.ts index c404a2ea..c80e2d46 100644 --- a/src/taco-remote/lib/requestRedirector.ts +++ b/src/taco-remote/lib/requestRedirector.ts @@ -25,8 +25,8 @@ import TacoErrorCode = tacoUtility.TacoErrorCode; import TacoPackageLoader = tacoUtility.TacoPackageLoader; import ITacoRemoteMultiplexer = TacoRemoteMultiplexer.ITacoRemoteMultiplexer; -var dynamicDependenciesLocation = path.join(__dirname, "../dynamicDependencies.json"); -var tacoRemoteMux = "taco-remote-multiplexer"; +var dynamicDependenciesLocation: string = path.join(__dirname, "../dynamicDependencies.json"); +var tacoRemoteMux: string = "taco-remote-multiplexer"; class RequestRedirector implements TacoRemoteLib.IRequestRedirector { public getPackageToServeRequest(req: Express.Request): Q.Promise { diff --git a/src/taco-remote/lib/selftest.ts b/src/taco-remote/lib/selftest.ts index 2e86298a..a643d1fd 100644 --- a/src/taco-remote/lib/selftest.ts +++ b/src/taco-remote/lib/selftest.ts @@ -45,11 +45,11 @@ class SelfTest { * @return a promise which is resolved if the build succeeded, or rejected if the build failed. */ public static test(host: string, modMountPoint: string, downloadDir: string, deviceBuild: boolean, agent: https.Agent): Q.Promise { - var vcordova = "4.3.0"; - var tempFolder = path.join(os.tmpdir(), "taco-remote", "selftest"); + var vcordova: string = "4.3.0"; + var tempFolder: string = path.join(os.tmpdir(), "taco-remote", "selftest"); rimraf.sync(tempFolder); utils.createDirectoryIfNecessary(tempFolder); - var cordovaApp = path.join(tempFolder, "helloCordova"); + var cordovaApp: string = path.join(tempFolder, "helloCordova"); return TacoPackageLoader.lazyRequire("cordova", "cordova@" + vcordova).then(function (cordova: typeof Cordova): Q.Promise { return cordova.raw.create(cordovaApp); @@ -58,19 +58,19 @@ class SelfTest { throw err; }).then(function (): Q.Promise { var pingInterval: number = 5000; - var maxPings = 10; - var vcli = require("../package.json").version; - var cfg = "debug"; - var buildOptions = deviceBuild ? "--device" : "--emulator"; + var maxPings: number = 10; + var vcli: string = require("../package.json").version; + var cfg: string = "debug"; + var buildOptions: string = deviceBuild ? "--device" : "--emulator"; var tgzProducingStream: NodeJS.ReadableStream = null; // TODO: Remove the casting once we've get some complete/up-to-date .d.ts files. See https://github.com/Microsoft/TACO/issues/18 - var cordovaAppDirReader = new fstream.Reader( { path: cordovaApp, type: "Directory", filter: SelfTest.filterForTar }); + var cordovaAppDirReader: fstream.Reader = new fstream.Reader( { path: cordovaApp, type: "Directory", filter: SelfTest.filterForTar }); tgzProducingStream = cordovaAppDirReader.pipe(tar.Pack()).pipe(zlib.createGzip()); - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); - var buildUrl = util.format("%s/%s/build/tasks/?vcordova=%s&vcli=%s&cfg=%s&command=build&options=%s", host, modMountPoint, vcordova, vcli, cfg, buildOptions); + var buildUrl: string = util.format("%s/%s/build/tasks/?vcordova=%s&vcli=%s&cfg=%s&command=build&options=%s", host, modMountPoint, vcordova, vcli, cfg, buildOptions); // TODO: Remove the casting once we've get some complete/up-to-date .d.ts files. See https://github.com/Microsoft/TACO/issues/18 tgzProducingStream.pipe(request.post( { url: buildUrl, agent: agent }, function (submitError: any, submitResponse: any, submitBody: any): void { if (submitError) { @@ -78,14 +78,14 @@ class SelfTest { return; } - var buildingUrl = submitResponse.headers["content-location"]; + var buildingUrl: string = submitResponse.headers["content-location"]; if (!buildingUrl) { deferred.reject(new Error(submitBody)); return; } - var i = 0; - var ping = setInterval(function (): void { + var i: number = 0; + var ping: NodeJS.Timer = setInterval(function (): void { i++; Logger.log(util.format("%d...", i)); // TODO: Remove the casting once we've get some complete/up-to-date .d.ts files. See https://github.com/Microsoft/TACO/issues/18 @@ -95,7 +95,7 @@ class SelfTest { deferred.reject(statusError); } - var build = JSON.parse(statusBody); + var build: any = JSON.parse(statusBody); if (build["status"] === BuildInfo.ERROR || build["status"] === BuildInfo.DOWNLOADED || build["status"] === BuildInfo.INVALID) { clearInterval(ping); deferred.reject(new Error("Build Failed: " + statusBody)); @@ -103,10 +103,10 @@ class SelfTest { clearInterval(ping); if (deviceBuild) { - var downloadUrl = util.format("%s/%s/build/%d/download", host, modMountPoint, build["buildNumber"]); - var buildNumber = build["buildNumber"]; - var downloadFile = path.join(downloadDir, "build_" + buildNumber + "_download.zip"); - var writeStream = fs.createWriteStream(downloadFile); + var downloadUrl: string = util.format("%s/%s/build/%d/download", host, modMountPoint, build["buildNumber"]); + var buildNumber: any = build["buildNumber"]; + var downloadFile: string = path.join(downloadDir, "build_" + buildNumber + "_download.zip"); + var writeStream: fs.WriteStream = fs.createWriteStream(downloadFile); writeStream.on("error", function (err: Error): void { deferred.reject(err); }); diff --git a/src/taco-remote/lib/server.ts b/src/taco-remote/lib/server.ts index ed97eca8..897c5a4a 100644 --- a/src/taco-remote/lib/server.ts +++ b/src/taco-remote/lib/server.ts @@ -36,33 +36,33 @@ import Logger = utils.Logger; class ServerModuleFactory implements RemoteBuild.IServerModuleFactory { public create(conf: RemoteBuild.IRemoteBuildConfiguration, modConfig: RemoteBuild.IServerModuleConfiguration, serverCapabilities: RemoteBuild.IServerCapabilities): Q.Promise { - var tacoRemoteConf = new TacoRemoteConfig(conf, modConfig); + var tacoRemoteConf: TacoRemoteConfig = new TacoRemoteConfig(conf, modConfig); return HostSpecifics.hostSpecifics.initialize(tacoRemoteConf).then(function (): RemoteBuild.IServerModule { return new Server(tacoRemoteConf, modConfig.mountPath); }); } public test(conf: RemoteBuild.IRemoteBuildConfiguration, modConfig: RemoteBuild.IServerModuleConfiguration, serverTestCapabilities: RemoteBuild.IServerTestCapabilities, cliArguments: string[]): Q.Promise { - var host = util.format("http%s://%s:%d", utils.ArgsHelper.argToBool(conf.secure) ? "s" : "", conf.hostname || os.hostname, conf.port); - var downloadDir = path.join(conf.serverDir, "selftest", "taco-remote"); + var host: string = util.format("http%s://%s:%d", utils.ArgsHelper.argToBool(conf.secure) ? "s" : "", conf.hostname || os.hostname, conf.port); + var downloadDir: string = path.join(conf.serverDir, "selftest", "taco-remote"); utils.UtilHelper.createDirectoryIfNecessary(downloadDir); return selftest.test(host, modConfig.mountPath, downloadDir, cliArguments.indexOf("--device") !== -1, serverTestCapabilities.agent); } public printHelp(conf: RemoteBuild.IRemoteBuildConfiguration, modConfig: RemoteBuild.IServerModuleConfiguration): void { - var tacoRemoteConf = new TacoRemoteConfig(conf, modConfig); - var resources = new utils.ResourceManager(path.join(__dirname, "..", "resources"), conf.lang); + var tacoRemoteConf: TacoRemoteConfig = new TacoRemoteConfig(conf, modConfig); + var resources: utils.ResourceManager = new utils.ResourceManager(path.join(__dirname, "..", "resources"), conf.lang); var help: Help = new Help(); help.run({ options: {}, original: ["taco-remote"], remain: ["taco-remote"] }).done(); } public getConfig(conf: RemoteBuild.IRemoteBuildConfiguration, modConfig: RemoteBuild.IServerModuleConfiguration): RemoteBuild.IServerModuleConfiguration { - var tacoRemoteConf = new TacoRemoteConfig(conf, modConfig); + var tacoRemoteConf: TacoRemoteConfig = new TacoRemoteConfig(conf, modConfig); return tacoRemoteConf.serialize(); } } -var serverModuleFactory = new ServerModuleFactory(); +var serverModuleFactory: ServerModuleFactory = new ServerModuleFactory(); export = serverModuleFactory; class Server implements RemoteBuild.IServerModule { @@ -81,7 +81,7 @@ class Server implements RemoteBuild.IServerModule { } public getRouter(): express.Router { - var router = express.Router(); + var router: express.Router = express.Router(); router.post("/build/tasks", this.submitNewBuild.bind(this)); router.get("/build/tasks/:id", this.getBuildStatus.bind(this)); router.get("/build/tasks/:id/log", this.getBuildLog.bind(this)); @@ -106,11 +106,11 @@ class Server implements RemoteBuild.IServerModule { // Submits a new build task private submitNewBuild(req: express.Request, res: express.Response): void { - var port = this.serverConf.port; - var modPath = this.modPath; - var self = this; + var port: number = this.serverConf.port; + var modPath: string = this.modPath; + var self: Server = this; this.buildManager.submitNewBuild(req).then(function (buildInfo: utils.BuildInfo): void { - var contentLocation = util.format("%s://%s:%d/%s/build/tasks/%d", req.protocol, req.hostname, port, modPath, buildInfo.buildNumber); + var contentLocation: string = util.format("%s://%s:%d/%s/build/tasks/%d", req.protocol, req.hostname, port, modPath, buildInfo.buildNumber); res.set({ "Content-Type": "application/json", "Content-Location": contentLocation @@ -128,7 +128,7 @@ class Server implements RemoteBuild.IServerModule { // Queries on the status of a build task, used by a client to poll private getBuildStatus(req: express.Request, res: express.Response): void { - var buildInfo = this.buildManager.getBuildInfo(req.params.id); + var buildInfo: utils.BuildInfo = this.buildManager.getBuildInfo(req.params.id); if (buildInfo) { buildInfo.localize(req, this.resources); if (!buildInfo.message) { @@ -144,7 +144,7 @@ class Server implements RemoteBuild.IServerModule { // Retrieves log file for a build task, can be used by a client when build failed private getBuildLog(req: express.Request, res: express.Response): void { - var buildInfo = this.buildManager.getBuildInfo(req.params.id); + var buildInfo: utils.BuildInfo = this.buildManager.getBuildInfo(req.params.id); if (buildInfo) { res.set("Content-Type", "text/plain"); this.buildManager.downloadBuildLog(req.params.id, parseInt(req.query.offset, 10) || 0, res); @@ -155,14 +155,14 @@ class Server implements RemoteBuild.IServerModule { // Queries on the status of all build tasks private getAllBuildStatus(req: express.Request, res: express.Response): void { - var allBuildInfo = this.buildManager.getAllBuildInfo(); + var allBuildInfo: TacoRemote.IServerInfo = this.buildManager.getAllBuildInfo(); res.status(200).json(allBuildInfo); } private checkBuildThenAction(func: (buildInfo: utils.BuildInfo, req: express.Request, res: express.Response) => void): (req: express.Request, res: express.Response) => void { - var self = this; + var self: Server = this; return function (req: express.Request, res: express.Response): void { - var buildInfo = self.buildManager.getBuildInfo(req.params.id); + var buildInfo: utils.BuildInfo = self.buildManager.getBuildInfo(req.params.id); if (!buildInfo) { res.status(404).send(self.resources.getStringForLanguage(req, "BuildNotFound", req.params.id)); return; diff --git a/src/taco-remote/lib/tacoRemoteConfig.ts b/src/taco-remote/lib/tacoRemoteConfig.ts index 2115cc92..ddcab99a 100644 --- a/src/taco-remote/lib/tacoRemoteConfig.ts +++ b/src/taco-remote/lib/tacoRemoteConfig.ts @@ -49,8 +49,8 @@ class TacoRemoteConfig implements RemoteBuild.IReadOnlyDictionary { deleteBuildsOnShutdown: true, allowsEmulate: true }; - var hostDefaults = HostSpecifics.hostSpecifics.defaults(defaults); - var self = this; + var hostDefaults: { [key: string]: any } = HostSpecifics.hostSpecifics.defaults(defaults); + var self: TacoRemoteConfig = this; Object.keys(hostDefaults).forEach(function (key: string): void { if (typeof (self.tacoRemoteConf[key]) === "undefined") { self.tacoRemoteConf[key] = hostDefaults[key]; @@ -140,7 +140,7 @@ class TacoRemoteConfig implements RemoteBuild.IReadOnlyDictionary { } public serialize(): RemoteBuild.IServerModuleConfiguration { - var confCopy = JSON.parse(JSON.stringify(this.tacoRemoteConf)); + var confCopy: any = JSON.parse(JSON.stringify(this.tacoRemoteConf)); // These three properties are taken from the root config, and are not individually configurable. Remove them when saving. delete confCopy.lang; delete confCopy.port; diff --git a/src/taco-remote/test/build.ts b/src/taco-remote/test/build.ts index 885f9117..66852b21 100644 --- a/src/taco-remote/test/build.ts +++ b/src/taco-remote/test/build.ts @@ -15,28 +15,28 @@ import TacoUtils = require ("taco-utils"); import UtilHelper = TacoUtils.UtilHelper; -var macOnlyIt = os.platform() === "darwin" ? it : it.skip; +var macOnlyIt: (expectation: string, assertion?: (mocha? : MochaDone) => void) => void = os.platform() === "darwin" ? it : it.skip; describe("taco-remote", function(): void { var server: http.Server; var serverMod: RemoteBuild.IServerModule; - var serverDir = path.join(os.tmpdir(), "taco-remote", "build"); - var downloadDir = path.join(serverDir, "selftest"); - var modMountPoint = "Test"; + var serverDir: string = path.join(os.tmpdir(), "taco-remote", "build"); + var downloadDir: string = path.join(serverDir, "selftest"); + var modMountPoint: string = "Test"; before(function(mocha: MochaDone): void { process.env["TACO_UNIT_TEST"] = true; process.env["TACO_HOME"] = serverDir; rimraf.sync(UtilHelper.tacoHome); UtilHelper.createDirectoryIfNecessary(UtilHelper.tacoHome); - var firstRunPath = path.join(UtilHelper.tacoHome, ".taco-remote"); + var firstRunPath: string = path.join(UtilHelper.tacoHome, ".taco-remote"); fs.writeFileSync(firstRunPath, ""); // Just need the file to exist so the test doesn't try to ask us about installing homebrew - var app = express(); + var app: express.Express = express(); app.use(expressLogger("dev")); UtilHelper.createDirectoryIfNecessary(serverDir); UtilHelper.createDirectoryIfNecessary(downloadDir); - var serverConfig = { + var serverConfig: any = { serverDir: serverDir, port: 3000, secure: false, diff --git a/src/taco-utils/buildInfo.ts b/src/taco-utils/buildInfo.ts index 2ba6e2ff..f5f7ecda 100644 --- a/src/taco-utils/buildInfo.ts +++ b/src/taco-utils/buildInfo.ts @@ -15,18 +15,18 @@ import InstallLogLevel = installLogLevel.InstallLogLevel; module TacoUtility { export class BuildInfo { - public static UPLOADING = "Uploading"; - public static UPLOADED = "Uploaded"; - public static EXTRACTED = "Extracted"; - public static INVALID = "Invalid"; - public static BUILDING = "Building"; - public static COMPLETE = "Complete"; - public static EMULATED = "Emulated"; - public static RUNNING = "Running"; - public static INSTALLED = "Installed"; - public static DEBUGGING = "Debugging"; - public static DOWNLOADED = "Downloaded"; - public static ERROR = "Error"; + public static UPLOADING: string = "Uploading"; + public static UPLOADED: string = "Uploaded"; + public static EXTRACTED: string = "Extracted"; + public static INVALID: string = "Invalid"; + public static BUILDING: string = "Building"; + public static COMPLETE: string = "Complete"; + public static EMULATED: string = "Emulated"; + public static RUNNING: string = "Running"; + public static INSTALLED: string = "Installed"; + public static DEBUGGING: string = "Debugging"; + public static DOWNLOADED: string = "Downloaded"; + public static ERROR: string = "Error"; public status: string; /** @@ -63,7 +63,7 @@ module TacoUtility { public logLevel: InstallLogLevel; constructor(params: { buildNumber?: number; status?: string; buildCommand?: string; configuration?: string; options?: any; buildDir?: string; buildLang?: string; buildPlatform?: string; logLevel?: string; [index: string]: any }) { - var self = this; + var self: BuildInfo = this; Object.keys(params).forEach(function (key: string): void { self[key] = params[key]; }); diff --git a/src/taco-utils/commands.ts b/src/taco-utils/commands.ts index 6ba13eec..d010c2fd 100644 --- a/src/taco-utils/commands.ts +++ b/src/taco-utils/commands.ts @@ -82,13 +82,13 @@ module TacoUtility { * Parse the arguments using overridden parseArgs, and then select the most appropriate subcommand to run */ public run(data: ICommandData): Q.Promise { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); this.data = this.parseArgs(data.original); // Determine which subcommand we are executing this.executedSubcommand = this.getSubCommand(this.data); if (this.executedSubcommand) { - return this.executedSubcommand.run(this.data).then(telemetryProperties => { + return this.executedSubcommand.run(this.data).then((telemetryProperties: telemetryHelper.ICommandTelemetryProperties) => { telemetryProperties["subCommand"] = telemetryHelper.TelemetryHelper.telemetryProperty(this.executedSubcommand.name, /*isPii*/ false); return telemetryProperties; }); @@ -100,8 +100,8 @@ module TacoUtility { } private getSubCommand(options: ICommandData): ICommand { - for (var i = 0; i < this.subcommands.length; ++i) { - var subCommand = this.subcommands[i]; + for (var i: number = 0; i < this.subcommands.length; ++i) { + var subCommand: ICommand = this.subcommands[i]; if (subCommand.canHandleArgs(options)) { return subCommand; } @@ -142,7 +142,7 @@ module TacoUtility { var moduleInfo: ICommandInfo = this.listings[name]; if (!moduleInfo) { // Check if {name} is a command alias - var commandForAlias = this.aliases ? this.aliases[name] : null; + var commandForAlias: string = this.aliases ? this.aliases[name] : null; if (commandForAlias) { moduleInfo = this.listings[commandForAlias]; } else { @@ -150,7 +150,7 @@ module TacoUtility { } } - var modulePath = path.join(commandsModulePath, moduleInfo.modulePath); + var modulePath: string = path.join(commandsModulePath, moduleInfo.modulePath); if (!fs.existsSync(modulePath + ".js")) { throw errorHelper.get(TacoErrorCodes.TacoUtilsExceptionMissingcommand, name); } diff --git a/src/taco-utils/cordovaConfig.ts b/src/taco-utils/cordovaConfig.ts index 33e51ef4..85a0d7da 100644 --- a/src/taco-utils/cordovaConfig.ts +++ b/src/taco-utils/cordovaConfig.ts @@ -15,7 +15,7 @@ import fs = require ("fs"); import path = require ("path"); /* tslint:disable:no-var-requires */ -var unorm = require ("unorm"); // Note no import: the compiler will remove the require since we don't use the unorm object, we just need it to add String.normalize +var unorm: any = require ("unorm"); // Note no import: the compiler will remove the require since we don't use the unorm object, we just need it to add String.normalize /* tslint:enable:no-var-requires */ import tacoUtility = require ("./utilHelper"); @@ -27,7 +27,7 @@ module TacoUtility { private doc: et.ElementTree; constructor(configXmlPath: string) { - var contents = UtilHelper.readFileContentsSync(configXmlPath, "utf-8"); + var contents: string = UtilHelper.readFileContentsSync(configXmlPath, "utf-8"); this.doc = new et.ElementTree(et.XML(contents)); } @@ -53,7 +53,7 @@ module TacoUtility { * @returns {String} The display name, normalized to NFC */ public name(): string { - var el = this.doc.find("name"); + var el: et.XMLElement = this.doc.find("name"); return el && el.text && el.text.trim().normalize(); } @@ -63,7 +63,7 @@ module TacoUtility { * @returns {string} The version */ public version(): string { - var el = this.doc.getroot(); + var el: et.XMLElement = this.doc.getroot(); return el && el.attrib && el.attrib["version"]; } @@ -74,7 +74,7 @@ module TacoUtility { */ public preferences(): { [key: string]: string } { var data: { [key: string]: string } = {}; - var preferences = this.doc.findall("preference"); + var preferences: et.XMLElement[] = this.doc.findall("preference"); preferences.forEach(function (preference: et.XMLElement): void { data[preference.attrib["name"]] = preference.attrib["value"]; }); diff --git a/src/taco-utils/countStream.ts b/src/taco-utils/countStream.ts index 9b23523d..4f1eac35 100644 --- a/src/taco-utils/countStream.ts +++ b/src/taco-utils/countStream.ts @@ -32,7 +32,7 @@ module TacoUtility { } public static count(originalStream: NodeJS.ReadableStream, callback: { (length: number): void }): NodeJS.ReadableStream { - var countedStream = originalStream.pipe(new CountStream()); + var countedStream: CountStream = originalStream.pipe(new CountStream()); countedStream.on("end", () => callback(countedStream.count)); return countedStream; } diff --git a/src/taco-utils/helpCommandBase.ts b/src/taco-utils/helpCommandBase.ts index 253918e8..ea9b47c2 100644 --- a/src/taco-utils/helpCommandBase.ts +++ b/src/taco-utils/helpCommandBase.ts @@ -97,7 +97,7 @@ module TacoUtility { var nameDescriptionPairs: INameDescription[] = new Array(); var listings: any = this.commandsFactory.listings; - Object.keys(listings).forEach(function(i: string) { + Object.keys(listings).forEach(function(i: string): void { nameDescriptionPairs.push({ name: i, description: listings[i].description, category: listings[i].categoryTitle }); }); @@ -128,7 +128,7 @@ module TacoUtility { this.printCommandHeader(this.cliName, command, list.synopsis, list.description); var optionsLeftIndent: string = LoggerHelper.repeat(" ", HelpCommandBase.OPTIONS_INDENT); if (args) { - args.forEach(arg => { + args.forEach((arg: any) => { // Push the arg first argList.push({ name: arg.name, @@ -136,7 +136,7 @@ module TacoUtility { }); if (arg.options) { var options: INameDescription[] = arg.options; - options.forEach(nvp => { + options.forEach((nvp: INameDescription) => { nvp.name = optionsLeftIndent + nvp.name; argList.push({ name: nvp.name, @@ -154,7 +154,7 @@ module TacoUtility { var longestArgsLength: number = LoggerHelper.getLongestNameLength(list.args); var longestOptionsLength: number = LoggerHelper.getLongestNameLength(list.options); var longestKeyLength: number = Math.max(longestArgsLength, longestOptionsLength + LoggerHelper.DEFAULT_INDENT); - var indent2 = LoggerHelper.getDescriptionColumnIndent(longestKeyLength); + var indent2: number = LoggerHelper.getDescriptionColumnIndent(longestKeyLength); if (list.args) { Logger.log(resources.getString("CommandHelpUsageParameters")); @@ -176,7 +176,7 @@ module TacoUtility { } private printCommandTable(nameDescriptionPairs: INameDescription[], indent1?: number, indent2?: number): void { - for (var i = 0; i < nameDescriptionPairs.length; i++) { + for (var i: number = 0; i < nameDescriptionPairs.length; i++) { nameDescriptionPairs[i].description = this.getResourceString(nameDescriptionPairs[i].description); if (nameDescriptionPairs[i].category) { nameDescriptionPairs[i].category = util.format("%s", this.getResourceString(nameDescriptionPairs[i].category)); @@ -191,7 +191,7 @@ module TacoUtility { Logger.log(resources.getString("CommandHelpUsageExamples")); var indent: string = LoggerHelper.repeat(" ", LoggerHelper.DEFAULT_INDENT); var indent2: string = LoggerHelper.repeat(" ", 2 * LoggerHelper.DEFAULT_INDENT); - for (var i = 0; i < examples.length; i++) { + for (var i: number = 0; i < examples.length; i++) { Logger.log(util.format("%s%s %s", indent, HelpCommandBase.DEFAULT_BULLET, this.getResourceString(examples[i].description))); Logger.logLine(); if (typeof examples[i].example === "string") { @@ -209,7 +209,7 @@ module TacoUtility { if (notes) { Logger.log(resources.getString("CommandHelpUsageNotes")); var indent: string = LoggerHelper.repeat(" ", LoggerHelper.DEFAULT_INDENT); - for (var i = 0; i < notes.length; i++) { + for (var i: number = 0; i < notes.length; i++) { var bullet: string = (notes.length > 1) ? (i + 1) + "." : HelpCommandBase.DEFAULT_BULLET; Logger.log(util.format("%s%s %s", indent, bullet, this.getResourceString(notes[i]))); Logger.logLine(); @@ -232,7 +232,7 @@ module TacoUtility { private printAliasTable(commandAliases: ICommandAlias[]): void { var leftIndent: string = LoggerHelper.repeat(" ", LoggerHelper.DEFAULT_INDENT); - commandAliases.forEach(cmdAliasPair => { + commandAliases.forEach((cmdAliasPair: ICommandAlias) => { Logger.log(util.format("%s%s %s %s", leftIndent, cmdAliasPair.alias, "->", cmdAliasPair.command)); }); } diff --git a/src/taco-utils/jsonSerializer.ts b/src/taco-utils/jsonSerializer.ts index cbd6050e..7f41840b 100644 --- a/src/taco-utils/jsonSerializer.ts +++ b/src/taco-utils/jsonSerializer.ts @@ -78,7 +78,7 @@ module TacoUtility { */ private getIndentedJsonForArrayValues(arr: Array, indent: string): string { var items: string[] = []; - for (var i = 0; i < arr.length; i++) { + for (var i: number = 0; i < arr.length; i++) { items.push(this.getIndentedJson(arr[i], indent)); } @@ -92,7 +92,7 @@ module TacoUtility { var keyValuePairs: string[] = []; var keys: string[] = Object.keys(obj); - for (var i = 0; i < keys.length; i++) { + for (var i: number = 0; i < keys.length; i++) { keyValuePairs.push(JsonSerializer.stringifyKvp(keys[i], this.getIndentedJson(obj[keys[i]], indent))); } @@ -116,7 +116,7 @@ module TacoUtility { var keyValuePairs: string[] = []; var currentLength: number = indent.length + 4; // +4 for curly braces and spaces around "{ %s }" - for (var i = 0; i < keys.length; i++) { + for (var i: number = 0; i < keys.length; i++) { var valueType: string = typeof obj[keys[i]]; // Nested object, not minifiable if (valueType === "object") { diff --git a/src/taco-utils/logFormatHelper.ts b/src/taco-utils/logFormatHelper.ts index aa969166..ea47b133 100644 --- a/src/taco-utils/logFormatHelper.ts +++ b/src/taco-utils/logFormatHelper.ts @@ -12,7 +12,7 @@ import assert = require ("assert"); /* tslint:disable:no-var-requires */ // Special case to allow using color package with index signature for style rules -var colors = require("colors/safe"); +var colors: any = require("colors/safe"); /* tslint:enable:no-var-requires */ import os = require ("os"); import util = require ("util"); @@ -127,7 +127,7 @@ module TacoUtility { } public static isFormattedString(msg: string): boolean { - var regex = new RegExp(LogFormatHelper.TAG_REGEX, "gm"); + var regex: RegExp = new RegExp(LogFormatHelper.TAG_REGEX, "gm"); return regex.test(msg); } @@ -141,7 +141,7 @@ module TacoUtility { private static forEachTagMatch(msg: string, callback: (tag: string, isStartTag: boolean, tagStartIndex: number, tagEndIndex: number) => void): void { // regex to match again all start/end tags strictly without spaces - var regex = new RegExp(LogFormatHelper.TAG_REGEX, "gm"); + var regex: RegExp = new RegExp(LogFormatHelper.TAG_REGEX, "gm"); // iterate over all start/end tags , // push start tags on stack and remove start tags when end tags are encountered diff --git a/src/taco-utils/loggerHelper.ts b/src/taco-utils/loggerHelper.ts index 2bf7ba92..a67e1bb1 100644 --- a/src/taco-utils/loggerHelper.ts +++ b/src/taco-utils/loggerHelper.ts @@ -125,11 +125,11 @@ module TacoUtility { indent1 = indent1 || LoggerHelper.DEFAULT_INDENT; } - var indentationString = this.repeat(" ", indent1); - var longestNameLength = this.longestValueLength(nameDescriptionPairs, e => e.name); - var longestDescriptionLength = this.longestValueLength(nameDescriptionPairs, e => e.description); - var totalSeparatorLength = LoggerHelper.getDescriptionColumnIndent(longestNameLength, indent1) + longestDescriptionLength - indent1; // ("\t\t" + Name + ....) + Description - "\t\t" - var sectionsSeparator = indentationString + LoggerHelper.repeat("-", totalSeparatorLength); + var indentationString: string = this.repeat(" ", indent1); + var longestNameLength: number = this.longestValueLength(nameDescriptionPairs, (e: INameDescription) => e.name); + var longestDescriptionLength: number = this.longestValueLength(nameDescriptionPairs, (e: INameDescription) => e.description); + var totalSeparatorLength: number = LoggerHelper.getDescriptionColumnIndent(longestNameLength, indent1) + longestDescriptionLength - indent1; // ("\t\t" + Name + ....) + Description - "\t\t" + var sectionsSeparator: string = indentationString + LoggerHelper.repeat("-", totalSeparatorLength); Logger.log(sectionsSeparator); LoggerHelper.logNameDescriptionTable(nameDescriptionPairs, indent1); Logger.log(sectionsSeparator); @@ -148,7 +148,7 @@ module TacoUtility { indent2 = indent2 || LoggerHelper.MINIMUM_RIGHT_INDENT; var leftIndent: string = LogFormatHelper.repeat(" ", indent1); - var keyLength = LogFormatHelper.getFormattedStringLength(key); + var keyLength: number = LogFormatHelper.getFormattedStringLength(key); var dots: string = LogFormatHelper.repeat(dotsCharacter, indent2 - indent1 - keyLength - 2); // -2, for spaces around "..." value = LoggerHelper.wordWrapString(value, indent2, LoggerHelper.maxRight); @@ -219,7 +219,7 @@ module TacoUtility { * Logs an array of strings with proper indentation and a fixed bullet (*) (This is a list, in the sense of an HTML
list) */ public static logList(listElements: string[]): void { - listElements.forEach(element => Logger.log(" * " + element)); + listElements.forEach((element: string) => Logger.log(" * " + element)); } /** @@ -228,7 +228,7 @@ module TacoUtility { * @param {propertyGetter} lambda function to extract the property we want to measure the length, from each element */ private static longestValueLength(list: T[], propertyGetter: { (element: T): string }): number { - var propertyValuesLength = list.map(propertyGetter).map(str => LogFormatHelper.getFormattedStringLength(str)); + var propertyValuesLength: number[] = list.map(propertyGetter).map((str: string) => LogFormatHelper.getFormattedStringLength(str)); return Math.max.apply(null, propertyValuesLength); } diff --git a/src/taco-utils/newlineNormalizerStream.ts b/src/taco-utils/newlineNormalizerStream.ts index 7e51396e..e8245778 100644 --- a/src/taco-utils/newlineNormalizerStream.ts +++ b/src/taco-utils/newlineNormalizerStream.ts @@ -22,9 +22,9 @@ module TacoUtility { export class NewlineNormalizerStream extends Transform { public _transform(chunk: any, encoding: string, callback: (err: Error, buf: string) => void): void { // Standardize all line endings first - var scrubbedInput = chunk.toString().replace(/\r\n/g, "\n"); + var scrubbedInput: string = chunk.toString().replace(/\r\n/g, "\n"); // Then convert to the OS dependent newline - var output = scrubbedInput.replace(/\n/g, os.EOL); + var output: string = scrubbedInput.replace(/\n/g, os.EOL); callback(null, output); } diff --git a/src/taco-utils/processLogger.ts b/src/taco-utils/processLogger.ts index f16c5131..db03cce7 100644 --- a/src/taco-utils/processLogger.ts +++ b/src/taco-utils/processLogger.ts @@ -36,12 +36,12 @@ module TacoUtility { * @param {ChildProcess} proc The process to log */ public begin(logDir: string, logFileName: string, language: string, proc: child_process.ChildProcess): void { - var pathToLog = path.join(logDir, logFileName); + var pathToLog: string = path.join(logDir, logFileName); this.stream = fs.createWriteStream(pathToLog); this.stream.on("error", function (err: any): void { Logger.logError(resources.getStringForLanguage(language, "ProcessLogError", pathToLog, err)); }); - var me = this; + var me: ProcessLogger = this; proc.stdout.on("data", function (data: any): void { me.log(data); }); diff --git a/src/taco-utils/resourceManager.ts b/src/taco-utils/resourceManager.ts index ab5c199b..f9f582bd 100644 --- a/src/taco-utils/resourceManager.ts +++ b/src/taco-utils/resourceManager.ts @@ -77,7 +77,7 @@ module TacoUtility { return locale; } - var parentLocale = locale.split("-")[0]; + var parentLocale: string = locale.split("-")[0]; if (availableLocales.indexOf(parentLocale) !== -1) { // Match on primary language (e.g. it from it-CH). We may find a better match later, so continue looking. bestLocale = parentLocale; @@ -92,8 +92,8 @@ module TacoUtility { } public getString(id: string, ...optionalArgs: any[]): string { - var args = ArgsHelper.getOptionalArgsArrayFromFunctionCall(arguments, 1); - var result = this.getStringForLocale(this.bestLanguageMatch(this.getCurrentLocale()), id, args); + var args: string[] = ArgsHelper.getOptionalArgsArrayFromFunctionCall(arguments, 1); + var result: string = this.getStringForLocale(this.bestLanguageMatch(this.getCurrentLocale()), id, args); if (result && process.env["TACO_UNIT_TEST"]) { // Mock out resources for consistency in unit tests, but only if they exist @@ -104,8 +104,8 @@ module TacoUtility { } public getStringForLanguage(requestOrAcceptLangs: any, id: string, ...optionalArgs: any[]): string { - var args = ArgsHelper.getOptionalArgsArrayFromFunctionCall(arguments, 2); - var result = this.getStringForLocale(this.bestLanguageMatch(requestOrAcceptLangs), id, args); + var args: string[] = ArgsHelper.getOptionalArgsArrayFromFunctionCall(arguments, 2); + var result: string = this.getStringForLocale(this.bestLanguageMatch(requestOrAcceptLangs), id, args); if (result && process.env["TACO_UNIT_TEST"]) { // Mock out resources for consistency in unit tests, but only if they exist @@ -119,7 +119,7 @@ module TacoUtility { var resourceSet: ResourceSet = this.getOrCreateResourceSet(locale); assert.notEqual(resourceSet, null, "We should get a non-null resource set"); - var args = ArgsHelper.getOptionalArgsArrayFromFunctionCall(arguments, 2); + var args: string[] = ArgsHelper.getOptionalArgsArrayFromFunctionCall(arguments, 2); return resourceSet.getString(id, args); } @@ -160,7 +160,7 @@ module TacoUtility { private getAvailableLocales(): string[] { if (!this.availableLocales) { this.availableLocales = []; - var self = this; + var self: ResourceManager = this; fs.readdirSync(this.resourceDirectory).forEach(function (filename: string): void { try { if (fs.existsSync(ResourceManager.getResourceFilePath(self.resourceDirectory, filename))) { diff --git a/src/taco-utils/resourceSet.ts b/src/taco-utils/resourceSet.ts index 7fb6694d..c38f993d 100644 --- a/src/taco-utils/resourceSet.ts +++ b/src/taco-utils/resourceSet.ts @@ -19,23 +19,23 @@ module TacoUtility { private resources: { [key: string]: any; } = {}; constructor(resourceFileName: string) { - var self = this; - var res = require(resourceFileName); + var self: ResourceSet = this; + var res: any = require(resourceFileName); Object.keys(res).forEach(function (key: string): void { self.resources[key] = res[key]; }); } public getString(id: string, ...optionalArgs: any[]): string { - var s = this.resources[id]; + var s: any = this.resources[id]; if (!s) { return s; } else if (Array.isArray(s)) { // Allow longer resources strings to be specified as a list of strings, which represent multiple lines - s = s.join("\n"); + s = ( s).join("\n"); } - var result: string = s; + var result: string = s; /*All args passed to current function: you can call getString('foo', 'bar', 'baz') or getString('foo',['bar', 'baz']) and the utility function will extract ['bar', 'baz'] as args in both cases*/ diff --git a/src/taco-utils/tacoPackageLoader.ts b/src/taco-utils/tacoPackageLoader.ts index f1105093..61c8af94 100644 --- a/src/taco-utils/tacoPackageLoader.ts +++ b/src/taco-utils/tacoPackageLoader.ts @@ -173,8 +173,8 @@ module TacoUtility { var updateRequested: boolean = (Date.now() - lastCheckTimestamp) > request.expirationIntervalInHours * 60 * 60 * 1000; if (updateRequested) { - var targetPath = request.targetPath; - var backupPath = request.targetPath + "_backup"; + var targetPath: string = request.targetPath; + var backupPath: string = request.targetPath + "_backup"; try { if (fs.existsSync(backupPath)) { rimraf.sync(backupPath); @@ -248,7 +248,7 @@ module TacoUtility { } } - var homePackageModulesPath = path.join(utils.tacoHome, "node_modules", packageName); + var homePackageModulesPath: string = path.join(utils.tacoHome, "node_modules", packageName); switch (packageType) { case PackageSpecType.Registry: var versionSubFolder: string = packageId.split("@")[1] || "latest"; @@ -308,8 +308,8 @@ module TacoUtility { args = args.concat(flags); } - var npmExecutable = process.platform === "win32" ? "npm.cmd" : "npm"; - var npmProcess = child_process.spawn(npmExecutable, args, { cwd: cwd, stdio: "inherit" }); + var npmExecutable: string = process.platform === "win32" ? "npm.cmd" : "npm"; + var npmProcess: child_process.ChildProcess = child_process.spawn(npmExecutable, args, { cwd: cwd, stdio: "inherit" }); npmProcess.on("error", function (error: Error): void { deferred.reject(error); }); @@ -351,7 +351,7 @@ module TacoUtility { } // 243 is the error code reported when npm fails due to EACCES - var errorCode = (err === 243) ? TacoErrorCodes.PackageLoaderNpmInstallFailedEaccess : TacoErrorCodes.PackageLoaderNpmInstallFailedWithCode; + var errorCode: TacoErrorCodes = (err === 243) ? TacoErrorCodes.PackageLoaderNpmInstallFailedEaccess : TacoErrorCodes.PackageLoaderNpmInstallFailedWithCode; deferred.reject(errorHelper.get(errorCode, request.packageName, err)); } else { deferred.reject(errorHelper.wrap(TacoErrorCodes.PackageLoaderNpmInstallErrorMessage, err, request.packageName)); @@ -370,7 +370,7 @@ module TacoUtility { rimraf(targetPath, function (): void { if (isFinite(err)) { // error code reported when npm fails due to EACCES - var errorCode = (err === 243) ? TacoErrorCodes.PackageLoaderNpmUpdateFailedEaccess : TacoErrorCodes.PackageLoaderNpmUpdateFailedWithCode; + var errorCode: TacoErrorCodes = (err === 243) ? TacoErrorCodes.PackageLoaderNpmUpdateFailedEaccess : TacoErrorCodes.PackageLoaderNpmUpdateFailedWithCode; deferred.reject(errorHelper.get(errorCode, packageName, err)); } else { deferred.reject(errorHelper.wrap(TacoErrorCodes.PackageLoaderNpmUpdateErrorMessage, err, packageName)); @@ -410,12 +410,12 @@ module TacoUtility { } private static removeStatusFile(targetPath: string): Q.Promise { - var statusFilePath = TacoPackageLoader.getStatusFilePath(targetPath); + var statusFilePath: string = TacoPackageLoader.getStatusFilePath(targetPath); return Q.denodeify(fs.unlink)(statusFilePath); } private static packageNeedsInstall(targetPath: string): boolean { - var statusFilePath = TacoPackageLoader.getStatusFilePath(targetPath); + var statusFilePath: string = TacoPackageLoader.getStatusFilePath(targetPath); // if package.json doesn't exist or status file is still lingering around // it is an invalid installation return !fs.existsSync(path.join(targetPath, "package.json")) || fs.existsSync(statusFilePath); diff --git a/src/taco-utils/tacoUtils.ts b/src/taco-utils/tacoUtils.ts index 3b112e98..75097150 100644 --- a/src/taco-utils/tacoUtils.ts +++ b/src/taco-utils/tacoUtils.ts @@ -34,29 +34,29 @@ module TacoUtility { /* tslint:disable:variable-name */ // We mostly export classes here from taco-utils and we prefer keeping them pascal cased // put more classes here, known limitation that classes in external modules CANNOT span multiple files - export var ArgsHelper = argsHelper.ArgsHelper; - export var BuildInfo = buildInfo.BuildInfo; - export var Commands = commands.Commands; - export var CordovaConfig = cordovaConfig.CordovaConfig; - export var CountStream = countStream.CountStream; - export var Logger = logger.Logger; - export var LoggerHelper = loggerHelper.LoggerHelper; - export var LogLevel = logLevel.LogLevel; - export var NewlineNormalizerStream = newlineNormalizerStream.NewlineNormalizerStream; - export var HelpCommandBase = helpCommandBase.HelpCommandBase; - export var InstallLogLevel = installLogLevel.InstallLogLevel; - export var JsonSerializer = jsonSerializer.JsonSerializer; - export var ProcessLogger = processLogger.ProcessLogger; - export var ResourceManager = resourceManager.ResourceManager; - export var TacoError = tacoError.TacoError; - export var TacoErrorCode = tacoErrorCodes.TacoErrorCode; - export var TacoGlobalConfig = tacoGlobalConfig.TacoGlobalConfig; - export var TacoPackageLoader = tacoPackageLoader.TacoPackageLoader; - export var TelemetryGenerator = telemetryHelper.TelemetryGenerator; - export var Telemetry = telemetry.Telemetry; - export var TelemetryHelper = telemetryHelper.TelemetryHelper; - export var UtilHelper = utilHelper.UtilHelper; - export var LogFormatHelper = logFormatHelper.LogFormatHelper; + export var ArgsHelper: any = argsHelper.ArgsHelper; + export var BuildInfo: any = buildInfo.BuildInfo; + export var Commands: any = commands.Commands; + export var CordovaConfig: any = cordovaConfig.CordovaConfig; + export var CountStream: any = countStream.CountStream; + export var Logger: any = logger.Logger; + export var LoggerHelper: any = loggerHelper.LoggerHelper; + export var LogLevel: any = logLevel.LogLevel; + export var NewlineNormalizerStream: any = newlineNormalizerStream.NewlineNormalizerStream; + export var HelpCommandBase: any = helpCommandBase.HelpCommandBase; + export var InstallLogLevel: any = installLogLevel.InstallLogLevel; + export var JsonSerializer: any = jsonSerializer.JsonSerializer; + export var ProcessLogger: any = processLogger.ProcessLogger; + export var ResourceManager: any = resourceManager.ResourceManager; + export var TacoError: any = tacoError.TacoError; + export var TacoErrorCode: any = tacoErrorCodes.TacoErrorCode; + export var TacoGlobalConfig: any = tacoGlobalConfig.TacoGlobalConfig; + export var TacoPackageLoader: any = tacoPackageLoader.TacoPackageLoader; + export var TelemetryGenerator: any = telemetryHelper.TelemetryGenerator; + export var Telemetry: any = telemetry.Telemetry; + export var TelemetryHelper: any = telemetryHelper.TelemetryHelper; + export var UtilHelper: any = utilHelper.UtilHelper; + export var LogFormatHelper: any = logFormatHelper.LogFormatHelper; /* tslint:enable:variable-name */ } diff --git a/src/taco-utils/telemetry.ts b/src/taco-utils/telemetry.ts index 09c09713..80e60362 100644 --- a/src/taco-utils/telemetry.ts +++ b/src/taco-utils/telemetry.ts @@ -51,7 +51,7 @@ module TacoUtility { * TelemetryEvent represents a basic telemetry data point */ export class TelemetryEvent { - private static PII_HASH_KEY = "959069c9-9e93-4fa1-bf16-3f8120d7db0c"; + private static PII_HASH_KEY: string = "959069c9-9e93-4fa1-bf16-3f8120d7db0c"; public name: string; public properties: ITelemetryProperties; private eventId: string; @@ -64,8 +64,8 @@ module TacoUtility { } public setPiiProperty(name: string, value: string): void { - var hmac = crypto.createHmac("sha256", new Buffer(TelemetryEvent.PII_HASH_KEY, "utf8")); - var hashedValue = hmac.update(value).digest("hex"); + var hmac: any = crypto.createHmac("sha256", new Buffer(TelemetryEvent.PII_HASH_KEY, "utf8")); + var hashedValue: any = hmac.update(value).digest("hex"); this.properties[name] = hashedValue; @@ -135,7 +135,7 @@ module TacoUtility { } export function sendPendingData(): Q.Promise { - var defer = Q.defer(); + var defer: Q.Deferred = Q.defer(); appInsights.client.sendPendingData((result: string) => defer.resolve(result)); return defer.promise; } @@ -157,7 +157,7 @@ module TacoUtility { logger.logLine(); logger.log(utilResources.getString(currentOptIn ? "TelemetryOptInYes" : "TelemetryOptInNo", Telemetry.appName)); - var promptStringId = currentOptIn ? "TelemetryCurrentlyOptedInPrompt" : "TelemetryCurrentlyOptedOutPrompt"; + var promptStringId: string = currentOptIn ? "TelemetryCurrentlyOptedInPrompt" : "TelemetryCurrentlyOptedOutPrompt"; newOptIn = TelemetryUtils.getUserConsentForTelemetry(utilResources.getString(promptStringId, Telemetry.appName)); @@ -183,8 +183,8 @@ module TacoUtility { } class TelemetryUtils { - public static USERTYPE_INTERNAL = "Internal"; - public static USERTYPE_EXTERNAL = "External"; + public static USERTYPE_INTERNAL: string = "Internal"; + public static USERTYPE_EXTERNAL: string = "External"; public static userType: string; public static sessionId: string; public static optInCollectedForCurrentSession: boolean; @@ -192,14 +192,14 @@ module TacoUtility { private static userId: string; private static machineId: string; private static telemetrySettings: ITelemetrySettings = null; - private static TELEMETRY_SETTINGS_FILENAME = "TelemetrySettings.json"; - private static APPINSIGHTS_INSTRUMENTATIONKEY = "10baf391-c2e3-4651-a726-e9b25d8470fd"; - private static REGISTRY_USERID_KEY = "HKCU\\SOFTWARE\\Microsoft\\SQMClient"; - private static REGISTRY_USERID_VALUE = "UserId"; - private static REGISTRY_MACHINEID_KEY = "HKLM\\SOFTWARE\\Microsoft\\SQMClient"; - private static REGISTRY_MACHINEID_VALUE = "MachineId"; - private static INTERNAL_DOMAIN_SUFFIX = "microsoft.com"; - private static INTERNAL_USER_ENV_VAR = "TACOINTERNAL"; + private static TELEMETRY_SETTINGS_FILENAME: string = "TelemetrySettings.json"; + private static APPINSIGHTS_INSTRUMENTATIONKEY: string = "10baf391-c2e3-4651-a726-e9b25d8470fd"; + private static REGISTRY_USERID_KEY: string = "HKCU\\SOFTWARE\\Microsoft\\SQMClient"; + private static REGISTRY_USERID_VALUE: string = "UserId"; + private static REGISTRY_MACHINEID_KEY: string = "HKLM\\SOFTWARE\\Microsoft\\SQMClient"; + private static REGISTRY_MACHINEID_VALUE: string = "MachineId"; + private static INTERNAL_DOMAIN_SUFFIX: string = "microsoft.com"; + private static INTERNAL_USER_ENV_VAR: string = "TACOINTERNAL"; private static get telemetrySettingsFile(): string { return path.join(UtilHelper.tacoHome, TelemetryUtils.TELEMETRY_SETTINGS_FILENAME); @@ -249,18 +249,18 @@ module TacoUtility { } public static generateGuid(): string { - var hexValues = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]; + var hexValues: string[] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]; // c.f. rfc4122 (UUID version 4 = xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx) - var oct = ""; + var oct: string = ""; var tmp: number; /* tslint:disable:no-bitwise */ - for (var a = 0; a < 4; a++) { + for (var a: number = 0; a < 4; a++) { tmp = (4294967296 * Math.random()) | 0; oct += hexValues[tmp & 0xF] + hexValues[tmp >> 4 & 0xF] + hexValues[tmp >> 8 & 0xF] + hexValues[tmp >> 12 & 0xF] + hexValues[tmp >> 16 & 0xF] + hexValues[tmp >> 20 & 0xF] + hexValues[tmp >> 24 & 0xF] + hexValues[tmp >> 28 & 0xF]; } // "Set the two most significant bits (bits 6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively" - var clockSequenceHi = hexValues[8 + (Math.random() * 4) | 0]; + var clockSequenceHi: string = hexValues[8 + (Math.random() * 4) | 0]; return oct.substr(0, 8) + "-" + oct.substr(9, 4) + "-4" + oct.substr(13, 3) + "-" + clockSequenceHi + oct.substr(16, 3) + "-" + oct.substr(19, 12); /* tslint:enable:no-bitwise */ } @@ -282,7 +282,7 @@ module TacoUtility { public static getUserConsentForTelemetry(optinMessage: string = ""): boolean { logger.logLine(); - var readlineSync = require("readline-sync"); + var readlineSync: any = require("readline-sync"); return !!readlineSync.keyInYNStrict(LogFormatHelper.toFormattedString(optinMessage)); } @@ -321,9 +321,9 @@ module TacoUtility { private static getRegistryValue(key: string, value: string): string { // TODO: Task 1186340:TACO cli telemetry: Update to use winreg package instead of windows-no-runnable - var windows = require("windows-no-runnable"); + var windows: any = require("windows-no-runnable"); try { - var regKey = windows.registry(key); + var regKey: {[key: string]: {value: string}} = windows.registry(key); if (regKey && regKey[value] && regKey[value].value) { return regKey[value].value; } @@ -367,9 +367,9 @@ module TacoUtility { private static getMacAddress(): string { var macAddress: string = ""; - var interfaces = os.networkInterfaces(); + var interfaces: any = os.networkInterfaces(); Object.keys(interfaces).some((key: string) => { - var mac = interfaces[key][0]["mac"]; + var mac: string = interfaces[key][0]["mac"]; if (mac && mac !== "00:00:00:00:00:00") { macAddress = mac; diff --git a/src/taco-utils/telemetryHelper.ts b/src/taco-utils/telemetryHelper.ts index 0071325d..5c273ae8 100644 --- a/src/taco-utils/telemetryHelper.ts +++ b/src/taco-utils/telemetryHelper.ts @@ -78,7 +78,7 @@ module TacoUtility { public addError(error: Error): TelemetryGenerator { this.add("error.message" + ++this.errorIndex, error, /*isPii*/ true); - var errorWithErrorCode = error; + var errorWithErrorCode: IHasErrorCode = error; if (errorWithErrorCode.errorCode) { this.add("error.code" + this.errorIndex, errorWithErrorCode.errorCode, /*isPii*/ false); } @@ -87,7 +87,7 @@ module TacoUtility { } public time(name: string, codeToMeasure: { (): T }): T { - var startTime = process.hrtime(); + var startTime: number[] = process.hrtime(); return executeAfter(codeToMeasure(), () => this.finishTime(name, startTime), (reason: any) => { @@ -118,20 +118,20 @@ module TacoUtility { private sendCurrentStep(): void { this.add("step", this.currentStep, /*isPii*/ false); - var telemetryEvent = new Telemetry.TelemetryEvent(Telemetry.appName + "/" + this.componentName); + var telemetryEvent: Telemetry.TelemetryEvent = new Telemetry.TelemetryEvent(Telemetry.appName + "/" + this.componentName); TelemetryHelper.addTelemetryEventProperties(telemetryEvent, this.telemetryProperties); Telemetry.send(telemetryEvent); } private addArray(baseName: string, array: any[], piiEvaluator: { (value: string, name: string): boolean }): void { // Object is an array, we add each element as baseNameNNN - var elementIndex = 1; // We send telemetry properties in a one-based index + var elementIndex: number = 1; // We send telemetry properties in a one-based index array.forEach((element: any) => this.addWithPiiEvaluator(baseName + elementIndex++, element, piiEvaluator)); } private addHash(baseName: string, hash: IDictionary, piiEvaluator: { (value: string, name: string): boolean }): void { // Object is a hash, we add each element as baseName.KEY - Object.keys(hash).forEach(key => this.addWithPiiEvaluator(baseName + "." + key, hash[key], piiEvaluator)); + Object.keys(hash).forEach((key: string) => this.addWithPiiEvaluator(baseName + "." + key, hash[key], piiEvaluator)); } private addString(name: string, value: string, piiEvaluator: { (value: string, name: string): boolean }): void { @@ -139,12 +139,12 @@ module TacoUtility { } private combine(...components: string[]): string { - var nonNullComponents = components.filter(component => !_.isNull(component)); + var nonNullComponents: string[] = components.filter((component: string) => !_.isNull(component)); return nonNullComponents.join("."); } private finishTime(name: string, startTime: number[]): void { - var endTime = process.hrtime(startTime); + var endTime: number[] = process.hrtime(startTime); this.add(this.combine(name, "time"), String(endTime[0] * 1000 + endTime[1] / 1000000), /*isPii*/ false); } } @@ -155,7 +155,7 @@ module TacoUtility { * It also supports attaching a fail callback in case it's a promise */ function executeAfter(valueOrPromise: T, afterCallback: { (): void }, failCallback: { (reason: any): void } = (reason: any) => Q.reject(reason)): T { - var valueAsPromise = > valueOrPromise; + var valueAsPromise: Q.Promise = > valueOrPromise; if (_.isObject(valueAsPromise) && _.isFunction(valueAsPromise.finally)) { // valueOrPromise must be a promise. We'll add the callback as a finally handler return valueAsPromise.finally(afterCallback).fail(failCallback); @@ -182,7 +182,7 @@ module TacoUtility { } public static sendCommandFailureTelemetry(commandName: string, error: any, projectProperties: ICommandTelemetryProperties, args: string[] = null): void { - var errorEvent = TelemetryHelper.createBasicCommandTelemetry(commandName, args); + var errorEvent: Telemetry.TelemetryEvent = TelemetryHelper.createBasicCommandTelemetry(commandName, args); if (error.isTacoError) { errorEvent.properties["tacoErrorCode"] = error.errorCode; @@ -196,7 +196,7 @@ module TacoUtility { } public static sendCommandSuccessTelemetry(commandName: string, commandProperties: ICommandTelemetryProperties, args: string[] = null): void { - var successEvent = TelemetryHelper.createBasicCommandTelemetry(commandName, args); + var successEvent: Telemetry.TelemetryEvent = TelemetryHelper.createBasicCommandTelemetry(commandName, args); TelemetryHelper.addTelemetryEventProperties(successEvent, commandProperties); @@ -204,7 +204,7 @@ module TacoUtility { } public static sanitizeTargetStringPropertyInfo(targetString: string): ITelemetryPropertyInfo { - var propertyInfo = { value: targetString, isPii: false }; + var propertyInfo: any = { value: targetString, isPii: false }; if (packageLoader.TacoPackageLoader.GIT_URI_REGEX.test(targetString) || packageLoader.TacoPackageLoader.FILE_URI_REGEX.test(targetString)) { propertyInfo.isPii = true; @@ -226,9 +226,9 @@ module TacoUtility { public static addPropertiesFromOptions(telemetryProperties: ICommandTelemetryProperties, knownOptions: Nopt.CommandData, commandOptions: { [flag: string]: any }, nonPiiOptions: string[] = []): ICommandTelemetryProperties { // We parse only the known options, to avoid potential private information that may appear on the command line - var unknownOptionIndex = 1; - Object.keys(commandOptions).forEach(key => { - var value = commandOptions[key]; + var unknownOptionIndex: number = 1; + Object.keys(commandOptions).forEach((key: string) => { + var value: any = commandOptions[key]; if (Object.keys(knownOptions).indexOf(key) >= 0) { // This is a known option. We'll check the list to decide if it's pii or not if (typeof (value) !== "undefined") { @@ -245,12 +245,12 @@ module TacoUtility { } public static generate(name: string, codeGeneratingTelemetry: { (telemetry: TelemetryGenerator): T }): T { - var generator = new TelemetryGenerator(name); + var generator: TelemetryGenerator = new TelemetryGenerator(name); return executeAfter(generator.time(null, () => codeGeneratingTelemetry(generator)), () => generator.send()); } private static createBasicCommandTelemetry(commandName: string, args: string[] = null): Telemetry.TelemetryEvent { - var commandEvent = new Telemetry.TelemetryEvent(Telemetry.appName + "/" + (commandName || "command")); + var commandEvent: Telemetry.TelemetryEvent = new Telemetry.TelemetryEvent(Telemetry.appName + "/" + (commandName || "command")); if (!commandName && args && args.length > 0) { commandEvent.setPiiProperty("command", args[0]); @@ -272,7 +272,7 @@ module TacoUtility { } private static addMultiValuedTelemetryEventProperty(event: Telemetry.TelemetryEvent, propertyName: string, propertyValue: string, isPii: boolean): void { - for (var i = 0; i < propertyValue.length; i++) { + for (var i: number = 0; i < propertyValue.length; i++) { TelemetryHelper.setTelemetryEventProperty(event, propertyName + i, propertyValue[i], isPii); } } diff --git a/src/taco-utils/test/cordovaConfig.ts b/src/taco-utils/test/cordovaConfig.ts index ebb69ebf..ca2f335f 100644 --- a/src/taco-utils/test/cordovaConfig.ts +++ b/src/taco-utils/test/cordovaConfig.ts @@ -8,6 +8,8 @@ "use strict"; /// /// +/// + import fs = require ("fs"); import mocha = require ("mocha"); import path = require ("path"); @@ -19,14 +21,14 @@ import CordovaConfig = util.CordovaConfig; describe("CordovaConfig", function (): void { it("should correctly parse config files", function (): void { - var cfg = new CordovaConfig(path.join(__dirname, "resources", "config.xml")); + var cfg: TacoUtility.CordovaConfig = new CordovaConfig(path.join(__dirname, "resources", "config.xml")); cfg.id().should.equal("org.foo.bar"); cfg.name().should.equal("FooBar"); cfg.version().should.equal("0.9.2"); }); it("should correctly normalize unicode display names", function (): void { - var cfg = new CordovaConfig(path.join(__dirname, "resources", "config_unicode.xml")); + var cfg: TacoUtility.CordovaConfig = new CordovaConfig(path.join(__dirname, "resources", "config_unicode.xml")); cfg.name().should.equal("隣兀﨩"); // Note that this is NOT identical to the name in config_unicode, it is the normalized form. }); }); diff --git a/src/taco-utils/test/packageLoader.ts b/src/taco-utils/test/packageLoader.ts index 3f9492d2..6009700a 100644 --- a/src/taco-utils/test/packageLoader.ts +++ b/src/taco-utils/test/packageLoader.ts @@ -23,7 +23,7 @@ import utils = require ("../tacoPackageLoader"); import TacoPackageLoader = utils.TacoPackageLoader; describe("TacoPackageLoader", function (): void { - var testHome = path.join(os.tmpdir(), "taco-utils", "packageLoader"); + var testHome: string = path.join(os.tmpdir(), "taco-utils", "packageLoader"); before(function (): void { process.env["TACO_HOME"] = testHome; rimraf.sync(testHome); @@ -39,7 +39,7 @@ describe("TacoPackageLoader", function (): void { it("should load packages from npm", function (done: MochaDone): void { // is-empty is an arbitrarily chosen fairly small package with no dependencies - var packageJsonFile = path.join(testHome, "node_modules", "is-empty", "0.0.1", "node_modules", "is-empty", "package.json"); + var packageJsonFile: string = path.join(testHome, "node_modules", "is-empty", "0.0.1", "node_modules", "is-empty", "package.json"); fs.existsSync(packageJsonFile).should.be.false; TacoPackageLoader.lazyRequire("is-empty", "is-empty@0.0.1").then(function (pkg: any): void { should(typeof pkg).not.equal("undefined"); @@ -53,8 +53,8 @@ describe("TacoPackageLoader", function (): void { it("should load packages from git", function (done: MochaDone): void { // is-empty is an arbitrarily chosen fairly small package with no dependencies - var gitUrl = "https://github.com/ianstormtaylor/is-empty.git"; - var packageJsonFile = path.join(testHome, "node_modules", "is-empty", encodeURIComponent(gitUrl), "node_modules", "is-empty", "package.json"); + var gitUrl: string = "https://github.com/ianstormtaylor/is-empty.git"; + var packageJsonFile: string = path.join(testHome, "node_modules", "is-empty", encodeURIComponent(gitUrl), "node_modules", "is-empty", "package.json"); fs.existsSync(packageJsonFile).should.be.false; TacoPackageLoader.lazyRequire("is-empty", gitUrl).then(function (pkg: any): void { should(typeof pkg).not.equal("undefined"); @@ -141,7 +141,7 @@ describe("TacoPackageLoader", function (): void { }); function delay(ms: number): Q.Promise { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); setTimeout(deferred.resolve, ms); return deferred.promise; }; diff --git a/src/taco-utils/test/resources.ts b/src/taco-utils/test/resources.ts index 793f82ca..04dc960a 100644 --- a/src/taco-utils/test/resources.ts +++ b/src/taco-utils/test/resources.ts @@ -26,75 +26,75 @@ describe("resources", function (): void { }); it("should use the default language by default", function (): void { - var expectedResources = require(path.join(__dirname, "/resources/en/resources.json")); - var actual = resources.getString("SimpleMessage"); - var expected = expectedResources["SimpleMessage"]; + var expectedResources: any = require(path.join(__dirname, "/resources/en/resources.json")); + var actual: string = resources.getString("SimpleMessage"); + var expected: string = expectedResources["SimpleMessage"]; actual.should.equal(expected); }); it("should correctly return strings for a primary language", function (): void { - var expectedResources = require(path.join(__dirname, "/resources/en/resources.json")); - var actual = resources.getStringForLanguage("en", "SimpleMessage"); - var expected = expectedResources["SimpleMessage"]; + var expectedResources: any = require(path.join(__dirname, "/resources/en/resources.json")); + var actual: string = resources.getStringForLanguage("en", "SimpleMessage"); + var expected: string = expectedResources["SimpleMessage"]; actual.should.equal(expected); }); it("should correctly return strings for a non-english primary language", function (): void { - var expectedResources = require(path.join(__dirname, "/resources/it/resources.json")); - var actual = resources.getStringForLanguage("it", "SimpleMessage"); - var expected = expectedResources["SimpleMessage"]; + var expectedResources: any = require(path.join(__dirname, "/resources/it/resources.json")); + var actual: string = resources.getStringForLanguage("it", "SimpleMessage"); + var expected: string = expectedResources["SimpleMessage"]; actual.should.equal(expected); }); it("should correctly substitute arguments in resource strings", function (): void { - var expectedResources = require(path.join(__dirname, "/resources/en/resources.json")); - var actual = resources.getStringForLanguage("en", "MessageWithArgs", "Billy", "Fish"); - var expected = expectedResources["MessageWithArgs"]; - var actualBackToExpected = actual.replace("Billy", "{0}").replace("Fish", "{1}"); + var expectedResources: any = require(path.join(__dirname, "/resources/en/resources.json")); + var actual: string = resources.getStringForLanguage("en", "MessageWithArgs", "Billy", "Fish"); + var expected: string = expectedResources["MessageWithArgs"]; + var actualBackToExpected: string = actual.replace("Billy", "{0}").replace("Fish", "{1}"); actualBackToExpected.should.equal(expected); - var actualWithArrayArgs = resources.getStringForLanguage("en", "MessageWithArgs", ["Billy", "Fish"]); + var actualWithArrayArgs: string = resources.getStringForLanguage("en", "MessageWithArgs", ["Billy", "Fish"]); actualWithArrayArgs.should.equal(actual); }); it("should find the most specific region for a language", function (): void { - var expectedResources = require(path.join(__dirname, "/resources/it-ch/resources.json")); - var actual = resources.getStringForLanguage("it-ch", "SimpleMessage"); - var expected = expectedResources["SimpleMessage"]; + var expectedResources: any = require(path.join(__dirname, "/resources/it-ch/resources.json")); + var actual: string = resources.getStringForLanguage("it-ch", "SimpleMessage"); + var expected: string = expectedResources["SimpleMessage"]; actual.should.equal(expected); }); it("should fall back to more general languages if a more specific one is not available", function (): void { - var expectedResources = require(path.join(__dirname, "/resources/it/resources.json")); - var actual = resources.getStringForLanguage("it-DE", "SimpleMessage"); - var expected = expectedResources["SimpleMessage"]; + var expectedResources: any = require(path.join(__dirname, "/resources/it/resources.json")); + var actual: string = resources.getStringForLanguage("it-DE", "SimpleMessage"); + var expected: string = expectedResources["SimpleMessage"]; actual.should.equal(expected); }); it("should fall back to english as a default if the language is unknown", function (): void { - var expectedResources = require(path.join(__dirname, "/resources/en/resources.json")); - var actual = resources.getStringForLanguage("hy-Latn-IT-arevela", "SimpleMessage"); - var expected = expectedResources["SimpleMessage"]; + var expectedResources: any = require(path.join(__dirname, "/resources/en/resources.json")); + var actual: string = resources.getStringForLanguage("hy-Latn-IT-arevela", "SimpleMessage"); + var expected: string = expectedResources["SimpleMessage"]; actual.should.equal(expected); }); it("should return undefined for bad resource identifiers", function (): void { - var actual = resources.getStringForLanguage("en", "NoResourceDefinedForThis"); + var actual: string = resources.getStringForLanguage("en", "NoResourceDefinedForThis"); should(actual).be.equal(undefined); }); it("should handle unicode in resource strings", function (): void { - var expectedResources = require(path.join(__dirname, "/resources/gb18030/resources.json")); - var actual = resources.getStringForLanguage("gb18030", "UnicodeMessage"); - var expected = expectedResources["UnicodeMessage"]; + var expectedResources: any = require(path.join(__dirname, "/resources/gb18030/resources.json")); + var actual: string = resources.getStringForLanguage("gb18030", "UnicodeMessage"); + var expected: string = expectedResources["UnicodeMessage"]; actual.should.equal(expected); }); it("should replace all placeholders correctly", function (): void { - var actual = resources.getStringForLanguage("en", "MessageWithRepeatedArgs", "X"); + var actual: string = resources.getStringForLanguage("en", "MessageWithRepeatedArgs", "X"); actual.indexOf("{0}").should.be.equal(-1); - var expectedResources = require(path.join(__dirname, "/resources/en/resources.json")); - var expected = expectedResources["MessageWithRepeatedArgs"]; + var expectedResources: any = require(path.join(__dirname, "/resources/en/resources.json")); + var expected: string = expectedResources["MessageWithRepeatedArgs"]; expected.replace(/\{0\}/g, "X").should.equal(actual); }); }); diff --git a/src/taco-utils/test/utilHelper.ts b/src/taco-utils/test/utilHelper.ts index b73f5261..1ecd9f3d 100644 --- a/src/taco-utils/test/utilHelper.ts +++ b/src/taco-utils/test/utilHelper.ts @@ -13,7 +13,7 @@ /* tslint:disable:no-var-requires */ // var require needed for should module to work correctly // Note not import: We don't want to refer to shouldModule, but we need the require to occur since it modifies the prototype of Object. -var shouldModule = require("should"); +var shouldModule: any = require("should"); /* tslint:enable:no-var-requires */ import mocha = require ("mocha"); diff --git a/src/taco-utils/utilHelper.ts b/src/taco-utils/utilHelper.ts index 48557173..53cf86d4 100644 --- a/src/taco-utils/utilHelper.ts +++ b/src/taco-utils/utilHelper.ts @@ -76,7 +76,7 @@ module TacoUtility { * @return {string} The contents of the file, excluding byte order markers. */ public static readFileContentsSync(filename: string, encoding?: string): string { - var contents = fs.readFileSync(filename, (encoding || "utf-8")); + var contents: string = fs.readFileSync(filename, (encoding || "utf-8")); if (contents) { contents = contents.replace(/^\uFEFF/, ""); // Windows is the BOM } @@ -93,9 +93,9 @@ module TacoUtility { * @returns {Q.Promise} A promise which is fulfilled when the file finishes copying, and is rejected on any error condition. */ public static copyFile(from: string, to: string, encoding?: string): Q.Promise { - var deferred = Q.defer(); - var newFile = fs.createWriteStream(to, { encoding: encoding }); - var oldFile = fs.createReadStream(from, { encoding: encoding }); + var deferred: Q.Deferred = Q.defer(); + var newFile: fs.WriteStream = fs.createWriteStream(to, { encoding: encoding }); + var oldFile: fs.ReadStream = fs.createReadStream(from, { encoding: encoding }); newFile.on("finish", function (): void { deferred.resolve({}); }); @@ -117,7 +117,7 @@ module TacoUtility { * @returns {Q.Promise} A promise which is fulfilled when the copy completes, and is rejected on error */ public static copyRecursive(source: string, target: string, options?: any): Q.Promise { - var deferred = Q.defer(); + var deferred: Q.Deferred = Q.defer(); options = options ? options : {}; @@ -162,8 +162,8 @@ module TacoUtility { * @return {boolean} true if the display name is acceptable, false otherwise */ public static isValidCordovaAppName(str: string): boolean { - for (var i = 0, n = str.length; i < n; i++) { - var code = str.charCodeAt(i); + for (var i: number = 0, n: number = str.length; i < n; i++) { + var code: number = str.charCodeAt(i); if (code < 32 || UtilHelper.INVALID_APP_NAME_CHARS[code]) { return false; } @@ -305,7 +305,7 @@ module TacoUtility { // if help flag is specified, use that // for "taco --help cmd" scenarios, update commandArgs to reflect the next argument or make it [] if it is not present // for "taco cmd --help" scenarios, update commandArgs to reflect the first argument instead - for (var i = 0; i < args.length; i++) { + for (var i: number = 0; i < args.length; i++) { if (/^(-*)(h|help)$/.test(args[i])) { return { helpTopic: (i === 0) ? (args[1] ? args[1] : "") : args[0] }; } @@ -328,7 +328,7 @@ module TacoUtility { // Note: Not using nopt to look for "--loglevel", because the autocmplete feature would catch things like "-l", when these may be intended for the command itself (not for taco loglevel). var logLevelTag: string = "--loglevel"; - var logLevelTagIndex = args.indexOf(logLevelTag); + var logLevelTagIndex: number = args.indexOf(logLevelTag); if (logLevelTagIndex === -1) { return args; From 09e70bfaa998358c9d5166f42adaeed294d695a0 Mon Sep 17 00:00:00 2001 From: Nisheet Jain Date: Wed, 7 Oct 2015 12:53:30 -0700 Subject: [PATCH 4/6] Fixing failing tests --- src/taco-cli/cli/utils/templateManager.ts | 1 - src/taco-cli/test/templateManager.ts | 19 +++++++------------ 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/src/taco-cli/cli/utils/templateManager.ts b/src/taco-cli/cli/utils/templateManager.ts index 1d1a7f78..50cad28a 100644 --- a/src/taco-cli/cli/utils/templateManager.ts +++ b/src/taco-cli/cli/utils/templateManager.ts @@ -41,7 +41,6 @@ module TemplateManager { export interface ITemplateDescriptor { id: string; name: string; - getDescription(): string; } export interface ITemplateList { diff --git a/src/taco-cli/test/templateManager.ts b/src/taco-cli/test/templateManager.ts index bdf19722..9ceb52db 100644 --- a/src/taco-cli/test/templateManager.ts +++ b/src/taco-cli/test/templateManager.ts @@ -301,18 +301,15 @@ describe("TemplateManager", function (): void { templates: [ { id: testTemplateOverrideInfo.templateId, - name: testTemplateOverrideInfo.templateInfo.name, - getDescription: null + name: testTemplateOverrideInfo.templateInfo.name }, { id: testTemplateOverrideInfo2.templateId, - name: testTemplateOverrideInfo2.templateInfo.name, - getDescription: null + name: testTemplateOverrideInfo2.templateInfo.name }, { id: testTemplateOverrideInfo3.templateId, - name: testTemplateOverrideInfo3.templateInfo.name, - getDescription: null + name: testTemplateOverrideInfo3.templateInfo.name } ] }; @@ -341,21 +338,19 @@ describe("TemplateManager", function (): void { templates: [ { id: testTemplateOverrideInfo.templateId, - name: testTemplateOverrideInfo.templateInfo.name, - getDescription: null + name: testTemplateOverrideInfo.templateInfo.name }, { id: testTemplateOverrideInfo2.templateId, - name: testTemplateOverrideInfo2.templateInfo.name, - getDescription: null + name: testTemplateOverrideInfo2.templateInfo.name }, { id: testTemplateOverrideInfo3.templateId, - name: testTemplateOverrideInfo3.templateInfo.name, - getDescription: null + name: testTemplateOverrideInfo3.templateInfo.name } ] }; + var expectedResultStringified: string = JSON.stringify(expectedResult); templates.getAllTemplates() From d7987dc29d2a2d8e6dd87f6b59571e14796425ca Mon Sep 17 00:00:00 2001 From: Nisheet Jain Date: Wed, 7 Oct 2015 22:16:03 -0700 Subject: [PATCH 5/6] Removing variable-declaration from tslint typedef. This helps us in keeping type inferences work by themselves for anonymous objects --- src/remotebuild/test/darwinCerts.ts | 2 +- src/taco-cli/test/checkForNewerVersion.ts | 2 +- src/taco-cli/test/create.ts | 2 +- src/taco-cli/test/help.ts | 2 +- src/taco-cli/test/platformPlugin.ts | 2 +- src/taco-cli/test/remote.ts | 6 +++--- src/taco-cli/test/run.ts | 4 ++-- src/taco-cli/test/templates.ts | 4 ++-- src/taco-cli/test/utils/serverMock.ts | 2 +- src/taco-remote/lib/tacoRemoteConfig.ts | 2 +- src/tslint.json | 1 - 11 files changed, 14 insertions(+), 15 deletions(-) diff --git a/src/remotebuild/test/darwinCerts.ts b/src/remotebuild/test/darwinCerts.ts index 189ff440..aecf59a0 100644 --- a/src/remotebuild/test/darwinCerts.ts +++ b/src/remotebuild/test/darwinCerts.ts @@ -109,7 +109,7 @@ macOnly("Certs", function(): void { certs.generateClientCert(conf({ serverDir: serverDir })). then(function(pin: number): void { throw "PIN should not be returned"; - }, function(error: any): void { + }, function(error: Error): void { // We should get an error if we try to create client certificates when there is no server certificate }).done(function(): void { done(); diff --git a/src/taco-cli/test/checkForNewerVersion.ts b/src/taco-cli/test/checkForNewerVersion.ts index 72a4d4a9..62f4d7f6 100644 --- a/src/taco-cli/test/checkForNewerVersion.ts +++ b/src/taco-cli/test/checkForNewerVersion.ts @@ -46,7 +46,7 @@ describe("Check for newer version", function (): void { process.env["TACO_HOME"] = tacoHome; // because of function overloading assigning "(buffer: string, cb?: Function) => boolean" as the type for // stdoutWrite just doesn't work - var stdoutWrite: any = process.stdout.write; // We save the original implementation, so we can restore it later + var stdoutWrite = process.stdout.write; // We save the original implementation, so we can restore it later var memoryStdout: ms.MemoryStream; var expectedRequestAndResponse: { expectedUrl: string; statusCode: number; head: any; response: any; waitForPayload?: boolean, responseDelay?: number }; diff --git a/src/taco-cli/test/create.ts b/src/taco-cli/test/create.ts index 6f52c5ee..3a954da2 100644 --- a/src/taco-cli/test/create.ts +++ b/src/taco-cli/test/create.ts @@ -442,7 +442,7 @@ describe("taco create", function (): void { describe("Onboarding experience", () => { // because of function overloading assigning "(buffer: string, cb?: Function) => boolean" as the type for // stdoutWrite just doesn't work - var stdoutWrite: any = process.stdout.write; // We save the original implementation, so we can restore it later + var stdoutWrite = process.stdout.write; // We save the original implementation, so we can restore it later var memoryStdout: ms.MemoryStream; beforeEach(() => { diff --git a/src/taco-cli/test/help.ts b/src/taco-cli/test/help.ts index 033e0a57..30305006 100644 --- a/src/taco-cli/test/help.ts +++ b/src/taco-cli/test/help.ts @@ -33,7 +33,7 @@ describe("help for a command", function (): void { var help: Help = new Help(); // because of function overloading assigning "(buffer: string, cb?: Function) => boolean" as the type for // stdoutWrite just doesn't work - var stdoutWrite: any = process.stdout.write; // We save the original implementation, so we can restore it later + var stdoutWrite = process.stdout.write; // We save the original implementation, so we can restore it later var memoryStdout: ms.MemoryStream; var previous: boolean; diff --git a/src/taco-cli/test/platformPlugin.ts b/src/taco-cli/test/platformPlugin.ts index d72e9c7d..efc28562 100644 --- a/src/taco-cli/test/platformPlugin.ts +++ b/src/taco-cli/test/platformPlugin.ts @@ -499,7 +499,7 @@ describe("taco platform for kit", function(): void { describe("Onboarding experience", () => { // because of function overloading assigning "(buffer: string, cb?: Function) => boolean" as the type for // stdoutWrite just doesn't work - var stdoutWrite: any = process.stdout.write; // We save the original implementation, so we can restore it later + var stdoutWrite = process.stdout.write; // We save the original implementation, so we can restore it later var memoryStdout: ms.MemoryStream; beforeEach(function(done: MochaDone): void { diff --git a/src/taco-cli/test/remote.ts b/src/taco-cli/test/remote.ts index 7cacf107..b92a7a7c 100755 --- a/src/taco-cli/test/remote.ts +++ b/src/taco-cli/test/remote.ts @@ -157,7 +157,7 @@ describe("taco remote", function(): void { it("should be able to configure secure connections", function(mocha: MochaDone): void { this.timeout(20000); var mockServer: https.Server = ServerMock.createSecureTestServer(); - var desiredState: any = { + var desiredState = { host: "localhost", port: 3000, pin: "123456", @@ -234,7 +234,7 @@ describe("taco remote", function(): void { describe("Onboarding experience", function(): void { // because of function overloading assigning "(buffer: string, cb?: Function) => boolean" as the type for // stdoutWrite just doesn't work - var stdoutWrite: any = process.stdout.write; // We save the original implementation, so we can restore it later + var stdoutWrite = process.stdout.write; // We save the original implementation, so we can restore it later var memoryStdout: ms.MemoryStream; beforeEach(() => { @@ -251,7 +251,7 @@ describe("taco remote", function(): void { // retrieve the contents from the memory stream it("prints the onboarding experience when adding a new remote", function(done: MochaDone): void { this.timeout(5000); - var desiredState: any = { + var desiredState = { host: "localhost", port: 3000, pin: "", diff --git a/src/taco-cli/test/run.ts b/src/taco-cli/test/run.ts index 6a7c242c..f6c9f14f 100755 --- a/src/taco-cli/test/run.ts +++ b/src/taco-cli/test/run.ts @@ -124,7 +124,7 @@ describe("taco run", function (): void { var configuration: string = "debug"; var buildNumber: number = 12343; - var buildInfo: any = { + var buildInfo = { buildNumber: buildNumber, status: BuildInfo.COMPLETE, buildLang: "en" @@ -190,7 +190,7 @@ describe("taco run", function (): void { var configuration: string = "debug"; var buildNumber: number = 12344; - var buildInfo: any = { + var buildInfo = { buildNumber: buildNumber, status: BuildInfo.COMPLETE, buildLang: "en" diff --git a/src/taco-cli/test/templates.ts b/src/taco-cli/test/templates.ts index a0212120..98fa736c 100644 --- a/src/taco-cli/test/templates.ts +++ b/src/taco-cli/test/templates.ts @@ -61,7 +61,7 @@ describe("templates", function (): void { describe("Onboarding experience", function (): void { // because of function overloading assigning "(buffer: string, cb?: Function) => boolean" as the type for // stdoutWrite just doesn't work - var stdoutWrite: any = process.stdout.write; // We save the original implementation, so we can restore it later + var stdoutWrite = process.stdout.write; // We save the original implementation, so we can restore it later var memoryStdout: ms.MemoryStream; beforeEach(() => { @@ -76,7 +76,7 @@ describe("templates", function (): void { it("templates prints the onboarding experience", function (done: MochaDone): void { templatesRun().done(() => { - var expected: any = [ + var expected = [ "CommandTemplatesHeader", "", " blank ............... BlankTemplateName", diff --git a/src/taco-cli/test/utils/serverMock.ts b/src/taco-cli/test/utils/serverMock.ts index 06d00423..bf92320b 100644 --- a/src/taco-cli/test/utils/serverMock.ts +++ b/src/taco-cli/test/utils/serverMock.ts @@ -32,7 +32,7 @@ class ServerMock { var sequenceIndex: number = 0; return function (request: http.ServerRequest, response: http.ServerResponse): void { if (sequenceIndex < sequence.length) { - var data: any = sequence[sequenceIndex]; + var data: IRemoteServerSequence = sequence[sequenceIndex]; ++sequenceIndex; if (request.url !== data.expectedUrl) { onErr(new Error("Expected request to " + data.expectedUrl + " got " + request.url)); diff --git a/src/taco-remote/lib/tacoRemoteConfig.ts b/src/taco-remote/lib/tacoRemoteConfig.ts index 6da56941..fce054e0 100644 --- a/src/taco-remote/lib/tacoRemoteConfig.ts +++ b/src/taco-remote/lib/tacoRemoteConfig.ts @@ -140,7 +140,7 @@ class TacoRemoteConfig implements RemoteBuild.IReadOnlyDictionary { } public serialize(): RemoteBuild.IServerModuleConfiguration { - var confCopy: any = JSON.parse(JSON.stringify(this.tacoRemoteConf)); + var confCopy = JSON.parse(JSON.stringify(this.tacoRemoteConf)); // These three properties are taken from the root config, and are not individually configurable. Remove them when saving. delete confCopy.lang; delete confCopy.port; diff --git a/src/tslint.json b/src/tslint.json index c0ef18f1..38082f2c 100644 --- a/src/tslint.json +++ b/src/tslint.json @@ -68,7 +68,6 @@ "call-signature", "parameter", "property-declaration", - "variable-declaration", "member-variable-declaration" ], "typedef-whitespace": [true, From b15cbdc1a283199eee590d6e953f8f7da7e31029 Mon Sep 17 00:00:00 2001 From: Nisheet Jain Date: Wed, 7 Oct 2015 22:31:36 -0700 Subject: [PATCH 6/6] Incorporating @meenakb feedback --- src/taco-cli/cli/create.ts | 20 ++++++++-------- src/taco-cli/cli/remote.ts | 6 ++--- src/taco-utils/tacoUtils.ts | 46 ++++++++++++++++++------------------- 3 files changed, 36 insertions(+), 36 deletions(-) diff --git a/src/taco-cli/cli/create.ts b/src/taco-cli/cli/create.ts index 1c69205a..514bb5c7 100644 --- a/src/taco-cli/cli/create.ts +++ b/src/taco-cli/cli/create.ts @@ -82,7 +82,7 @@ class Create extends commands.TacoCommandBase { var templateDisplayName: string; return this.createProject() - .then(function(templateUsed: string): Q.Promise { + .then(function (templateUsed: string): Q.Promise { templateDisplayName = templateUsed; var kitProject: boolean = self.isKitProject(); @@ -90,11 +90,11 @@ class Create extends commands.TacoCommandBase { return projectHelper.createTacoJsonFile(self.commandParameters.cordovaParameters.projectPath, kitProject, valueToSerialize); }) - .then(function(): Q.Promise { + .then(function (): Q.Promise { self.finalize(templateDisplayName); return Q.resolve({}); - }).then(function(): Q.Promise { + }).then(function (): Q.Promise { return self.generateTelemetryProperties(); }); } @@ -113,7 +113,7 @@ class Create extends commands.TacoCommandBase { var telemetryProperties: ICommandTelemetryProperties = {}; telemetryProperties["cliVersion"] = telemetryHelper.telemetryProperty(require("../package.json").version); var self: Create = this; - return kitHelper.getDefaultKit().then(function(defaultKitId: string): Q.Promise { + return kitHelper.getDefaultKit().then(function (defaultKitId: string): Q.Promise { if (self.isKitProject()) { telemetryProperties["kit"] = telemetryHelper.telemetryProperty(self.commandParameters.data.options["kit"] || defaultKitId); telemetryProperties["template"] = telemetryHelper.telemetryProperty(self.commandParameters.data.options["template"] || "blank"); @@ -190,25 +190,25 @@ class Create extends commands.TacoCommandBase { // Create the project if (!this.isKitProject()) { return this.printStatusMessage() - .then(function(): Q.Promise { + .then(function (): Q.Promise { // Use the CLI version specified as an argument to create the project "command.create.status.cliProject return cordovaWrapper.create(cordovaCli, self.commandParameters.cordovaParameters); }); } else { - return kitHelper.getValidCordovaCli(kitId).then(function(cordovaCliToUse: string): void { + return kitHelper.getValidCordovaCli(kitId).then(function (cordovaCliToUse: string): void { cordovaCli = cordovaCliToUse; }) - .then(function(): Q.Promise { + .then(function (): Q.Promise { return self.printStatusMessage(); }) - .then(function(): Q.Promise { + .then(function (): Q.Promise { if (kitId) { return kitHelper.getKitInfo(kitId); } else { return Q.resolve(null); } }) - .then(function(kitInfo: TacoKits.IKitInfo): Q.Promise { + .then(function (kitInfo: TacoKits.IKitInfo): Q.Promise { if (kitInfo && !!kitInfo.deprecated) { // Warn the user logger.log(resources.getString("CommandCreateWarningDeprecatedKit", kitId)); @@ -218,7 +218,7 @@ class Create extends commands.TacoCommandBase { var templates: templateManager = new templateManager(kitHelper); return templates.createKitProjectWithTemplate(kitId, templateId, cordovaCli, self.commandParameters.cordovaParameters) - .then(function(templateDisplayName: string): Q.Promise { + .then(function (templateDisplayName: string): Q.Promise { return Q.resolve(templateDisplayName); }); } else { diff --git a/src/taco-cli/cli/remote.ts b/src/taco-cli/cli/remote.ts index 8a7ce9cb..479bfaf5 100644 --- a/src/taco-cli/cli/remote.ts +++ b/src/taco-cli/cli/remote.ts @@ -38,7 +38,7 @@ import UtilHelper = tacoUtility.UtilHelper; import ICommandTelemetryProperties = tacoUtility.ICommandTelemetryProperties; -interface IcliSession { +interface ICliSession { question: (question: string, callback: (answer: string) => void) => void; close: () => void; }; @@ -52,7 +52,7 @@ class Remote extends commands.TacoCommandBase { /** * Mockable CLI for test purposes */ - public static cliSession: IcliSession = null; + public static cliSession: ICliSession = null; private static HTTP_TIMEOUT_IN_MS: number = 20000; private static KNOWN_OPTIONS: Nopt.CommandData = {}; @@ -212,7 +212,7 @@ class Remote extends commands.TacoCommandBase { var portPromise: Q.Deferred<{ host: string; port: number }> = Q.defer<{ host: string; port: number }>(); var pinPromise: Q.Deferred<{ host: string; port: number; pin: number }> = Q.defer<{ host: string; port: number; pin: number }>(); - var cliSession: IcliSession = Remote.cliSession ? Remote.cliSession : readline.createInterface({ input: process.stdin, output: process.stdout }); + var cliSession: ICliSession = Remote.cliSession ? Remote.cliSession : readline.createInterface({ input: process.stdin, output: process.stdout }); // Query the user for the host, port, and PIN, but don't keep asking questions if they input a known-invalid argument cliSession.question(resources.getString("CommandRemoteQueryHost"), function (hostAnswer: string): void { diff --git a/src/taco-utils/tacoUtils.ts b/src/taco-utils/tacoUtils.ts index 75097150..d667031e 100644 --- a/src/taco-utils/tacoUtils.ts +++ b/src/taco-utils/tacoUtils.ts @@ -34,29 +34,29 @@ module TacoUtility { /* tslint:disable:variable-name */ // We mostly export classes here from taco-utils and we prefer keeping them pascal cased // put more classes here, known limitation that classes in external modules CANNOT span multiple files - export var ArgsHelper: any = argsHelper.ArgsHelper; - export var BuildInfo: any = buildInfo.BuildInfo; - export var Commands: any = commands.Commands; - export var CordovaConfig: any = cordovaConfig.CordovaConfig; - export var CountStream: any = countStream.CountStream; - export var Logger: any = logger.Logger; - export var LoggerHelper: any = loggerHelper.LoggerHelper; - export var LogLevel: any = logLevel.LogLevel; - export var NewlineNormalizerStream: any = newlineNormalizerStream.NewlineNormalizerStream; - export var HelpCommandBase: any = helpCommandBase.HelpCommandBase; - export var InstallLogLevel: any = installLogLevel.InstallLogLevel; - export var JsonSerializer: any = jsonSerializer.JsonSerializer; - export var ProcessLogger: any = processLogger.ProcessLogger; - export var ResourceManager: any = resourceManager.ResourceManager; - export var TacoError: any = tacoError.TacoError; - export var TacoErrorCode: any = tacoErrorCodes.TacoErrorCode; - export var TacoGlobalConfig: any = tacoGlobalConfig.TacoGlobalConfig; - export var TacoPackageLoader: any = tacoPackageLoader.TacoPackageLoader; - export var TelemetryGenerator: any = telemetryHelper.TelemetryGenerator; - export var Telemetry: any = telemetry.Telemetry; - export var TelemetryHelper: any = telemetryHelper.TelemetryHelper; - export var UtilHelper: any = utilHelper.UtilHelper; - export var LogFormatHelper: any = logFormatHelper.LogFormatHelper; + export var ArgsHelper: typeof argsHelper.ArgsHelper = argsHelper.ArgsHelper; + export var BuildInfo: typeof buildInfo.BuildInfo = buildInfo.BuildInfo; + export var Commands: typeof commands.Commands = commands.Commands; + export var CordovaConfig: typeof cordovaConfig.CordovaConfig = cordovaConfig.CordovaConfig; + export var CountStream: typeof countStream.CountStream = countStream.CountStream; + export var Logger: typeof logger.Logger = logger.Logger; + export var LoggerHelper: typeof loggerHelper.LoggerHelper = loggerHelper.LoggerHelper; + export var LogLevel: typeof logLevel.LogLevel = logLevel.LogLevel; + export var NewlineNormalizerStream: typeof newlineNormalizerStream.NewlineNormalizerStream = newlineNormalizerStream.NewlineNormalizerStream; + export var HelpCommandBase: typeof helpCommandBase.HelpCommandBase = helpCommandBase.HelpCommandBase; + export var InstallLogLevel: typeof installLogLevel.InstallLogLevel = installLogLevel.InstallLogLevel; + export var JsonSerializer: typeof jsonSerializer.JsonSerializer = jsonSerializer.JsonSerializer; + export var ProcessLogger: typeof processLogger.ProcessLogger = processLogger.ProcessLogger; + export var ResourceManager: typeof resourceManager.ResourceManager = resourceManager.ResourceManager; + export var TacoError: typeof tacoError.TacoError = tacoError.TacoError; + export var TacoErrorCode: typeof tacoErrorCodes.TacoErrorCode = tacoErrorCodes.TacoErrorCode; + export var TacoGlobalConfig: typeof tacoGlobalConfig.TacoGlobalConfig = tacoGlobalConfig.TacoGlobalConfig; + export var TacoPackageLoader: typeof tacoPackageLoader.TacoPackageLoader = tacoPackageLoader.TacoPackageLoader; + export var TelemetryGenerator: typeof telemetryHelper.TelemetryGenerator = telemetryHelper.TelemetryGenerator; + export var Telemetry: typeof telemetry.Telemetry = telemetry.Telemetry; + export var TelemetryHelper: typeof telemetryHelper.TelemetryHelper = telemetryHelper.TelemetryHelper; + export var UtilHelper: typeof utilHelper.UtilHelper = utilHelper.UtilHelper; + export var LogFormatHelper: typeof logFormatHelper.LogFormatHelper = logFormatHelper.LogFormatHelper; /* tslint:enable:variable-name */ }