diff --git a/.gitignore b/.gitignore index 656f1cda5..a111d5647 100644 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,7 @@ Properties *~ # test folder +!_infrastructure/*.js !_infrastructure/tests/* !_infrastructure/tests/*.js !_infrastructure/tests/*/*.js diff --git a/README.md b/README.md index 83e4ffbca..960c06c80 100755 --- a/README.md +++ b/README.md @@ -99,6 +99,7 @@ List of Definitions * [jQuery.Globalize](https://github.com/jquery/globalize) (by [Boris Yankov](https://github.com/borisyankov)) * [jQuery.jNotify](http://jnotify.codeplex.com) (by [James Curran](https://github.com/jamescurran/)) * [jQuery.noty](http://needim.github.io/noty/) (by [Aaron King](https://github.com/kingdango/)) +* [jQuery.pickadate](https://github.com/amsul/pickadate.js) (by [Theodore Brown](https://github.com/theodorejb)) * [jQuery.scrollTo](https://github.com/flesler/jquery.scrollTo) (by [Neil Stalker](https://github.com/nestalk/)) * [jQuery.simplePagination](https://github.com/flaviusmatis/simplePagination.js) (by [Natan Vivo](https://github.com/nvivo/)) * [jQuery.timeago](http://timeago.yarp.com/) (by [François Guillot](http://fguillot.developpez.com/)) diff --git a/_infrastructure/tests/runner.js b/_infrastructure/tests/runner.js new file mode 100644 index 000000000..8b1ff53dd --- /dev/null +++ b/_infrastructure/tests/runner.js @@ -0,0 +1,1058 @@ +var ExecResult = (function () { + function ExecResult() { + this.stdout = ""; + this.stderr = ""; + } + return ExecResult; +})(); + +var WindowsScriptHostExec = (function () { + function WindowsScriptHostExec() { + } + WindowsScriptHostExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { + var result = new ExecResult(); + var shell = new ActiveXObject('WScript.Shell'); + try { + var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' ')); + } catch (e) { + result.stderr = e.message; + result.exitCode = 1; + handleResult(result); + return; + } + + while (process.Status != 0) { + } + + result.exitCode = process.ExitCode; + if (!process.StdOut.AtEndOfStream) + result.stdout = process.StdOut.ReadAll(); + if (!process.StdErr.AtEndOfStream) + result.stderr = process.StdErr.ReadAll(); + + handleResult(result); + }; + return WindowsScriptHostExec; +})(); + +var NodeExec = (function () { + function NodeExec() { + } + NodeExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { + var nodeExec = require('child_process').exec; + + var result = new ExecResult(); + result.exitCode = null; + var cmdLine = filename + ' ' + cmdLineArgs.join(' '); + + var process = nodeExec(cmdLine, function (error, stdout, stderr) { + result.stdout = stdout; + result.stderr = stderr; + result.exitCode = error ? error.code : 0; + handleResult(result); + }); + }; + return NodeExec; +})(); + +var Exec = (function () { + var global = Function("return this;").call(null); + if (typeof global.ActiveXObject !== "undefined") { + return new WindowsScriptHostExec(); + } else { + return new NodeExec(); + } +})(); +var IOUtils; +(function (IOUtils) { + function createDirectoryStructure(ioHost, dirName) { + if (ioHost.directoryExists(dirName)) { + return; + } + + var parentDirectory = ioHost.dirName(dirName); + if (parentDirectory != "") { + createDirectoryStructure(ioHost, parentDirectory); + } + ioHost.createDirectory(dirName); + } + + function createFileAndFolderStructure(ioHost, fileName, useUTF8) { + var path = ioHost.resolvePath(fileName); + var dirName = ioHost.dirName(path); + createDirectoryStructure(ioHost, dirName); + return ioHost.createFile(path, useUTF8); + } + IOUtils.createFileAndFolderStructure = createFileAndFolderStructure; + + function throwIOError(message, error) { + var errorMessage = message; + if (error && error.message) { + errorMessage += (" " + error.message); + } + throw new Error(errorMessage); + } + IOUtils.throwIOError = throwIOError; +})(IOUtils || (IOUtils = {})); + +var IO = (function () { + function getWindowsScriptHostIO() { + var fso = new ActiveXObject("Scripting.FileSystemObject"); + var streamObjectPool = []; + + function getStreamObject() { + if (streamObjectPool.length > 0) { + return streamObjectPool.pop(); + } else { + return new ActiveXObject("ADODB.Stream"); + } + } + + function releaseStreamObject(obj) { + streamObjectPool.push(obj); + } + + var args = []; + for (var i = 0; i < WScript.Arguments.length; i++) { + args[i] = WScript.Arguments.Item(i); + } + + return { + readFile: function (path) { + try { + var streamObj = getStreamObject(); + streamObj.Open(); + streamObj.Type = 2; + streamObj.Charset = 'x-ansi'; + streamObj.LoadFromFile(path); + var bomChar = streamObj.ReadText(2); + streamObj.Position = 0; + if ((bomChar.charCodeAt(0) == 0xFE && bomChar.charCodeAt(1) == 0xFF) || (bomChar.charCodeAt(0) == 0xFF && bomChar.charCodeAt(1) == 0xFE)) { + streamObj.Charset = 'unicode'; + } else if (bomChar.charCodeAt(0) == 0xEF && bomChar.charCodeAt(1) == 0xBB) { + streamObj.Charset = 'utf-8'; + } + + var str = streamObj.ReadText(-1); + streamObj.Close(); + releaseStreamObject(streamObj); + return str; + } catch (err) { + IOUtils.throwIOError("Error reading file \"" + path + "\".", err); + } + }, + writeFile: function (path, contents) { + var file = this.createFile(path); + file.Write(contents); + file.Close(); + }, + fileExists: function (path) { + return fso.FileExists(path); + }, + resolvePath: function (path) { + return fso.GetAbsolutePathName(path); + }, + dirName: function (path) { + return fso.GetParentFolderName(path); + }, + findFile: function (rootPath, partialFilePath) { + var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; + + while (true) { + if (fso.FileExists(path)) { + try { + var content = this.readFile(path); + return { content: content, path: path }; + } catch (err) { + } + } else { + rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); + + if (rootPath == "") { + return null; + } else { + path = fso.BuildPath(rootPath, partialFilePath); + } + } + } + }, + deleteFile: function (path) { + try { + if (fso.FileExists(path)) { + fso.DeleteFile(path, true); + } + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + createFile: function (path, useUTF8) { + try { + var streamObj = getStreamObject(); + streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi'; + streamObj.Open(); + return { + Write: function (str) { + streamObj.WriteText(str, 0); + }, + WriteLine: function (str) { + streamObj.WriteText(str, 1); + }, + Close: function () { + try { + streamObj.SaveToFile(path, 2); + } catch (saveError) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError); + } finally { + if (streamObj.State != 0) { + streamObj.Close(); + } + releaseStreamObject(streamObj); + } + } + }; + } catch (creationError) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError); + } + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + createDirectory: function (path) { + try { + if (!this.directoryExists(path)) { + fso.CreateFolder(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + dir: function (path, spec, options) { + options = options || {}; + function filesInFolder(folder, root) { + var paths = []; + var fc; + + if (options.recursive) { + fc = new Enumerator(folder.subfolders); + + for (; !fc.atEnd(); fc.moveNext()) { + paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); + } + } + + fc = new Enumerator(folder.files); + + for (; !fc.atEnd(); fc.moveNext()) { + if (!spec || fc.item().Name.match(spec)) { + paths.push(root + "/" + fc.item().Name); + } + } + + return paths; + } + + var folder = fso.GetFolder(path); + var paths = []; + + return filesInFolder(folder, path); + }, + print: function (str) { + WScript.StdOut.Write(str); + }, + printLine: function (str) { + WScript.Echo(str); + }, + arguments: args, + stderr: WScript.StdErr, + stdout: WScript.StdOut, + watchFile: null, + run: function (source, filename) { + try { + eval(source); + } catch (e) { + IOUtils.throwIOError("Error while executing file '" + filename + "'.", e); + } + }, + getExecutingFilePath: function () { + return WScript.ScriptFullName; + }, + quit: function (exitCode) { + if (typeof exitCode === "undefined") { exitCode = 0; } + try { + WScript.Quit(exitCode); + } catch (e) { + } + } + }; + } + ; + + function getNodeIO() { + var _fs = require('fs'); + var _path = require('path'); + var _module = require('module'); + + return { + readFile: function (file) { + try { + var buffer = _fs.readFileSync(file); + switch (buffer[0]) { + case 0xFE: + if (buffer[1] == 0xFF) { + var i = 0; + while ((i + 1) < buffer.length) { + var temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + i += 2; + } + return buffer.toString("ucs2", 2); + } + break; + case 0xFF: + if (buffer[1] == 0xFE) { + return buffer.toString("ucs2", 2); + } + break; + case 0xEF: + if (buffer[1] == 0xBB) { + return buffer.toString("utf8", 3); + } + } + + return buffer.toString(); + } catch (e) { + IOUtils.throwIOError("Error reading file \"" + file + "\".", e); + } + }, + writeFile: _fs.writeFileSync, + deleteFile: function (path) { + try { + _fs.unlinkSync(path); + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + createFile: function (path, useUTF8) { + function mkdirRecursiveSync(path) { + var stats = _fs.statSync(path); + if (stats.isFile()) { + IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null); + } else if (stats.isDirectory()) { + return; + } else { + mkdirRecursiveSync(_path.dirname(path)); + _fs.mkdirSync(path, 0775); + } + } + + mkdirRecursiveSync(_path.dirname(path)); + + try { + var fd = _fs.openSync(path, 'w'); + } catch (e) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e); + } + return { + Write: function (str) { + _fs.writeSync(fd, str); + }, + WriteLine: function (str) { + _fs.writeSync(fd, str + '\r\n'); + }, + Close: function () { + _fs.closeSync(fd); + fd = null; + } + }; + }, + dir: function dir(path, spec, options) { + options = options || {}; + + function filesInFolder(folder, deep) { + var paths = []; + + var files = _fs.readdirSync(folder); + for (var i = 0; i < files.length; i++) { + var stat = _fs.statSync(folder + "/" + files[i]); + if (options.recursive && stat.isDirectory()) { + if (deep < (options.deep || 100)) { + paths = paths.concat(filesInFolder(folder + "/" + files[i], 1)); + } + } else if (stat.isFile() && (!spec || files[i].match(spec))) { + paths.push(folder + "/" + files[i]); + } + } + + return paths; + } + + return filesInFolder(path, 0); + }, + createDirectory: function (path) { + try { + if (!this.directoryExists(path)) { + _fs.mkdirSync(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); + }, + resolvePath: function (path) { + return _path.resolve(path); + }, + dirName: function (path) { + return _path.dirname(path); + }, + findFile: function (rootPath, partialFilePath) { + var path = rootPath + "/" + partialFilePath; + + while (true) { + if (_fs.existsSync(path)) { + try { + var content = this.readFile(path); + return { content: content, path: path }; + } catch (err) { + } + } else { + var parentPath = _path.resolve(rootPath, ".."); + + if (rootPath === parentPath) { + return null; + } else { + rootPath = parentPath; + path = _path.resolve(rootPath, partialFilePath); + } + } + } + }, + print: function (str) { + process.stdout.write(str); + }, + printLine: function (str) { + process.stdout.write(str + '\n'); + }, + arguments: process.argv.slice(2), + stderr: { + Write: function (str) { + process.stderr.write(str); + }, + WriteLine: function (str) { + process.stderr.write(str + '\n'); + }, + Close: function () { + } + }, + stdout: { + Write: function (str) { + process.stdout.write(str); + }, + WriteLine: function (str) { + process.stdout.write(str + '\n'); + }, + Close: function () { + } + }, + watchFile: function (filename, callback) { + var firstRun = true; + var processingChange = false; + + var fileChanged = function (curr, prev) { + if (!firstRun) { + if (curr.mtime < prev.mtime) { + return; + } + + _fs.unwatchFile(filename, fileChanged); + if (!processingChange) { + processingChange = true; + callback(filename); + setTimeout(function () { + processingChange = false; + }, 100); + } + } + firstRun = false; + _fs.watchFile(filename, { persistent: true, interval: 500 }, fileChanged); + }; + + fileChanged(); + return { + filename: filename, + close: function () { + _fs.unwatchFile(filename, fileChanged); + } + }; + }, + run: function (source, filename) { + require.main.filename = filename; + require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename))); + require.main._compile(source, filename); + }, + getExecutingFilePath: function () { + return process.mainModule.filename; + }, + quit: process.exit + }; + } + ; + + if (typeof ActiveXObject === "function") + return getWindowsScriptHostIO(); else if (typeof require === "function") + return getNodeIO(); else + return null; +})(); +var DefinitelyTyped; +(function (DefinitelyTyped) { + (function (TestManager) { + var path = require('path'); + + function endsWith(str, suffix) { + return str.indexOf(suffix, str.length - suffix.length) !== -1; + } + + var Iterator = (function () { + function Iterator(list) { + this.list = list; + this.index = -1; + } + Iterator.prototype.next = function () { + this.index++; + return this.list[this.index]; + }; + + Iterator.prototype.hasNext = function () { + return this.list[1 + this.index] != null; + }; + return Iterator; + })(); + + var Tsc = (function () { + function Tsc() { + } + Tsc.run = function (tsfile, callback) { + Exec.exec('node ./_infrastructure/tests/typescript/tsc.js ', [tsfile], function (ExecResult) { + callback(ExecResult); + }); + }; + return Tsc; + })(); + + var Test = (function () { + function Test(tsfile) { + this.tsfile = tsfile; + } + Test.prototype.run = function (callback) { + Tsc.run(this.tsfile, callback); + }; + return Test; + })(); + + var Typing = (function () { + function Typing(name, baseDir) { + this.name = name; + this.fileHandler = new FileHandler(baseDir + '/' + name + '/', /.\.ts/g); + } + return Typing; + })(); + + var FileHandler = (function () { + function FileHandler(path, pattern) { + this.path = path; + this.files = []; + this.typings = []; + this.files = IO.dir(path, pattern, { recursive: true }); + } + FileHandler.prototype.allTS = function () { + return this.files; + }; + + FileHandler.prototype.allTests = function () { + var tests = []; + + for (var i = 0; i < this.files.length; i++) { + if (endsWith(this.files[i].toUpperCase(), '-TESTS.TS')) { + tests.push(this.files[i]); + } + } + + return tests; + }; + + FileHandler.prototype.allTypings = function () { + var typings = {}; + + for (var i = 0; i < this.files.length; i++) { + var file = this.files[i]; + var firName = path.dirname(file.substr(this.path.length + 1)).replace('\\', '/'); + var dir = firName.split('/')[0]; + + if (!typings[dir]) + typings[dir] = true; + } + + var list = []; + for (var attr in typings) { + list.push(attr); + } + + return list; + }; + return FileHandler; + })(); + + var Timer = (function () { + function Timer() { + this.time = 0; + } + Timer.prettyDate = function (date1, date2) { + var diff = ((date2 - date1) / 1000), day_diff = Math.floor(diff / 86400); + + if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) + return; + + return (day_diff == 0 && (diff < 60 && (diff + " secconds") || diff < 120 && "1 minute" || diff < 3600 && Math.floor(diff / 60) + " minutes" || diff < 7200 && "1 hour" || diff < 86400 && Math.floor(diff / 3600) + " hours") || day_diff == 1 && "Yesterday" || day_diff < 7 && day_diff + " days" || day_diff < 31 && Math.ceil(day_diff / 7) + " weeks"); + }; + + Timer.prototype.start = function () { + this.time = 0; + this.startTime = this.now(); + }; + + Timer.prototype.now = function () { + return Date.now(); + }; + + Timer.prototype.end = function () { + this.time = (this.now() - this.startTime) / 1000; + this.asString = Timer.prettyDate(this.startTime, this.now()); + }; + return Timer; + })(); + + var Print = (function () { + function Print(version, typings, tsFiles) { + this.version = version; + this.typings = typings; + this.tsFiles = tsFiles; + } + Print.prototype.out = function (s) { + process.stdout.write(s); + }; + + Print.prototype.printHeader = function () { + this.out('=============================================================================\n'); + this.out(' \33[36m\33[1mDefinitelyTyped test runner 0.2.0\33[0m\n'); + this.out('=============================================================================\n'); + this.out(' \33[36m\33[1mTypescript version:\33[0m ' + this.version + '\n'); + this.out(' \33[36m\33[1mTypings :\33[0m ' + this.typings + '\n'); + this.out(' \33[36m\33[1mTypeScript files :\33[0m ' + this.tsFiles + '\n'); + }; + + Print.prototype.printSyntaxCheking = function () { + this.out('============================ \33[34m\33[1mSyntax cheking\33[0m =================================\n'); + }; + + Print.prototype.printTypingTests = function () { + this.out('============================= \33[34m\33[1mTyping tests\33[0m ==================================\n'); + }; + + Print.prototype.printSuccess = function () { + this.out('\33[36m\33[1m.\33[0m'); + }; + + Print.prototype.printFailure = function () { + this.out('x'); + }; + + Print.prototype.printDiv = function () { + this.out('-----------------------------------------------------------------------------\n'); + }; + + Print.prototype.printfilesWithSintaxErrorMessage = function () { + this.out(' \33[36m\33[1mFiles with syntax error\33[0m\n'); + }; + + Print.prototype.printFailedTestMessage = function () { + this.out(' \33[36m\33[1mFailed tests\33[0m\n'); + }; + + Print.prototype.printTypingsWithoutTestsMessage = function () { + this.out(' \33[36m\33[1mTyping without tests\33[0m\n'); + }; + + Print.prototype.printTotalMessage = function () { + this.out(' \33[36m\33[1mTotal\33[0m\n'); + }; + + Print.prototype.printErrorFile = function (file) { + this.out(' - ' + file + '\n'); + }; + + Print.prototype.printTypingsWithoutTest = function (file) { + this.out(' - \33[33m\33[1m' + file + '\33[0m\n'); + }; + + Print.prototype.breack = function () { + this.out('\n'); + }; + + Print.prototype.printSuccessCount = function (current, total) { + this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + }; + + Print.prototype.printFailedCount = function (current, total) { + this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + }; + + Print.prototype.printElapsedTime = function (time, s) { + this.out(' \33[36m\33[1mElapsed time :\33[0m ~' + time + ' (' + s + 's)\n'); + }; + + Print.prototype.printSyntaxErrorCount = function (current, total) { + this.out(' \33[36m\33[1mSyntaxe error :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + }; + + Print.prototype.printTestErrorCount = function (current, total) { + this.out(' \33[36m\33[1mFailed tests :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + }; + + Print.prototype.printWithoutTestCount = function (current, total) { + this.out(' \33[36m\33[1mWithout tests :\33[0m \33[33m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + }; + return Print; + })(); + + var File = (function () { + function File(name, hasError) { + this.name = name; + this.hasError = hasError; + } + File.prototype.formatName = function (baseDir) { + var dirName = path.dirname(this.name.substr(baseDir.length + 1)).replace('\\', '/'); + var dir = dirName.split('/')[0]; + var file = path.basename(this.name, '.ts'); + var ext = path.extname(this.name); + + return dir + ((dirName.split('/').length > 1) ? '/-/' : '/') + '\33[36m\33[1m' + file + '\33[0m' + ext; + }; + return File; + })(); + + var SyntaxCheking = (function () { + function SyntaxCheking(fielHandler, out) { + this.fielHandler = fielHandler; + this.out = out; + this.files = []; + this.timer = new Timer(); + } + SyntaxCheking.prototype.getFailedFiles = function () { + var list = []; + + for (var i = 0; i < this.files.length; i++) { + if (this.files[i].hasError) { + list.push(this.files[i]); + } + } + + return list; + }; + + SyntaxCheking.prototype.getSuccessFiles = function () { + var list = []; + + for (var i = 0; i < this.files.length; i++) { + if (!this.files[i].hasError) { + list.push(this.files[i]); + } + } + + return list; + }; + + SyntaxCheking.prototype.printStats = function () { + this.out.printDiv(); + this.out.printElapsedTime(this.timer.asString, this.timer.time); + this.out.printSuccessCount(this.getSuccessFiles().length, this.files.length); + this.out.printFailedCount(this.getFailedFiles().length, this.files.length); + }; + + SyntaxCheking.prototype.printFailedFiles = function () { + if (this.getFailedFiles().length > 0) { + this.out.printDiv(); + + this.out.printfilesWithSintaxErrorMessage(); + + this.out.printDiv(); + + for (var i = 0; i < this.getFailedFiles().length; i++) { + var errorFile = this.getFailedFiles()[i]; + this.out.printErrorFile(errorFile.formatName(this.fielHandler.path)); + } + } + }; + + SyntaxCheking.prototype.run = function (it, file, len, maxLen, callback) { + var _this = this; + if (!endsWith(file, '-tests.ts')) { + new Test(file).run(function (o) { + var failed = false; + + if (o.exitCode === 1) { + _this.out.printFailure(); + failed = true; + len++; + } else { + _this.out.printSuccess(); + len++; + } + + _this.files.push(new File(file, failed)); + + if (len > maxLen) { + len = 0; + _this.out.breack(); + } + + if (it.hasNext()) { + _this.run(it, it.next(), len, maxLen, callback); + } else { + _this.out.breack(); + _this.timer.end(); + _this.printFailedFiles(); + _this.printStats(); + + callback(_this.getFailedFiles().length, _this.files.length); + } + }); + } else if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } else { + this.out.breack(); + this.timer.end(); + this.printStats(); + this.printFailedFiles(); + + callback(this.getFailedFiles().length, this.files.length); + } + }; + + SyntaxCheking.prototype.start = function (callback) { + this.timer.start(); + + var tsFiles = this.fielHandler.allTS(); + + var it = new Iterator(tsFiles); + + var len = 0; + var maxLen = 76; + + if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } + }; + return SyntaxCheking; + })(); + + var TestEval = (function () { + function TestEval(fielHandler, out) { + this.fielHandler = fielHandler; + this.out = out; + this.files = []; + this.timer = new Timer(); + } + TestEval.prototype.getFailedFiles = function () { + var list = []; + + for (var i = 0; i < this.files.length; i++) { + if (this.files[i].hasError) { + list.push(this.files[i]); + } + } + + return list; + }; + + TestEval.prototype.getSuccessFiles = function () { + var list = []; + + for (var i = 0; i < this.files.length; i++) { + if (!this.files[i].hasError) { + list.push(this.files[i]); + } + } + + return list; + }; + + TestEval.prototype.printStats = function () { + this.out.printDiv(); + this.out.printElapsedTime(this.timer.asString, this.timer.time); + this.out.printSuccessCount(this.getSuccessFiles().length, this.files.length); + this.out.printFailedCount(this.getFailedFiles().length, this.files.length); + }; + + TestEval.prototype.printFailedFiles = function () { + if (this.getFailedFiles().length > 0) { + this.out.printDiv(); + + this.out.printFailedTestMessage(); + + this.out.printDiv(); + + for (var i = 0; i < this.getFailedFiles().length; i++) { + var errorFile = this.getFailedFiles()[i]; + this.out.printErrorFile(errorFile.formatName(this.fielHandler.path)); + } + } + }; + + TestEval.prototype.run = function (it, file, len, maxLen, callback) { + var _this = this; + if (endsWith(file, '-tests.ts')) { + new Test(file).run(function (o) { + var failed = false; + + if (o.exitCode === 1) { + _this.out.printFailure(); + failed = true; + len++; + } else { + _this.out.printSuccess(); + len++; + } + + _this.files.push(new File(file, failed)); + + if (len > maxLen) { + len = 0; + _this.out.breack(); + } + + if (it.hasNext()) { + _this.run(it, it.next(), len, maxLen, callback); + } else { + _this.out.breack(); + _this.timer.end(); + _this.printFailedFiles(); + _this.printStats(); + + callback(_this.getFailedFiles().length, _this.files.length); + } + }); + } else if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } else { + this.out.breack(); + this.timer.end(); + this.printFailedFiles(); + this.printStats(); + + callback(this.getFailedFiles().length, this.files.length); + } + }; + + TestEval.prototype.start = function (callback) { + this.timer.start(); + + var tsFiles = this.fielHandler.allTS(); + + var it = new Iterator(tsFiles); + + var len = 0; + var maxLen = 76; + + if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } + }; + return TestEval; + })(); + + var TestRunner = (function () { + function TestRunner(dtPath) { + this.dtPath = dtPath; + this.typings = []; + this.fh = new FileHandler(dtPath, /.\.ts/g); + this.out = new Print('0.9.0.0', this.fh.allTypings().length, this.fh.allTS().length); + this.sc = new SyntaxCheking(this.fh, this.out); + this.te = new TestEval(this.fh, this.out); + + var tpgs = this.fh.allTypings(); + for (var i = 0; i < tpgs.length; i++) { + this.typings.push(new Typing(tpgs[i], this.dtPath)); + } + } + TestRunner.prototype.printTypingsWithoutTest = function () { + var count = 0; + + if (this.typings.length > 0) { + this.out.printDiv(); + + this.out.printTypingsWithoutTestsMessage(); + + this.out.printDiv(); + + for (var i = 0; i < this.typings.length; i++) { + var typing = this.typings[i]; + if (typing.fileHandler.allTests().length == 0) { + if (typing.name != '_infrastructure' && typing.name != '_ReSharper.DefinitelyTyped' && typing.name != 'obj' && typing.name != 'bin' && typing.name != 'Properties') { + this.out.printTypingsWithoutTest(typing.name); + count++; + } + } + } + } + + return count; + }; + + TestRunner.prototype.run = function () { + var _this = this; + var timer = new Timer(); + timer.start(); + + this.out.printHeader(); + this.out.printSyntaxCheking(); + + this.sc.start(function (syntaxFailedCount, syntaxTotal) { + _this.out.printTypingTests(); + _this.te.start(function (testFailedCount, testTotal) { + var total = _this.printTypingsWithoutTest(); + + timer.end(); + + _this.out.printDiv(); + _this.out.printTotalMessage(); + _this.out.printDiv(); + + _this.out.printElapsedTime(timer.asString, timer.time); + _this.out.printSyntaxErrorCount(syntaxFailedCount, syntaxTotal); + _this.out.printTestErrorCount(testFailedCount, testTotal); + _this.out.printWithoutTestCount(total, _this.fh.allTypings().length); + + _this.out.printDiv(); + + if (syntaxFailedCount > 0 || testFailedCount > 0) { + process.exit(1); + } + }); + }); + }; + return TestRunner; + })(); + TestManager.TestRunner = TestRunner; + })(DefinitelyTyped.TestManager || (DefinitelyTyped.TestManager = {})); + var TestManager = DefinitelyTyped.TestManager; +})(DefinitelyTyped || (DefinitelyTyped = {})); + +var dtPath = __dirname + '/../..'; + +var runner = new DefinitelyTyped.TestManager.TestRunner(dtPath); +runner.run(); diff --git a/_infrastructure/tests/runner.ts b/_infrastructure/tests/runner.ts new file mode 100644 index 000000000..175194755 --- /dev/null +++ b/_infrastructure/tests/runner.ts @@ -0,0 +1,557 @@ +/// +/// + +module DefinitelyTyped { + + export module TestManager { + + var path = require('path'); + + function endsWith(str, suffix) { + return str.indexOf(suffix, str.length - suffix.length) !== -1; + } + + class Iterator { + index: number = -1; + + constructor(public list: any[]){} + + public next() { + this.index++; + return this.list[this.index]; + } + + public hasNext() { + return this.list[1 + this.index] != null; + } + } + + class Tsc { + public static run(tsfile: string, callback: Function) { + Exec.exec('node ./_infrastructure/tests/typescript/tsc.js ', [tsfile], (ExecResult) => { + callback(ExecResult); + }); + } + } + + class Test { + constructor(public tsfile: string) {} + + public run(callback: Function) { + Tsc.run(this.tsfile , callback); + } + } + + class Typing { + public fileHandler: FileHandler; + + constructor(public name: string, baseDir: string) { + this.fileHandler = new FileHandler(baseDir + '/' + name + '/', /.\.ts/g); + } + } + + class FileHandler { + public files: string[] = []; + public typings: Typing[] = []; + + constructor(public path: string, pattern: any) { + this.files = IO.dir(path, pattern, { recursive: true }); + } + + public allTS(): string[] { + return this.files; + } + + public allTests(): string[] { + var tests = []; + + for(var i = 0; i < this.files.length; i++) { + if (endsWith(this.files[i].toUpperCase(), '-TESTS.TS')) { + tests.push(this.files[i]); + } + } + + return tests; + } + + public allTypings(): string[] { + var typings = {}; + + for(var i = 0; i < this.files.length; i++) { + var file = this.files[i]; + var firName = path.dirname(file.substr(this.path.length + 1)).replace('\\', '/'); + var dir = firName.split('/')[0]; + + if(!typings[dir]) typings[dir] = true; + } + + var list = []; + for(var attr in typings) { + list.push(attr); + } + + return list; + } + } + + class Timer { + public startTime; + public time = 0; + public asString: string; + + private static prettyDate(date1, date2): string { + var diff = ((date2 - date1) / 1000), + day_diff = Math.floor(diff / 86400); + + if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 ) + return; + + return (day_diff == 0 && ( + diff < 60 && (diff + " secconds") || + diff < 120 && "1 minute" || + diff < 3600 && Math.floor( diff / 60 ) + " minutes" || + diff < 7200 && "1 hour" || + diff < 86400 && Math.floor( diff / 3600 ) + " hours") || + day_diff == 1 && "Yesterday" || + day_diff < 7 && day_diff + " days" || + day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks"); + } + + public start() { + this.time = 0; + this.startTime = this.now(); + } + + private now() { + return Date.now(); + } + + public end() { + this.time = (this.now() - this.startTime) / 1000; + this.asString = Timer.prettyDate(this.startTime, this.now()); + } + } + + class Print { + constructor(public version: string, public typings: number, public tsFiles: number) { } + + public out(s) { + process.stdout.write(s); + } + + public printHeader() { + this.out('=============================================================================\n'); + this.out(' \33[36m\33[1mDefinitelyTyped test runner 0.2.0\33[0m\n'); + this.out('=============================================================================\n'); + this.out(' \33[36m\33[1mTypescript version:\33[0m ' + this.version + '\n'); + this.out(' \33[36m\33[1mTypings :\33[0m ' + this.typings + '\n'); + this.out(' \33[36m\33[1mTypeScript files :\33[0m ' + this.tsFiles + '\n'); + } + + public printSyntaxCheking() { + this.out('============================ \33[34m\33[1mSyntax cheking\33[0m =================================\n'); + } + + public printTypingTests() { + this.out('============================= \33[34m\33[1mTyping tests\33[0m ==================================\n'); + } + + public printSuccess() { + this.out('\33[36m\33[1m.\33[0m'); + } + + public printFailure() { + this.out('x'); + } + + public printDiv() { + this.out('-----------------------------------------------------------------------------\n'); + } + + public printfilesWithSintaxErrorMessage() { + this.out(' \33[36m\33[1mFiles with syntax error\33[0m\n'); + } + + public printFailedTestMessage() { + this.out(' \33[36m\33[1mFailed tests\33[0m\n'); + } + + public printTypingsWithoutTestsMessage() { + this.out(' \33[36m\33[1mTyping without tests\33[0m\n'); + } + + public printTotalMessage() { + this.out(' \33[36m\33[1mTotal\33[0m\n'); + } + + public printErrorFile(file) { + this.out(' - ' + file + '\n'); + } + + public printTypingsWithoutTest(file) { + this.out(' - \33[33m\33[1m' + file + '\33[0m\n'); + } + + public breack() { + this.out('\n'); + } + + public printSuccessCount(current: number, total: number) { + this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + + public printFailedCount(current: number, total: number) { + this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + + public printElapsedTime(time, s) { + this.out(' \33[36m\33[1mElapsed time :\33[0m ~' + time + ' (' + s + 's)\n'); + } + + public printSyntaxErrorCount(current: number, total: number) { + this.out(' \33[36m\33[1mSyntaxe error :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + + public printTestErrorCount(current: number, total: number) { + this.out(' \33[36m\33[1mFailed tests :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + + public printWithoutTestCount(current: number, total: number) { + this.out(' \33[36m\33[1mWithout tests :\33[0m \33[33m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + } + + class File { + + constructor(public name: string, public hasError: boolean) {} + + public formatName(baseDir: string): string { + var dirName = path.dirname(this.name.substr(baseDir.length + 1)).replace('\\', '/'); + var dir = dirName.split('/')[0]; + var file = path.basename(this.name, '.ts'); + var ext = path.extname(this.name); + + return dir + ((dirName.split('/').length > 1) ? '/-/' : '/') + '\33[36m\33[1m' + file + '\33[0m' + ext; + } + } + + class SyntaxCheking { + + private timer: Timer; + + public files: File[] = []; + + private getFailedFiles(): File[] { + var list: File[] = []; + + for(var i = 0; i < this.files.length; i++) { + if(this.files[i].hasError) { + list.push(this.files[i]); + } + } + + return list; + } + + private getSuccessFiles(): File[] { + var list: File[] = []; + + for(var i = 0; i < this.files.length; i++) { + if(!this.files[i].hasError) { + list.push(this.files[i]); + } + } + + return list; + } + + constructor(public fielHandler: FileHandler, public out: Print) { + this.timer = new Timer(); + } + + private printStats() { + this.out.printDiv(); + this.out.printElapsedTime(this.timer.asString, this.timer.time); + this.out.printSuccessCount(this.getSuccessFiles().length, this.files.length); + this.out.printFailedCount(this.getFailedFiles().length, this.files.length); + } + + private printFailedFiles() { + if (this.getFailedFiles().length > 0) { + this.out.printDiv(); + + this.out.printfilesWithSintaxErrorMessage(); + + this.out.printDiv(); + + for(var i = 0; i < this.getFailedFiles().length; i++) { + var errorFile = this.getFailedFiles()[i]; + this.out.printErrorFile(errorFile.formatName(this.fielHandler.path)); + } + } + } + + private run(it, file, len, maxLen, callback: Function) { + if (!endsWith(file, '-tests.ts')) { + new Test(file).run((o) => { + var failed = false; + + if(o.exitCode === 1) { + this.out.printFailure(); + failed = true; + len++; + } else { + this.out.printSuccess(); + len++; + } + + this.files.push(new File(file, failed)); + + if(len > maxLen) { + len = 0; + this.out.breack(); + } + + if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } else { + this.out.breack(); + this.timer.end(); + this.printFailedFiles(); + this.printStats(); + + callback(this.getFailedFiles().length, this.files.length); + } + }); + } else if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } else { + this.out.breack(); + this.timer.end(); + this.printStats(); + this.printFailedFiles(); + + callback(this.getFailedFiles().length, this.files.length); + } + } + + public start(callback: Function) { + this.timer.start(); + + var tsFiles = this.fielHandler.allTS(); + + var it = new Iterator(tsFiles); + + var len = 0; + var maxLen = 76; + + if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } + } + } + + class TestEval { + + private timer: Timer; + + public files: File[] = []; + + private getFailedFiles(): File[] { + var list: File[] = []; + + for(var i = 0; i < this.files.length; i++) { + if(this.files[i].hasError) { + list.push(this.files[i]); + } + } + + return list; + } + + private getSuccessFiles(): File[] { + var list: File[] = []; + + for(var i = 0; i < this.files.length; i++) { + if(!this.files[i].hasError) { + list.push(this.files[i]); + } + } + + return list; + } + + constructor(public fielHandler: FileHandler, public out: Print) { + this.timer = new Timer(); + } + + private printStats() { + this.out.printDiv(); + this.out.printElapsedTime(this.timer.asString, this.timer.time); + this.out.printSuccessCount(this.getSuccessFiles().length, this.files.length); + this.out.printFailedCount(this.getFailedFiles().length, this.files.length); + } + + private printFailedFiles() { + if (this.getFailedFiles().length > 0) { + this.out.printDiv(); + + this.out.printFailedTestMessage(); + + this.out.printDiv(); + + for(var i = 0; i < this.getFailedFiles().length; i++) { + var errorFile = this.getFailedFiles()[i]; + this.out.printErrorFile(errorFile.formatName(this.fielHandler.path)); + } + } + } + + private run(it, file, len, maxLen, callback: Function) { + if (endsWith(file, '-tests.ts')) { + new Test(file).run((o) => { + var failed = false; + + if(o.exitCode === 1) { + this.out.printFailure(); + failed = true; + len++; + } else { + this.out.printSuccess(); + len++; + } + + this.files.push(new File(file, failed)); + + if(len > maxLen) { + len = 0; + this.out.breack(); + } + + if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } else { + this.out.breack(); + this.timer.end(); + this.printFailedFiles(); + this.printStats(); + + callback(this.getFailedFiles().length, this.files.length); + } + }); + } else if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } else { + this.out.breack(); + this.timer.end(); + this.printFailedFiles(); + this.printStats(); + + callback(this.getFailedFiles().length, this.files.length); + } + } + + public start(callback: Function) { + this.timer.start(); + + var tsFiles = this.fielHandler.allTS(); + + var it = new Iterator(tsFiles); + + var len = 0; + var maxLen = 76; + + if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } + } + } + + export class TestRunner { + private fh: FileHandler; + private out: Print; + private sc: SyntaxCheking; + private te: TestEval; + private typings: Typing[] = []; + + private printTypingsWithoutTest() { + var count = 0; + + if (this.typings.length > 0) { + this.out.printDiv(); + + this.out.printTypingsWithoutTestsMessage(); + + this.out.printDiv(); + + for(var i = 0; i < this.typings.length; i++) { + var typing = this.typings[i]; + if(typing.fileHandler.allTests().length == 0) { + if (typing.name != '_infrastructure' + && typing.name != '_ReSharper.DefinitelyTyped' + && typing.name != 'obj' + && typing.name != 'bin' + && typing.name != 'Properties') { + this.out.printTypingsWithoutTest(typing.name); + count++; + } + } + } + } + + return count; + } + + constructor(public dtPath: string) { + this.fh = new FileHandler(dtPath, /.\.ts/g); + this.out = new Print('0.9.0.0', this.fh.allTypings().length, this.fh.allTS().length); + this.sc = new SyntaxCheking(this.fh, this.out); + this.te = new TestEval(this.fh, this.out); + + var tpgs = this.fh.allTypings(); + for(var i = 0; i < tpgs.length; i++) { + this.typings.push(new Typing(tpgs[i], this.dtPath)); + } + } + + public run() { + var timer = new Timer(); + timer.start(); + + this.out.printHeader(); + this.out.printSyntaxCheking(); + + this.sc.start((syntaxFailedCount, syntaxTotal) => { + this.out.printTypingTests(); + this.te.start((testFailedCount, testTotal) => { + var total = this.printTypingsWithoutTest(); + + timer.end(); + + this.out.printDiv(); + this.out.printTotalMessage(); + this.out.printDiv(); + + this.out.printElapsedTime(timer.asString, timer.time); + this.out.printSyntaxErrorCount(syntaxFailedCount, syntaxTotal); + this.out.printTestErrorCount(testFailedCount, testTotal); + this.out.printWithoutTestCount(total, this.fh.allTypings().length); + + this.out.printDiv(); + + if (syntaxFailedCount > 0 || testFailedCount > 0) { + process.exit(1); + } + }); + }); + } + } + } +} + +declare var __dirname: any; + +var dtPath = __dirname + '/../..'; + +var runner = new DefinitelyTyped.TestManager.TestRunner(dtPath); +runner.run(); diff --git a/_infrastructure/tests/src/exec.js b/_infrastructure/tests/src/exec.js index 8c18ab42d..f6c3d257c 100644 --- a/_infrastructure/tests/src/exec.js +++ b/_infrastructure/tests/src/exec.js @@ -1,65 +1,65 @@ -var ExecResult = (function () { - function ExecResult() { - this.stdout = ""; - this.stderr = ""; - } - return ExecResult; -})(); - -var WindowsScriptHostExec = (function () { - function WindowsScriptHostExec() { - } - WindowsScriptHostExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { - var result = new ExecResult(); - var shell = new ActiveXObject('WScript.Shell'); - try { - var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' ')); - } catch (e) { - result.stderr = e.message; - result.exitCode = 1; - handleResult(result); - return; - } - - while (process.Status != 0) { - } - - result.exitCode = process.ExitCode; - if (!process.StdOut.AtEndOfStream) - result.stdout = process.StdOut.ReadAll(); - if (!process.StdErr.AtEndOfStream) - result.stderr = process.StdErr.ReadAll(); - - handleResult(result); - }; - return WindowsScriptHostExec; -})(); - -var NodeExec = (function () { - function NodeExec() { - } - NodeExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { - var nodeExec = require('child_process').exec; - - var result = new ExecResult(); - result.exitCode = null; - var cmdLine = filename + ' ' + cmdLineArgs.join(' '); - - var process = nodeExec(cmdLine, function (error, stdout, stderr) { - result.stdout = stdout; - result.stderr = stderr; - result.exitCode = error ? error.code : 0; - handleResult(result); - }); - }; - return NodeExec; -})(); - -var Exec = (function () { - var global = Function("return this;").call(null); - if (typeof global.ActiveXObject !== "undefined") { - return new WindowsScriptHostExec(); - } else { - return new NodeExec(); - } -})(); +var ExecResult = (function () { + function ExecResult() { + this.stdout = ""; + this.stderr = ""; + } + return ExecResult; +})(); + +var WindowsScriptHostExec = (function () { + function WindowsScriptHostExec() { + } + WindowsScriptHostExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { + var result = new ExecResult(); + var shell = new ActiveXObject('WScript.Shell'); + try { + var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' ')); + } catch (e) { + result.stderr = e.message; + result.exitCode = 1; + handleResult(result); + return; + } + + while (process.Status != 0) { + } + + result.exitCode = process.ExitCode; + if (!process.StdOut.AtEndOfStream) + result.stdout = process.StdOut.ReadAll(); + if (!process.StdErr.AtEndOfStream) + result.stderr = process.StdErr.ReadAll(); + + handleResult(result); + }; + return WindowsScriptHostExec; +})(); + +var NodeExec = (function () { + function NodeExec() { + } + NodeExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { + var nodeExec = require('child_process').exec; + + var result = new ExecResult(); + result.exitCode = null; + var cmdLine = filename + ' ' + cmdLineArgs.join(' '); + + var process = nodeExec(cmdLine, function (error, stdout, stderr) { + result.stdout = stdout; + result.stderr = stderr; + result.exitCode = error ? error.code : 0; + handleResult(result); + }); + }; + return NodeExec; +})(); + +var Exec = (function () { + var global = Function("return this;").call(null); + if (typeof global.ActiveXObject !== "undefined") { + return new WindowsScriptHostExec(); + } else { + return new NodeExec(); + } +})(); diff --git a/_infrastructure/tests/src/io.js b/_infrastructure/tests/src/io.js index 772e97c02..0058d59f9 100644 --- a/_infrastructure/tests/src/io.js +++ b/_infrastructure/tests/src/io.js @@ -1,443 +1,445 @@ -var IOUtils; -(function (IOUtils) { - function createDirectoryStructure(ioHost, dirName) { - if (ioHost.directoryExists(dirName)) { - return; - } - - var parentDirectory = ioHost.dirName(dirName); - if (parentDirectory != "") { - createDirectoryStructure(ioHost, parentDirectory); - } - ioHost.createDirectory(dirName); - } - - function createFileAndFolderStructure(ioHost, fileName, useUTF8) { - var path = ioHost.resolvePath(fileName); - var dirName = ioHost.dirName(path); - createDirectoryStructure(ioHost, dirName); - return ioHost.createFile(path, useUTF8); - } - IOUtils.createFileAndFolderStructure = createFileAndFolderStructure; - - function throwIOError(message, error) { - var errorMessage = message; - if (error && error.message) { - errorMessage += (" " + error.message); - } - throw new Error(errorMessage); - } - IOUtils.throwIOError = throwIOError; -})(IOUtils || (IOUtils = {})); - -var IO = (function () { - function getWindowsScriptHostIO() { - var fso = new ActiveXObject("Scripting.FileSystemObject"); - var streamObjectPool = []; - - function getStreamObject() { - if (streamObjectPool.length > 0) { - return streamObjectPool.pop(); - } else { - return new ActiveXObject("ADODB.Stream"); - } - } - - function releaseStreamObject(obj) { - streamObjectPool.push(obj); - } - - var args = []; - for (var i = 0; i < WScript.Arguments.length; i++) { - args[i] = WScript.Arguments.Item(i); - } - - return { - readFile: function (path) { - try { - var streamObj = getStreamObject(); - streamObj.Open(); - streamObj.Type = 2; - streamObj.Charset = 'x-ansi'; - streamObj.LoadFromFile(path); - var bomChar = streamObj.ReadText(2); - streamObj.Position = 0; - if ((bomChar.charCodeAt(0) == 0xFE && bomChar.charCodeAt(1) == 0xFF) || (bomChar.charCodeAt(0) == 0xFF && bomChar.charCodeAt(1) == 0xFE)) { - streamObj.Charset = 'unicode'; - } else if (bomChar.charCodeAt(0) == 0xEF && bomChar.charCodeAt(1) == 0xBB) { - streamObj.Charset = 'utf-8'; - } - - var str = streamObj.ReadText(-1); - streamObj.Close(); - releaseStreamObject(streamObj); - return str; - } catch (err) { - IOUtils.throwIOError("Error reading file \"" + path + "\".", err); - } - }, - writeFile: function (path, contents) { - var file = this.createFile(path); - file.Write(contents); - file.Close(); - }, - fileExists: function (path) { - return fso.FileExists(path); - }, - resolvePath: function (path) { - return fso.GetAbsolutePathName(path); - }, - dirName: function (path) { - return fso.GetParentFolderName(path); - }, - findFile: function (rootPath, partialFilePath) { - var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; - - while (true) { - if (fso.FileExists(path)) { - try { - var content = this.readFile(path); - return { content: content, path: path }; - } catch (err) { - } - } else { - rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); - - if (rootPath == "") { - return null; - } else { - path = fso.BuildPath(rootPath, partialFilePath); - } - } - } - }, - deleteFile: function (path) { - try { - if (fso.FileExists(path)) { - fso.DeleteFile(path, true); - } - } catch (e) { - IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); - } - }, - createFile: function (path, useUTF8) { - try { - var streamObj = getStreamObject(); - streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi'; - streamObj.Open(); - return { - Write: function (str) { - streamObj.WriteText(str, 0); - }, - WriteLine: function (str) { - streamObj.WriteText(str, 1); - }, - Close: function () { - try { - streamObj.SaveToFile(path, 2); - } catch (saveError) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError); - } finally { - if (streamObj.State != 0) { - streamObj.Close(); - } - releaseStreamObject(streamObj); - } - } - }; - } catch (creationError) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError); - } - }, - directoryExists: function (path) { - return fso.FolderExists(path); - }, - createDirectory: function (path) { - try { - if (!this.directoryExists(path)) { - fso.CreateFolder(path); - } - } catch (e) { - IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); - } - }, - dir: function (path, spec, options) { - options = options || {}; - function filesInFolder(folder, root) { - var paths = []; - var fc; - - if (options.recursive) { - fc = new Enumerator(folder.subfolders); - - for (; !fc.atEnd(); fc.moveNext()) { - paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); - } - } - - fc = new Enumerator(folder.files); - - for (; !fc.atEnd(); fc.moveNext()) { - if (!spec || fc.item().Name.match(spec)) { - paths.push(root + "/" + fc.item().Name); - } - } - - return paths; - } - - var folder = fso.GetFolder(path); - var paths = []; - - return filesInFolder(folder, path); - }, - print: function (str) { - WScript.StdOut.Write(str); - }, - printLine: function (str) { - WScript.Echo(str); - }, - arguments: args, - stderr: WScript.StdErr, - stdout: WScript.StdOut, - watchFile: null, - run: function (source, filename) { - try { - eval(source); - } catch (e) { - IOUtils.throwIOError("Error while executing file '" + filename + "'.", e); - } - }, - getExecutingFilePath: function () { - return WScript.ScriptFullName; - }, - quit: function (exitCode) { - if (typeof exitCode === "undefined") { exitCode = 0; } - try { - WScript.Quit(exitCode); - } catch (e) { - } - } - }; - } - ; - - function getNodeIO() { - var _fs = require('fs'); - var _path = require('path'); - var _module = require('module'); - - return { - readFile: function (file) { - try { - var buffer = _fs.readFileSync(file); - switch (buffer[0]) { - case 0xFE: - if (buffer[1] == 0xFF) { - var i = 0; - while ((i + 1) < buffer.length) { - var temp = buffer[i]; - buffer[i] = buffer[i + 1]; - buffer[i + 1] = temp; - i += 2; - } - return buffer.toString("ucs2", 2); - } - break; - case 0xFF: - if (buffer[1] == 0xFE) { - return buffer.toString("ucs2", 2); - } - break; - case 0xEF: - if (buffer[1] == 0xBB) { - return buffer.toString("utf8", 3); - } - } - - return buffer.toString(); - } catch (e) { - IOUtils.throwIOError("Error reading file \"" + file + "\".", e); - } - }, - writeFile: _fs.writeFileSync, - deleteFile: function (path) { - try { - _fs.unlinkSync(path); - } catch (e) { - IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); - } - }, - fileExists: function (path) { - return _fs.existsSync(path); - }, - createFile: function (path, useUTF8) { - function mkdirRecursiveSync(path) { - var stats = _fs.statSync(path); - if (stats.isFile()) { - IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null); - } else if (stats.isDirectory()) { - return; - } else { - mkdirRecursiveSync(_path.dirname(path)); - _fs.mkdirSync(path, 0775); - } - } - - mkdirRecursiveSync(_path.dirname(path)); - - try { - var fd = _fs.openSync(path, 'w'); - } catch (e) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e); - } - return { - Write: function (str) { - _fs.writeSync(fd, str); - }, - WriteLine: function (str) { - _fs.writeSync(fd, str + '\r\n'); - }, - Close: function () { - _fs.closeSync(fd); - fd = null; - } - }; - }, - dir: function dir(path, spec, options) { - options = options || {}; - - function filesInFolder(folder) { - var paths = []; - - var files = _fs.readdirSync(folder); - for (var i = 0; i < files.length; i++) { - var stat = _fs.statSync(folder + "/" + files[i]); - if (options.recursive && stat.isDirectory()) { - paths = paths.concat(filesInFolder(folder + "/" + files[i])); - } else if (stat.isFile() && (!spec || files[i].match(spec))) { - paths.push(folder + "/" + files[i]); - } - } - - return paths; - } - - return filesInFolder(path); - }, - createDirectory: function (path) { - try { - if (!this.directoryExists(path)) { - _fs.mkdirSync(path); - } - } catch (e) { - IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); - } - }, - directoryExists: function (path) { - return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); - }, - resolvePath: function (path) { - return _path.resolve(path); - }, - dirName: function (path) { - return _path.dirname(path); - }, - findFile: function (rootPath, partialFilePath) { - var path = rootPath + "/" + partialFilePath; - - while (true) { - if (_fs.existsSync(path)) { - try { - var content = this.readFile(path); - return { content: content, path: path }; - } catch (err) { - } - } else { - var parentPath = _path.resolve(rootPath, ".."); - - if (rootPath === parentPath) { - return null; - } else { - rootPath = parentPath; - path = _path.resolve(rootPath, partialFilePath); - } - } - } - }, - print: function (str) { - process.stdout.write(str); - }, - printLine: function (str) { - process.stdout.write(str + '\n'); - }, - arguments: process.argv.slice(2), - stderr: { - Write: function (str) { - process.stderr.write(str); - }, - WriteLine: function (str) { - process.stderr.write(str + '\n'); - }, - Close: function () { - } - }, - stdout: { - Write: function (str) { - process.stdout.write(str); - }, - WriteLine: function (str) { - process.stdout.write(str + '\n'); - }, - Close: function () { - } - }, - watchFile: function (filename, callback) { - var firstRun = true; - var processingChange = false; - - var fileChanged = function (curr, prev) { - if (!firstRun) { - if (curr.mtime < prev.mtime) { - return; - } - - _fs.unwatchFile(filename, fileChanged); - if (!processingChange) { - processingChange = true; - callback(filename); - setTimeout(function () { - processingChange = false; - }, 100); - } - } - firstRun = false; - _fs.watchFile(filename, { persistent: true, interval: 500 }, fileChanged); - }; - - fileChanged(); - return { - filename: filename, - close: function () { - _fs.unwatchFile(filename, fileChanged); - } - }; - }, - run: function (source, filename) { - require.main.filename = filename; - require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename))); - require.main._compile(source, filename); - }, - getExecutingFilePath: function () { - return process.mainModule.filename; - }, - quit: process.exit - }; - } - ; - - if (typeof ActiveXObject === "function") - return getWindowsScriptHostIO(); else if (typeof require === "function") - return getNodeIO(); else - return null; -})(); +var IOUtils; +(function (IOUtils) { + function createDirectoryStructure(ioHost, dirName) { + if (ioHost.directoryExists(dirName)) { + return; + } + + var parentDirectory = ioHost.dirName(dirName); + if (parentDirectory != "") { + createDirectoryStructure(ioHost, parentDirectory); + } + ioHost.createDirectory(dirName); + } + + function createFileAndFolderStructure(ioHost, fileName, useUTF8) { + var path = ioHost.resolvePath(fileName); + var dirName = ioHost.dirName(path); + createDirectoryStructure(ioHost, dirName); + return ioHost.createFile(path, useUTF8); + } + IOUtils.createFileAndFolderStructure = createFileAndFolderStructure; + + function throwIOError(message, error) { + var errorMessage = message; + if (error && error.message) { + errorMessage += (" " + error.message); + } + throw new Error(errorMessage); + } + IOUtils.throwIOError = throwIOError; +})(IOUtils || (IOUtils = {})); + +var IO = (function () { + function getWindowsScriptHostIO() { + var fso = new ActiveXObject("Scripting.FileSystemObject"); + var streamObjectPool = []; + + function getStreamObject() { + if (streamObjectPool.length > 0) { + return streamObjectPool.pop(); + } else { + return new ActiveXObject("ADODB.Stream"); + } + } + + function releaseStreamObject(obj) { + streamObjectPool.push(obj); + } + + var args = []; + for (var i = 0; i < WScript.Arguments.length; i++) { + args[i] = WScript.Arguments.Item(i); + } + + return { + readFile: function (path) { + try { + var streamObj = getStreamObject(); + streamObj.Open(); + streamObj.Type = 2; + streamObj.Charset = 'x-ansi'; + streamObj.LoadFromFile(path); + var bomChar = streamObj.ReadText(2); + streamObj.Position = 0; + if ((bomChar.charCodeAt(0) == 0xFE && bomChar.charCodeAt(1) == 0xFF) || (bomChar.charCodeAt(0) == 0xFF && bomChar.charCodeAt(1) == 0xFE)) { + streamObj.Charset = 'unicode'; + } else if (bomChar.charCodeAt(0) == 0xEF && bomChar.charCodeAt(1) == 0xBB) { + streamObj.Charset = 'utf-8'; + } + + var str = streamObj.ReadText(-1); + streamObj.Close(); + releaseStreamObject(streamObj); + return str; + } catch (err) { + IOUtils.throwIOError("Error reading file \"" + path + "\".", err); + } + }, + writeFile: function (path, contents) { + var file = this.createFile(path); + file.Write(contents); + file.Close(); + }, + fileExists: function (path) { + return fso.FileExists(path); + }, + resolvePath: function (path) { + return fso.GetAbsolutePathName(path); + }, + dirName: function (path) { + return fso.GetParentFolderName(path); + }, + findFile: function (rootPath, partialFilePath) { + var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; + + while (true) { + if (fso.FileExists(path)) { + try { + var content = this.readFile(path); + return { content: content, path: path }; + } catch (err) { + } + } else { + rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); + + if (rootPath == "") { + return null; + } else { + path = fso.BuildPath(rootPath, partialFilePath); + } + } + } + }, + deleteFile: function (path) { + try { + if (fso.FileExists(path)) { + fso.DeleteFile(path, true); + } + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + createFile: function (path, useUTF8) { + try { + var streamObj = getStreamObject(); + streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi'; + streamObj.Open(); + return { + Write: function (str) { + streamObj.WriteText(str, 0); + }, + WriteLine: function (str) { + streamObj.WriteText(str, 1); + }, + Close: function () { + try { + streamObj.SaveToFile(path, 2); + } catch (saveError) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError); + } finally { + if (streamObj.State != 0) { + streamObj.Close(); + } + releaseStreamObject(streamObj); + } + } + }; + } catch (creationError) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError); + } + }, + directoryExists: function (path) { + return fso.FolderExists(path); + }, + createDirectory: function (path) { + try { + if (!this.directoryExists(path)) { + fso.CreateFolder(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + dir: function (path, spec, options) { + options = options || {}; + function filesInFolder(folder, root) { + var paths = []; + var fc; + + if (options.recursive) { + fc = new Enumerator(folder.subfolders); + + for (; !fc.atEnd(); fc.moveNext()) { + paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); + } + } + + fc = new Enumerator(folder.files); + + for (; !fc.atEnd(); fc.moveNext()) { + if (!spec || fc.item().Name.match(spec)) { + paths.push(root + "/" + fc.item().Name); + } + } + + return paths; + } + + var folder = fso.GetFolder(path); + var paths = []; + + return filesInFolder(folder, path); + }, + print: function (str) { + WScript.StdOut.Write(str); + }, + printLine: function (str) { + WScript.Echo(str); + }, + arguments: args, + stderr: WScript.StdErr, + stdout: WScript.StdOut, + watchFile: null, + run: function (source, filename) { + try { + eval(source); + } catch (e) { + IOUtils.throwIOError("Error while executing file '" + filename + "'.", e); + } + }, + getExecutingFilePath: function () { + return WScript.ScriptFullName; + }, + quit: function (exitCode) { + if (typeof exitCode === "undefined") { exitCode = 0; } + try { + WScript.Quit(exitCode); + } catch (e) { + } + } + }; + } + ; + + function getNodeIO() { + var _fs = require('fs'); + var _path = require('path'); + var _module = require('module'); + + return { + readFile: function (file) { + try { + var buffer = _fs.readFileSync(file); + switch (buffer[0]) { + case 0xFE: + if (buffer[1] == 0xFF) { + var i = 0; + while ((i + 1) < buffer.length) { + var temp = buffer[i]; + buffer[i] = buffer[i + 1]; + buffer[i + 1] = temp; + i += 2; + } + return buffer.toString("ucs2", 2); + } + break; + case 0xFF: + if (buffer[1] == 0xFE) { + return buffer.toString("ucs2", 2); + } + break; + case 0xEF: + if (buffer[1] == 0xBB) { + return buffer.toString("utf8", 3); + } + } + + return buffer.toString(); + } catch (e) { + IOUtils.throwIOError("Error reading file \"" + file + "\".", e); + } + }, + writeFile: _fs.writeFileSync, + deleteFile: function (path) { + try { + _fs.unlinkSync(path); + } catch (e) { + IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); + } + }, + fileExists: function (path) { + return _fs.existsSync(path); + }, + createFile: function (path, useUTF8) { + function mkdirRecursiveSync(path) { + var stats = _fs.statSync(path); + if (stats.isFile()) { + IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null); + } else if (stats.isDirectory()) { + return; + } else { + mkdirRecursiveSync(_path.dirname(path)); + _fs.mkdirSync(path, 0775); + } + } + + mkdirRecursiveSync(_path.dirname(path)); + + try { + var fd = _fs.openSync(path, 'w'); + } catch (e) { + IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e); + } + return { + Write: function (str) { + _fs.writeSync(fd, str); + }, + WriteLine: function (str) { + _fs.writeSync(fd, str + '\r\n'); + }, + Close: function () { + _fs.closeSync(fd); + fd = null; + } + }; + }, + dir: function dir(path, spec, options) { + options = options || {}; + + function filesInFolder(folder, deep) { + var paths = []; + + var files = _fs.readdirSync(folder); + for (var i = 0; i < files.length; i++) { + var stat = _fs.statSync(folder + "/" + files[i]); + if (options.recursive && stat.isDirectory()) { + if (deep < (options.deep || 100)) { + paths = paths.concat(filesInFolder(folder + "/" + files[i], 1)); + } + } else if (stat.isFile() && (!spec || files[i].match(spec))) { + paths.push(folder + "/" + files[i]); + } + } + + return paths; + } + + return filesInFolder(path, 0); + }, + createDirectory: function (path) { + try { + if (!this.directoryExists(path)) { + _fs.mkdirSync(path); + } + } catch (e) { + IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); + } + }, + directoryExists: function (path) { + return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); + }, + resolvePath: function (path) { + return _path.resolve(path); + }, + dirName: function (path) { + return _path.dirname(path); + }, + findFile: function (rootPath, partialFilePath) { + var path = rootPath + "/" + partialFilePath; + + while (true) { + if (_fs.existsSync(path)) { + try { + var content = this.readFile(path); + return { content: content, path: path }; + } catch (err) { + } + } else { + var parentPath = _path.resolve(rootPath, ".."); + + if (rootPath === parentPath) { + return null; + } else { + rootPath = parentPath; + path = _path.resolve(rootPath, partialFilePath); + } + } + } + }, + print: function (str) { + process.stdout.write(str); + }, + printLine: function (str) { + process.stdout.write(str + '\n'); + }, + arguments: process.argv.slice(2), + stderr: { + Write: function (str) { + process.stderr.write(str); + }, + WriteLine: function (str) { + process.stderr.write(str + '\n'); + }, + Close: function () { + } + }, + stdout: { + Write: function (str) { + process.stdout.write(str); + }, + WriteLine: function (str) { + process.stdout.write(str + '\n'); + }, + Close: function () { + } + }, + watchFile: function (filename, callback) { + var firstRun = true; + var processingChange = false; + + var fileChanged = function (curr, prev) { + if (!firstRun) { + if (curr.mtime < prev.mtime) { + return; + } + + _fs.unwatchFile(filename, fileChanged); + if (!processingChange) { + processingChange = true; + callback(filename); + setTimeout(function () { + processingChange = false; + }, 100); + } + } + firstRun = false; + _fs.watchFile(filename, { persistent: true, interval: 500 }, fileChanged); + }; + + fileChanged(); + return { + filename: filename, + close: function () { + _fs.unwatchFile(filename, fileChanged); + } + }; + }, + run: function (source, filename) { + require.main.filename = filename; + require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename))); + require.main._compile(source, filename); + }, + getExecutingFilePath: function () { + return process.mainModule.filename; + }, + quit: process.exit + }; + } + ; + + if (typeof ActiveXObject === "function") + return getWindowsScriptHostIO(); else if (typeof require === "function") + return getNodeIO(); else + return null; +})(); diff --git a/_infrastructure/tests/src/io.ts b/_infrastructure/tests/src/io.ts index 3c68154a1..9c5345136 100644 --- a/_infrastructure/tests/src/io.ts +++ b/_infrastructure/tests/src/io.ts @@ -25,11 +25,11 @@ interface IFileWatcher { interface IIO { readFile(path: string): string; writeFile(path: string, contents: string): void; - createFile(path: string, useUTF8?: boolean): ITextWriter; + createFile(path: string, useUTF8?: bool): ITextWriter; deleteFile(path: string): void; - dir(path: string, re?: RegExp, options?: { recursive?: boolean; }): string[]; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; + dir(path: string, re?: RegExp, options?: { recursive?: bool; deep?: number; }): string[]; + fileExists(path: string): bool; + directoryExists(path: string): bool; createDirectory(path: string): void; resolvePath(path: string): string; dirName(path: string): string; @@ -60,7 +60,7 @@ module IOUtils { } // Creates a file including its directory structure if not already present - export function createFileAndFolderStructure(ioHost: IIO, fileName: string, useUTF8?: boolean) { + export function createFileAndFolderStructure(ioHost: IIO, fileName: string, useUTF8?: bool) { var path = ioHost.resolvePath(fileName); var dirName = ioHost.dirName(path); createDirectoryStructure(ioHost, dirName); @@ -78,13 +78,13 @@ module IOUtils { // Declare dependencies needed for all supported hosts declare class Enumerator { - public atEnd(): boolean; + public atEnd(): bool; public moveNext(); public item(): any; constructor (o: any); } declare function setTimeout(callback: () =>void , ms?: number); -declare var require: any; +//declare var require: any; declare module process { export var argv: string[]; export var platform: string; @@ -160,7 +160,7 @@ var IO = (function() { file.Close(); }, - fileExists: function(path: string): boolean { + fileExists: function(path: string): bool { return fso.FileExists(path); }, @@ -236,7 +236,7 @@ var IO = (function() { }, directoryExists: function(path) { - return fso.FolderExists(path); + return fso.FolderExists(path); }, createDirectory: function(path) { @@ -250,7 +250,7 @@ var IO = (function() { }, dir: function(path, spec?, options?) { - options = options || <{ recursive?: boolean; }>{}; + options = options || <{ recursive?: bool; deep?: number; }>{}; function filesInFolder(folder, root): string[]{ var paths = []; var fc: Enumerator; @@ -365,7 +365,7 @@ var IO = (function() { IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); } }, - fileExists: function(path): boolean { + fileExists: function(path): bool { return _fs.existsSync(path); }, createFile: function(path, useUTF8?) { @@ -395,16 +395,18 @@ var IO = (function() { }; }, dir: function dir(path, spec?, options?) { - options = options || <{ recursive?: boolean; }>{}; + options = options || <{ recursive?: bool; deep?: number; }>{}; - function filesInFolder(folder: string): string[]{ + function filesInFolder(folder: string, deep?: number): string[]{ var paths = []; var files = _fs.readdirSync(folder); for (var i = 0; i < files.length; i++) { var stat = _fs.statSync(folder + "/" + files[i]); if (options.recursive && stat.isDirectory()) { - paths = paths.concat(filesInFolder(folder + "/" + files[i])); + if (deep < (options.deep || 100)) { + paths = paths.concat(filesInFolder(folder + "/" + files[i], 1)); + } } else if (stat.isFile() && (!spec || files[i].match(spec))) { paths.push(folder + "/" + files[i]); } @@ -413,7 +415,7 @@ var IO = (function() { return paths; } - return filesInFolder(path); + return filesInFolder(path, 0); }, createDirectory: function(path: string): void { try { @@ -425,7 +427,7 @@ var IO = (function() { } }, - directoryExists: function(path: string): boolean { + directoryExists: function(path: string): bool { return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); }, resolvePath: function(path: string): string { diff --git a/_infrastructure/tests/testRunner.js b/_infrastructure/tests/testRunner.js deleted file mode 100644 index a2f54dd5f..000000000 --- a/_infrastructure/tests/testRunner.js +++ /dev/null @@ -1,619 +0,0 @@ -var ExecResult = (function () { - function ExecResult() { - this.stdout = ""; - this.stderr = ""; - } - return ExecResult; -})(); -var WindowsScriptHostExec = (function () { - function WindowsScriptHostExec() { } - WindowsScriptHostExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { - var result = new ExecResult(); - var shell = new ActiveXObject('WScript.Shell'); - try { - var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' ')); - } catch (e) { - result.stderr = e.message; - result.exitCode = 1; - handleResult(result); - return; - } - while(process.Status != 0) { - } - result.exitCode = process.ExitCode; - if(!process.StdOut.AtEndOfStream) { - result.stdout = process.StdOut.ReadAll(); - } - if(!process.StdErr.AtEndOfStream) { - result.stderr = process.StdErr.ReadAll(); - } - handleResult(result); - }; - return WindowsScriptHostExec; -})(); -var NodeExec = (function () { - function NodeExec() { } - NodeExec.prototype.exec = function (filename, cmdLineArgs, handleResult) { - var nodeExec = require('child_process').exec; - var result = new ExecResult(); - result.exitCode = null; - var cmdLine = filename + ' ' + cmdLineArgs.join(' '); - var process = nodeExec(cmdLine, function (error, stdout, stderr) { - result.stdout = stdout; - result.stderr = stderr; - result.exitCode = error ? error.code : 0; - handleResult(result); - }); - }; - return NodeExec; -})(); -var Exec = (function () { - var global = Function("return this;").call(null); - if(typeof global.ActiveXObject !== "undefined") { - return new WindowsScriptHostExec(); - } else { - return new NodeExec(); - } -})(); -var IOUtils; -(function (IOUtils) { - function createDirectoryStructure(ioHost, dirName) { - if(ioHost.directoryExists(dirName)) { - return; - } - var parentDirectory = ioHost.dirName(dirName); - if(parentDirectory != "") { - createDirectoryStructure(ioHost, parentDirectory); - } - ioHost.createDirectory(dirName); - } - function createFileAndFolderStructure(ioHost, fileName, useUTF8) { - var path = ioHost.resolvePath(fileName); - var dirName = ioHost.dirName(path); - createDirectoryStructure(ioHost, dirName); - return ioHost.createFile(path, useUTF8); - } - IOUtils.createFileAndFolderStructure = createFileAndFolderStructure; - function throwIOError(message, error) { - var errorMessage = message; - if(error && error.message) { - errorMessage += (" " + error.message); - } - throw new Error(errorMessage); - } - IOUtils.throwIOError = throwIOError; -})(IOUtils || (IOUtils = {})); - -var IO = (function () { - function getWindowsScriptHostIO() { - var fso = new ActiveXObject("Scripting.FileSystemObject"); - var streamObjectPool = []; - function getStreamObject() { - if(streamObjectPool.length > 0) { - return streamObjectPool.pop(); - } else { - return new ActiveXObject("ADODB.Stream"); - } - } - function releaseStreamObject(obj) { - streamObjectPool.push(obj); - } - var args = []; - for(var i = 0; i < WScript.Arguments.length; i++) { - args[i] = WScript.Arguments.Item(i); - } - return { - readFile: function (path) { - try { - var streamObj = getStreamObject(); - streamObj.Open(); - streamObj.Type = 2; - streamObj.Charset = 'x-ansi'; - streamObj.LoadFromFile(path); - var bomChar = streamObj.ReadText(2); - streamObj.Position = 0; - if((bomChar.charCodeAt(0) == 254 && bomChar.charCodeAt(1) == 255) || (bomChar.charCodeAt(0) == 255 && bomChar.charCodeAt(1) == 254)) { - streamObj.Charset = 'unicode'; - } else if(bomChar.charCodeAt(0) == 239 && bomChar.charCodeAt(1) == 187) { - streamObj.Charset = 'utf-8'; - } - var str = streamObj.ReadText(-1); - streamObj.Close(); - releaseStreamObject(streamObj); - return str; - } catch (err) { - IOUtils.throwIOError("Error reading file \"" + path + "\".", err); - } - }, - writeFile: function (path, contents) { - var file = this.createFile(path); - file.Write(contents); - file.Close(); - }, - fileExists: function (path) { - return fso.FileExists(path); - }, - resolvePath: function (path) { - return fso.GetAbsolutePathName(path); - }, - dirName: function (path) { - return fso.GetParentFolderName(path); - }, - findFile: function (rootPath, partialFilePath) { - var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath; - while(true) { - if(fso.FileExists(path)) { - try { - var content = this.readFile(path); - return { - content: content, - path: path - }; - } catch (err) { - } - } else { - rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath)); - if(rootPath == "") { - return null; - } else { - path = fso.BuildPath(rootPath, partialFilePath); - } - } - } - }, - deleteFile: function (path) { - try { - if(fso.FileExists(path)) { - fso.DeleteFile(path, true); - } - } catch (e) { - IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); - } - }, - createFile: function (path, useUTF8) { - try { - var streamObj = getStreamObject(); - streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi'; - streamObj.Open(); - return { - Write: function (str) { - streamObj.WriteText(str, 0); - }, - WriteLine: function (str) { - streamObj.WriteText(str, 1); - }, - Close: function () { - try { - streamObj.SaveToFile(path, 2); - } catch (saveError) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError); - }finally { - if(streamObj.State != 0) { - streamObj.Close(); - } - releaseStreamObject(streamObj); - } - } - }; - } catch (creationError) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError); - } - }, - directoryExists: function (path) { - return fso.FolderExists(path); - }, - createDirectory: function (path) { - try { - if(!this.directoryExists(path)) { - fso.CreateFolder(path); - } - } catch (e) { - IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); - } - }, - dir: function (path, spec, options) { - options = options || { - }; - function filesInFolder(folder, root) { - var paths = []; - var fc; - if(options.recursive) { - fc = new Enumerator(folder.subfolders); - for(; !fc.atEnd(); fc.moveNext()) { - paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name)); - } - } - fc = new Enumerator(folder.files); - for(; !fc.atEnd(); fc.moveNext()) { - if(!spec || fc.item().Name.match(spec)) { - paths.push(root + "/" + fc.item().Name); - } - } - return paths; - } - var folder = fso.GetFolder(path); - var paths = []; - return filesInFolder(folder, path); - }, - print: function (str) { - WScript.StdOut.Write(str); - }, - printLine: function (str) { - WScript.Echo(str); - }, - arguments: args, - stderr: WScript.StdErr, - stdout: WScript.StdOut, - watchFile: null, - run: function (source, filename) { - try { - eval(source); - } catch (e) { - IOUtils.throwIOError("Error while executing file '" + filename + "'.", e); - } - }, - getExecutingFilePath: function () { - return WScript.ScriptFullName; - }, - quit: function (exitCode) { - if (typeof exitCode === "undefined") { exitCode = 0; } - try { - WScript.Quit(exitCode); - } catch (e) { - } - } - }; - } - ; - function getNodeIO() { - var _fs = require('fs'); - var _path = require('path'); - var _module = require('module'); - return { - readFile: function (file) { - try { - var buffer = _fs.readFileSync(file); - switch(buffer[0]) { - case 254: - if(buffer[1] == 255) { - var i = 0; - while((i + 1) < buffer.length) { - var temp = buffer[i]; - buffer[i] = buffer[i + 1]; - buffer[i + 1] = temp; - i += 2; - } - return buffer.toString("ucs2", 2); - } - break; - case 255: - if(buffer[1] == 254) { - return buffer.toString("ucs2", 2); - } - break; - case 239: - if(buffer[1] == 187) { - return buffer.toString("utf8", 3); - } - } - return buffer.toString(); - } catch (e) { - IOUtils.throwIOError("Error reading file \"" + file + "\".", e); - } - }, - writeFile: _fs.writeFileSync, - deleteFile: function (path) { - try { - _fs.unlinkSync(path); - } catch (e) { - IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e); - } - }, - fileExists: function (path) { - return _fs.existsSync(path); - }, - createFile: function (path, useUTF8) { - function mkdirRecursiveSync(path) { - var stats = _fs.statSync(path); - if(stats.isFile()) { - IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null); - } else if(stats.isDirectory()) { - return; - } else { - mkdirRecursiveSync(_path.dirname(path)); - _fs.mkdirSync(path, 775); - } - } - mkdirRecursiveSync(_path.dirname(path)); - try { - var fd = _fs.openSync(path, 'w'); - } catch (e) { - IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e); - } - return { - Write: function (str) { - _fs.writeSync(fd, str); - }, - WriteLine: function (str) { - _fs.writeSync(fd, str + '\r\n'); - }, - Close: function () { - _fs.closeSync(fd); - fd = null; - } - }; - }, - dir: function dir(path, spec, options) { - options = options || { - }; - function filesInFolder(folder, deep) { - var paths = []; - var files = _fs.readdirSync(folder); - for(var i = 0; i < files.length; i++) { - var stat = _fs.statSync(folder + "/" + files[i]); - if(options.recursive && stat.isDirectory()) { - if(deep < (options.deep || 100)) { - paths = paths.concat(filesInFolder(folder + "/" + files[i], 1)); - } - } else if(stat.isFile() && (!spec || files[i].match(spec))) { - paths.push(folder + "/" + files[i]); - } - } - return paths; - } - return filesInFolder(path, 0); - }, - createDirectory: function (path) { - try { - if(!this.directoryExists(path)) { - _fs.mkdirSync(path); - } - } catch (e) { - IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e); - } - }, - directoryExists: function (path) { - return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory(); - }, - resolvePath: function (path) { - return _path.resolve(path); - }, - dirName: function (path) { - return _path.dirname(path); - }, - findFile: function (rootPath, partialFilePath) { - var path = rootPath + "/" + partialFilePath; - while(true) { - if(_fs.existsSync(path)) { - try { - var content = this.readFile(path); - return { - content: content, - path: path - }; - } catch (err) { - } - } else { - var parentPath = _path.resolve(rootPath, ".."); - if(rootPath === parentPath) { - return null; - } else { - rootPath = parentPath; - path = _path.resolve(rootPath, partialFilePath); - } - } - } - }, - print: function (str) { - process.stdout.write(str); - }, - printLine: function (str) { - process.stdout.write(str + '\n'); - }, - arguments: process.argv.slice(2), - stderr: { - Write: function (str) { - process.stderr.write(str); - }, - WriteLine: function (str) { - process.stderr.write(str + '\n'); - }, - Close: function () { - } - }, - stdout: { - Write: function (str) { - process.stdout.write(str); - }, - WriteLine: function (str) { - process.stdout.write(str + '\n'); - }, - Close: function () { - } - }, - watchFile: function (filename, callback) { - var firstRun = true; - var processingChange = false; - var fileChanged = function (curr, prev) { - if(!firstRun) { - if(curr.mtime < prev.mtime) { - return; - } - _fs.unwatchFile(filename, fileChanged); - if(!processingChange) { - processingChange = true; - callback(filename); - setTimeout(function () { - processingChange = false; - }, 100); - } - } - firstRun = false; - _fs.watchFile(filename, { - persistent: true, - interval: 500 - }, fileChanged); - }; - fileChanged(); - return { - filename: filename, - close: function () { - _fs.unwatchFile(filename, fileChanged); - } - }; - }, - run: function (source, filename) { - require.main.filename = filename; - require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename))); - require.main._compile(source, filename); - }, - getExecutingFilePath: function () { - return process.mainModule.filename; - }, - quit: process.exit - }; - } - ; - if(typeof ActiveXObject === "function") { - return getWindowsScriptHostIO(); - } else if(typeof require === "function") { - return getNodeIO(); - } else { - return null; - } -})(); -var cfg = { - root: '.', - pattern: /.\-tests\.ts/g, - tsc: 'node ./_infrastructure/tests/typescript/tsc.js ', - exclude: { - '.git': true, - '.gitignore': true, - 'package.json': true, - '_infrastructure': true, - '.travis.yml': true, - 'LICENSE': true, - 'README.md': true, - '_ReSharper.DefinitelyTyped': true, - 'obj': true, - 'bin': true, - 'Properties': true, - 'DefinitelyTyped.csproj': true, - 'DefinitelyTyped.csproj.user': true, - 'DefinitelyTyped.sln': true, - 'DefinitelyTyped.v11.suo': true - } -}; -if(process.argv.length > 2) { - cfg.root = process.argv[2]; -} -var TestFile = (function () { - function TestFile() { - this.errors = []; - } - return TestFile; -})(); -var Test = (function () { - function Test(lib) { - this.lib = lib; - this.files = []; - } - return Test; -})(); -var Tests = (function () { - function Tests() { - this.tests = []; - } - return Tests; -})(); -function getLibDirectory(file) { - return file.substr(cfg.root.length).split('/')[1]; -} -function getErrorList(out) { - var splitContentByNewlines = function (content) { - var lines = content.split('\r\n'); - if(lines.length === 1) { - lines = content.split('\n'); - } - return lines; - }; - var result = []; - var lines = splitContentByNewlines(out); - for(var i = 0; i < lines.length; i++) { - if(lines[i]) { - result.push(lines[i]); - } - } - return result; -} -function runTests(testFiles) { - var tests = new Tests(); - Exec.exec(cfg.tsc, [ - testFiles[testIndex] - ], function (ExecResult) { - var lib = getLibDirectory(testFiles[testIndex]); - cache_visited_libs[lib] = true; - var testFile = new TestFile(); - testFile.name = testFiles[testIndex]; - testFile.errors = getErrorList(ExecResult.stderr); - if(testFile.errors.length == 0) { - total_success++; - } else { - total_failure++; - } - console.log(' [\033[36m' + lib + '\033[0m] ' + testFiles[testIndex].substr(cfg.root.length) + ' - ' + (testFile.errors.length == 0 ? '\033[32msuccess\033[0m' : '\033[31mfailure\033[0m')); - var test = new Test(lib); - test.files.push(testFile); - tests.tests.push(test); - testIndex++; - if(testIndex < totalTest) { - Exec.exec(cfg.tsc, [ - testFiles[testIndex] - ], arguments.callee); - } else { - var withoutTests = { - }; - for(var k = 0; k < allFiles.length; k++) { - var rootFolder = allFiles[k].substr(cfg.root.length).split('/')[1]; - if(!(rootFolder in cfg.exclude)) { - if(!(rootFolder in cache_visited_libs)) { - withoutTests[rootFolder] = true; - } - } - } - var withoutTestsCount = 0; - for(var attr in withoutTests) { - var test = new Test(attr); - tests.tests.push(test); - console.log(' [\033[36m' + attr + '\033[0m] without tests'); - withoutTestsCount++; - } - console.log('\n> ' + (total_failure + total_success + withoutTestsCount) + ' tests. ' + '\033[32m' + total_success + ' tests success\033[0m, ' + '\033[31m' + total_failure + ' tests failed\033[0m and ' + withoutTestsCount + ' definitions without tests.\n'); - if(total_failure > 0) { - process.exit(1); - } - } - }); -} -var testFiles = IO.dir(cfg.root, cfg.pattern, { - recursive: true, - deep: 1 -}); -var allFiles = IO.dir(cfg.root, null, { - recursive: true -}); -var totalTest = testFiles.length; -var testIndex = 0; -var cache_visited_libs = { -}; -var total_failure = 0; -var total_success = 0; -var tscVersion = '?.?.?'; -Exec.exec(cfg.tsc, [ - '-version' -], function (ExecResult) { - tscVersion = ExecResult.stdout; - console.log('$ tsc -version'); - console.log(tscVersion); - runTests(testFiles); -}); diff --git a/_infrastructure/tests/testRunner.ts b/_infrastructure/tests/testRunner.ts deleted file mode 100644 index c70da8d3c..000000000 --- a/_infrastructure/tests/testRunner.ts +++ /dev/null @@ -1,168 +0,0 @@ -/// -/// - -var cfg = { - root: '.', - pattern: /.\-tests\.ts/g, - tsc: 'node ./_infrastructure/tests/typescript/tsc.js ', - exclude: { - '.git': true, - '.gitignore': true, - 'package.json': true, - '_infrastructure': true, - '.travis.yml': true, - 'LICENSE': true, - 'README.md': true, - '_ReSharper.DefinitelyTyped': true, - 'obj': true, - 'bin': true, - 'Properties': true, - 'DefinitelyTyped.csproj': true, - 'DefinitelyTyped.csproj.user': true, - 'DefinitelyTyped.sln': true, - 'DefinitelyTyped.v11.suo': true - } -}; - -if (process.argv.length > 2) { - cfg.root = process.argv[2]; -} - -class TestFile { - public name: string; - public errors: string[] = []; -} - -class Test { - public files: TestFile[] = []; - constructor(public lib: string) { } -} - -class Tests { - public tests: Test[] = []; -} - -function getLibDirectory(file: string) { - return file.substr(cfg.root.length).split('/')[1]; -} - -function getErrorList(out): string[] { - var splitContentByNewlines = function (content: string) { - var lines = content.split('\r\n'); - if (lines.length === 1) { - lines = content.split('\n'); - } - return lines; - } - - var result: string[] = []; - - var lines = splitContentByNewlines(out); - - for (var i = 0; i < lines.length; i++) { - if (lines[i]) { - result.push(lines[i]); - } - } - - return result; -} - -function runTests(testFiles) { - var tests = new Tests(); - - Exec.exec( - cfg.tsc, - [testFiles[testIndex]], - (ExecResult) => { - var lib = getLibDirectory(testFiles[testIndex]); - - cache_visited_libs[lib] = true; - - var testFile = new TestFile(); - testFile.name = testFiles[testIndex]; - testFile.errors = getErrorList(ExecResult.stderr); - - if (testFile.errors.length == 0) { - total_success++; - } else { - total_failure++; - } - - console.log(' [\033[36m' + lib + '\033[0m] ' + testFiles[testIndex].substr(cfg.root.length) - + ' - ' + (testFile.errors.length == 0 ? '\033[32msuccess\033[0m' : '\033[31mfailure\033[0m')); - - var test = new Test(lib); - test.files.push(testFile); - tests.tests.push(test); - - testIndex++; - if (testIndex < totalTest) { - Exec.exec( - cfg.tsc, - [testFiles[testIndex]], - <(ExecResult) => any>arguments.callee); - } else { - var withoutTests = {}; - for (var k = 0; k < allFiles.length; k++) { - var rootFolder = allFiles[k].substr(cfg.root.length).split('/')[1]; - if (!(rootFolder in cfg.exclude)) { - if (!(rootFolder in cache_visited_libs)) { - withoutTests[rootFolder] = true; - } - } - } - - var withoutTestsCount = 0; - for (var attr in withoutTests) { - - var test = new Test(attr); - tests.tests.push(test); - - console.log(' [\033[36m' + attr + '\033[0m] without tests'); - withoutTestsCount++; - } - - console.log('\n> ' + (total_failure + total_success + withoutTestsCount) - + ' tests. ' - + '\033[32m' + total_success + ' tests success\033[0m, ' - + '\033[31m' + total_failure + ' tests failed\033[0m and ' - + withoutTestsCount + ' definitions without tests.\n'); - - if (total_failure > 0) { - process.exit(1); - } - } - }); -} - -////// GLOBAL VARS - -// get all files: "*-tests.ts" -var testFiles = IO.dir(cfg.root, cfg.pattern, { recursive: true, deep: 1 }); - -// get all proect files -var allFiles = IO.dir(cfg.root, null, { recursive: true }); - -var totalTest = testFiles.length; -var testIndex = 0; -var cache_visited_libs = {}; - -// total -var total_failure = 0; -var total_success = 0; - -// var to have current typescript version -var tscVersion = '?.?.?'; - -////// END GLOBAL VARS - -// entry point -Exec.exec(cfg.tsc, ['-version'], (ExecResult) => { - tscVersion = ExecResult.stdout; - - console.log('$ tsc -version'); - console.log(tscVersion); - - runTests(testFiles); -}); \ No newline at end of file diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 10fb67a3f..8e5e2a007 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -173,7 +173,7 @@ declare module ng { // see http://docs.angularjs.org/api/ng.$rootScope.Scope /////////////////////////////////////////////////////////////////////////// interface IScope { - // Documentation says exp is optional, but actual implementaton counts on it + $apply(): any; $apply(exp: string): any; $apply(exp: (scope: IScope) => any): any; diff --git a/chai/chai-tests.ts b/chai/chai-tests.ts index ab26aadbc..3774e3895 100644 --- a/chai/chai-tests.ts +++ b/chai/chai-tests.ts @@ -1,5 +1,6 @@ /// +var chai: chai; var expect = chai.expect; function test_be() { diff --git a/chai/chai.d.ts b/chai/chai.d.ts index 5034b8153..f74673727 100644 --- a/chai/chai.d.ts +++ b/chai/chai.d.ts @@ -33,9 +33,9 @@ declare module chai { (expected: RegExp, message?: string); } - interface TypeComparison { + interface TypeComparison { (type: string, message?: string): bool; - instanceof(type: Object): bool; + instanceof(type: Object): bool; } interface NumericComparison { @@ -116,7 +116,10 @@ declare module chai { to: To; } - var expect : { - (target: any): ExpectMatchers; +} + +interface chai { + expect: { + (target: any): chai.ExpectMatchers; } -} \ No newline at end of file +} diff --git a/durandal/durandal.d.ts b/durandal/durandal.d.ts index 33dd732f7..6f3a72a3e 100644 --- a/durandal/durandal.d.ts +++ b/durandal/durandal.d.ts @@ -284,7 +284,7 @@ interface IViewModelDefaults { * called after deactivating a module */ afterDeactivate(): any; -}; +} interface IDurandalViewModelActiveItem { /** @@ -339,7 +339,7 @@ interface IDurandalViewModelActiveItem { * Sets up a collection representing a pool of objects which the activator will activate. See below for details. Activators without an item bool always close their values on deactivate. Activators with an items pool only deactivate, but do not close them. */ forItems(items): IDurandalViewModelActiveItem; -}; +} /** * A router plugin, currently based on SammyJS. The router abstracts away the core configuration of Sammy and re-interprets it in terms of durandal's composition and activation mechanism. To use the router, you must require it, configure it and bind it in the UI. @@ -365,7 +365,7 @@ declare module "durandal/plugins/router" { hash: string; /** only present on visible routes to track if they are active in the nav */ isActive?: KnockoutComputed; - }; + } /** * Parameters to the map function. e only required parameter is url the rest can be derived. The derivation * happens by stripping parameters from the url and casing where appropriate. You can always explicitly provide diff --git a/jquery.pickadate/jquery.pickadate-tests.ts b/jquery.pickadate/jquery.pickadate-tests.ts new file mode 100644 index 000000000..ca68d6e91 --- /dev/null +++ b/jquery.pickadate/jquery.pickadate-tests.ts @@ -0,0 +1,400 @@ +/// + +/* +* Date picker tests +* From http://amsul.ca/pickadate.js/date.htm +*/ + +$('.datepicker').pickadate(); + +$('.datepicker').pickadate({ + weekdaysShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + showMonthsShort: true +}); + +$('.datepicker').pickadate({ + today: '', + clear: 'Clear selection' +}); + +// Extend the default picker options for all instances. +$.extend($.fn.pickadate.defaults, { + monthsFull: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'], + weekdaysShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'], + today: 'aujourd\'hui', + clear: 'effacer', + formatSubmit: 'yyyy/mm/dd' +}); + +// Or, pass the months and weekdays as an array for each invocation. +$('.datepicker').pickadate({ + monthsFull: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'], + weekdaysShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'], + today: 'aujourd\'hui', + clear: 'effacer', + formatSubmit: 'yyyy/mm/dd' +}); + +$('.datepicker').pickadate({ + // Escape any "rule" characters with an exclamation mark (!). + format: 'You selecte!d: dddd, dd mmm, yyyy', + formatSubmit: 'yyyy/mm/dd', + hiddenSuffix: '--submit' +}); + +$('.datepicker').pickadate({ + selectYears: true, + selectMonths: true +}); + +$('.datepicker').pickadate({ + // `true` defaults to 10. + selectYears: 4 +}); + +$('.datepicker').pickadate({ + firstDay: 1 +}); + +$('.datepicker').pickadate({ + min: new Date(2013, 3, 20), + max: new Date(2013, 7, 14) +}); + +$('.datepicker').pickadate({ + min: [2013, 3, 20], + max: [2013, 7, 14] +}); + +$('.datepicker').pickadate({ + // An integer (positive/negative) sets it relative to today. + min: -15, + // `true` sets it to today. `false` removes any limits. + max: true +}); + +$('.datepicker').pickadate({ + disable: [ + [2013, 3, 3], + [2013, 3, 12], + [2013, 3, 20], + [2013, 3, 29] + ] +}); + +$('.datepicker').pickadate({ + disable: [ + 1, 4, 7 + ] +}); + +$('.datepicker').pickadate({ + disable: [ + true, + 1, 4, 7, + [2013, 3, 3], + [2013, 3, 12], + [2013, 3, 20], + [2013, 3, 29] + ] +}); + +$('.datepicker').pickadate({ + onStart: function () { + console.log('Hello there :)') + }, + onRender: function () { + console.log('Whoa.. rendered anew') + }, + onOpen: function () { + console.log('Opened up') + }, + onClose: function () { + console.log('Closed now') + }, + onStop: function () { + console.log('See ya.') + }, + onSet: function (event) { + console.log('Just set stuff:', event) + } +}); + +/* +* Time picker tests +* From http://amsul.ca/pickadate.js/time.htm +*/ + +$('.timepicker').pickatime(); + +$('.timepicker').pickatime({ + clear: '' +}); + +$('.timepicker').pickatime({ + // Escape any "rule" characters with an exclamation mark (!). + format: 'T!ime selected: h:i a', + formatLabel: 'h:i a', + formatSubmit: 'HH:i', + hiddenSuffix: '--submit' +}); + +$('.timepicker').pickatime({ + formatLabel: function (time: TimePickerItemObject) { + var hours = (time.pick - this.get('now').pick) / 60, + label = hours < 0 ? ' !hours to now' : hours > 0 ? ' !hours from now' : 'now' + return 'h:i a ' + (hours ? Math.abs(hours).toString() : '') + label + '' + } +}); + +$('.datepicker').pickadate({ + interval: 150 +}); + +$('.timepicker').pickatime({ + min: [7, 30], + max: [14, 0] +}); + +$('.timepicker').pickatime({ + // An integer (positive/negative) sets it as intervals relative from now. + min: -5, + // `true` sets it to now. `false` removes any limits. + max: true +}); + +$('.timepicker').pickatime({ + disable: [ + [0, 30], + [2, 0], + [8, 30], + [9, 0] + ] +}); + +$('.timepicker').pickatime({ + disable: [ + 3, 5, 7 + ] +}); + +$('.timepicker').pickatime({ + disable: [ + true, + 3, 5, 7, + [0, 30], + [2, 0], + [8, 30], + [9, 0] + ] +}); + +$('.timepicker').pickatime({ + onStart: function () { + console.log('Hello there :)') + }, + onRender: function () { + console.log('Whoa.. rendered anew') + }, + onOpen: function () { + console.log('Opened up') + }, + onClose: function () { + console.log('Closed now') + }, + onStop: function () { + console.log('See ya.') + }, + onSet: function (event) { + console.log('Just set stuff:', event) + } +}); + +/* +* API tests +* From http://amsul.ca/pickadate.js/api.htm +*/ + +var $input = $('.datepicker').pickadate(); + +// Use the picker object directly. +var picker = $input.pickadate('picker'); + +picker.open().clear().close(); + +picker.open(); +picker.close(); +picker.close(true); + +picker.open(false) +$(document).on('click', function () { + picker.close() +}); + +picker.start(); +picker.stop(); +picker.render(); +picker.clear(); + +picker.get() // Short for `picker.get('value')` + +picker.get('select'); +picker.get('select', 'yyyy/mm/dd'); + +picker.get('highlight'); +picker.get('highlight', 'yyyy/mm/dd'); + +picker.get('view'); + +picker.get('min'); +picker.get('min', 'yyyy/mm/dd'); +picker.get('max'); +picker.get('max', 'yyyy/mm/dd'); + +picker.get('open'); +picker.get('start'); +picker.get('id'); +picker.get('disable'); + +picker.set('clear'); + +// Using arrays formatted as [YEAR,MONTH,DATE]. +picker.set('select', [2013, 3, 20]); + +// Using JavaScript Date objects. +picker.set('select', new Date(2013,03,20)); + +// Using positive integers as UNIX timestamps. +picker.set('select', 1365961912346); + +// Using arrays formatted as [HOUR,MINUTE]. +picker.set('select', [3, 0]); + +// Using positive integers as minutes. +picker.set('select', 540); + +// Using arrays formatted as [YEAR,MONTH,DATE]. +picker.set('highlight', [2013, 3, 20]); + +// Using JavaScript Date objects. +picker.set('highlight', new Date(2013,7,14)); + +// Using positive integers as UNIX timestamps. +picker.set('highlight', 1365961912346); + +// Using arrays formatted as [HOUR,MINUTE]. +picker.set('highlight', [15, 30]); + +// Using positive integers as minutes. +picker.set('highlight', 1080); + +// Using arrays formatted as [YEAR,MONTH,DATE]. +picker.set('view', [2000, 3, 20]); + +// Using JavaScript Date objects. +picker.set('view', new Date(1988,7,14)); + +// Using positive integers as UNIX timestamps. +picker.set('view', 1587355200000); + +// Using arrays formatted as [HOUR,MINUTE]. +picker.set('view', [15, 30]); + +// Using positive integers as minutes. +picker.set('view', 1080); + +// Using arrays formatted as [YEAR,MONTH,DATE]. +picker.set('min', [2013, 3, 20]); + +// Using JavaScript Date objects. +picker.set('min', new Date(2013,7,14)); + +// Using integers as days relative to today. +picker.set('min', -4); + +// Using `true` for "today". +picker.set('min', true); + +// Using `false` to remove. +picker.set('min', false); + +// Using arrays formatted as [HOUR,MINUTE]. +picker.set('min', [15, 30]); + +// Using integers as intervals relative from now. +picker.set('min', -4); + +// Using `true` for "now". +picker.set('min', true); + +// Using `false` to remove. +picker.set('min', false); + +// Using arrays formatted as [YEAR,MONTH,DATE]. +picker.set('max', [2013, 3, 20]); + +// Using JavaScript Date objects. +picker.set('max', new Date(2013,7,14)); + +// Using integers as days relative to today. +picker.set('max', 4); + +// Using `true` for "today". +picker.set('max', true); + +// Using `false` to remove. +picker.set('max', false); + +// Using arrays formatted as [HOUR,MINUTE]. +picker.set('max', [15, 30]); + +// Using integers as intervals relative from now. +picker.set('max', 4); + +// Using `true` for "now". +picker.set('max', true); + +// Using `false` to remove. +picker.set('max', false); + +picker.on('open', function () { + console.log('Opened.. and here I am!'); +}); + +picker.on({ + open: function () { + console.log('Opened.. and here I am!'); + }, + close: function () { + console.log('Closed.. and here I am!'); + } +}); + +$('.datepicker').pickadate({ + onOpen: function () { + console.log('Opened up!') + }, + onClose: function () { + console.log('Closed now') + }, + onRender: function () { + console.log('Just rendered anew') + }, + onStart: function () { + console.log('Hello there :)') + }, + onStop: function () { + console.log('See ya') + }, + onSet: function (event) { + console.log('Set stuff:', event) + } +}); + +picker.on('open', function () { + console.log('Didn't open.. yet here I am!'); +}) +picker.trigger('open'); + +picker.$node; +picker.$root; \ No newline at end of file diff --git a/jquery.pickadate/jquery.pickadate.d.ts b/jquery.pickadate/jquery.pickadate.d.ts new file mode 100644 index 000000000..0de785108 --- /dev/null +++ b/jquery.pickadate/jquery.pickadate.d.ts @@ -0,0 +1,375 @@ +// Type definitions for pickadate.js 3.0.5 +// Project: https://github.com/amsul/pickadate.js +// Definitions by: Theodore Brown +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface pickadateOptions { + // Strings and translations + monthsFull?: string[]; // default 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' + monthsShort?: string[]; // default 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' + weekdaysFull?: string[]; // default 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' + weekdaysShort?: string[]; // default 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' + showMonthsShort?: boolean; + showWeekdaysFull?: boolean; + + // Buttons + today?: string; // default 'Today' + clear?: string; // default 'Clear' + + // Formats + format?: string; // default 'd mmmm, yyyy' + formatSubmit?: string; // e.g. 'yyyy/mm/dd' + hiddenSuffix?: string; // default '_submit' + + // Dropdown selectors + selectYears?: any; // Specify the number of years selectable using an even integer - half before and half after the year in focus: + selectMonths?: boolean; + + // First day of the week + firstDay?: any; // The first day of the week can be set to either Sunday or Monday. Anything truth-y sets it as Monday and anything false-y as Sunday + + // Date limits + min?: any; // date object, array formatted as [YEAR,MONTH,DATE], or dates relative to today using integers or a boolean (`true` sets it to today. `false` removes any limits). + max?: any; + + // Disable dates + disable?: any[]; // arrays formatted as [YEAR,MONTH,DATE] or integers representing days of the week (from 1 to 7). Switch to whitelist by setting first item in collection to `true`. + + // Events + onStart?: (event: any) => void; + onRender?: (event: any) => void; + onOpen?: (event: any) => void; + onClose?: (event: any) => void; + onSet?: (event: any) => void; + onStop?: (event: any) => void; + + // Classes + klass?: { + + // The element states + input?: string; // default 'picker__input' + active?: string; // default 'picker__input--active' + + // The root picker and states + picker?: string; // default 'picker' + opened?: string; // default 'picker--opened' + focused?: string; // default 'picker--focused' + + // The picker holder + holder?: string; // default 'picker__holder' + + // The picker frame, wrapper, and box + frame?: string; // default 'picker__frame' + wrap?: string; // default 'picker__wrap' + box?: string; // default 'picker__box' + + // The picker header + header?: string; // default 'picker__header' + + // Month navigation + navPrev?: string; // default 'picker__nav--prev' + navNext?: string; // default 'picker__nav--next' + navDisabled?: string; // default 'picker__nav--disabled' + + // Month & year labels + month?: string; // default 'picker__month' + year?: string; // default 'picker__year' + + // Month & year dropdowns + selectMonth?: string; // default 'picker__select--month' + selectYear?: string; // default 'picker__select--year' + + // Table of dates + table?: string; // default 'picker__table' + + // Weekday labels + weekdays?: string; // default 'picker__weekday' + + // Day states + day?: string; // default 'picker__day' + disabled?: string; // default 'picker__day--disabled' + selected?: string // default 'picker__day--selected' + highlighted?: string // default 'picker__day--highlighted' + now?: string; // default 'picker__day--today' + infocus?: string; // default 'picker__day--infocus' + outfocus?: string; // default 'picker__day--outfocus' + + // The picker footer + footer?: string; // default 'picker__footer' + + // Today & clear buttons + buttonClear?: string; // default 'picker__button--clear' + buttonToday?: string; // default 'picker__button--today' + } +} + +interface pickatimeOptions { + // Translations and clear button + clear?: string; // default 'Clear' + + // Formats + format?: string; // default 'h:i A' + formatLabel?: any; + formatSubmit?: string; + hiddenSuffix?: string; // default '_submit' + + // Time intervals + interval?: number; // interval in minutes. default 30. + + // Time limits + min?: any; // array formatted as [HOUR,MINUTE], or as times relative to now using integers or a boolean (`true` sets it to now, `false` removes any limits). + max?: any; + + // Disable times + disable?: any[]; // arrays formatted as [HOUR,MINUTE] or integers representing hours (from 0 to 23). Switch to whitelist by setting true as the first item in the collection. + + // Events + onStart?: (event: any) => void; + onRender?: (event: any) => void; + onOpen?: (event: any) => void; + onClose?: (event: any) => void; + onSet?: (event: any) => void; + onStop?: (event: any) => void; + + // Classes + klass?: { + + // The element states + input?: string; // default 'picker__input' + active?: string; // default 'picker__input--active' + + // The root picker and states + picker?: string; // default 'picker picker--time' + opened?: string; // default 'picker--opened' + focused?: string; // default 'picker--focused' + + // The picker holder + holder?: string; // default 'picker__holder' + + // The picker frame, wrapper, and box + frame?: string; // default 'picker__frame' + wrap?: string; // default 'picker__wrap' + box?: string; // default 'picker__box' + + // List of times + list?: string; // default 'picker__list' + listItem?: string; // default 'picker__list-item' + + // Time states + disabled?: string; // default 'picker__list-item--disabled' + selected?: string; // default 'picker__list-item--selected' + highlighted?: string; // default 'picker__list-item--highlighted' + viewset?: string; // default 'picker__list-item--viewset' + now?: string; // default 'picker__list-item--now' + + // Clear button + buttonClear?: string; // default 'picker__button--clear' + } +} + +interface PickerItemObject { + /** The "pick" value used for comparisons. */ + pick: number; +} + +interface DatePickerItemObject extends PickerItemObject { + /** The full year. */ + year: number; + + /** The month with zero-as-index. */ + month: number; + + /** The date of the month. */ + date: number; + + /** The day of the week with zero-as-index. */ + day: number; + + /** The underlying JavaScript Date object. */ + obj: Date; +} + +interface TimePickerItemObject extends PickerItemObject { + /** Hour of the day from 0 to 23. */ + hour: number; + + /** The minutes of the hour from 0 to 59 (based on the interval). */ + mins: number; +} + +interface CallbackObject { + open?: () => void; + close?: () => void; + render?: () => void; + start?: () => void; + stop?: () => void; + set?: () => void; +} + +interface SetThings { + clear?; + select?: any; + highlight?: any; + view?: any; + min?: any; + max?: any; + disable?: any; + enable?: any; +} + +interface TimePickerSetThings extends SetThings { + interval?: any; +} + +interface PickerObject { + /** The picker's relative input element wrapped as a jQuery object. */ + $node: JQuery; + + /** The picker's relative root holder element wrapped as a jQuery object. */ + $root: JQuery; +} + +interface DatePickerObject extends PickerObject { + open(withoutFocus?: boolean): DatePickerObject; + close(withFocus?: boolean): DatePickerObject; + + /** Rebuild the picker. */ + start(): DatePickerObject; + + /** Destroy the picker. */ + stop(): DatePickerObject; + + /** Refresh the picker after adding something to the holder. */ + render(): DatePickerObject; + + /** Clear the value in the picker's input element. */ + clear(): DatePickerObject; + + /** Get the properties, objects, and states that make up the current state of the picker. */ + get(thing: string): any; + + /** Returns the string value of the picker's input element. */ + get(thing?: 'value'): string; + + /** Returns the item object that is visually selected. */ + get(thing: 'select'): DatePickerItemObject; + + /** Returns the item object that is visually highlighted. */ + get(thing: 'highlight'): DatePickerItemObject; + + /** Returns the item object that sets the current view. */ + get(thing: 'view'): DatePickerItemObject; + + /** Returns the item object that limits the picker�s lower range. */ + get(thing: 'min'): DatePickerItemObject; + + /** Returns the item object that limits the picker�s upper range. */ + get(thing: 'max'): DatePickerItemObject; + + /** Returns a boolean value of whether the picker is open or not. */ + get(thing: 'open'): boolean; + + /** Returns a boolean value of whether the picker has started or not. */ + get(thing: 'start'): boolean; + + /** Returns a unique 9-digit integer that is the ID of the picker. */ + get(thing: 'id'): number; + + /** Returns an array of items that determine which item objects to disable on the picker. */ + get(thing: 'disable'): any[]; + + /** Returns a formatted string for the item object specified by `thing` */ + get(thing: string, format: string): string; + + /** Set the properties, objects, and states to change the state of the picker. */ + set(thing: string, value?: any): DatePickerObject; + set(things: SetThings): DatePickerObject; + + /** Bind callbacks to get fired off when the relative picker method is called. */ + on(methodName, callback: () => void ): DatePickerObject; + + /** Bind multiple callbacks at once to get fired off when the relative picker method is called. */ + on(callbackObject: CallbackObject): DatePickerObject; + + /** Trigger callbacks that have been queued up using the the on method. */ + trigger(event: string): DatePickerObject; +} + +interface TimePickerObject extends PickerObject { + open(withoutFocus?: boolean): TimePickerObject; + close(withFocus?: boolean): TimePickerObject; + + /** Rebuild the picker. */ + start(): TimePickerObject; + + /** Destroy the picker. */ + stop(): TimePickerObject; + + /** Refresh the picker after adding something to the holder. */ + render(): TimePickerObject; + + /** Clear the value in the picker�s input element. */ + clear(): TimePickerObject; + + /** Get the properties, objects, and states that make up the current state of the picker. */ + get(thing: string): any; + + /** Returns the string value of the picker�s input element. */ + get(thing?: 'value'): string; + + /** Returns the item object that is visually selected. */ + get(thing: 'select'): TimePickerItemObject; + + /** Returns the item object that is visually highlighted. */ + get(thing: 'highlight'): TimePickerItemObject; + + /** Returns the item object that sets the current view. */ + get(thing: 'view'): TimePickerItemObject; + + /** Returns the item object that limits the picker�s lower range. */ + get(thing: 'min'): TimePickerItemObject; + + /** Returns the item object that limits the picker�s upper range. */ + get(thing: 'max'): TimePickerItemObject; + + /** Returns a boolean value of whether the picker is open or not. */ + get(thing: 'open'): boolean; + + /** Returns a boolean value of whether the picker has started or not. */ + get(thing: 'start'): boolean; + + /** Returns a unique 9-digit integer that is the ID of the picker. */ + get(thing: 'id'): number; + + /** Returns an array of items that determine which item objects to disable on the picker. */ + get(thing: 'disable'): any[]; + + /** Returns a formatted string for the item object specified by `thing` */ + get(thing: string, format: string): string; + + /** Set the properties, objects, and states to change the state of the picker. */ + set(thing: string, value?: any): TimePickerObject; + set(things: TimePickerSetThings): TimePickerObject; + + /** Bind callbacks to get fired off when the relative picker method is called. */ + on(methodName, callback: () => void ): TimePickerObject; + + /** Bind multiple callbacks at once to get fired off when the relative picker method is called. */ + on(callbackObject: CallbackObject): TimePickerObject; + + /** Trigger callbacks that have been queued up using the the on method. */ + trigger(event: string): TimePickerObject; +} + +interface JQuery { + pickadate(options?: pickadateOptions): HTMLInputElement; + pickatime(options?: pickatimeOptions): HTMLInputElement; +} + +interface HTMLInputElement { + pickadate(picker: string): DatePickerObject; + pickatime(picker: string): TimePickerObject; + +} \ No newline at end of file diff --git a/knockout.mapping/knockout.mapping.d.ts b/knockout.mapping/knockout.mapping.d.ts index 69b6ccaff..010f18801 100644 --- a/knockout.mapping/knockout.mapping.d.ts +++ b/knockout.mapping/knockout.mapping.d.ts @@ -13,7 +13,7 @@ interface KnockoutMappingCreateOptions { interface KnockoutMappingUpdateOptions { data: any; parent: any; - observable: KnockoutObservableAny; + observable: KnockoutObservable; } interface KnockoutMappingOptions { diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index ba9e74303..f0909ddc9 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -15,7 +15,7 @@ interface KnockoutSubscribableFunctions { interface KnockoutComputedFunctions extends KnockoutSubscribableFunctions { getDependenciesCount(): number; - hasWriteFunction(): bool; + hasWriteFunction(): boolean; } interface KnockoutObservableFunctions extends KnockoutSubscribableFunctions { @@ -72,15 +72,15 @@ interface KnockoutComputed extends KnockoutComputedFunctions { (value: T): void; subscribe(callback: (newValue: T) => void, target?:any, topic?: string): KnockoutSubscription; - notifySubscribers(valueToWrite: T, topic?: string); + notifySubscribers(valueToWrite: T, topic?: string); } interface KnockoutObservableArrayStatic { fn: KnockoutObservableArrayFunctions; - + (): KnockoutObservableArray; - (value: T[]): KnockoutObservableArray; + (value: T[]): KnockoutObservableArray; } interface KnockoutObservableArray extends KnockoutObservableArrayFunctions { @@ -94,17 +94,18 @@ interface KnockoutObservableArray extends KnockoutObservableArrayFunctions interface KnockoutObservableStatic { fn: KnockoutObservableFunctions; - (value: T): KnockoutObservable; + (value?: T): KnockoutObservable; + (): KnockoutObservable; } /** use as method to get/set the value */ interface KnockoutObservableBase extends KnockoutObservableFunctions { getSubscriptionsCount(): number; } - + interface KnockoutObservable extends KnockoutObservableBase { (): T; - (value: T): void; + (value: T): void; subscribe(callback: (newValue: T) => void, target?:any, topic?: string): KnockoutSubscription; notifySubscribers(valueToWrite: T, topic?: string); @@ -175,7 +176,7 @@ interface KnockoutMemoization { interface KnockoutVirtualElement {} interface KnockoutVirtualElements { - allowedBindings: { [bindingName: string]: bool; }; + allowedBindings: { [bindingName: string]: boolean; }; emptyNode( e: KnockoutVirtualElement ); firstChild( e: KnockoutVirtualElement ); insertAfter( container: KnockoutVirtualElement, nodeToInsert: HTMLElement, insertAfter: HTMLElement ); @@ -215,7 +216,7 @@ interface KnockoutUtils { set (node: Element, key: string, value: any); - getAll(node: Element, createIfNotFound: bool); + getAll(node: Element, createIfNotFound: boolean); clear(node: Element); }; @@ -244,7 +245,7 @@ interface KnockoutUtils { arrayIndexOf(array: any[], item: any): number; - arrayFirst(array: any[], predicate: (item) => bool, predicateOwner?: any): any; + arrayFirst(array: any[], predicate: (item) => boolean, predicateOwner?: any): any; arrayRemoveItem(array: any[], itemToRemove: any): void; @@ -252,7 +253,7 @@ interface KnockoutUtils { arrayMap(array: any[], mapping: (item) => any): any[]; - arrayFilter(array: any[], predicate: (item) => bool): any[]; + arrayFilter(array: any[], predicate: (item) => boolean): any[]; arrayPushAll(array: any[], valuesToPush: any[]): any[]; @@ -262,13 +263,13 @@ interface KnockoutUtils { moveCleanedNodesToContainerElement(nodes: any[]): HTMLElement; - cloneNodes(nodesArray: any[], shouldCleanNodes: bool): any[]; + cloneNodes(nodesArray: any[], shouldCleanNodes: boolean): any[]; setDomNodeChildren(domNode: any, childNodes: any[]): void; replaceDomNodes(nodeToReplaceOrNodeArray: any, newNodesArray: any[]): void; - setOptionNodeSelectionState(optionNode: any, isSelected: bool): void; + setOptionNodeSelectionState(optionNode: any, isSelected: boolean): void; stringTrim(str: string): string; @@ -276,9 +277,9 @@ interface KnockoutUtils { stringStartsWith(str: string, startsWith: string): string; - domNodeIsContainedBy(node: any, containedByNode: any): bool; + domNodeIsContainedBy(node: any, containedByNode: any): boolean; - domNodeIsAttachedToDocument(node: any): bool; + domNodeIsAttachedToDocument(node: any): boolean; tagNameLower(element: any): string; @@ -288,7 +289,7 @@ interface KnockoutUtils { unwrapObservable(value: any): any; - toggleDomNodeCssClass(node: any, className: string, shouldHaveClass: bool): void; + toggleDomNodeCssClass(node: any, className: string, shouldHaveClass: boolean): void; //setTextContent(element: any, textContent: string): void; // NOT PART OF THE MINIFIED API SURFACE (ONLY IN knockout-{version}.debug.js) https://github.com/SteveSanderson/knockout/issues/670 @@ -314,9 +315,9 @@ interface KnockoutUtils { ieVersion: number; - isIe6: bool; + isIe6: boolean; - isIe7: bool; + isIe7: boolean; } ////////////////////////////////// @@ -364,7 +365,7 @@ interface KnockoutTemplateEngine extends KnockoutNativeTemplateEngine { renderTemplate(template, bindingContext, options, templateDocument); - isTemplateRewritten(template, templateDocument): bool; + isTemplateRewritten(template, templateDocument): boolean; rewriteTemplate(template, rewriterCallback, templateDocument); } @@ -388,11 +389,11 @@ interface KnockoutStatic { observableArray: KnockoutObservableArrayStatic; contextFor(node: any): any; - isSubscribable(instance: any): bool; + isSubscribable(instance: any): boolean; toJSON(viewModel: any, replacer?: Function, space?: any): string; toJS(viewModel: any): any; - isObservable(instance: any): bool; - isComputed(instance: any): bool; + isObservable(instance: any): boolean; + isComputed(instance: any): boolean; dataFor(node: any): any; removeNode(node: Element); cleanNode(node: Element); diff --git a/knockout/tests/knockout-templatingBehaviors-tests.ts b/knockout/tests/knockout-templatingBehaviors-tests.ts index b000015f2..7be02d4cd 100644 --- a/knockout/tests/knockout-templatingBehaviors-tests.ts +++ b/knockout/tests/knockout-templatingBehaviors-tests.ts @@ -2,8 +2,6 @@ /// /// -declare var $; - var dummyTemplateEngine = function (templates?) { var inMemoryTemplates = templates || {}; var inMemoryTemplateData = {}; @@ -137,7 +135,7 @@ describe('Templating', function() { }); it('Should automatically rerender into DOM element when dependencies change', function () { - var dependency = new ko.observable("A"); + var dependency = ko.observable("A"); ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: function () { return "Value = " + dependency(); } @@ -153,7 +151,7 @@ describe('Templating', function() { }); it('Should not rerender DOM element if observable accessed in \'afterRender\' callaback is changed', function () { - var observable = new ko.observable("A"), count = 0; + var observable = ko.observable("A"), count = 0; var myCallback = function(elementsArray, dataItem) { observable(); // access observable in callback }; @@ -171,7 +169,7 @@ describe('Templating', function() { }); it('If the supplied data item is observable, evaluates it and has subscription on it', function () { - var observable = new ko.observable("A"); + var observable = ko.observable("A"); ko.setTemplateEngine(new dummyTemplateEngine({ someTemplate: function (data) { return "Value = " + data; } @@ -184,7 +182,7 @@ describe('Templating', function() { }); it('Should stop updating DOM nodes when the dependency next changes if the DOM node has been removed from the document', function () { - var dependency = new ko.observable("A"); + var dependency = ko.observable("A"); var template = { someTemplate: function () { return "Value = " + dependency() } }; ko.setTemplateEngine(new dummyTemplateEngine(template)); @@ -275,7 +273,7 @@ describe('Templating', function() { }); it('Should rerender chained templates when their dependencies change, without rerendering parent templates', function () { - var observable = new ko.observable("ABC"); + var observable = ko.observable("ABC"); var timesRenderedOuter = 0, timesRenderedInner = 0; ko.setTemplateEngine(new dummyTemplateEngine({ outerTemplate: function () { timesRenderedOuter++; return "outer template output, [renderTemplate:innerTemplate]" }, // [renderTemplate:...] is special syntax supported by dummy template engine @@ -390,7 +388,7 @@ describe('Templating', function() { }); it('Data binding syntax should support \'foreach\' option, whereby it renders for each item in an array but doesn\'t rerender everything if you push or splice', function () { - var myArray = new ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); + var myArray = ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "
The item is [js: personName]
" })); testNode.innerHTML = "
"; @@ -406,7 +404,7 @@ describe('Templating', function() { }); it('Data binding \'foreach\' option should apply bindings within the context of each item in the array', function () { - var myArray = new ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); + var myArray = ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item is " })); testNode.innerHTML = "
"; @@ -479,7 +477,7 @@ describe('Templating', function() { }); it('Data binding \'foreach\' option should apply bindings with an $index in the context', function () { - var myArray = new ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); + var myArray = ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item # is " })); testNode.innerHTML = "
"; @@ -488,7 +486,7 @@ describe('Templating', function() { }); it('Data binding \'foreach\' option should update bindings that reference an $index if the list changes', function () { - var myArray = new ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); + var myArray = ko.observableArray([{ personName: "Bob" }, { personName: "Frank"}]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item is " })); testNode.innerHTML = "
"; @@ -504,7 +502,7 @@ describe('Templating', function() { }); it('Data binding \'foreach\' option should accept array with "undefined" and "null" items', function () { - var myArray = new ko.observableArray([undefined, null]); + var myArray = ko.observableArray([undefined, null]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item is " })); testNode.innerHTML = "
"; @@ -513,8 +511,8 @@ describe('Templating', function() { }); it('Data binding \'foreach\' option should update DOM nodes when a dependency of their mapping function changes', function() { - var myObservable = new ko.observable("Steve"); - var myArray = new ko.observableArray([{ personName: "Bob" }, { personName: myObservable }, { personName: "Another" }]); + var myObservable = ko.observable("Steve"); + var myArray = ko.observableArray([{ personName: "Bob" }, { personName: myObservable }, { personName: "Another" }]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "
The item is [js: ko.utils.unwrapObservable(personName)]
" })); testNode.innerHTML = "
"; @@ -535,7 +533,7 @@ describe('Templating', function() { }); it('Data binding \'foreach\' option should treat a null parameter as meaning \'no items\'', function() { - var myArray = new ko.observableArray(["A", "B"]); + var myArray = ko.observableArray(["A", "B"]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "hello" })); testNode.innerHTML = "
"; @@ -551,7 +549,7 @@ describe('Templating', function() { it('Data binding \'foreach\' option should accept an \"as\" option to define an alias for the iteration variable', function() { // Note: There are more detailed specs (e.g., covering nesting) associated with the "foreach" binding which // uses this templating functionality internally. - var myArray = new ko.observableArray(["A", "B"]); + var myArray = ko.observableArray(["A", "B"]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "[js:myAliasedItem]" })); testNode.innerHTML = "
"; @@ -561,7 +559,7 @@ describe('Templating', function() { it('Data binding \'foreach\' option should stop tracking inner observables when the container node is removed', function() { var innerObservable = ko.observable("some value"); - var myArray = new ko.observableArray([{obsVal:innerObservable}, {obsVal:innerObservable}]); + var myArray = ko.observableArray([{obsVal:innerObservable}, {obsVal:innerObservable}]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item is [js: ko.utils.unwrapObservable(obsVal)]" })); testNode.innerHTML = "
"; @@ -574,7 +572,7 @@ describe('Templating', function() { it('Data binding \'foreach\' option should stop tracking inner observables related to each array item when that array item is removed', function() { var innerObservable = ko.observable("some value"); - var myArray = new ko.observableArray([{obsVal:innerObservable}, {obsVal:innerObservable}]); + var myArray = ko.observableArray([{obsVal:innerObservable}, {obsVal:innerObservable}]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "The item is [js: ko.utils.unwrapObservable(obsVal)]" })); testNode.innerHTML = "
"; @@ -588,7 +586,7 @@ describe('Templating', function() { }); it('Data binding syntax should omit any items whose \'_destroy\' flag is set (unwrapping the flag if it is observable)', function() { - var myArray = new ko.observableArray([{ someProp: 1 }, { someProp: 2, _destroy: 'evals to true' }, { someProp : 3 }, { someProp: 4, _destroy: ko.observable(false) }]); + var myArray = ko.observableArray([{ someProp: 1 }, { someProp: 2, _destroy: 'evals to true' }, { someProp : 3 }, { someProp: 4, _destroy: ko.observable(false) }]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "
someProp=[js: someProp]
" })); testNode.innerHTML = "
"; @@ -597,7 +595,7 @@ describe('Templating', function() { }); it('Data binding syntax should include any items whose \'_destroy\' flag is set if you use includeDestroyed', function() { - var myArray = new ko.observableArray([{ someProp: 1 }, { someProp: 2, _destroy: 'evals to true' }, { someProp : 3 }]); + var myArray = ko.observableArray([{ someProp: 1 }, { someProp: 2, _destroy: 'evals to true' }, { someProp : 3 }]); ko.setTemplateEngine(new dummyTemplateEngine({ itemTemplate: "
someProp=[js: someProp]
" })); testNode.innerHTML = "
"; @@ -677,7 +675,7 @@ describe('Templating', function() { }); it('Should be able to render a different template for each array entry by passing a function as template name, with the array entry\'s binding context available as a second parameter', function() { - var myArray = new ko.observableArray([ + var myArray = ko.observableArray([ { preferredTemplate: 1, someProperty: 'firstItemValue' }, { preferredTemplate: 2, someProperty: 'secondItemValue' } ]); @@ -700,7 +698,7 @@ describe('Templating', function() { it('Data binding \'templateOptions\' should be passed to template', function() { var myModel = { someAdditionalData: { myAdditionalProp: "someAdditionalValue" }, - people: new ko.observableArray([ + people: ko.observableArray([ { name: "Alpha" }, { name: "Beta" } ]) diff --git a/knockout/tests/knockout-tests.ts b/knockout/tests/knockout-tests.ts index 6682eb363..e2fbf4c02 100644 --- a/knockout/tests/knockout-tests.ts +++ b/knockout/tests/knockout-tests.ts @@ -53,7 +53,7 @@ function test_computed() { }); } - function MyViewModel() { + function MyViewModel1() { this.price = ko.observable(25.99); this.formattedPrice = ko.computed({ @@ -68,7 +68,7 @@ function test_computed() { }); } - function MyViewModel() { + function MyViewModel2() { this.acceptedNumericValue = ko.observable(123); this.lastInputWasValid = ko.observable(true); @@ -90,13 +90,13 @@ function test_computed() { } class GetterViewModel { - private _selectedRange: KnockoutObservableAny; + private _selectedRange: KnockoutObservable; constructor() { this._selectedRange = ko.observable(); } - public range: KnockoutObservableAny; + public range: KnockoutObservable; } function testGetter() { @@ -333,12 +333,12 @@ function test_more() { return target; }; - function AppViewModel(first, last) { + function AppViewModel2(first, last) { this.firstName = ko.observable(first).extend({ required: "Please enter a first name" }); this.lastName = ko.observable(last).extend({ required: "" }); } - ko.applyBindings(new AppViewModel("Bob", "Smith")); + ko.applyBindings(new AppViewModel2("Bob", "Smith")); var first; this.firstName = ko.observable(first).extend({ required: "Please enter a first name", logChange: "first name" }); @@ -347,7 +347,7 @@ function test_more() { return name.toUpperCase(); }).extend({ throttle: 500 }); - function AppViewModel() { + function AppViewModel3() { this.instantaneousValue = ko.observable(); this.throttledValue = ko.computed(this.instantaneousValue) .extend({ throttle: 400 }); @@ -420,7 +420,7 @@ function test_more() { this.done = ko.observable(done); } - function AppViewModel() { + function AppViewModel4() { this.tasks = ko.observableArray([ new Task('Find new desktop background', true), new Task('Put shiny stickers on laptop', false), @@ -430,7 +430,7 @@ function test_more() { this.doneTasks = this.tasks.filterByProperty("done", true); } - ko.applyBindings(new AppViewModel()); + ko.applyBindings(new AppViewModel4()); this.doneTasks = ko.computed(function () { var all = this.tasks(), done = []; for (var i = 0; i < all.length; i++) @@ -441,7 +441,7 @@ function test_more() { } function test_mappingplugin() { - var viewModel = { + var viewModel0 = { serverTime: ko.observable(), numUsers: ko.observable() } @@ -449,8 +449,8 @@ function test_mappingplugin() { serverTime: '2010-01-07', numUsers: 3 }; - viewModel.serverTime(data.serverTime); - viewModel.numUsers(data.numUsers); + viewModel0.serverTime(data.serverTime); + viewModel0.numUsers(data.numUsers); var viewModel = ko.mapping.fromJS(data); ko.mapping.fromJS(data, viewModel); @@ -526,7 +526,7 @@ function test_misc() { return this; }; - this.myObservable = ko.observable("myValue").publishOn("myTopic"); + this.myObservable = >ko.observable("myValue").publishOn("myTopic"); ko.subscribable.fn.subscribeTo = function (topic) { postbox.subscribe(this, null, topic); @@ -534,7 +534,7 @@ function test_misc() { return this; }; - this.observableFromAnotherVM = ko.observable().subscribeTo("myTopic"); + this.observableFromAnotherVM = >ko.observable().subscribeTo("myTopic"); postbox.subscribe(function (newValue) { this(newValue); diff --git a/package.json b/package.json index e2b00d192..8044c470a 100644 --- a/package.json +++ b/package.json @@ -2,6 +2,6 @@ "name": "DefinitelyTyped", "version": "0.0.0", "scripts": { - "test": "node ./_infrastructure/tests/testRunner.js" + "test": "node ./_infrastructure/tests/runner.js" } } diff --git a/qunit/qunit-tests.ts b/qunit/qunit-tests.ts index 9a4849379..abc1af8c7 100644 --- a/qunit/qunit-tests.ts +++ b/qunit/qunit-tests.ts @@ -122,7 +122,7 @@ test("a test", function () { QUnit.config.autostart = false; QUnit.start(); -QUnit.config.urlConfig.push({ +QUnit.config.urlConfig.push({ id: "min", label: "Minified source", tooltip: "Load minified source files instead of the regular unminified ones." @@ -729,13 +729,7 @@ test("just a test", function() { // ************** BUG ? ****************** // TODO disable reordering for this suite! -var begin = 0, - moduleStart = 0, - moduleDone = 0, - testStart = 0, - testDone = 0, - log = 0, - moduleContext, +var moduleContext, moduleDoneContext, testContext, testDoneContext, diff --git a/raphael/raphael.d.ts b/raphael/raphael.d.ts index c17a8d4fa..fc8503cd3 100644 --- a/raphael/raphael.d.ts +++ b/raphael/raphael.d.ts @@ -245,7 +245,6 @@ interface RaphaelStatic { format(token: string, ...parameters: any[]): string; fullfill(token: string, json: JSON): string; getColor(value?: number): string; - getColor: { reset(); }; getPointAtLength(path: string, length: number): { x: number; y: number; alpha: number; }; getRGB(colour: string): { r: number; g: number; b: number; hex: string; error: bool; }; getSubpath(path: string, from: number, to: number): string;