diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 9cf1c9d8f3f..f3c59a61717 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -7,7 +7,7 @@ // ${cwd}: the current working directory of the spawned process { "version": "0.1.0", - "command": "jake", + "command": "gulp", "isShellCommand": true, "showOutput": "silent", "tasks": [ @@ -18,25 +18,6 @@ "problemMatcher": [ "$tsc" ] - }, - { - "taskName": "lint-server", - "args": [], - "problemMatcher": { - "owner": "typescript", - "fileLocation": ["relative", "${workspaceRoot}"], - "pattern": { - "regexp": "^(warning|error)\\s+([^(]+)\\s+\\((\\d+|\\d+,\\d+|\\d+,\\d+,\\d+,\\d+)\\):\\s+(.*)$", - "severity": 1, - "file": 2, - "location": 3, - "message": 4 - }, - "watchedTaskBeginsRegExp": "^\\*\\*\\*Lint failure\\*\\*\\*$", - "watchedTaskEndsRegExp": "^\\*\\*\\* Total \\d+ failures\\.$" - }, - "showOutput": "always", - "isWatching": true } ] } \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1c242022979..5cde901a576 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -40,6 +40,10 @@ In general, things we find useful when reviewing suggestions are: # Instructions for Contributing Code +## Code of Conduct + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + ## Contributing bug fixes TypeScript is currently accepting contributions in the form of bug fixes. A bug must have an issue tracking it in the issue tracker that has been approved ("Milestone == Community") by the TypeScript team. Your pull request should include a link to the bug that you are fixing. If you've submitted a PR for a bug, please post a comment in the bug to avoid duplication of effort. diff --git a/Gulpfile.ts b/Gulpfile.ts new file mode 100644 index 00000000000..74113b4b0c7 --- /dev/null +++ b/Gulpfile.ts @@ -0,0 +1,1047 @@ +/// +/// + +import * as cp from "child_process"; +import * as path from "path"; +import * as fs from "fs"; +import originalGulp = require("gulp"); +import helpMaker = require("gulp-help"); +import runSequence = require("run-sequence"); +import concat = require("gulp-concat"); +import clone = require("gulp-clone"); +import newer = require("gulp-newer"); +import tsc = require("gulp-typescript"); +declare module "gulp-typescript" { + interface Settings { + stripInternal?: boolean; + newLine?: string; + } + interface CompileStream extends NodeJS.ReadWriteStream {} // Either gulp or gulp-typescript has some odd typings which don't reflect reality, making this required +} +import * as insert from "gulp-insert"; +import * as sourcemaps from "gulp-sourcemaps"; +declare global { + // This is silly. We include Q because orchestrator (a part of gulp) depends on it, but its not included. + // `del` further depends on `Promise` (and is also not included), so we just, patch the global scope's Promise to Q's + type Promise = Q.Promise; +} +import del = require("del"); +import mkdirP = require("mkdirp"); +import minimist = require("minimist"); +import browserify = require("browserify"); +import through2 = require("through2"); +import merge2 = require("merge2"); +import intoStream = require("into-stream"); +import * as os from "os"; +import Linter = require("tslint"); +const gulp = helpMaker(originalGulp); +const mochaParallel = require("./scripts/mocha-parallel.js"); +const {runTestsInParallel} = mochaParallel; + +const cmdLineOptions = minimist(process.argv.slice(2), { + boolean: ["debug", "light", "colors", "lint", "soft"], + string: ["browser", "tests", "host", "reporter"], + alias: { + d: "debug", + t: "tests", + test: "tests", + r: "reporter", + color: "colors", + f: "files", + file: "files" + }, + default: { + soft: false, + colors: process.env.colors || process.env.color || true, + debug: process.env.debug || process.env.d, + host: process.env.TYPESCRIPT_HOST || process.env.host || "node", + browser: process.env.browser || process.env.b || "IE", + tests: process.env.test || process.env.tests || process.env.t, + light: process.env.light || false, + port: process.env.port || process.env.p || "8888", + reporter: process.env.reporter || process.env.r, + lint: process.env.lint || true, + files: process.env.f || process.env.file || process.env.files || "", + } +}); + +function exec(cmd: string, args: string[], complete: () => void = (() => {}), error: (e: any, status: number) => void = (() => {})) { + console.log(`${cmd} ${args.join(" ")}`); + // TODO (weswig): Update child_process types to add windowsVerbatimArguments to the type definition + const subshellFlag = isWin ? "/c" : "-c"; + const command = isWin ? [possiblyQuote(cmd), ...args] : [`${cmd} ${args.join(" ")}`]; + const ex = cp.spawn(isWin ? "cmd" : "/bin/sh", [subshellFlag, ...command], { stdio: "inherit", windowsVerbatimArguments: true } as any); + ex.on("exit", (code) => code === 0 ? complete() : error(/*e*/ undefined, code)); + ex.on("error", error); +} + +function possiblyQuote(cmd: string) { + return cmd.indexOf(" ") >= 0 ? `"${cmd}"` : cmd; +} + +let useDebugMode = true; +let host = cmdLineOptions["host"]; + +// Constants +const compilerDirectory = "src/compiler/"; +const servicesDirectory = "src/services/"; +const serverDirectory = "src/server/"; +const harnessDirectory = "src/harness/"; +const libraryDirectory = "src/lib/"; +const scriptsDirectory = "scripts/"; +const unittestsDirectory = "tests/cases/unittests/"; +const docDirectory = "doc/"; + +const builtDirectory = "built/"; +const builtLocalDirectory = "built/local/"; +const LKGDirectory = "lib/"; + +const copyright = "CopyrightNotice.txt"; + +const compilerFilename = "tsc.js"; +const LKGCompiler = path.join(LKGDirectory, compilerFilename); +const builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename); + +const nodeModulesPathPrefix = path.resolve("./node_modules/.bin/"); +const isWin = /^win/.test(process.platform); +const mocha = path.join(nodeModulesPathPrefix, "mocha") + (isWin ? ".cmd" : ""); + +const compilerSources = require("./src/compiler/tsconfig.json").files.map((file) => path.join(compilerDirectory, file)); + +const servicesSources = require("./src/services/tsconfig.json").files.map((file) => path.join(servicesDirectory, file)); + +const serverCoreSources = require("./src/server/tsconfig.json").files.map((file) => path.join(serverDirectory, file)); + +const languageServiceLibrarySources = [ + "editorServices.ts", + "protocol.d.ts", + "session.ts" +].map(function (f) { + return path.join(serverDirectory, f); +}).concat(servicesSources); + +const harnessCoreSources = [ + "harness.ts", + "sourceMapRecorder.ts", + "harnessLanguageService.ts", + "fourslash.ts", + "runnerbase.ts", + "compilerRunner.ts", + "typeWriter.ts", + "fourslashRunner.ts", + "projectsRunner.ts", + "loggedIO.ts", + "rwcRunner.ts", + "test262Runner.ts", + "runner.ts" +].map(function (f) { + return path.join(harnessDirectory, f); +}); + +const harnessSources = harnessCoreSources.concat([ + "incrementalParser.ts", + "jsDocParsing.ts", + "services/colorization.ts", + "services/documentRegistry.ts", + "services/preProcessFile.ts", + "services/patternMatcher.ts", + "session.ts", + "versionCache.ts", + "convertToBase64.ts", + "transpile.ts", + "reuseProgramStructure.ts", + "cachingInServerLSHost.ts", + "moduleResolution.ts", + "tsconfigParsing.ts", + "commandLineParsing.ts", + "convertCompilerOptionsFromJson.ts", + "convertTypingOptionsFromJson.ts", + "tsserverProjectSystem.ts", + "matchFiles.ts", +].map(function (f) { + return path.join(unittestsDirectory, f); +})).concat([ + "protocol.d.ts", + "session.ts", + "client.ts", + "editorServices.ts" +].map(function (f) { + return path.join(serverDirectory, f); +})); + +const es2015LibrarySources = [ + "es2015.core.d.ts", + "es2015.collection.d.ts", + "es2015.generator.d.ts", + "es2015.iterable.d.ts", + "es2015.promise.d.ts", + "es2015.proxy.d.ts", + "es2015.reflect.d.ts", + "es2015.symbol.d.ts", + "es2015.symbol.wellknown.d.ts" +]; + +const es2015LibrarySourceMap = es2015LibrarySources.map(function(source) { + return { target: "lib." + source, sources: ["header.d.ts", source] }; +}); + +const es2016LibrarySource = [ "es2016.array.include.d.ts" ]; + +const es2016LibrarySourceMap = es2016LibrarySource.map(function (source) { + return { target: "lib." + source, sources: ["header.d.ts", source] }; +}); + +const es2017LibrarySource = [ + "es2017.object.d.ts", + "es2017.sharedmemory.d.ts" +]; + +const es2017LibrarySourceMap = es2017LibrarySource.map(function (source) { + return { target: "lib." + source, sources: ["header.d.ts", source] }; +}); + +const hostsLibrarySources = ["dom.generated.d.ts", "webworker.importscripts.d.ts", "scripthost.d.ts"]; + +const librarySourceMap = [ + // Host library + { target: "lib.dom.d.ts", sources: ["header.d.ts", "dom.generated.d.ts"] }, + { target: "lib.dom.iterable.d.ts", sources: ["header.d.ts", "dom.iterable.d.ts"] }, + { target: "lib.webworker.d.ts", sources: ["header.d.ts", "webworker.generated.d.ts"] }, + { target: "lib.scripthost.d.ts", sources: ["header.d.ts", "scripthost.d.ts"] }, + + // JavaScript library + { target: "lib.es5.d.ts", sources: ["header.d.ts", "es5.d.ts"] }, + { target: "lib.es2015.d.ts", sources: ["header.d.ts", "es2015.d.ts"] }, + { target: "lib.es2016.d.ts", sources: ["header.d.ts", "es2016.d.ts"] }, + { target: "lib.es2017.d.ts", sources: ["header.d.ts", "es2017.d.ts"] }, + + // JavaScript + all host library + { target: "lib.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(hostsLibrarySources) }, + { target: "lib.es6.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") } +].concat(es2015LibrarySourceMap, es2016LibrarySourceMap, es2017LibrarySourceMap); + +const libraryTargets = librarySourceMap.map(function (f) { + return path.join(builtLocalDirectory, f.target); +}); + +for (const i in libraryTargets) { + const entry = librarySourceMap[i]; + const target = libraryTargets[i]; + const sources = [copyright].concat(entry.sources.map(function (s) { + return path.join(libraryDirectory, s); + })); + gulp.task(target, false, [], function() { + return gulp.src(sources) + .pipe(newer(target)) + .pipe(concat(target, { newLine: "" })) + .pipe(gulp.dest(".")); + }); +} + +const configureNightlyJs = path.join(scriptsDirectory, "configureNightly.js"); +const configureNightlyTs = path.join(scriptsDirectory, "configureNightly.ts"); +const packageJson = "package.json"; +const programTs = path.join(compilerDirectory, "program.ts"); + +function needsUpdate(source: string | string[], dest: string | string[]): boolean { + if (typeof source === "string" && typeof dest === "string") { + if (fs.existsSync(dest)) { + const {mtime: outTime} = fs.statSync(dest); + const {mtime: inTime} = fs.statSync(source); + if (+inTime <= +outTime) { + return false; + } + } + } + else if (typeof source === "string" && typeof dest !== "string") { + const {mtime: inTime} = fs.statSync(source); + for (const filepath of dest) { + if (fs.existsSync(filepath)) { + const {mtime: outTime} = fs.statSync(filepath); + if (+inTime > +outTime) { + return true; + } + } + else { + return true; + } + } + return false; + } + else if (typeof source !== "string" && typeof dest === "string") { + if (fs.existsSync(dest)) { + const {mtime: outTime} = fs.statSync(dest); + for (const filepath of source) { + if (fs.existsSync(filepath)) { + const {mtime: inTime} = fs.statSync(filepath); + if (+inTime > +outTime) { + return true; + } + } + else { + return true; + } + } + return false; + } + } + else if (typeof source !== "string" && typeof dest !== "string") { + for (let i = 0; i < source.length; i++) { + if (!dest[i]) { + continue; + } + if (fs.existsSync(dest[i])) { + const {mtime: outTime} = fs.statSync(dest[i]); + const {mtime: inTime} = fs.statSync(source[i]); + if (+inTime > +outTime) { + return true; + } + } + else { + return true; + } + } + return false; + } + return true; +} + +function getCompilerSettings(base: tsc.Settings, useBuiltCompiler?: boolean): tsc.Settings { + const copy: tsc.Settings = {}; + for (const key in base) { + copy[key] = base[key]; + } + if (!useDebugMode) { + if (copy.removeComments === undefined) copy.removeComments = true; + copy.newLine = "lf"; + } + else { + copy.preserveConstEnums = true; + } + if (useBuiltCompiler === true) { + copy.typescript = require("./built/local/typescript.js"); + } + else if (useBuiltCompiler === false) { + copy.typescript = require("./lib/typescript.js"); + } + return copy; +} + +gulp.task(configureNightlyJs, false, [], () => { + const settings: tsc.Settings = { + declaration: false, + removeComments: true, + noResolve: false, + stripInternal: false, + }; + return gulp.src(configureNightlyTs) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(path.dirname(configureNightlyJs))) + .pipe(gulp.dest(path.dirname(configureNightlyJs))); +}); + + +// Nightly management tasks +gulp.task("configure-nightly", "Runs scripts/configureNightly.ts to prepare a build for nightly publishing", [configureNightlyJs], (done) => { + exec(host, [configureNightlyJs, packageJson, programTs], done, done); +}); +gulp.task("publish-nightly", "Runs `npm publish --tag next` to create a new nightly build on npm", ["LKG"], () => { + return runSequence("clean", "useDebugMode", "runtests", (done) => { + exec("npm", ["publish", "--tag", "next"], done, done); + }); +}); + +const importDefinitelyTypedTestsDirectory = path.join(scriptsDirectory, "importDefinitelyTypedTests"); +const importDefinitelyTypedTestsJs = path.join(importDefinitelyTypedTestsDirectory, "importDefinitelyTypedTests.js"); +const importDefinitelyTypedTestsTs = path.join(importDefinitelyTypedTestsDirectory, "importDefinitelyTypedTests.ts"); + +gulp.task(importDefinitelyTypedTestsJs, false, [], () => { + const settings: tsc.Settings = getCompilerSettings({ + declaration: false, + removeComments: true, + noResolve: false, + stripInternal: false, + outFile: importDefinitelyTypedTestsJs + }, /*useBuiltCompiler*/ false); + return gulp.src(importDefinitelyTypedTestsTs) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(".")); +}); + +gulp.task("importDefinitelyTypedTests", "Runs scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts to copy DT's tests to the TS-internal RWC tests", [importDefinitelyTypedTestsJs], (done) => { + exec(host, [importDefinitelyTypedTestsJs, "./", "../DefinitelyTyped"], done, done); +}); + +gulp.task("lib", "Builds the library targets", libraryTargets); + + +// Generate diagnostics +const processDiagnosticMessagesJs = path.join(scriptsDirectory, "processDiagnosticMessages.js"); +const processDiagnosticMessagesTs = path.join(scriptsDirectory, "processDiagnosticMessages.ts"); +const diagnosticMessagesJson = path.join(compilerDirectory, "diagnosticMessages.json"); +const diagnosticInfoMapTs = path.join(compilerDirectory, "diagnosticInformationMap.generated.ts"); +const generatedDiagnosticMessagesJSON = path.join(compilerDirectory, "diagnosticMessages.generated.json"); +const builtGeneratedDiagnosticMessagesJSON = path.join(builtLocalDirectory, "diagnosticMessages.generated.json"); + +// processDiagnosticMessages script +gulp.task(processDiagnosticMessagesJs, false, [], () => { + const settings: tsc.Settings = getCompilerSettings({ + declaration: false, + removeComments: true, + noResolve: false, + stripInternal: false, + outFile: processDiagnosticMessagesJs + }, /*useBuiltCompiler*/ false); + return gulp.src(processDiagnosticMessagesTs) + .pipe(newer(processDiagnosticMessagesJs)) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(".")); +}); + +// The generated diagnostics map; built for the compiler and for the "generate-diagnostics" task +gulp.task(diagnosticInfoMapTs, [processDiagnosticMessagesJs], (done) => { + if (needsUpdate(diagnosticMessagesJson, [generatedDiagnosticMessagesJSON, diagnosticInfoMapTs])) { + exec(host, [processDiagnosticMessagesJs, diagnosticMessagesJson], done, done); + } + else { + done(); + } +}); + +gulp.task(builtGeneratedDiagnosticMessagesJSON, [diagnosticInfoMapTs], (done) => { + if (fs.existsSync(builtLocalDirectory) && needsUpdate(generatedDiagnosticMessagesJSON, builtGeneratedDiagnosticMessagesJSON)) { + fs.writeFileSync(builtGeneratedDiagnosticMessagesJSON, fs.readFileSync(generatedDiagnosticMessagesJSON)); + } + done(); +}); + +gulp.task("generate-diagnostics", "Generates a diagnostic file in TypeScript based on an input JSON file", [diagnosticInfoMapTs]); + + +const servicesFile = path.join(builtLocalDirectory, "typescriptServices.js"); +const standaloneDefinitionsFile = path.join(builtLocalDirectory, "typescriptServices.d.ts"); +const nodePackageFile = path.join(builtLocalDirectory, "typescript.js"); +const nodeDefinitionsFile = path.join(builtLocalDirectory, "typescript.d.ts"); +const nodeStandaloneDefinitionsFile = path.join(builtLocalDirectory, "typescript_standalone.d.ts"); + +let copyrightContent: string; +function prependCopyright(outputCopyright: boolean = !useDebugMode) { + return insert.prepend(outputCopyright ? (copyrightContent || (copyrightContent = fs.readFileSync(copyright).toString())) : ""); +} + +gulp.task(builtLocalCompiler, false, [servicesFile], () => { + const localCompilerProject = tsc.createProject("src/compiler/tsconfig.json", getCompilerSettings({}, /*useBuiltCompiler*/true)); + return localCompilerProject.src() + .pipe(newer(builtLocalCompiler)) + .pipe(sourcemaps.init()) + .pipe(tsc(localCompilerProject)) + .pipe(prependCopyright()) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(builtLocalDirectory)); +}); + +gulp.task(servicesFile, false, ["lib", "generate-diagnostics"], () => { + const servicesProject = tsc.createProject("src/services/tsconfig.json", getCompilerSettings({ removeComments: false }, /*useBuiltCompiler*/false)); + const {js, dts} = servicesProject.src() + .pipe(newer(servicesFile)) + .pipe(sourcemaps.init()) + .pipe(tsc(servicesProject)); + const completedJs = js.pipe(prependCopyright()) + .pipe(sourcemaps.write(".")); + const completedDts = dts.pipe(prependCopyright(/*outputCopyright*/true)) + .pipe(insert.transform((contents, file) => { + file.path = standaloneDefinitionsFile; + return contents.replace(/^(\s*)(export )?const enum (\S+) {(\s*)$/gm, "$1$2enum $3 {$4"); + })); + return merge2([ + completedJs, + completedJs.pipe(clone()) + .pipe(insert.transform((content, file) => (file.path = nodePackageFile, content))), + completedDts, + completedDts.pipe(clone()) + .pipe(insert.transform((content, file) => { + file.path = nodeDefinitionsFile; + return content + "\r\nexport = ts;"; + })) + .pipe(gulp.dest(builtLocalDirectory)), + completedDts.pipe(clone()) + .pipe(insert.transform((content, file) => { + file.path = nodeStandaloneDefinitionsFile; + return content.replace(/declare (namespace|module) ts/g, 'declare module "typescript"'); + })) + ]).pipe(gulp.dest(builtLocalDirectory)); +}); + +const serverFile = path.join(builtLocalDirectory, "tsserver.js"); + +gulp.task(serverFile, false, [servicesFile], () => { + const serverProject = tsc.createProject("src/server/tsconfig.json", getCompilerSettings({}, /*useBuiltCompiler*/true)); + return serverProject.src() + .pipe(newer(serverFile)) + .pipe(sourcemaps.init()) + .pipe(tsc(serverProject)) + .pipe(prependCopyright()) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(builtLocalDirectory)); +}); + +const tsserverLibraryFile = path.join(builtLocalDirectory, "tsserverlibrary.js"); +const tsserverLibraryDefinitionFile = path.join(builtLocalDirectory, "tsserverlibrary.d.ts"); + +gulp.task(tsserverLibraryFile, false, [servicesFile], (done) => { + const settings: tsc.Settings = getCompilerSettings({ + declaration: true, + outFile: tsserverLibraryFile + }, /*useBuiltCompiler*/ true); + const {js, dts}: {js: NodeJS.ReadableStream, dts: NodeJS.ReadableStream} = gulp.src(languageServiceLibrarySources) + .pipe(sourcemaps.init()) + .pipe(newer(tsserverLibraryFile)) + .pipe(tsc(settings)); + + return merge2([ + js.pipe(prependCopyright()) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(".")), + dts.pipe(prependCopyright()) + .pipe(gulp.dest(".")) + ]); +}); + +gulp.task("lssl", "Builds language service server library", [tsserverLibraryFile]); +gulp.task("local", "Builds the full compiler and services", [builtLocalCompiler, servicesFile, serverFile, builtGeneratedDiagnosticMessagesJSON]); +gulp.task("tsc", "Builds only the compiler", [builtLocalCompiler]); + + +// Generate Markdown spec +const word2mdJs = path.join(scriptsDirectory, "word2md.js"); +const word2mdTs = path.join(scriptsDirectory, "word2md.ts"); +const specWord = path.join(docDirectory, "TypeScript Language Specification.docx"); +const specMd = path.join(docDirectory, "spec.md"); + +gulp.task(word2mdJs, false, [], () => { + const settings: tsc.Settings = getCompilerSettings({ + outFile: word2mdJs + }, /*useBuiltCompiler*/ false); + return gulp.src(word2mdTs) + .pipe(newer(word2mdJs)) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(".")); +}); + +gulp.task(specMd, false, [word2mdJs], (done) => { + const specWordFullPath = path.resolve(specWord); + const specMDFullPath = path.resolve(specMd); + const cmd = "cscript //nologo " + word2mdJs + " \"" + specWordFullPath + "\" " + "\"" + specMDFullPath + "\""; + console.log(cmd); + cp.exec(cmd, function () { + done(); + }); +}); + +gulp.task("generate-spec", "Generates a Markdown version of the Language Specification", [specMd]); + +gulp.task("clean", "Cleans the compiler output, declare files, and tests", [], () => { + return del([builtDirectory]); +}); + +gulp.task("useDebugMode", false, [], (done) => { useDebugMode = true; done(); }); +gulp.task("dontUseDebugMode", false, [], (done) => { useDebugMode = false; done(); }); + +gulp.task("VerifyLKG", false, [], () => { + const expectedFiles = [builtLocalCompiler, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, tsserverLibraryFile, tsserverLibraryDefinitionFile].concat(libraryTargets); + const missingFiles = expectedFiles.filter(function (f) { + return !fs.existsSync(f); + }); + if (missingFiles.length > 0) { + throw new Error("Cannot replace the LKG unless all built targets are present in directory " + builtLocalDirectory + + ". The following files are missing:\n" + missingFiles.join("\n")); + } + // Copy all the targets into the LKG directory + return gulp.src(expectedFiles).pipe(gulp.dest(LKGDirectory)); +}); + +gulp.task("LKGInternal", false, ["lib", "local", "lssl"]); + +gulp.task("LKG", "Makes a new LKG out of the built js files", ["clean", "dontUseDebugMode"], () => { + return runSequence("LKGInternal", "VerifyLKG"); +}); + + +// Task to build the tests infrastructure using the built compiler +const run = path.join(builtLocalDirectory, "run.js"); +gulp.task(run, false, [servicesFile], () => { + const settings: tsc.Settings = getCompilerSettings({ + outFile: run + }, /*useBuiltCompiler*/ true); + return gulp.src(harnessSources) + .pipe(newer(run)) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(".", { includeContent: false, sourceRoot: "../../" })) + .pipe(gulp.dest(".")); +}); + +const internalTests = "internal/"; + +const localBaseline = "tests/baselines/local/"; +const refBaseline = "tests/baselines/reference/"; + +const localRwcBaseline = path.join(internalTests, "baselines/rwc/local"); +const refRwcBaseline = path.join(internalTests, "baselines/rwc/reference"); + +const localTest262Baseline = path.join(internalTests, "baselines/test262/local"); +const refTest262Baseline = path.join(internalTests, "baselines/test262/reference"); + + +gulp.task("tests", "Builds the test infrastructure using the built compiler", [run]); +gulp.task("tests-debug", "Builds the test sources and automation in debug mode", () => { + return runSequence("useDebugMode", "tests"); +}); + +function deleteTemporaryProjectOutput() { + return del(path.join(localBaseline, "projectOutput/")); +} + +let savedNodeEnv: string; +function setNodeEnvToDevelopment() { + savedNodeEnv = process.env.NODE_ENV; + process.env.NODE_ENV = "development"; +} + +function restoreSavedNodeEnv() { + process.env.NODE_ENV = savedNodeEnv; +} + +let testTimeout = 20000; +function runConsoleTests(defaultReporter: string, runInParallel: boolean, done: (e?: any) => void) { + const lintFlag = cmdLineOptions["lint"]; + cleanTestDirs((err) => { + if (err) { console.error(err); failWithStatus(err, 1); } + const debug = cmdLineOptions["debug"]; + const tests = cmdLineOptions["tests"]; + const light = cmdLineOptions["light"]; + const testConfigFile = "test.config"; + if (fs.existsSync(testConfigFile)) { + fs.unlinkSync(testConfigFile); + } + let workerCount, taskConfigsFolder; + if (runInParallel) { + // generate name to store task configuration files + const prefix = os.tmpdir() + "/ts-tests"; + let i = 1; + do { + taskConfigsFolder = prefix + i; + i++; + } while (fs.existsSync(taskConfigsFolder)); + fs.mkdirSync(taskConfigsFolder); + + workerCount = process.env.workerCount || os.cpus().length; + } + + if (tests || light || taskConfigsFolder) { + writeTestConfigFile(tests, light, taskConfigsFolder, workerCount); + } + + if (tests && tests.toLocaleLowerCase() === "rwc") { + testTimeout = 100000; + } + + const colors = cmdLineOptions["colors"]; + const reporter = cmdLineOptions["reporter"] || defaultReporter; + + // timeout normally isn"t necessary but Travis-CI has been timing out on compiler baselines occasionally + // default timeout is 2sec which really should be enough, but maybe we just need a small amount longer + if (!runInParallel) { + const args = []; + if (debug) { + args.push("--debug-brk"); + } + args.push("-R", reporter); + if (tests) { + args.push("-g", `"${tests}"`); + } + if (colors) { + args.push("--colors"); + } + else { + args.push("--no-colors"); + } + args.push("-t", testTimeout); + args.push(run); + setNodeEnvToDevelopment(); + exec(mocha, args, lintThenFinish, function(e, status) { + finish(e, status); + }); + + } + else { + // run task to load all tests and partition them between workers + const args = []; + args.push("-R", "min"); + if (colors) { + args.push("--colors"); + } + else { + args.push("--no-colors"); + } + args.push(run); + setNodeEnvToDevelopment(); + runTestsInParallel(taskConfigsFolder, run, { testTimeout: testTimeout, noColors: colors === " --no-colors " }, function (err) { + // last worker clean everything and runs linter in case if there were no errors + del(taskConfigsFolder).then(() => { + if (!err) { + lintThenFinish(); + } + else { + finish(err); + } + }); + }); + } + }); + + function failWithStatus(err?: any, status?: number) { + if (err) { + console.log(err); + } + done(err || status); + process.exit(status); + } + + function lintThenFinish() { + if (lintFlag) { + runSequence("lint", finish); + } + else { + finish(); + } + } + + function finish(error?: any, errorStatus?: number) { + restoreSavedNodeEnv(); + deleteTemporaryProjectOutput().then(() => { + if (error !== undefined || errorStatus !== undefined) { + failWithStatus(error, errorStatus); + } + else { + done(); + } + }); + } +} + +gulp.task("runtests-parallel", "Runs all the tests in parallel using the built run.js file. Optional arguments are: --t[ests]=category1|category2|... --d[ebug]=true.", ["build-rules", "tests"], (done) => { + runConsoleTests("min", /*runInParallel*/ true, done); +}); +gulp.task("runtests", + "Runs the tests using the built run.js file. Optional arguments are: --t[ests]=regex --r[eporter]=[list|spec|json|] --d[ebug]=true --color[s]=false --lint=true.", + ["build-rules", "tests"], + (done) => { + runConsoleTests("mocha-fivemat-progress-reporter", /*runInParallel*/ false, done); +}); + +const nodeServerOutFile = "tests/webTestServer.js"; +const nodeServerInFile = "tests/webTestServer.ts"; +gulp.task(nodeServerOutFile, false, [servicesFile], () => { + const settings: tsc.Settings = getCompilerSettings({ module: "commonjs" }, /*useBuiltCompiler*/ true); + return gulp.src(nodeServerInFile) + .pipe(newer(nodeServerOutFile)) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(path.dirname(nodeServerOutFile))); +}); + +gulp.task("browserify", "Runs browserify on run.js to produce a file suitable for running tests in the browser", [servicesFile], (done) => { + const settings: tsc.Settings = getCompilerSettings({ + outFile: "built/local/bundle.js" + }, /*useBuiltCompiler*/ true); + return gulp.src(harnessSources) + .pipe(newer("built/local/bundle.js")) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(through2.obj((file, enc, next) => { + browserify(intoStream(file.contents)) + .bundle((err, res) => { + // assumes file.contents is a Buffer + file.contents = res; + next(undefined, file); + }); + })) + .pipe(sourcemaps.write(".", { includeContent: false, sourceRoot: "../../" })) + .pipe(gulp.dest(".")); +}); + + +function cleanTestDirs(done: (e?: any) => void) { + // Clean the local baselines & Rwc baselines directories + del([ + localBaseline, + localRwcBaseline, + ]).then(() => { + mkdirP(localRwcBaseline, (err) => { + if (err) done(err); + mkdirP(localTest262Baseline, () => { + if (err) done(err); + mkdirP(localBaseline, (err) => done(err)); + }); + }); + }); +} + +// used to pass data from jake command line directly to run.js +function writeTestConfigFile(tests: string, light: boolean, taskConfigsFolder?: string, workerCount?: number) { + const testConfigContents = JSON.stringify({ test: tests ? [tests] : undefined, light: light, workerCount: workerCount, taskConfigsFolder: taskConfigsFolder }); + console.log("Running tests with config: " + testConfigContents); + fs.writeFileSync("test.config", testConfigContents); +} + + +gulp.task("runtests-browser", "Runs the tests using the built run.js file like 'gulp runtests'. Syntax is gulp runtests-browser. Additional optional parameters --tests=[regex], --port=, --browser=[chrome|IE]", ["browserify", nodeServerOutFile], (done) => { + cleanTestDirs((err) => { + if (err) { console.error(err); done(err); process.exit(1); } + host = "node"; + const tests = cmdLineOptions["tests"]; + const light = cmdLineOptions["light"]; + const testConfigFile = "test.config"; + if (fs.existsSync(testConfigFile)) { + fs.unlinkSync(testConfigFile); + } + if (tests || light) { + writeTestConfigFile(tests, light); + } + + const args = [nodeServerOutFile]; + if (cmdLineOptions["port"]) { + args.push(cmdLineOptions["port"]); + } + if (cmdLineOptions["browser"]) { + args.push(cmdLineOptions["browser"]); + } + if (tests) { + args.push(JSON.stringify(tests)); + } + exec(host, args, done, done); + }); +}); + +gulp.task("generate-code-coverage", "Generates code coverage data via istanbul", ["tests"], (done) => { + exec("istanbul", ["cover", "node_modules/mocha/bin/_mocha", "--", "-R", "min", "-t", testTimeout.toString(), run], done, done); +}); + + +function getDiffTool() { + const program = process.env["DIFF"]; + if (!program) { + console.error("Add the 'DIFF' environment variable to the path of the program you want to use."); + process.exit(1); + } + return program; +} + +gulp.task("diff", "Diffs the compiler baselines using the diff tool specified by the 'DIFF' environment variable", (done) => { + exec(getDiffTool(), [refBaseline, localBaseline], done, done); +}); +gulp.task("diff-rwc", "Diffs the RWC baselines using the diff tool specified by the 'DIFF' environment variable", (done) => { + exec(getDiffTool(), [refRwcBaseline, localRwcBaseline], done, done); +}); + + +gulp.task("baseline-accept", "Makes the most recent test results the new baseline, overwriting the old baseline", (done) => { + const softAccept = cmdLineOptions["soft"]; + if (!softAccept) { + del(refBaseline).then(() => { + fs.renameSync(localBaseline, refBaseline); + done(); + }, done); + } + else { + gulp.src(localBaseline) + .pipe(gulp.dest(refBaseline)) + .on("end", () => { + del(path.join(refBaseline, "local")).then(() => done(), done); + }); + } +}); +gulp.task("baseline-accept-rwc", "Makes the most recent rwc test results the new baseline, overwriting the old baseline", () => { + return del(refRwcBaseline).then(() => { + fs.renameSync(localRwcBaseline, refRwcBaseline); + }); +}); +gulp.task("baseline-accept-test262", "Makes the most recent test262 test results the new baseline, overwriting the old baseline", () => { + return del(refTest262Baseline).then(() => { + fs.renameSync(localTest262Baseline, refTest262Baseline); + }); +}); + + +// Webhost +const webhostPath = "tests/webhost/webtsc.ts"; +const webhostJsPath = "tests/webhost/webtsc.js"; +gulp.task(webhostJsPath, false, [servicesFile], () => { + const settings: tsc.Settings = getCompilerSettings({ + outFile: webhostJsPath + }, /*useBuiltCompiler*/ true); + return gulp.src(webhostPath) + .pipe(newer(webhostJsPath)) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(path.dirname(webhostJsPath))); +}); + +gulp.task("webhost", "Builds the tsc web host", [webhostJsPath], () => { + return gulp.src(path.join(builtLocalDirectory, "lib.d.ts")).pipe(gulp.dest("tests/webhost/")); +}); + + +// Perf compiler +const perftscPath = "tests/perftsc.ts"; +const perftscJsPath = "built/local/perftsc.js"; +gulp.task(perftscJsPath, false, [servicesFile], () => { + const settings: tsc.Settings = getCompilerSettings({ + outFile: perftscJsPath + }, /*useBuiltCompiler*/ true); + return gulp.src(perftscPath) + .pipe(newer(perftscJsPath)) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(".")); +}); + +gulp.task("perftsc", "Builds augmented version of the compiler for perf tests", [perftscJsPath]); + + +// Instrumented compiler +const loggedIOpath = path.join(harnessDirectory, "loggedIO.ts"); +const loggedIOJsPath = path.join(builtLocalDirectory, "loggedIO.js"); +gulp.task(loggedIOJsPath, false, [], (done) => { + const temp = path.join(builtLocalDirectory, "temp"); + mkdirP(temp, (err) => { + if (err) { console.error(err); done(err); process.exit(1); }; + exec(host, [LKGCompiler, "--outdir", temp, loggedIOpath], () => { + fs.renameSync(path.join(temp, "/harness/loggedIO.js"), loggedIOJsPath); + del(temp).then(() => done(), done); + }, done); + }); +}); + +const instrumenterPath = path.join(harnessDirectory, "instrumenter.ts"); +const instrumenterJsPath = path.join(builtLocalDirectory, "instrumenter.js"); +gulp.task(instrumenterJsPath, false, [servicesFile], () => { + const settings: tsc.Settings = getCompilerSettings({ + outFile: instrumenterJsPath + }, /*useBuiltCompiler*/ true); + return gulp.src(instrumenterPath) + .pipe(newer(instrumenterJsPath)) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(".")); +}); + +gulp.task("tsc-instrumented", "Builds an instrumented tsc.js", [loggedIOJsPath, instrumenterJsPath, servicesFile], (done) => { + exec(host, [instrumenterJsPath, "record", "iocapture", builtLocalDirectory, compilerFilename], done, done); +}); + +gulp.task("update-sublime", "Updates the sublime plugin's tsserver", ["local", serverFile], () => { + return gulp.src([serverFile, serverFile + ".map"]).pipe(gulp.dest("../TypeScript-Sublime-Plugin/tsserver/")); +}); + + +const tslintRuleDir = "scripts/tslint"; +const tslintRules = [ + "nextLineRule", + "preferConstRule", + "booleanTriviaRule", + "typeOperatorSpacingRule", + "noInOperatorRule", + "noIncrementDecrementRule", + "objectLiteralSurroundingSpaceRule", +]; +const tslintRulesFiles = tslintRules.map(function(p) { + return path.join(tslintRuleDir, p + ".ts"); +}); +const tslintRulesOutFiles = tslintRules.map(function(p, i) { + const pathname = path.join(builtLocalDirectory, "tslint", p + ".js"); + gulp.task(pathname, false, [], () => { + const settings: tsc.Settings = getCompilerSettings({ module: "commonjs" }, /*useBuiltCompiler*/ false); + return gulp.src(tslintRulesFiles[i]) + .pipe(newer(pathname)) + .pipe(sourcemaps.init()) + .pipe(tsc(settings)) + .pipe(sourcemaps.write(".")) + .pipe(gulp.dest(path.join(builtLocalDirectory, "tslint"))); + }); + return pathname; +}); + +gulp.task("build-rules", "Compiles tslint rules to js", tslintRulesOutFiles); + + +function getLinterOptions() { + return { + configuration: require("./tslint.json"), + formatter: "prose", + formattersDirectory: undefined, + rulesDirectory: "built/local/tslint" + }; +} + +function lintFileContents(options, path, contents) { + const ll = new Linter(path, contents, options); + console.log("Linting '" + path + "'."); + return ll.lint(); +} + +function lintFile(options, path) { + const contents = fs.readFileSync(path, "utf8"); + return lintFileContents(options, path, contents); +} + +const lintTargets = ["Gulpfile.ts"] + .concat(compilerSources) + .concat(harnessSources) + // Other harness sources + .concat(["instrumenter.ts"].map(function(f) { return path.join(harnessDirectory, f); })) + .concat(serverCoreSources) + .concat(tslintRulesFiles) + .concat(servicesSources); + + +gulp.task("lint", "Runs tslint on the compiler sources. Optional arguments are: --f[iles]=regex", ["build-rules"], () => { + const lintOptions = getLinterOptions(); + let failed = 0; + const fileMatcher = RegExp(cmdLineOptions["files"]); + const done = {}; + for (const i in lintTargets) { + const target = lintTargets[i]; + if (!done[target] && fileMatcher.test(target)) { + const result = lintFile(lintOptions, target); + if (result.failureCount > 0) { + console.log(result.output); + failed += result.failureCount; + } + done[target] = true; + } + } + if (failed > 0) { + console.error("Linter errors."); + process.exit(1); + } +}); + + +gulp.task("default", "Runs 'local'", ["local"]); + +gulp.task("watch", "Watches the src/ directory for changes and executes runtests-parallel.", [], () => { + gulp.watch("src/**/*.*", ["runtests-parallel"]); +}); diff --git a/Jakefile.js b/Jakefile.js index b7bf34a5f3d..a40fa4215e9 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -307,7 +307,7 @@ var builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename); function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts, callback) { file(outFile, prereqs, function() { var compilerPath = useBuiltCompiler ? builtLocalCompiler : LKGCompiler; - var options = "--noImplicitAny --noEmitOnError --pretty"; + var options = "--noImplicitAny --noEmitOnError --types --pretty"; opts = opts || {}; // Keep comments when specifically requested // or when in debug mode. @@ -1018,7 +1018,8 @@ var tslintRules = [ "booleanTriviaRule", "typeOperatorSpacingRule", "noInOperatorRule", - "noIncrementDecrementRule" + "noIncrementDecrementRule", + "objectLiteralSurroundingSpaceRule", ]; var tslintRulesFiles = tslintRules.map(function(p) { return path.join(tslintRuleDir, p + ".ts"); @@ -1069,7 +1070,8 @@ var lintTargets = compilerSources .concat(["instrumenter.ts"].map(function(f) { return path.join(harnessDirectory, f) })) .concat(serverCoreSources) .concat(tslintRulesFiles) - .concat(servicesSources); + .concat(servicesSources) + .concat(["Gulpfile.ts"]); desc("Runs tslint on the compiler sources. Optional arguments are: f[iles]=regex"); diff --git a/README.md b/README.md index 13e1f3e4786..fca2890bc77 100644 --- a/README.md +++ b/README.md @@ -56,29 +56,29 @@ Change to the TypeScript directory: cd TypeScript ``` -Install Jake tools and dev dependencies: +Install Gulp tools and dev dependencies: ``` -npm install -g jake +npm install -g gulp npm install ``` Use one of the following to build and test: ``` -jake local # Build the compiler into built/local -jake clean # Delete the built compiler -jake LKG # Replace the last known good with the built one. +gulp local # Build the compiler into built/local +gulp clean # Delete the built compiler +gulp LKG # Replace the last known good with the built one. # Bootstrapping step to be executed when the built compiler reaches a stable state. -jake tests # Build the test infrastructure using the built compiler. -jake runtests # Run tests using the built compiler and test infrastructure. +gulp tests # Build the test infrastructure using the built compiler. +gulp runtests # Run tests using the built compiler and test infrastructure. # You can override the host or specify a test for this command. # Use host= or tests=. -jake runtests-browser # Runs the tests using the built run.js file. Syntax is jake runtests. Optional +gulp runtests-browser # Runs the tests using the built run.js file. Syntax is gulp runtests. Optional parameters 'host=', 'tests=[regex], reporter=[list|spec|json|]'. -jake baseline-accept # This replaces the baseline test results with the results obtained from jake runtests. -jake lint # Runs tslint on the TypeScript source. -jake -T # List the above commands. +gulp baseline-accept # This replaces the baseline test results with the results obtained from gulp runtests. +gulp lint # Runs tslint on the TypeScript source. +gulp help # List the above commands. ``` diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 2881834e678..e25105cc98e 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -1271,13 +1271,33 @@ declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | P interface PromiseLike { /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): PromiseLike; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): PromiseLike; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike): PromiseLike; + + /** + * Creates a new Promise with the same internal state of this Promise. + * @returns A Promise. + */ + then(): PromiseLike; } interface ArrayLike { @@ -1540,7 +1560,7 @@ interface Int8Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -1813,7 +1833,7 @@ interface Uint8Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2087,7 +2107,7 @@ interface Uint8ClampedArray { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2360,7 +2380,7 @@ interface Int16Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2634,7 +2654,7 @@ interface Uint16Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2907,7 +2927,7 @@ interface Int32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3180,7 +3200,7 @@ interface Uint32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3453,7 +3473,7 @@ interface Float32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3727,7 +3747,7 @@ interface Float64Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -4126,7 +4146,7 @@ interface Date { ///////////////////////////// interface Algorithm { - name?: string; + name: string; } interface AriaRequestEventInit extends EventInit { @@ -4973,6 +4993,7 @@ interface UIEventInit extends EventInit { } interface WebGLContextAttributes { + failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; depth?: boolean; stencil?: boolean; @@ -5041,7 +5062,7 @@ interface ApplicationCache extends EventTarget { oncached: (ev: Event) => any; onchecking: (ev: Event) => any; ondownloading: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onnoupdate: (ev: Event) => any; onobsolete: (ev: Event) => any; onprogress: (ev: ProgressEvent) => any; @@ -6411,7 +6432,7 @@ declare var DeviceRotationRate: { interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent { /** - * Sets or gets the URL for the current document. + * Sets or gets the URL for the current document. */ readonly URL: string; /** @@ -6439,7 +6460,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ applets: HTMLCollectionOf; /** - * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. */ bgColor: string; /** @@ -6467,19 +6488,19 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ designMode: string; /** - * Sets or retrieves a value that indicates the reading order of the object. + * Sets or retrieves a value that indicates the reading order of the object. */ dir: string; /** - * Gets an object representing the document type declaration associated with the current document. + * Gets an object representing the document type declaration associated with the current document. */ readonly doctype: DocumentType; /** - * Gets a reference to the root node of the document. + * Gets a reference to the root node of the document. */ documentElement: HTMLElement; /** - * Sets or gets the security domain of the document. + * Sets or gets the security domain of the document. */ domain: string; /** @@ -6503,7 +6524,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ images: HTMLCollectionOf; /** - * Gets the implementation object of the current document. + * Gets the implementation object of the current document. */ readonly implementation: DOMImplementation; /** @@ -6511,11 +6532,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ readonly inputEncoding: string | null; /** - * Gets the date that the page was last modified, if the page supplies one. + * Gets the date that the page was last modified, if the page supplies one. */ readonly lastModified: string; /** - * Sets or gets the color of the document links. + * Sets or gets the color of the document links. */ linkColor: string; /** @@ -6523,7 +6544,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ links: HTMLCollectionOf; /** - * Contains information about the current URL. + * Contains information about the current URL. */ readonly location: Location; msCSSOMElementFloatMetrics: boolean; @@ -6532,7 +6553,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Fires when the user aborts the download. * @param ev The event. */ - onabort: (ev: Event) => any; + onabort: (ev: UIEvent) => any; /** * Fires when the object is set as the active element. * @param ev The event. @@ -6548,19 +6569,19 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param ev The event. */ onbeforedeactivate: (ev: UIEvent) => any; - /** - * Fires when the object loses the input focus. + /** + * Fires when the object loses the input focus. * @param ev The focus event. */ onblur: (ev: FocusEvent) => any; /** - * Occurs when playback is possible, but would require further buffering. + * Occurs when playback is possible, but would require further buffering. * @param ev The event. */ oncanplay: (ev: Event) => any; oncanplaythrough: (ev: Event) => any; /** - * Fires when the contents of the object or selection have changed. + * Fires when the contents of the object or selection have changed. * @param ev The event. */ onchange: (ev: Event) => any; @@ -6570,7 +6591,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onclick: (ev: MouseEvent) => any; /** - * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * Fires when the user clicks the right mouse button in the client area, opening the context menu. * @param ev The mouse event. */ oncontextmenu: (ev: PointerEvent) => any; @@ -6594,12 +6615,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param ev The event. */ ondragend: (ev: DragEvent) => any; - /** + /** * Fires on the target element when the user drags the object to a valid drop target. * @param ev The drag event. */ ondragenter: (ev: DragEvent) => any; - /** + /** * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. * @param ev The drag event. */ @@ -6610,23 +6631,23 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ ondragover: (ev: DragEvent) => any; /** - * Fires on the source object when the user starts to drag a text selection or selected object. + * Fires on the source object when the user starts to drag a text selection or selected object. * @param ev The event. */ ondragstart: (ev: DragEvent) => any; ondrop: (ev: DragEvent) => any; /** - * Occurs when the duration attribute is updated. + * Occurs when the duration attribute is updated. * @param ev The event. */ ondurationchange: (ev: Event) => any; /** - * Occurs when the media element is reset to its initial state. + * Occurs when the media element is reset to its initial state. * @param ev The event. */ onemptied: (ev: Event) => any; /** - * Occurs when the end of playback is reached. + * Occurs when the end of playback is reached. * @param ev The event */ onended: (ev: MediaStreamErrorEvent) => any; @@ -6634,9 +6655,9 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Fires when an error occurs during object loading. * @param ev The event. */ - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; /** - * Fires when the object receives focus. + * Fires when the object receives focus. * @param ev The event. */ onfocus: (ev: FocusEvent) => any; @@ -6660,12 +6681,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onkeyup: (ev: KeyboardEvent) => any; /** - * Fires immediately after the browser loads the object. + * Fires immediately after the browser loads the object. * @param ev The event. */ onload: (ev: Event) => any; /** - * Occurs when media data is loaded at the current playback position. + * Occurs when media data is loaded at the current playback position. * @param ev The event. */ onloadeddata: (ev: Event) => any; @@ -6675,22 +6696,22 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onloadedmetadata: (ev: Event) => any; /** - * Occurs when Internet Explorer begins looking for media data. + * Occurs when Internet Explorer begins looking for media data. * @param ev The event. */ onloadstart: (ev: Event) => any; /** - * Fires when the user clicks the object with either mouse button. + * Fires when the user clicks the object with either mouse button. * @param ev The mouse event. */ onmousedown: (ev: MouseEvent) => any; /** - * Fires when the user moves the mouse over the object. + * Fires when the user moves the mouse over the object. * @param ev The mouse event. */ onmousemove: (ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer outside the boundaries of the object. + * Fires when the user moves the mouse pointer outside the boundaries of the object. * @param ev The mouse event. */ onmouseout: (ev: MouseEvent) => any; @@ -6700,12 +6721,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onmouseover: (ev: MouseEvent) => any; /** - * Fires when the user releases a mouse button while the mouse is over the object. + * Fires when the user releases a mouse button while the mouse is over the object. * @param ev The mouse event. */ onmouseup: (ev: MouseEvent) => any; /** - * Fires when the wheel button is rotated. + * Fires when the wheel button is rotated. * @param ev The mouse event */ onmousewheel: (ev: WheelEvent) => any; @@ -6727,7 +6748,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onmspointerover: (ev: MSPointerEvent) => any; onmspointerup: (ev: MSPointerEvent) => any; /** - * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. * @param ev The event. */ onmssitemodejumplistitemremoved: (ev: MSSiteModeEvent) => any; @@ -6742,24 +6763,24 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onpause: (ev: Event) => any; /** - * Occurs when the play method is requested. + * Occurs when the play method is requested. * @param ev The event. */ onplay: (ev: Event) => any; /** - * Occurs when the audio or video has started playing. + * Occurs when the audio or video has started playing. * @param ev The event. */ onplaying: (ev: Event) => any; onpointerlockchange: (ev: Event) => any; onpointerlockerror: (ev: Event) => any; /** - * Occurs to indicate progress while downloading media data. + * Occurs to indicate progress while downloading media data. * @param ev The event. */ onprogress: (ev: ProgressEvent) => any; /** - * Occurs when the playback rate is increased or decreased. + * Occurs when the playback rate is increased or decreased. * @param ev The event. */ onratechange: (ev: Event) => any; @@ -6769,22 +6790,22 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onreadystatechange: (ev: ProgressEvent) => any; /** - * Fires when the user resets a form. + * Fires when the user resets a form. * @param ev The event. */ onreset: (ev: Event) => any; /** - * Fires when the user repositions the scroll box in the scroll bar on the object. + * Fires when the user repositions the scroll box in the scroll bar on the object. * @param ev The event. */ onscroll: (ev: UIEvent) => any; /** - * Occurs when the seek operation ends. + * Occurs when the seek operation ends. * @param ev The event. */ onseeked: (ev: Event) => any; /** - * Occurs when the current playback position is moved. + * Occurs when the current playback position is moved. * @param ev The event. */ onseeking: (ev: Event) => any; @@ -6800,7 +6821,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onselectionchange: (ev: Event) => any; onselectstart: (ev: Event) => any; /** - * Occurs when the download has stopped. + * Occurs when the download has stopped. * @param ev The event. */ onstalled: (ev: Event) => any; @@ -6811,7 +6832,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onstop: (ev: Event) => any; onsubmit: (ev: Event) => any; /** - * Occurs if the load operation has been intentionally halted. + * Occurs if the load operation has been intentionally halted. * @param ev The event. */ onsuspend: (ev: Event) => any; @@ -6830,7 +6851,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onvolumechange: (ev: Event) => any; /** - * Occurs when playback stops because the next frame of a video resource is not available. + * Occurs when playback stops because the next frame of a video resource is not available. * @param ev The event. */ onwaiting: (ev: Event) => any; @@ -6864,7 +6885,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ title: string; readonly visibilityState: string; - /** + /** * Sets or gets the color of the links that the user has visited. */ vlinkColor: string; @@ -7054,7 +7075,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; createNSResolver(nodeResolver: Node): XPathNSResolver; /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. * @param root The root element or node to start traversing on. * @param whatToShow The type of nodes or elements to appear in the node list * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. @@ -7063,11 +7084,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator; createProcessingInstruction(target: string, data: string): ProcessingInstruction; /** - * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. */ createRange(): Range; /** - * Creates a text string from the specified value. + * Creates a text string from the specified value. * @param data String that specifies the nodeValue property of the text node. */ createTextNode(data: string): Text; @@ -7082,7 +7103,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; /** - * Returns the element for the specified x coordinate and the specified y coordinate. + * Returns the element for the specified x coordinate and the specified y coordinate. * @param x The x-offset * @param y The y-offset */ @@ -7110,7 +7131,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Returns a reference to the first object with the specified value of the ID or NAME attribute. * @param elementId String that specifies the ID value. Case-insensitive. */ - getElementById(elementId: string): HTMLElement; + getElementById(elementId: string): HTMLElement | null; getElementsByClassName(classNames: string): HTMLCollectionOf; /** * Gets a collection of objects based on the value of the NAME or ID attribute. @@ -7320,7 +7341,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param replace Specifies whether the existing entry for the document is replaced in the history list. */ open(url?: string, name?: string, features?: string, replace?: boolean): Document; - /** + /** * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. * @param commandId Specifies a command identifier. */ @@ -7342,7 +7363,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven queryCommandSupported(commandId: string): boolean; /** * Retrieves the string associated with a command. - * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. + * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. */ queryCommandText(commandId: string): string; /** @@ -7358,12 +7379,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** - * Writes one or more HTML expressions to a document in the specified window. + * Writes one or more HTML expressions to a document in the specified window. * @param content Specifies the text and HTML tags to write. */ write(...content: string[]): void; /** - * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. * @param content The text and HTML tags to write. */ writeln(...content: string[]): void; @@ -7585,7 +7606,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec readonly scrollWidth: number; readonly tagName: string; innerHTML: string; - getAttribute(name?: string): string | null; + getAttribute(name: string): string | null; getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; getAttributeNodeNS(namespaceURI: string, localName: string): Attr; @@ -7795,6 +7816,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec webkitRequestFullscreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; + closest(selector: string): Element | null; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -8091,12 +8113,12 @@ interface HTMLAnchorElement extends HTMLElement { */ target: string; /** - * Retrieves or sets the text of the object as a string. + * Retrieves or sets the text of the object as a string. */ text: string; type: string; urn: string; - /** + /** * Returns a string representation of an object. */ toString(): string; @@ -8198,7 +8220,7 @@ interface HTMLAreaElement extends HTMLElement { */ host: string; /** - * Sets or retrieves the host name part of the location or URL. + * Sets or retrieves the host name part of the location or URL. */ hostname: string; /** @@ -8234,7 +8256,7 @@ interface HTMLAreaElement extends HTMLElement { * Sets or retrieves the window or frame at which to target content. */ target: string; - /** + /** * Returns a string representation of an object. */ toString(): string; @@ -8325,7 +8347,7 @@ interface HTMLBodyElement extends HTMLElement { onbeforeprint: (ev: Event) => any; onbeforeunload: (ev: BeforeUnloadEvent) => any; onblur: (ev: FocusEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onfocus: (ev: FocusEvent) => any; onhashchange: (ev: HashChangeEvent) => any; onload: (ev: Event) => any; @@ -8500,7 +8522,7 @@ interface HTMLButtonElement extends HTMLElement { * Overrides the target attribute on a form element. */ formTarget: string; - /** + /** * Sets or retrieves the name of the object. */ name: string; @@ -8517,7 +8539,7 @@ interface HTMLButtonElement extends HTMLElement { * Returns a ValidityState object that represents the validity states of an element. */ readonly validity: ValidityState; - /** + /** * Sets or retrieves the default or selected value of the control. */ value: string; @@ -8554,9 +8576,9 @@ interface HTMLCanvasElement extends HTMLElement { * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); */ - getContext(contextId: "2d"): CanvasRenderingContext2D; - getContext(contextId: "experimental-webgl"): WebGLRenderingContext; - getContext(contextId: string, ...args: any[]): CanvasRenderingContext2D | WebGLRenderingContext; + getContext(contextId: "2d", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null; + getContext(contextId: "webgl" | "experimental-webgl", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null; + getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null; /** * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. */ @@ -8566,7 +8588,7 @@ interface HTMLCanvasElement extends HTMLElement { * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. */ toDataURL(type?: string, ...args: any[]): string; - toBlob(): Blob; + toBlob(callback: (result: Blob | null) => void, ... arguments: any[]): void; } declare var HTMLCanvasElement: { @@ -8624,7 +8646,7 @@ declare var HTMLDirectoryElement: { interface HTMLDivElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. + * Sets or retrieves how the object is aligned with adjacent text. */ align: string; /** @@ -8664,7 +8686,7 @@ interface HTMLElement extends Element { readonly offsetParent: Element; readonly offsetTop: number; readonly offsetWidth: number; - onabort: (ev: Event) => any; + onabort: (ev: UIEvent) => any; onactivate: (ev: UIEvent) => any; onbeforeactivate: (ev: UIEvent) => any; onbeforecopy: (ev: ClipboardEvent) => any; @@ -8692,7 +8714,7 @@ interface HTMLElement extends Element { ondurationchange: (ev: Event) => any; onemptied: (ev: Event) => any; onended: (ev: MediaStreamErrorEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onfocus: (ev: FocusEvent) => any; oninput: (ev: Event) => any; oninvalid: (ev: Event) => any; @@ -9242,7 +9264,7 @@ interface HTMLFrameSetElement extends HTMLElement { * Fires when the object loses the input focus. */ onblur: (ev: FocusEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; /** * Fires when the object receives focus. */ @@ -9765,9 +9787,9 @@ interface HTMLInputElement extends HTMLElement { /** * Returns a FileList object on a file type input object. */ - readonly files: FileList; + readonly files: FileList | null; /** - * Retrieves a reference to the form that the object is embedded in. + * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement; /** @@ -10487,7 +10509,7 @@ interface HTMLMetaElement extends HTMLElement { */ scheme: string; /** - * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ url: string; } @@ -10736,7 +10758,7 @@ declare var HTMLOptionElement: { create(): HTMLOptionElement; } -interface HTMLOptionsCollection extends HTMLCollection { +interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; selectedIndex: number; add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; @@ -10750,7 +10772,7 @@ declare var HTMLOptionsCollection: { interface HTMLParagraphElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. + * Sets or retrieves how the object is aligned with adjacent text. */ align: string; clear: string; @@ -10852,10 +10874,10 @@ interface HTMLScriptElement extends HTMLElement { */ defer: boolean; /** - * Sets or retrieves the event for which the script is written. + * Sets or retrieves the event for which the script is written. */ event: string; - /** + /** * Sets or retrieves the object that is bound to the event script. */ htmlFor: string; @@ -10864,7 +10886,7 @@ interface HTMLScriptElement extends HTMLElement { */ src: string; /** - * Retrieves or sets the text of the object as a string. + * Retrieves or sets the text of the object as a string. */ text: string; /** @@ -10885,7 +10907,7 @@ interface HTMLSelectElement extends HTMLElement { autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. + * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement; /** @@ -10900,7 +10922,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; - options: HTMLCollectionOf; + readonly options: HTMLOptionsCollection; /** * When present, marks an element that can't be submitted without a value. */ @@ -10911,7 +10933,7 @@ interface HTMLSelectElement extends HTMLElement { selectedIndex: number; selectedOptions: HTMLCollectionOf; /** - * Sets or retrieves the number of rows in the list box. + * Sets or retrieves the number of rows in the list box. */ size: number; /** @@ -10937,7 +10959,7 @@ interface HTMLSelectElement extends HTMLElement { /** * Adds an element to the areas, controlRange, or options collection. * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. - * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. */ add(element: HTMLElement, before?: HTMLElement | number): void; /** @@ -11132,7 +11154,7 @@ interface HTMLTableElement extends HTMLElement { */ border: string; /** - * Sets or retrieves the border color of the object. + * Sets or retrieves the border color of the object. */ borderColor: any; /** @@ -11427,7 +11449,7 @@ declare var HTMLTextAreaElement: { interface HTMLTitleElement extends HTMLElement { /** - * Retrieves or sets the text of the object as a string. + * Retrieves or sets the text of the object as a string. */ text: string; } @@ -11696,7 +11718,7 @@ interface IDBDatabase extends EventTarget { readonly name: string; readonly objectStoreNames: DOMStringList; onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; version: number; onversionchange: (ev: IDBVersionChangeEvent) => any; close(): void; @@ -11799,7 +11821,7 @@ declare var IDBOpenDBRequest: { interface IDBRequest extends EventTarget { readonly error: DOMError; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onsuccess: (ev: Event) => any; readonly readyState: string; readonly result: any; @@ -11821,7 +11843,7 @@ interface IDBTransaction extends EventTarget { readonly mode: string; onabort: (ev: Event) => any; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; abort(): void; objectStore(name: string): IDBObjectStore; readonly READ_ONLY: string; @@ -11964,7 +11986,7 @@ declare var MSApp: MSApp; interface MSAppAsyncOperation extends EventTarget { readonly error: DOMError; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; readonly readyState: number; readonly result: any; start(): void; @@ -12324,7 +12346,7 @@ declare var MSStreamReader: { interface MSWebViewAsyncOperation extends EventTarget { readonly error: DOMError; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; readonly readyState: number; readonly result: any; readonly target: MSHTMLWebViewElement; @@ -12860,7 +12882,7 @@ interface Node extends EventTarget { contains(child: Node): boolean; hasAttributes(): boolean; hasChildNodes(): boolean; - insertBefore(newChild: Node, refChild: Node): Node; + insertBefore(newChild: Node, refChild: Node | null): Node; isDefaultNamespace(namespaceURI: string | null): boolean; isEqualNode(arg: Node): boolean; isSameNode(other: Node): boolean; @@ -12869,7 +12891,6 @@ interface Node extends EventTarget { normalize(): void; removeChild(oldChild: Node): Node; replaceChild(newChild: Node, oldChild: Node): Node; - contains(node: Node): boolean; readonly ATTRIBUTE_NODE: number; readonly CDATA_SECTION_NODE: number; readonly COMMENT_NODE: number; @@ -13405,7 +13426,7 @@ declare var RTCDTMFToneChangeEvent: { interface RTCDtlsTransport extends RTCStatsProvider { ondtlsstatechange: ((ev: RTCDtlsTransportStateChangedEvent) => any) | null; - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; readonly state: string; readonly transport: RTCIceTransport; getLocalParameters(): RTCDtlsParameters; @@ -13460,7 +13481,7 @@ declare var RTCIceCandidatePairChangedEvent: { interface RTCIceGatherer extends RTCStatsProvider { readonly component: string; - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; onlocalcandidate: ((ev: RTCIceGathererEvent) => any) | null; createAssociatedGatherer(): RTCIceGatherer; getLocalCandidates(): RTCIceCandidate[]; @@ -13519,7 +13540,7 @@ declare var RTCIceTransportStateChangedEvent: { } interface RTCRtpReceiver extends RTCStatsProvider { - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack | null; readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; @@ -13539,7 +13560,7 @@ declare var RTCRtpReceiver: { } interface RTCRtpSender extends RTCStatsProvider { - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; onssrcconflict: ((ev: RTCSsrcConflictEvent) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack; @@ -13560,7 +13581,7 @@ declare var RTCRtpSender: { } interface RTCSrtpSdesTransport extends EventTarget { - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; readonly transport: RTCIceTransport; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -15600,18 +15621,24 @@ declare var StyleSheetPageList: { } interface SubtleCrypto { - decrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): PromiseLike; - deriveBits(algorithm: string | Algorithm, baseKey: CryptoKey, length: number): PromiseLike; - deriveKey(algorithm: string | Algorithm, baseKey: CryptoKey, derivedKeyType: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; - digest(algorithm: string | Algorithm, data: ArrayBufferView): PromiseLike; - encrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): PromiseLike; - exportKey(format: string, key: CryptoKey): PromiseLike; - generateKey(algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; - importKey(format: string, keyData: ArrayBufferView, algorithm: string | Algorithm | null, extractable: boolean, keyUsages: string[]): PromiseLike; - sign(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): PromiseLike; - unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm | null, extractable: boolean, keyUsages: string[]): PromiseLike; - verify(algorithm: string | Algorithm, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): PromiseLike; - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike; + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; + deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + exportKey(format: "jwk", key: CryptoKey): PromiseLike; + exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; + exportKey(format: string, key: CryptoKey): PromiseLike; + generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; + importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; + unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; } declare var SubtleCrypto: { @@ -15679,7 +15706,7 @@ interface TextTrack extends EventTarget { readonly language: string; mode: any; oncuechange: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; readonly readyState: number; addCue(cue: TextTrackCue): void; @@ -16168,18 +16195,12 @@ interface WebGLRenderingContext { stencilMaskSeparate(face: number, mask: number): void; stencilOp(fail: number, zfail: number, zpass: number): void; stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void; - texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, image: HTMLImageElement): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, canvas: HTMLCanvasElement): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, video: HTMLVideoElement): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageData): void; + texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels?: ArrayBufferView): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels?: ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void; texParameterf(target: number, pname: number, param: number): void; texParameteri(target: number, pname: number, param: number): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, image: HTMLImageElement): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, canvas: HTMLCanvasElement): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, video: HTMLVideoElement): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageData): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels?: ArrayBufferView): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels?: ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void; uniform1f(location: WebGLUniformLocation | null, x: number): void; uniform1fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; uniform1i(location: WebGLUniformLocation | null, x: number): void; @@ -16902,7 +16923,7 @@ interface WebSocket extends EventTarget { readonly bufferedAmount: number; readonly extensions: string; onclose: (ev: CloseEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onmessage: (ev: MessageEvent) => any; onopen: (ev: Event) => any; readonly protocol: string; @@ -16977,7 +16998,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window name: string; readonly navigator: Navigator; offscreenBuffering: string | boolean; - onabort: (ev: Event) => any; + onabort: (ev: UIEvent) => any; onafterprint: (ev: Event) => any; onbeforeprint: (ev: Event) => any; onbeforeunload: (ev: BeforeUnloadEvent) => any; @@ -17093,6 +17114,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly top: Window; readonly window: Window; URL: typeof URL; + Blob: typeof Blob; alert(message?: any): void; blur(): void; cancelAnimationFrame(handle: number): void; @@ -17249,7 +17271,6 @@ declare var XMLDocument: { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - msCaching: string; onreadystatechange: (ev: ProgressEvent) => any; readonly readyState: number; readonly response: any; @@ -17261,6 +17282,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { timeout: number; readonly upload: XMLHttpRequestUpload; withCredentials: boolean; + msCaching?: string; abort(): void; getAllResponseHeaders(): string; getResponseHeader(header: string): string | null; @@ -17399,7 +17421,7 @@ declare var XSLTProcessor: { } interface AbstractWorker { - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -17558,7 +17580,7 @@ interface LinkStyle { interface MSBaseReader { onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; onloadstart: (ev: Event) => any; @@ -17623,7 +17645,359 @@ interface NavigatorUserMedia { } interface NodeSelector { + querySelector(selectors: "a"): HTMLAnchorElement; + querySelector(selectors: "abbr"): HTMLElement; + querySelector(selectors: "acronym"): HTMLElement; + querySelector(selectors: "address"): HTMLElement; + querySelector(selectors: "applet"): HTMLAppletElement; + querySelector(selectors: "area"): HTMLAreaElement; + querySelector(selectors: "article"): HTMLElement; + querySelector(selectors: "aside"): HTMLElement; + querySelector(selectors: "audio"): HTMLAudioElement; + querySelector(selectors: "b"): HTMLElement; + querySelector(selectors: "base"): HTMLBaseElement; + querySelector(selectors: "basefont"): HTMLBaseFontElement; + querySelector(selectors: "bdo"): HTMLElement; + querySelector(selectors: "big"): HTMLElement; + querySelector(selectors: "blockquote"): HTMLQuoteElement; + querySelector(selectors: "body"): HTMLBodyElement; + querySelector(selectors: "br"): HTMLBRElement; + querySelector(selectors: "button"): HTMLButtonElement; + querySelector(selectors: "canvas"): HTMLCanvasElement; + querySelector(selectors: "caption"): HTMLTableCaptionElement; + querySelector(selectors: "center"): HTMLElement; + querySelector(selectors: "circle"): SVGCircleElement; + querySelector(selectors: "cite"): HTMLElement; + querySelector(selectors: "clippath"): SVGClipPathElement; + querySelector(selectors: "code"): HTMLElement; + querySelector(selectors: "col"): HTMLTableColElement; + querySelector(selectors: "colgroup"): HTMLTableColElement; + querySelector(selectors: "datalist"): HTMLDataListElement; + querySelector(selectors: "dd"): HTMLElement; + querySelector(selectors: "defs"): SVGDefsElement; + querySelector(selectors: "del"): HTMLModElement; + querySelector(selectors: "desc"): SVGDescElement; + querySelector(selectors: "dfn"): HTMLElement; + querySelector(selectors: "dir"): HTMLDirectoryElement; + querySelector(selectors: "div"): HTMLDivElement; + querySelector(selectors: "dl"): HTMLDListElement; + querySelector(selectors: "dt"): HTMLElement; + querySelector(selectors: "ellipse"): SVGEllipseElement; + querySelector(selectors: "em"): HTMLElement; + querySelector(selectors: "embed"): HTMLEmbedElement; + querySelector(selectors: "feblend"): SVGFEBlendElement; + querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement; + querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement; + querySelector(selectors: "fecomposite"): SVGFECompositeElement; + querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement; + querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement; + querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement; + querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement; + querySelector(selectors: "feflood"): SVGFEFloodElement; + querySelector(selectors: "fefunca"): SVGFEFuncAElement; + querySelector(selectors: "fefuncb"): SVGFEFuncBElement; + querySelector(selectors: "fefuncg"): SVGFEFuncGElement; + querySelector(selectors: "fefuncr"): SVGFEFuncRElement; + querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement; + querySelector(selectors: "feimage"): SVGFEImageElement; + querySelector(selectors: "femerge"): SVGFEMergeElement; + querySelector(selectors: "femergenode"): SVGFEMergeNodeElement; + querySelector(selectors: "femorphology"): SVGFEMorphologyElement; + querySelector(selectors: "feoffset"): SVGFEOffsetElement; + querySelector(selectors: "fepointlight"): SVGFEPointLightElement; + querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement; + querySelector(selectors: "fespotlight"): SVGFESpotLightElement; + querySelector(selectors: "fetile"): SVGFETileElement; + querySelector(selectors: "feturbulence"): SVGFETurbulenceElement; + querySelector(selectors: "fieldset"): HTMLFieldSetElement; + querySelector(selectors: "figcaption"): HTMLElement; + querySelector(selectors: "figure"): HTMLElement; + querySelector(selectors: "filter"): SVGFilterElement; + querySelector(selectors: "font"): HTMLFontElement; + querySelector(selectors: "footer"): HTMLElement; + querySelector(selectors: "foreignobject"): SVGForeignObjectElement; + querySelector(selectors: "form"): HTMLFormElement; + querySelector(selectors: "frame"): HTMLFrameElement; + querySelector(selectors: "frameset"): HTMLFrameSetElement; + querySelector(selectors: "g"): SVGGElement; + querySelector(selectors: "h1"): HTMLHeadingElement; + querySelector(selectors: "h2"): HTMLHeadingElement; + querySelector(selectors: "h3"): HTMLHeadingElement; + querySelector(selectors: "h4"): HTMLHeadingElement; + querySelector(selectors: "h5"): HTMLHeadingElement; + querySelector(selectors: "h6"): HTMLHeadingElement; + querySelector(selectors: "head"): HTMLHeadElement; + querySelector(selectors: "header"): HTMLElement; + querySelector(selectors: "hgroup"): HTMLElement; + querySelector(selectors: "hr"): HTMLHRElement; + querySelector(selectors: "html"): HTMLHtmlElement; + querySelector(selectors: "i"): HTMLElement; + querySelector(selectors: "iframe"): HTMLIFrameElement; + querySelector(selectors: "image"): SVGImageElement; + querySelector(selectors: "img"): HTMLImageElement; + querySelector(selectors: "input"): HTMLInputElement; + querySelector(selectors: "ins"): HTMLModElement; + querySelector(selectors: "isindex"): HTMLUnknownElement; + querySelector(selectors: "kbd"): HTMLElement; + querySelector(selectors: "keygen"): HTMLElement; + querySelector(selectors: "label"): HTMLLabelElement; + querySelector(selectors: "legend"): HTMLLegendElement; + querySelector(selectors: "li"): HTMLLIElement; + querySelector(selectors: "line"): SVGLineElement; + querySelector(selectors: "lineargradient"): SVGLinearGradientElement; + querySelector(selectors: "link"): HTMLLinkElement; + querySelector(selectors: "listing"): HTMLPreElement; + querySelector(selectors: "map"): HTMLMapElement; + querySelector(selectors: "mark"): HTMLElement; + querySelector(selectors: "marker"): SVGMarkerElement; + querySelector(selectors: "marquee"): HTMLMarqueeElement; + querySelector(selectors: "mask"): SVGMaskElement; + querySelector(selectors: "menu"): HTMLMenuElement; + querySelector(selectors: "meta"): HTMLMetaElement; + querySelector(selectors: "metadata"): SVGMetadataElement; + querySelector(selectors: "meter"): HTMLMeterElement; + querySelector(selectors: "nav"): HTMLElement; + querySelector(selectors: "nextid"): HTMLUnknownElement; + querySelector(selectors: "nobr"): HTMLElement; + querySelector(selectors: "noframes"): HTMLElement; + querySelector(selectors: "noscript"): HTMLElement; + querySelector(selectors: "object"): HTMLObjectElement; + querySelector(selectors: "ol"): HTMLOListElement; + querySelector(selectors: "optgroup"): HTMLOptGroupElement; + querySelector(selectors: "option"): HTMLOptionElement; + querySelector(selectors: "p"): HTMLParagraphElement; + querySelector(selectors: "param"): HTMLParamElement; + querySelector(selectors: "path"): SVGPathElement; + querySelector(selectors: "pattern"): SVGPatternElement; + querySelector(selectors: "picture"): HTMLPictureElement; + querySelector(selectors: "plaintext"): HTMLElement; + querySelector(selectors: "polygon"): SVGPolygonElement; + querySelector(selectors: "polyline"): SVGPolylineElement; + querySelector(selectors: "pre"): HTMLPreElement; + querySelector(selectors: "progress"): HTMLProgressElement; + querySelector(selectors: "q"): HTMLQuoteElement; + querySelector(selectors: "radialgradient"): SVGRadialGradientElement; + querySelector(selectors: "rect"): SVGRectElement; + querySelector(selectors: "rt"): HTMLElement; + querySelector(selectors: "ruby"): HTMLElement; + querySelector(selectors: "s"): HTMLElement; + querySelector(selectors: "samp"): HTMLElement; + querySelector(selectors: "script"): HTMLScriptElement; + querySelector(selectors: "section"): HTMLElement; + querySelector(selectors: "select"): HTMLSelectElement; + querySelector(selectors: "small"): HTMLElement; + querySelector(selectors: "source"): HTMLSourceElement; + querySelector(selectors: "span"): HTMLSpanElement; + querySelector(selectors: "stop"): SVGStopElement; + querySelector(selectors: "strike"): HTMLElement; + querySelector(selectors: "strong"): HTMLElement; + querySelector(selectors: "style"): HTMLStyleElement; + querySelector(selectors: "sub"): HTMLElement; + querySelector(selectors: "sup"): HTMLElement; + querySelector(selectors: "svg"): SVGSVGElement; + querySelector(selectors: "switch"): SVGSwitchElement; + querySelector(selectors: "symbol"): SVGSymbolElement; + querySelector(selectors: "table"): HTMLTableElement; + querySelector(selectors: "tbody"): HTMLTableSectionElement; + querySelector(selectors: "td"): HTMLTableDataCellElement; + querySelector(selectors: "template"): HTMLTemplateElement; + querySelector(selectors: "text"): SVGTextElement; + querySelector(selectors: "textpath"): SVGTextPathElement; + querySelector(selectors: "textarea"): HTMLTextAreaElement; + querySelector(selectors: "tfoot"): HTMLTableSectionElement; + querySelector(selectors: "th"): HTMLTableHeaderCellElement; + querySelector(selectors: "thead"): HTMLTableSectionElement; + querySelector(selectors: "title"): HTMLTitleElement; + querySelector(selectors: "tr"): HTMLTableRowElement; + querySelector(selectors: "track"): HTMLTrackElement; + querySelector(selectors: "tspan"): SVGTSpanElement; + querySelector(selectors: "tt"): HTMLElement; + querySelector(selectors: "u"): HTMLElement; + querySelector(selectors: "ul"): HTMLUListElement; + querySelector(selectors: "use"): SVGUseElement; + querySelector(selectors: "var"): HTMLElement; + querySelector(selectors: "video"): HTMLVideoElement; + querySelector(selectors: "view"): SVGViewElement; + querySelector(selectors: "wbr"): HTMLElement; + querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement; + querySelector(selectors: "xmp"): HTMLPreElement; querySelector(selectors: string): Element; + querySelectorAll(selectors: "a"): NodeListOf; + querySelectorAll(selectors: "abbr"): NodeListOf; + querySelectorAll(selectors: "acronym"): NodeListOf; + querySelectorAll(selectors: "address"): NodeListOf; + querySelectorAll(selectors: "applet"): NodeListOf; + querySelectorAll(selectors: "area"): NodeListOf; + querySelectorAll(selectors: "article"): NodeListOf; + querySelectorAll(selectors: "aside"): NodeListOf; + querySelectorAll(selectors: "audio"): NodeListOf; + querySelectorAll(selectors: "b"): NodeListOf; + querySelectorAll(selectors: "base"): NodeListOf; + querySelectorAll(selectors: "basefont"): NodeListOf; + querySelectorAll(selectors: "bdo"): NodeListOf; + querySelectorAll(selectors: "big"): NodeListOf; + querySelectorAll(selectors: "blockquote"): NodeListOf; + querySelectorAll(selectors: "body"): NodeListOf; + querySelectorAll(selectors: "br"): NodeListOf; + querySelectorAll(selectors: "button"): NodeListOf; + querySelectorAll(selectors: "canvas"): NodeListOf; + querySelectorAll(selectors: "caption"): NodeListOf; + querySelectorAll(selectors: "center"): NodeListOf; + querySelectorAll(selectors: "circle"): NodeListOf; + querySelectorAll(selectors: "cite"): NodeListOf; + querySelectorAll(selectors: "clippath"): NodeListOf; + querySelectorAll(selectors: "code"): NodeListOf; + querySelectorAll(selectors: "col"): NodeListOf; + querySelectorAll(selectors: "colgroup"): NodeListOf; + querySelectorAll(selectors: "datalist"): NodeListOf; + querySelectorAll(selectors: "dd"): NodeListOf; + querySelectorAll(selectors: "defs"): NodeListOf; + querySelectorAll(selectors: "del"): NodeListOf; + querySelectorAll(selectors: "desc"): NodeListOf; + querySelectorAll(selectors: "dfn"): NodeListOf; + querySelectorAll(selectors: "dir"): NodeListOf; + querySelectorAll(selectors: "div"): NodeListOf; + querySelectorAll(selectors: "dl"): NodeListOf; + querySelectorAll(selectors: "dt"): NodeListOf; + querySelectorAll(selectors: "ellipse"): NodeListOf; + querySelectorAll(selectors: "em"): NodeListOf; + querySelectorAll(selectors: "embed"): NodeListOf; + querySelectorAll(selectors: "feblend"): NodeListOf; + querySelectorAll(selectors: "fecolormatrix"): NodeListOf; + querySelectorAll(selectors: "fecomponenttransfer"): NodeListOf; + querySelectorAll(selectors: "fecomposite"): NodeListOf; + querySelectorAll(selectors: "feconvolvematrix"): NodeListOf; + querySelectorAll(selectors: "fediffuselighting"): NodeListOf; + querySelectorAll(selectors: "fedisplacementmap"): NodeListOf; + querySelectorAll(selectors: "fedistantlight"): NodeListOf; + querySelectorAll(selectors: "feflood"): NodeListOf; + querySelectorAll(selectors: "fefunca"): NodeListOf; + querySelectorAll(selectors: "fefuncb"): NodeListOf; + querySelectorAll(selectors: "fefuncg"): NodeListOf; + querySelectorAll(selectors: "fefuncr"): NodeListOf; + querySelectorAll(selectors: "fegaussianblur"): NodeListOf; + querySelectorAll(selectors: "feimage"): NodeListOf; + querySelectorAll(selectors: "femerge"): NodeListOf; + querySelectorAll(selectors: "femergenode"): NodeListOf; + querySelectorAll(selectors: "femorphology"): NodeListOf; + querySelectorAll(selectors: "feoffset"): NodeListOf; + querySelectorAll(selectors: "fepointlight"): NodeListOf; + querySelectorAll(selectors: "fespecularlighting"): NodeListOf; + querySelectorAll(selectors: "fespotlight"): NodeListOf; + querySelectorAll(selectors: "fetile"): NodeListOf; + querySelectorAll(selectors: "feturbulence"): NodeListOf; + querySelectorAll(selectors: "fieldset"): NodeListOf; + querySelectorAll(selectors: "figcaption"): NodeListOf; + querySelectorAll(selectors: "figure"): NodeListOf; + querySelectorAll(selectors: "filter"): NodeListOf; + querySelectorAll(selectors: "font"): NodeListOf; + querySelectorAll(selectors: "footer"): NodeListOf; + querySelectorAll(selectors: "foreignobject"): NodeListOf; + querySelectorAll(selectors: "form"): NodeListOf; + querySelectorAll(selectors: "frame"): NodeListOf; + querySelectorAll(selectors: "frameset"): NodeListOf; + querySelectorAll(selectors: "g"): NodeListOf; + querySelectorAll(selectors: "h1"): NodeListOf; + querySelectorAll(selectors: "h2"): NodeListOf; + querySelectorAll(selectors: "h3"): NodeListOf; + querySelectorAll(selectors: "h4"): NodeListOf; + querySelectorAll(selectors: "h5"): NodeListOf; + querySelectorAll(selectors: "h6"): NodeListOf; + querySelectorAll(selectors: "head"): NodeListOf; + querySelectorAll(selectors: "header"): NodeListOf; + querySelectorAll(selectors: "hgroup"): NodeListOf; + querySelectorAll(selectors: "hr"): NodeListOf; + querySelectorAll(selectors: "html"): NodeListOf; + querySelectorAll(selectors: "i"): NodeListOf; + querySelectorAll(selectors: "iframe"): NodeListOf; + querySelectorAll(selectors: "image"): NodeListOf; + querySelectorAll(selectors: "img"): NodeListOf; + querySelectorAll(selectors: "input"): NodeListOf; + querySelectorAll(selectors: "ins"): NodeListOf; + querySelectorAll(selectors: "isindex"): NodeListOf; + querySelectorAll(selectors: "kbd"): NodeListOf; + querySelectorAll(selectors: "keygen"): NodeListOf; + querySelectorAll(selectors: "label"): NodeListOf; + querySelectorAll(selectors: "legend"): NodeListOf; + querySelectorAll(selectors: "li"): NodeListOf; + querySelectorAll(selectors: "line"): NodeListOf; + querySelectorAll(selectors: "lineargradient"): NodeListOf; + querySelectorAll(selectors: "link"): NodeListOf; + querySelectorAll(selectors: "listing"): NodeListOf; + querySelectorAll(selectors: "map"): NodeListOf; + querySelectorAll(selectors: "mark"): NodeListOf; + querySelectorAll(selectors: "marker"): NodeListOf; + querySelectorAll(selectors: "marquee"): NodeListOf; + querySelectorAll(selectors: "mask"): NodeListOf; + querySelectorAll(selectors: "menu"): NodeListOf; + querySelectorAll(selectors: "meta"): NodeListOf; + querySelectorAll(selectors: "metadata"): NodeListOf; + querySelectorAll(selectors: "meter"): NodeListOf; + querySelectorAll(selectors: "nav"): NodeListOf; + querySelectorAll(selectors: "nextid"): NodeListOf; + querySelectorAll(selectors: "nobr"): NodeListOf; + querySelectorAll(selectors: "noframes"): NodeListOf; + querySelectorAll(selectors: "noscript"): NodeListOf; + querySelectorAll(selectors: "object"): NodeListOf; + querySelectorAll(selectors: "ol"): NodeListOf; + querySelectorAll(selectors: "optgroup"): NodeListOf; + querySelectorAll(selectors: "option"): NodeListOf; + querySelectorAll(selectors: "p"): NodeListOf; + querySelectorAll(selectors: "param"): NodeListOf; + querySelectorAll(selectors: "path"): NodeListOf; + querySelectorAll(selectors: "pattern"): NodeListOf; + querySelectorAll(selectors: "picture"): NodeListOf; + querySelectorAll(selectors: "plaintext"): NodeListOf; + querySelectorAll(selectors: "polygon"): NodeListOf; + querySelectorAll(selectors: "polyline"): NodeListOf; + querySelectorAll(selectors: "pre"): NodeListOf; + querySelectorAll(selectors: "progress"): NodeListOf; + querySelectorAll(selectors: "q"): NodeListOf; + querySelectorAll(selectors: "radialgradient"): NodeListOf; + querySelectorAll(selectors: "rect"): NodeListOf; + querySelectorAll(selectors: "rt"): NodeListOf; + querySelectorAll(selectors: "ruby"): NodeListOf; + querySelectorAll(selectors: "s"): NodeListOf; + querySelectorAll(selectors: "samp"): NodeListOf; + querySelectorAll(selectors: "script"): NodeListOf; + querySelectorAll(selectors: "section"): NodeListOf; + querySelectorAll(selectors: "select"): NodeListOf; + querySelectorAll(selectors: "small"): NodeListOf; + querySelectorAll(selectors: "source"): NodeListOf; + querySelectorAll(selectors: "span"): NodeListOf; + querySelectorAll(selectors: "stop"): NodeListOf; + querySelectorAll(selectors: "strike"): NodeListOf; + querySelectorAll(selectors: "strong"): NodeListOf; + querySelectorAll(selectors: "style"): NodeListOf; + querySelectorAll(selectors: "sub"): NodeListOf; + querySelectorAll(selectors: "sup"): NodeListOf; + querySelectorAll(selectors: "svg"): NodeListOf; + querySelectorAll(selectors: "switch"): NodeListOf; + querySelectorAll(selectors: "symbol"): NodeListOf; + querySelectorAll(selectors: "table"): NodeListOf; + querySelectorAll(selectors: "tbody"): NodeListOf; + querySelectorAll(selectors: "td"): NodeListOf; + querySelectorAll(selectors: "template"): NodeListOf; + querySelectorAll(selectors: "text"): NodeListOf; + querySelectorAll(selectors: "textpath"): NodeListOf; + querySelectorAll(selectors: "textarea"): NodeListOf; + querySelectorAll(selectors: "tfoot"): NodeListOf; + querySelectorAll(selectors: "th"): NodeListOf; + querySelectorAll(selectors: "thead"): NodeListOf; + querySelectorAll(selectors: "title"): NodeListOf; + querySelectorAll(selectors: "tr"): NodeListOf; + querySelectorAll(selectors: "track"): NodeListOf; + querySelectorAll(selectors: "tspan"): NodeListOf; + querySelectorAll(selectors: "tt"): NodeListOf; + querySelectorAll(selectors: "u"): NodeListOf; + querySelectorAll(selectors: "ul"): NodeListOf; + querySelectorAll(selectors: "use"): NodeListOf; + querySelectorAll(selectors: "var"): NodeListOf; + querySelectorAll(selectors: "video"): NodeListOf; + querySelectorAll(selectors: "view"): NodeListOf; + querySelectorAll(selectors: "wbr"): NodeListOf; + querySelectorAll(selectors: "x-ms-webview"): NodeListOf; + querySelectorAll(selectors: "xmp"): NodeListOf; querySelectorAll(selectors: string): NodeListOf; } @@ -17711,18 +18085,21 @@ interface WindowSessionStorage { interface WindowTimers extends Object, WindowTimersExtension { clearInterval(handle: number): void; clearTimeout(handle: number): void; + setInterval(handler: (...args: any[]) => void, timeout: number): number; setInterval(handler: any, timeout?: any, ...args: any[]): number; + setTimeout(handler: (...args: any[]) => void, timeout: number): number; setTimeout(handler: any, timeout?: any, ...args: any[]): number; } interface WindowTimersExtension { clearImmediate(handle: number): void; - setImmediate(expression: any, ...args: any[]): number; + setImmediate(handler: (...args: any[]) => void): number; + setImmediate(handler: any, ...args: any[]): number; } interface XMLHttpRequestEventTarget { onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; onloadstart: (ev: Event) => any; @@ -17746,6 +18123,13 @@ interface StorageEventInit extends EventInit { storageArea?: Storage; } +interface Canvas2DContextAttributes { + alpha?: boolean; + willReadFrequently?: boolean; + storage?: boolean; + [attribute: string]: boolean | string | undefined; +} + interface NodeListOf extends NodeList { length: number; item(index: number): TNode; @@ -17795,6 +18179,177 @@ interface ClipboardEventInit extends EventInit { interface IDBArrayKey extends Array { } +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: AlgorithmIdentifier; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: AlgorithmIdentifier; +} + +interface RsaHashedImportParams { + hash: AlgorithmIdentifier; +} + +interface RsaPssParams { + saltLength: number; +} + +interface RsaOaepParams extends Algorithm { + label?: BufferSource; +} + +interface EcdsaParams extends Algorithm { + hash: AlgorithmIdentifier; +} + +interface EcKeyGenParams extends Algorithm { + typedCurve: string; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + typedCurve: string; +} + +interface EcKeyImportParams { + namedCurve: string; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesCbcParams extends Algorithm { + iv: BufferSource; +} + +interface AesCmacParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + iv: BufferSource; + additionalData?: BufferSource; + tagLength?: number; +} + +interface AesCfbParams extends Algorithm { + iv: BufferSource; +} + +interface HmacImportParams extends Algorithm { + hash?: AlgorithmIdentifier; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: AlgorithmIdentifier; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: AlgorithmIdentifier; + length?: number; +} + +interface DhKeyGenParams extends Algorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface DhKeyAlgorithm extends KeyAlgorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface DhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface DhImportKeyParams extends Algorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface ConcatParams extends Algorithm { + hash?: AlgorithmIdentifier; + algorithmId: Uint8Array; + partyUInfo: Uint8Array; + partyVInfo: Uint8Array; + publicInfo?: Uint8Array; + privateInfo?: Uint8Array; +} + +interface HkdfCtrParams extends Algorithm { + hash: AlgorithmIdentifier; + label: BufferSource; + context: BufferSource; +} + +interface Pbkdf2Params extends Algorithm { + salt: BufferSource; + iterations: number; + hash: AlgorithmIdentifier; +} + +interface RsaOtherPrimesInfo { + r: string; + d: string; + t: string; +} + +interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + kid?: string; + x5u?: string; + x5c?: string; + x5t?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { @@ -17868,7 +18423,7 @@ declare var msCredentials: MSCredentials; declare var name: string; declare var navigator: Navigator; declare var offscreenBuffering: string | boolean; -declare var onabort: (ev: Event) => any; +declare var onabort: (ev: UIEvent) => any; declare var onafterprint: (ev: Event) => any; declare var onbeforeprint: (ev: Event) => any; declare var onbeforeunload: (ev: BeforeUnloadEvent) => any; @@ -18018,10 +18573,13 @@ declare function dispatchEvent(evt: Event): boolean; declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; declare function clearInterval(handle: number): void; declare function clearTimeout(handle: number): void; +declare function setInterval(handler: (...args: any[]) => void, timeout: number): number; declare function setInterval(handler: any, timeout?: any, ...args: any[]): number; +declare function setTimeout(handler: (...args: any[]) => void, timeout: number): number; declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number; declare function clearImmediate(handle: number): void; -declare function setImmediate(expression: any, ...args: any[]): number; +declare function setImmediate(handler: (...args: any[]) => void): number; +declare function setImmediate(handler: any, ...args: any[]): number; declare var sessionStorage: Storage; declare var localStorage: Storage; declare var console: Console; @@ -18165,6 +18723,8 @@ type RTCIceGatherCandidate = RTCIceCandidate | RTCIceCandidateComplete; type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; type payloadtype = number; type IDBValidKey = number | string | Date | IDBArrayKey; +type BufferSource = ArrayBuffer | ArrayBufferView; +type MouseWheelEvent = WheelEvent; ///////////////////////////// /// WorkerGlobalScope APIs ///////////////////////////// diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 673bd34ee3c..117168cb9d1 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -20,7 +20,7 @@ and limitations under the License. ///////////////////////////// interface Algorithm { - name?: string; + name: string; } interface AriaRequestEventInit extends EventInit { @@ -867,6 +867,7 @@ interface UIEventInit extends EventInit { } interface WebGLContextAttributes { + failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; depth?: boolean; stencil?: boolean; @@ -935,7 +936,7 @@ interface ApplicationCache extends EventTarget { oncached: (ev: Event) => any; onchecking: (ev: Event) => any; ondownloading: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onnoupdate: (ev: Event) => any; onobsolete: (ev: Event) => any; onprogress: (ev: ProgressEvent) => any; @@ -2305,7 +2306,7 @@ declare var DeviceRotationRate: { interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent { /** - * Sets or gets the URL for the current document. + * Sets or gets the URL for the current document. */ readonly URL: string; /** @@ -2333,7 +2334,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ applets: HTMLCollectionOf; /** - * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. */ bgColor: string; /** @@ -2361,19 +2362,19 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ designMode: string; /** - * Sets or retrieves a value that indicates the reading order of the object. + * Sets or retrieves a value that indicates the reading order of the object. */ dir: string; /** - * Gets an object representing the document type declaration associated with the current document. + * Gets an object representing the document type declaration associated with the current document. */ readonly doctype: DocumentType; /** - * Gets a reference to the root node of the document. + * Gets a reference to the root node of the document. */ documentElement: HTMLElement; /** - * Sets or gets the security domain of the document. + * Sets or gets the security domain of the document. */ domain: string; /** @@ -2397,7 +2398,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ images: HTMLCollectionOf; /** - * Gets the implementation object of the current document. + * Gets the implementation object of the current document. */ readonly implementation: DOMImplementation; /** @@ -2405,11 +2406,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ readonly inputEncoding: string | null; /** - * Gets the date that the page was last modified, if the page supplies one. + * Gets the date that the page was last modified, if the page supplies one. */ readonly lastModified: string; /** - * Sets or gets the color of the document links. + * Sets or gets the color of the document links. */ linkColor: string; /** @@ -2417,7 +2418,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ links: HTMLCollectionOf; /** - * Contains information about the current URL. + * Contains information about the current URL. */ readonly location: Location; msCSSOMElementFloatMetrics: boolean; @@ -2426,7 +2427,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Fires when the user aborts the download. * @param ev The event. */ - onabort: (ev: Event) => any; + onabort: (ev: UIEvent) => any; /** * Fires when the object is set as the active element. * @param ev The event. @@ -2442,19 +2443,19 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param ev The event. */ onbeforedeactivate: (ev: UIEvent) => any; - /** - * Fires when the object loses the input focus. + /** + * Fires when the object loses the input focus. * @param ev The focus event. */ onblur: (ev: FocusEvent) => any; /** - * Occurs when playback is possible, but would require further buffering. + * Occurs when playback is possible, but would require further buffering. * @param ev The event. */ oncanplay: (ev: Event) => any; oncanplaythrough: (ev: Event) => any; /** - * Fires when the contents of the object or selection have changed. + * Fires when the contents of the object or selection have changed. * @param ev The event. */ onchange: (ev: Event) => any; @@ -2464,7 +2465,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onclick: (ev: MouseEvent) => any; /** - * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * Fires when the user clicks the right mouse button in the client area, opening the context menu. * @param ev The mouse event. */ oncontextmenu: (ev: PointerEvent) => any; @@ -2488,12 +2489,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param ev The event. */ ondragend: (ev: DragEvent) => any; - /** + /** * Fires on the target element when the user drags the object to a valid drop target. * @param ev The drag event. */ ondragenter: (ev: DragEvent) => any; - /** + /** * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. * @param ev The drag event. */ @@ -2504,23 +2505,23 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ ondragover: (ev: DragEvent) => any; /** - * Fires on the source object when the user starts to drag a text selection or selected object. + * Fires on the source object when the user starts to drag a text selection or selected object. * @param ev The event. */ ondragstart: (ev: DragEvent) => any; ondrop: (ev: DragEvent) => any; /** - * Occurs when the duration attribute is updated. + * Occurs when the duration attribute is updated. * @param ev The event. */ ondurationchange: (ev: Event) => any; /** - * Occurs when the media element is reset to its initial state. + * Occurs when the media element is reset to its initial state. * @param ev The event. */ onemptied: (ev: Event) => any; /** - * Occurs when the end of playback is reached. + * Occurs when the end of playback is reached. * @param ev The event */ onended: (ev: MediaStreamErrorEvent) => any; @@ -2528,9 +2529,9 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Fires when an error occurs during object loading. * @param ev The event. */ - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; /** - * Fires when the object receives focus. + * Fires when the object receives focus. * @param ev The event. */ onfocus: (ev: FocusEvent) => any; @@ -2554,12 +2555,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onkeyup: (ev: KeyboardEvent) => any; /** - * Fires immediately after the browser loads the object. + * Fires immediately after the browser loads the object. * @param ev The event. */ onload: (ev: Event) => any; /** - * Occurs when media data is loaded at the current playback position. + * Occurs when media data is loaded at the current playback position. * @param ev The event. */ onloadeddata: (ev: Event) => any; @@ -2569,22 +2570,22 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onloadedmetadata: (ev: Event) => any; /** - * Occurs when Internet Explorer begins looking for media data. + * Occurs when Internet Explorer begins looking for media data. * @param ev The event. */ onloadstart: (ev: Event) => any; /** - * Fires when the user clicks the object with either mouse button. + * Fires when the user clicks the object with either mouse button. * @param ev The mouse event. */ onmousedown: (ev: MouseEvent) => any; /** - * Fires when the user moves the mouse over the object. + * Fires when the user moves the mouse over the object. * @param ev The mouse event. */ onmousemove: (ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer outside the boundaries of the object. + * Fires when the user moves the mouse pointer outside the boundaries of the object. * @param ev The mouse event. */ onmouseout: (ev: MouseEvent) => any; @@ -2594,12 +2595,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onmouseover: (ev: MouseEvent) => any; /** - * Fires when the user releases a mouse button while the mouse is over the object. + * Fires when the user releases a mouse button while the mouse is over the object. * @param ev The mouse event. */ onmouseup: (ev: MouseEvent) => any; /** - * Fires when the wheel button is rotated. + * Fires when the wheel button is rotated. * @param ev The mouse event */ onmousewheel: (ev: WheelEvent) => any; @@ -2621,7 +2622,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onmspointerover: (ev: MSPointerEvent) => any; onmspointerup: (ev: MSPointerEvent) => any; /** - * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. * @param ev The event. */ onmssitemodejumplistitemremoved: (ev: MSSiteModeEvent) => any; @@ -2636,24 +2637,24 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onpause: (ev: Event) => any; /** - * Occurs when the play method is requested. + * Occurs when the play method is requested. * @param ev The event. */ onplay: (ev: Event) => any; /** - * Occurs when the audio or video has started playing. + * Occurs when the audio or video has started playing. * @param ev The event. */ onplaying: (ev: Event) => any; onpointerlockchange: (ev: Event) => any; onpointerlockerror: (ev: Event) => any; /** - * Occurs to indicate progress while downloading media data. + * Occurs to indicate progress while downloading media data. * @param ev The event. */ onprogress: (ev: ProgressEvent) => any; /** - * Occurs when the playback rate is increased or decreased. + * Occurs when the playback rate is increased or decreased. * @param ev The event. */ onratechange: (ev: Event) => any; @@ -2663,22 +2664,22 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onreadystatechange: (ev: ProgressEvent) => any; /** - * Fires when the user resets a form. + * Fires when the user resets a form. * @param ev The event. */ onreset: (ev: Event) => any; /** - * Fires when the user repositions the scroll box in the scroll bar on the object. + * Fires when the user repositions the scroll box in the scroll bar on the object. * @param ev The event. */ onscroll: (ev: UIEvent) => any; /** - * Occurs when the seek operation ends. + * Occurs when the seek operation ends. * @param ev The event. */ onseeked: (ev: Event) => any; /** - * Occurs when the current playback position is moved. + * Occurs when the current playback position is moved. * @param ev The event. */ onseeking: (ev: Event) => any; @@ -2694,7 +2695,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onselectionchange: (ev: Event) => any; onselectstart: (ev: Event) => any; /** - * Occurs when the download has stopped. + * Occurs when the download has stopped. * @param ev The event. */ onstalled: (ev: Event) => any; @@ -2705,7 +2706,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onstop: (ev: Event) => any; onsubmit: (ev: Event) => any; /** - * Occurs if the load operation has been intentionally halted. + * Occurs if the load operation has been intentionally halted. * @param ev The event. */ onsuspend: (ev: Event) => any; @@ -2724,7 +2725,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onvolumechange: (ev: Event) => any; /** - * Occurs when playback stops because the next frame of a video resource is not available. + * Occurs when playback stops because the next frame of a video resource is not available. * @param ev The event. */ onwaiting: (ev: Event) => any; @@ -2758,7 +2759,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ title: string; readonly visibilityState: string; - /** + /** * Sets or gets the color of the links that the user has visited. */ vlinkColor: string; @@ -2948,7 +2949,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; createNSResolver(nodeResolver: Node): XPathNSResolver; /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. * @param root The root element or node to start traversing on. * @param whatToShow The type of nodes or elements to appear in the node list * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. @@ -2957,11 +2958,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator; createProcessingInstruction(target: string, data: string): ProcessingInstruction; /** - * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. */ createRange(): Range; /** - * Creates a text string from the specified value. + * Creates a text string from the specified value. * @param data String that specifies the nodeValue property of the text node. */ createTextNode(data: string): Text; @@ -2976,7 +2977,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; /** - * Returns the element for the specified x coordinate and the specified y coordinate. + * Returns the element for the specified x coordinate and the specified y coordinate. * @param x The x-offset * @param y The y-offset */ @@ -3004,7 +3005,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Returns a reference to the first object with the specified value of the ID or NAME attribute. * @param elementId String that specifies the ID value. Case-insensitive. */ - getElementById(elementId: string): HTMLElement; + getElementById(elementId: string): HTMLElement | null; getElementsByClassName(classNames: string): HTMLCollectionOf; /** * Gets a collection of objects based on the value of the NAME or ID attribute. @@ -3214,7 +3215,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param replace Specifies whether the existing entry for the document is replaced in the history list. */ open(url?: string, name?: string, features?: string, replace?: boolean): Document; - /** + /** * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. * @param commandId Specifies a command identifier. */ @@ -3236,7 +3237,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven queryCommandSupported(commandId: string): boolean; /** * Retrieves the string associated with a command. - * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. + * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. */ queryCommandText(commandId: string): string; /** @@ -3252,12 +3253,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** - * Writes one or more HTML expressions to a document in the specified window. + * Writes one or more HTML expressions to a document in the specified window. * @param content Specifies the text and HTML tags to write. */ write(...content: string[]): void; /** - * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. * @param content The text and HTML tags to write. */ writeln(...content: string[]): void; @@ -3479,7 +3480,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec readonly scrollWidth: number; readonly tagName: string; innerHTML: string; - getAttribute(name?: string): string | null; + getAttribute(name: string): string | null; getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; getAttributeNodeNS(namespaceURI: string, localName: string): Attr; @@ -3689,6 +3690,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec webkitRequestFullscreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; + closest(selector: string): Element | null; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -3985,12 +3987,12 @@ interface HTMLAnchorElement extends HTMLElement { */ target: string; /** - * Retrieves or sets the text of the object as a string. + * Retrieves or sets the text of the object as a string. */ text: string; type: string; urn: string; - /** + /** * Returns a string representation of an object. */ toString(): string; @@ -4092,7 +4094,7 @@ interface HTMLAreaElement extends HTMLElement { */ host: string; /** - * Sets or retrieves the host name part of the location or URL. + * Sets or retrieves the host name part of the location or URL. */ hostname: string; /** @@ -4128,7 +4130,7 @@ interface HTMLAreaElement extends HTMLElement { * Sets or retrieves the window or frame at which to target content. */ target: string; - /** + /** * Returns a string representation of an object. */ toString(): string; @@ -4219,7 +4221,7 @@ interface HTMLBodyElement extends HTMLElement { onbeforeprint: (ev: Event) => any; onbeforeunload: (ev: BeforeUnloadEvent) => any; onblur: (ev: FocusEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onfocus: (ev: FocusEvent) => any; onhashchange: (ev: HashChangeEvent) => any; onload: (ev: Event) => any; @@ -4394,7 +4396,7 @@ interface HTMLButtonElement extends HTMLElement { * Overrides the target attribute on a form element. */ formTarget: string; - /** + /** * Sets or retrieves the name of the object. */ name: string; @@ -4411,7 +4413,7 @@ interface HTMLButtonElement extends HTMLElement { * Returns a ValidityState object that represents the validity states of an element. */ readonly validity: ValidityState; - /** + /** * Sets or retrieves the default or selected value of the control. */ value: string; @@ -4448,9 +4450,9 @@ interface HTMLCanvasElement extends HTMLElement { * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); */ - getContext(contextId: "2d"): CanvasRenderingContext2D; - getContext(contextId: "experimental-webgl"): WebGLRenderingContext; - getContext(contextId: string, ...args: any[]): CanvasRenderingContext2D | WebGLRenderingContext; + getContext(contextId: "2d", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null; + getContext(contextId: "webgl" | "experimental-webgl", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null; + getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null; /** * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. */ @@ -4460,7 +4462,7 @@ interface HTMLCanvasElement extends HTMLElement { * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. */ toDataURL(type?: string, ...args: any[]): string; - toBlob(): Blob; + toBlob(callback: (result: Blob | null) => void, ... arguments: any[]): void; } declare var HTMLCanvasElement: { @@ -4518,7 +4520,7 @@ declare var HTMLDirectoryElement: { interface HTMLDivElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. + * Sets or retrieves how the object is aligned with adjacent text. */ align: string; /** @@ -4558,7 +4560,7 @@ interface HTMLElement extends Element { readonly offsetParent: Element; readonly offsetTop: number; readonly offsetWidth: number; - onabort: (ev: Event) => any; + onabort: (ev: UIEvent) => any; onactivate: (ev: UIEvent) => any; onbeforeactivate: (ev: UIEvent) => any; onbeforecopy: (ev: ClipboardEvent) => any; @@ -4586,7 +4588,7 @@ interface HTMLElement extends Element { ondurationchange: (ev: Event) => any; onemptied: (ev: Event) => any; onended: (ev: MediaStreamErrorEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onfocus: (ev: FocusEvent) => any; oninput: (ev: Event) => any; oninvalid: (ev: Event) => any; @@ -5136,7 +5138,7 @@ interface HTMLFrameSetElement extends HTMLElement { * Fires when the object loses the input focus. */ onblur: (ev: FocusEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; /** * Fires when the object receives focus. */ @@ -5659,9 +5661,9 @@ interface HTMLInputElement extends HTMLElement { /** * Returns a FileList object on a file type input object. */ - readonly files: FileList; + readonly files: FileList | null; /** - * Retrieves a reference to the form that the object is embedded in. + * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement; /** @@ -6381,7 +6383,7 @@ interface HTMLMetaElement extends HTMLElement { */ scheme: string; /** - * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ url: string; } @@ -6630,7 +6632,7 @@ declare var HTMLOptionElement: { create(): HTMLOptionElement; } -interface HTMLOptionsCollection extends HTMLCollection { +interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; selectedIndex: number; add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; @@ -6644,7 +6646,7 @@ declare var HTMLOptionsCollection: { interface HTMLParagraphElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. + * Sets or retrieves how the object is aligned with adjacent text. */ align: string; clear: string; @@ -6746,10 +6748,10 @@ interface HTMLScriptElement extends HTMLElement { */ defer: boolean; /** - * Sets or retrieves the event for which the script is written. + * Sets or retrieves the event for which the script is written. */ event: string; - /** + /** * Sets or retrieves the object that is bound to the event script. */ htmlFor: string; @@ -6758,7 +6760,7 @@ interface HTMLScriptElement extends HTMLElement { */ src: string; /** - * Retrieves or sets the text of the object as a string. + * Retrieves or sets the text of the object as a string. */ text: string; /** @@ -6779,7 +6781,7 @@ interface HTMLSelectElement extends HTMLElement { autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. + * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement; /** @@ -6794,7 +6796,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; - options: HTMLCollectionOf; + readonly options: HTMLOptionsCollection; /** * When present, marks an element that can't be submitted without a value. */ @@ -6805,7 +6807,7 @@ interface HTMLSelectElement extends HTMLElement { selectedIndex: number; selectedOptions: HTMLCollectionOf; /** - * Sets or retrieves the number of rows in the list box. + * Sets or retrieves the number of rows in the list box. */ size: number; /** @@ -6831,7 +6833,7 @@ interface HTMLSelectElement extends HTMLElement { /** * Adds an element to the areas, controlRange, or options collection. * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. - * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. */ add(element: HTMLElement, before?: HTMLElement | number): void; /** @@ -7026,7 +7028,7 @@ interface HTMLTableElement extends HTMLElement { */ border: string; /** - * Sets or retrieves the border color of the object. + * Sets or retrieves the border color of the object. */ borderColor: any; /** @@ -7321,7 +7323,7 @@ declare var HTMLTextAreaElement: { interface HTMLTitleElement extends HTMLElement { /** - * Retrieves or sets the text of the object as a string. + * Retrieves or sets the text of the object as a string. */ text: string; } @@ -7590,7 +7592,7 @@ interface IDBDatabase extends EventTarget { readonly name: string; readonly objectStoreNames: DOMStringList; onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; version: number; onversionchange: (ev: IDBVersionChangeEvent) => any; close(): void; @@ -7693,7 +7695,7 @@ declare var IDBOpenDBRequest: { interface IDBRequest extends EventTarget { readonly error: DOMError; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onsuccess: (ev: Event) => any; readonly readyState: string; readonly result: any; @@ -7715,7 +7717,7 @@ interface IDBTransaction extends EventTarget { readonly mode: string; onabort: (ev: Event) => any; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; abort(): void; objectStore(name: string): IDBObjectStore; readonly READ_ONLY: string; @@ -7858,7 +7860,7 @@ declare var MSApp: MSApp; interface MSAppAsyncOperation extends EventTarget { readonly error: DOMError; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; readonly readyState: number; readonly result: any; start(): void; @@ -8218,7 +8220,7 @@ declare var MSStreamReader: { interface MSWebViewAsyncOperation extends EventTarget { readonly error: DOMError; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; readonly readyState: number; readonly result: any; readonly target: MSHTMLWebViewElement; @@ -8754,7 +8756,7 @@ interface Node extends EventTarget { contains(child: Node): boolean; hasAttributes(): boolean; hasChildNodes(): boolean; - insertBefore(newChild: Node, refChild: Node): Node; + insertBefore(newChild: Node, refChild: Node | null): Node; isDefaultNamespace(namespaceURI: string | null): boolean; isEqualNode(arg: Node): boolean; isSameNode(other: Node): boolean; @@ -8763,7 +8765,6 @@ interface Node extends EventTarget { normalize(): void; removeChild(oldChild: Node): Node; replaceChild(newChild: Node, oldChild: Node): Node; - contains(node: Node): boolean; readonly ATTRIBUTE_NODE: number; readonly CDATA_SECTION_NODE: number; readonly COMMENT_NODE: number; @@ -9299,7 +9300,7 @@ declare var RTCDTMFToneChangeEvent: { interface RTCDtlsTransport extends RTCStatsProvider { ondtlsstatechange: ((ev: RTCDtlsTransportStateChangedEvent) => any) | null; - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; readonly state: string; readonly transport: RTCIceTransport; getLocalParameters(): RTCDtlsParameters; @@ -9354,7 +9355,7 @@ declare var RTCIceCandidatePairChangedEvent: { interface RTCIceGatherer extends RTCStatsProvider { readonly component: string; - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; onlocalcandidate: ((ev: RTCIceGathererEvent) => any) | null; createAssociatedGatherer(): RTCIceGatherer; getLocalCandidates(): RTCIceCandidate[]; @@ -9413,7 +9414,7 @@ declare var RTCIceTransportStateChangedEvent: { } interface RTCRtpReceiver extends RTCStatsProvider { - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack | null; readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; @@ -9433,7 +9434,7 @@ declare var RTCRtpReceiver: { } interface RTCRtpSender extends RTCStatsProvider { - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; onssrcconflict: ((ev: RTCSsrcConflictEvent) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack; @@ -9454,7 +9455,7 @@ declare var RTCRtpSender: { } interface RTCSrtpSdesTransport extends EventTarget { - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; readonly transport: RTCIceTransport; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -11494,18 +11495,24 @@ declare var StyleSheetPageList: { } interface SubtleCrypto { - decrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): PromiseLike; - deriveBits(algorithm: string | Algorithm, baseKey: CryptoKey, length: number): PromiseLike; - deriveKey(algorithm: string | Algorithm, baseKey: CryptoKey, derivedKeyType: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; - digest(algorithm: string | Algorithm, data: ArrayBufferView): PromiseLike; - encrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): PromiseLike; - exportKey(format: string, key: CryptoKey): PromiseLike; - generateKey(algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; - importKey(format: string, keyData: ArrayBufferView, algorithm: string | Algorithm | null, extractable: boolean, keyUsages: string[]): PromiseLike; - sign(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): PromiseLike; - unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm | null, extractable: boolean, keyUsages: string[]): PromiseLike; - verify(algorithm: string | Algorithm, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): PromiseLike; - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike; + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; + deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + exportKey(format: "jwk", key: CryptoKey): PromiseLike; + exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; + exportKey(format: string, key: CryptoKey): PromiseLike; + generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; + importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; + unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; } declare var SubtleCrypto: { @@ -11573,7 +11580,7 @@ interface TextTrack extends EventTarget { readonly language: string; mode: any; oncuechange: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; readonly readyState: number; addCue(cue: TextTrackCue): void; @@ -12062,18 +12069,12 @@ interface WebGLRenderingContext { stencilMaskSeparate(face: number, mask: number): void; stencilOp(fail: number, zfail: number, zpass: number): void; stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void; - texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, image: HTMLImageElement): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, canvas: HTMLCanvasElement): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, video: HTMLVideoElement): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageData): void; + texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels?: ArrayBufferView): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels?: ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void; texParameterf(target: number, pname: number, param: number): void; texParameteri(target: number, pname: number, param: number): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, image: HTMLImageElement): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, canvas: HTMLCanvasElement): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, video: HTMLVideoElement): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageData): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels?: ArrayBufferView): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels?: ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void; uniform1f(location: WebGLUniformLocation | null, x: number): void; uniform1fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; uniform1i(location: WebGLUniformLocation | null, x: number): void; @@ -12796,7 +12797,7 @@ interface WebSocket extends EventTarget { readonly bufferedAmount: number; readonly extensions: string; onclose: (ev: CloseEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onmessage: (ev: MessageEvent) => any; onopen: (ev: Event) => any; readonly protocol: string; @@ -12871,7 +12872,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window name: string; readonly navigator: Navigator; offscreenBuffering: string | boolean; - onabort: (ev: Event) => any; + onabort: (ev: UIEvent) => any; onafterprint: (ev: Event) => any; onbeforeprint: (ev: Event) => any; onbeforeunload: (ev: BeforeUnloadEvent) => any; @@ -12987,6 +12988,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly top: Window; readonly window: Window; URL: typeof URL; + Blob: typeof Blob; alert(message?: any): void; blur(): void; cancelAnimationFrame(handle: number): void; @@ -13143,7 +13145,6 @@ declare var XMLDocument: { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - msCaching: string; onreadystatechange: (ev: ProgressEvent) => any; readonly readyState: number; readonly response: any; @@ -13155,6 +13156,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { timeout: number; readonly upload: XMLHttpRequestUpload; withCredentials: boolean; + msCaching?: string; abort(): void; getAllResponseHeaders(): string; getResponseHeader(header: string): string | null; @@ -13293,7 +13295,7 @@ declare var XSLTProcessor: { } interface AbstractWorker { - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -13452,7 +13454,7 @@ interface LinkStyle { interface MSBaseReader { onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; onloadstart: (ev: Event) => any; @@ -13517,7 +13519,359 @@ interface NavigatorUserMedia { } interface NodeSelector { + querySelector(selectors: "a"): HTMLAnchorElement; + querySelector(selectors: "abbr"): HTMLElement; + querySelector(selectors: "acronym"): HTMLElement; + querySelector(selectors: "address"): HTMLElement; + querySelector(selectors: "applet"): HTMLAppletElement; + querySelector(selectors: "area"): HTMLAreaElement; + querySelector(selectors: "article"): HTMLElement; + querySelector(selectors: "aside"): HTMLElement; + querySelector(selectors: "audio"): HTMLAudioElement; + querySelector(selectors: "b"): HTMLElement; + querySelector(selectors: "base"): HTMLBaseElement; + querySelector(selectors: "basefont"): HTMLBaseFontElement; + querySelector(selectors: "bdo"): HTMLElement; + querySelector(selectors: "big"): HTMLElement; + querySelector(selectors: "blockquote"): HTMLQuoteElement; + querySelector(selectors: "body"): HTMLBodyElement; + querySelector(selectors: "br"): HTMLBRElement; + querySelector(selectors: "button"): HTMLButtonElement; + querySelector(selectors: "canvas"): HTMLCanvasElement; + querySelector(selectors: "caption"): HTMLTableCaptionElement; + querySelector(selectors: "center"): HTMLElement; + querySelector(selectors: "circle"): SVGCircleElement; + querySelector(selectors: "cite"): HTMLElement; + querySelector(selectors: "clippath"): SVGClipPathElement; + querySelector(selectors: "code"): HTMLElement; + querySelector(selectors: "col"): HTMLTableColElement; + querySelector(selectors: "colgroup"): HTMLTableColElement; + querySelector(selectors: "datalist"): HTMLDataListElement; + querySelector(selectors: "dd"): HTMLElement; + querySelector(selectors: "defs"): SVGDefsElement; + querySelector(selectors: "del"): HTMLModElement; + querySelector(selectors: "desc"): SVGDescElement; + querySelector(selectors: "dfn"): HTMLElement; + querySelector(selectors: "dir"): HTMLDirectoryElement; + querySelector(selectors: "div"): HTMLDivElement; + querySelector(selectors: "dl"): HTMLDListElement; + querySelector(selectors: "dt"): HTMLElement; + querySelector(selectors: "ellipse"): SVGEllipseElement; + querySelector(selectors: "em"): HTMLElement; + querySelector(selectors: "embed"): HTMLEmbedElement; + querySelector(selectors: "feblend"): SVGFEBlendElement; + querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement; + querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement; + querySelector(selectors: "fecomposite"): SVGFECompositeElement; + querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement; + querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement; + querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement; + querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement; + querySelector(selectors: "feflood"): SVGFEFloodElement; + querySelector(selectors: "fefunca"): SVGFEFuncAElement; + querySelector(selectors: "fefuncb"): SVGFEFuncBElement; + querySelector(selectors: "fefuncg"): SVGFEFuncGElement; + querySelector(selectors: "fefuncr"): SVGFEFuncRElement; + querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement; + querySelector(selectors: "feimage"): SVGFEImageElement; + querySelector(selectors: "femerge"): SVGFEMergeElement; + querySelector(selectors: "femergenode"): SVGFEMergeNodeElement; + querySelector(selectors: "femorphology"): SVGFEMorphologyElement; + querySelector(selectors: "feoffset"): SVGFEOffsetElement; + querySelector(selectors: "fepointlight"): SVGFEPointLightElement; + querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement; + querySelector(selectors: "fespotlight"): SVGFESpotLightElement; + querySelector(selectors: "fetile"): SVGFETileElement; + querySelector(selectors: "feturbulence"): SVGFETurbulenceElement; + querySelector(selectors: "fieldset"): HTMLFieldSetElement; + querySelector(selectors: "figcaption"): HTMLElement; + querySelector(selectors: "figure"): HTMLElement; + querySelector(selectors: "filter"): SVGFilterElement; + querySelector(selectors: "font"): HTMLFontElement; + querySelector(selectors: "footer"): HTMLElement; + querySelector(selectors: "foreignobject"): SVGForeignObjectElement; + querySelector(selectors: "form"): HTMLFormElement; + querySelector(selectors: "frame"): HTMLFrameElement; + querySelector(selectors: "frameset"): HTMLFrameSetElement; + querySelector(selectors: "g"): SVGGElement; + querySelector(selectors: "h1"): HTMLHeadingElement; + querySelector(selectors: "h2"): HTMLHeadingElement; + querySelector(selectors: "h3"): HTMLHeadingElement; + querySelector(selectors: "h4"): HTMLHeadingElement; + querySelector(selectors: "h5"): HTMLHeadingElement; + querySelector(selectors: "h6"): HTMLHeadingElement; + querySelector(selectors: "head"): HTMLHeadElement; + querySelector(selectors: "header"): HTMLElement; + querySelector(selectors: "hgroup"): HTMLElement; + querySelector(selectors: "hr"): HTMLHRElement; + querySelector(selectors: "html"): HTMLHtmlElement; + querySelector(selectors: "i"): HTMLElement; + querySelector(selectors: "iframe"): HTMLIFrameElement; + querySelector(selectors: "image"): SVGImageElement; + querySelector(selectors: "img"): HTMLImageElement; + querySelector(selectors: "input"): HTMLInputElement; + querySelector(selectors: "ins"): HTMLModElement; + querySelector(selectors: "isindex"): HTMLUnknownElement; + querySelector(selectors: "kbd"): HTMLElement; + querySelector(selectors: "keygen"): HTMLElement; + querySelector(selectors: "label"): HTMLLabelElement; + querySelector(selectors: "legend"): HTMLLegendElement; + querySelector(selectors: "li"): HTMLLIElement; + querySelector(selectors: "line"): SVGLineElement; + querySelector(selectors: "lineargradient"): SVGLinearGradientElement; + querySelector(selectors: "link"): HTMLLinkElement; + querySelector(selectors: "listing"): HTMLPreElement; + querySelector(selectors: "map"): HTMLMapElement; + querySelector(selectors: "mark"): HTMLElement; + querySelector(selectors: "marker"): SVGMarkerElement; + querySelector(selectors: "marquee"): HTMLMarqueeElement; + querySelector(selectors: "mask"): SVGMaskElement; + querySelector(selectors: "menu"): HTMLMenuElement; + querySelector(selectors: "meta"): HTMLMetaElement; + querySelector(selectors: "metadata"): SVGMetadataElement; + querySelector(selectors: "meter"): HTMLMeterElement; + querySelector(selectors: "nav"): HTMLElement; + querySelector(selectors: "nextid"): HTMLUnknownElement; + querySelector(selectors: "nobr"): HTMLElement; + querySelector(selectors: "noframes"): HTMLElement; + querySelector(selectors: "noscript"): HTMLElement; + querySelector(selectors: "object"): HTMLObjectElement; + querySelector(selectors: "ol"): HTMLOListElement; + querySelector(selectors: "optgroup"): HTMLOptGroupElement; + querySelector(selectors: "option"): HTMLOptionElement; + querySelector(selectors: "p"): HTMLParagraphElement; + querySelector(selectors: "param"): HTMLParamElement; + querySelector(selectors: "path"): SVGPathElement; + querySelector(selectors: "pattern"): SVGPatternElement; + querySelector(selectors: "picture"): HTMLPictureElement; + querySelector(selectors: "plaintext"): HTMLElement; + querySelector(selectors: "polygon"): SVGPolygonElement; + querySelector(selectors: "polyline"): SVGPolylineElement; + querySelector(selectors: "pre"): HTMLPreElement; + querySelector(selectors: "progress"): HTMLProgressElement; + querySelector(selectors: "q"): HTMLQuoteElement; + querySelector(selectors: "radialgradient"): SVGRadialGradientElement; + querySelector(selectors: "rect"): SVGRectElement; + querySelector(selectors: "rt"): HTMLElement; + querySelector(selectors: "ruby"): HTMLElement; + querySelector(selectors: "s"): HTMLElement; + querySelector(selectors: "samp"): HTMLElement; + querySelector(selectors: "script"): HTMLScriptElement; + querySelector(selectors: "section"): HTMLElement; + querySelector(selectors: "select"): HTMLSelectElement; + querySelector(selectors: "small"): HTMLElement; + querySelector(selectors: "source"): HTMLSourceElement; + querySelector(selectors: "span"): HTMLSpanElement; + querySelector(selectors: "stop"): SVGStopElement; + querySelector(selectors: "strike"): HTMLElement; + querySelector(selectors: "strong"): HTMLElement; + querySelector(selectors: "style"): HTMLStyleElement; + querySelector(selectors: "sub"): HTMLElement; + querySelector(selectors: "sup"): HTMLElement; + querySelector(selectors: "svg"): SVGSVGElement; + querySelector(selectors: "switch"): SVGSwitchElement; + querySelector(selectors: "symbol"): SVGSymbolElement; + querySelector(selectors: "table"): HTMLTableElement; + querySelector(selectors: "tbody"): HTMLTableSectionElement; + querySelector(selectors: "td"): HTMLTableDataCellElement; + querySelector(selectors: "template"): HTMLTemplateElement; + querySelector(selectors: "text"): SVGTextElement; + querySelector(selectors: "textpath"): SVGTextPathElement; + querySelector(selectors: "textarea"): HTMLTextAreaElement; + querySelector(selectors: "tfoot"): HTMLTableSectionElement; + querySelector(selectors: "th"): HTMLTableHeaderCellElement; + querySelector(selectors: "thead"): HTMLTableSectionElement; + querySelector(selectors: "title"): HTMLTitleElement; + querySelector(selectors: "tr"): HTMLTableRowElement; + querySelector(selectors: "track"): HTMLTrackElement; + querySelector(selectors: "tspan"): SVGTSpanElement; + querySelector(selectors: "tt"): HTMLElement; + querySelector(selectors: "u"): HTMLElement; + querySelector(selectors: "ul"): HTMLUListElement; + querySelector(selectors: "use"): SVGUseElement; + querySelector(selectors: "var"): HTMLElement; + querySelector(selectors: "video"): HTMLVideoElement; + querySelector(selectors: "view"): SVGViewElement; + querySelector(selectors: "wbr"): HTMLElement; + querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement; + querySelector(selectors: "xmp"): HTMLPreElement; querySelector(selectors: string): Element; + querySelectorAll(selectors: "a"): NodeListOf; + querySelectorAll(selectors: "abbr"): NodeListOf; + querySelectorAll(selectors: "acronym"): NodeListOf; + querySelectorAll(selectors: "address"): NodeListOf; + querySelectorAll(selectors: "applet"): NodeListOf; + querySelectorAll(selectors: "area"): NodeListOf; + querySelectorAll(selectors: "article"): NodeListOf; + querySelectorAll(selectors: "aside"): NodeListOf; + querySelectorAll(selectors: "audio"): NodeListOf; + querySelectorAll(selectors: "b"): NodeListOf; + querySelectorAll(selectors: "base"): NodeListOf; + querySelectorAll(selectors: "basefont"): NodeListOf; + querySelectorAll(selectors: "bdo"): NodeListOf; + querySelectorAll(selectors: "big"): NodeListOf; + querySelectorAll(selectors: "blockquote"): NodeListOf; + querySelectorAll(selectors: "body"): NodeListOf; + querySelectorAll(selectors: "br"): NodeListOf; + querySelectorAll(selectors: "button"): NodeListOf; + querySelectorAll(selectors: "canvas"): NodeListOf; + querySelectorAll(selectors: "caption"): NodeListOf; + querySelectorAll(selectors: "center"): NodeListOf; + querySelectorAll(selectors: "circle"): NodeListOf; + querySelectorAll(selectors: "cite"): NodeListOf; + querySelectorAll(selectors: "clippath"): NodeListOf; + querySelectorAll(selectors: "code"): NodeListOf; + querySelectorAll(selectors: "col"): NodeListOf; + querySelectorAll(selectors: "colgroup"): NodeListOf; + querySelectorAll(selectors: "datalist"): NodeListOf; + querySelectorAll(selectors: "dd"): NodeListOf; + querySelectorAll(selectors: "defs"): NodeListOf; + querySelectorAll(selectors: "del"): NodeListOf; + querySelectorAll(selectors: "desc"): NodeListOf; + querySelectorAll(selectors: "dfn"): NodeListOf; + querySelectorAll(selectors: "dir"): NodeListOf; + querySelectorAll(selectors: "div"): NodeListOf; + querySelectorAll(selectors: "dl"): NodeListOf; + querySelectorAll(selectors: "dt"): NodeListOf; + querySelectorAll(selectors: "ellipse"): NodeListOf; + querySelectorAll(selectors: "em"): NodeListOf; + querySelectorAll(selectors: "embed"): NodeListOf; + querySelectorAll(selectors: "feblend"): NodeListOf; + querySelectorAll(selectors: "fecolormatrix"): NodeListOf; + querySelectorAll(selectors: "fecomponenttransfer"): NodeListOf; + querySelectorAll(selectors: "fecomposite"): NodeListOf; + querySelectorAll(selectors: "feconvolvematrix"): NodeListOf; + querySelectorAll(selectors: "fediffuselighting"): NodeListOf; + querySelectorAll(selectors: "fedisplacementmap"): NodeListOf; + querySelectorAll(selectors: "fedistantlight"): NodeListOf; + querySelectorAll(selectors: "feflood"): NodeListOf; + querySelectorAll(selectors: "fefunca"): NodeListOf; + querySelectorAll(selectors: "fefuncb"): NodeListOf; + querySelectorAll(selectors: "fefuncg"): NodeListOf; + querySelectorAll(selectors: "fefuncr"): NodeListOf; + querySelectorAll(selectors: "fegaussianblur"): NodeListOf; + querySelectorAll(selectors: "feimage"): NodeListOf; + querySelectorAll(selectors: "femerge"): NodeListOf; + querySelectorAll(selectors: "femergenode"): NodeListOf; + querySelectorAll(selectors: "femorphology"): NodeListOf; + querySelectorAll(selectors: "feoffset"): NodeListOf; + querySelectorAll(selectors: "fepointlight"): NodeListOf; + querySelectorAll(selectors: "fespecularlighting"): NodeListOf; + querySelectorAll(selectors: "fespotlight"): NodeListOf; + querySelectorAll(selectors: "fetile"): NodeListOf; + querySelectorAll(selectors: "feturbulence"): NodeListOf; + querySelectorAll(selectors: "fieldset"): NodeListOf; + querySelectorAll(selectors: "figcaption"): NodeListOf; + querySelectorAll(selectors: "figure"): NodeListOf; + querySelectorAll(selectors: "filter"): NodeListOf; + querySelectorAll(selectors: "font"): NodeListOf; + querySelectorAll(selectors: "footer"): NodeListOf; + querySelectorAll(selectors: "foreignobject"): NodeListOf; + querySelectorAll(selectors: "form"): NodeListOf; + querySelectorAll(selectors: "frame"): NodeListOf; + querySelectorAll(selectors: "frameset"): NodeListOf; + querySelectorAll(selectors: "g"): NodeListOf; + querySelectorAll(selectors: "h1"): NodeListOf; + querySelectorAll(selectors: "h2"): NodeListOf; + querySelectorAll(selectors: "h3"): NodeListOf; + querySelectorAll(selectors: "h4"): NodeListOf; + querySelectorAll(selectors: "h5"): NodeListOf; + querySelectorAll(selectors: "h6"): NodeListOf; + querySelectorAll(selectors: "head"): NodeListOf; + querySelectorAll(selectors: "header"): NodeListOf; + querySelectorAll(selectors: "hgroup"): NodeListOf; + querySelectorAll(selectors: "hr"): NodeListOf; + querySelectorAll(selectors: "html"): NodeListOf; + querySelectorAll(selectors: "i"): NodeListOf; + querySelectorAll(selectors: "iframe"): NodeListOf; + querySelectorAll(selectors: "image"): NodeListOf; + querySelectorAll(selectors: "img"): NodeListOf; + querySelectorAll(selectors: "input"): NodeListOf; + querySelectorAll(selectors: "ins"): NodeListOf; + querySelectorAll(selectors: "isindex"): NodeListOf; + querySelectorAll(selectors: "kbd"): NodeListOf; + querySelectorAll(selectors: "keygen"): NodeListOf; + querySelectorAll(selectors: "label"): NodeListOf; + querySelectorAll(selectors: "legend"): NodeListOf; + querySelectorAll(selectors: "li"): NodeListOf; + querySelectorAll(selectors: "line"): NodeListOf; + querySelectorAll(selectors: "lineargradient"): NodeListOf; + querySelectorAll(selectors: "link"): NodeListOf; + querySelectorAll(selectors: "listing"): NodeListOf; + querySelectorAll(selectors: "map"): NodeListOf; + querySelectorAll(selectors: "mark"): NodeListOf; + querySelectorAll(selectors: "marker"): NodeListOf; + querySelectorAll(selectors: "marquee"): NodeListOf; + querySelectorAll(selectors: "mask"): NodeListOf; + querySelectorAll(selectors: "menu"): NodeListOf; + querySelectorAll(selectors: "meta"): NodeListOf; + querySelectorAll(selectors: "metadata"): NodeListOf; + querySelectorAll(selectors: "meter"): NodeListOf; + querySelectorAll(selectors: "nav"): NodeListOf; + querySelectorAll(selectors: "nextid"): NodeListOf; + querySelectorAll(selectors: "nobr"): NodeListOf; + querySelectorAll(selectors: "noframes"): NodeListOf; + querySelectorAll(selectors: "noscript"): NodeListOf; + querySelectorAll(selectors: "object"): NodeListOf; + querySelectorAll(selectors: "ol"): NodeListOf; + querySelectorAll(selectors: "optgroup"): NodeListOf; + querySelectorAll(selectors: "option"): NodeListOf; + querySelectorAll(selectors: "p"): NodeListOf; + querySelectorAll(selectors: "param"): NodeListOf; + querySelectorAll(selectors: "path"): NodeListOf; + querySelectorAll(selectors: "pattern"): NodeListOf; + querySelectorAll(selectors: "picture"): NodeListOf; + querySelectorAll(selectors: "plaintext"): NodeListOf; + querySelectorAll(selectors: "polygon"): NodeListOf; + querySelectorAll(selectors: "polyline"): NodeListOf; + querySelectorAll(selectors: "pre"): NodeListOf; + querySelectorAll(selectors: "progress"): NodeListOf; + querySelectorAll(selectors: "q"): NodeListOf; + querySelectorAll(selectors: "radialgradient"): NodeListOf; + querySelectorAll(selectors: "rect"): NodeListOf; + querySelectorAll(selectors: "rt"): NodeListOf; + querySelectorAll(selectors: "ruby"): NodeListOf; + querySelectorAll(selectors: "s"): NodeListOf; + querySelectorAll(selectors: "samp"): NodeListOf; + querySelectorAll(selectors: "script"): NodeListOf; + querySelectorAll(selectors: "section"): NodeListOf; + querySelectorAll(selectors: "select"): NodeListOf; + querySelectorAll(selectors: "small"): NodeListOf; + querySelectorAll(selectors: "source"): NodeListOf; + querySelectorAll(selectors: "span"): NodeListOf; + querySelectorAll(selectors: "stop"): NodeListOf; + querySelectorAll(selectors: "strike"): NodeListOf; + querySelectorAll(selectors: "strong"): NodeListOf; + querySelectorAll(selectors: "style"): NodeListOf; + querySelectorAll(selectors: "sub"): NodeListOf; + querySelectorAll(selectors: "sup"): NodeListOf; + querySelectorAll(selectors: "svg"): NodeListOf; + querySelectorAll(selectors: "switch"): NodeListOf; + querySelectorAll(selectors: "symbol"): NodeListOf; + querySelectorAll(selectors: "table"): NodeListOf; + querySelectorAll(selectors: "tbody"): NodeListOf; + querySelectorAll(selectors: "td"): NodeListOf; + querySelectorAll(selectors: "template"): NodeListOf; + querySelectorAll(selectors: "text"): NodeListOf; + querySelectorAll(selectors: "textpath"): NodeListOf; + querySelectorAll(selectors: "textarea"): NodeListOf; + querySelectorAll(selectors: "tfoot"): NodeListOf; + querySelectorAll(selectors: "th"): NodeListOf; + querySelectorAll(selectors: "thead"): NodeListOf; + querySelectorAll(selectors: "title"): NodeListOf; + querySelectorAll(selectors: "tr"): NodeListOf; + querySelectorAll(selectors: "track"): NodeListOf; + querySelectorAll(selectors: "tspan"): NodeListOf; + querySelectorAll(selectors: "tt"): NodeListOf; + querySelectorAll(selectors: "u"): NodeListOf; + querySelectorAll(selectors: "ul"): NodeListOf; + querySelectorAll(selectors: "use"): NodeListOf; + querySelectorAll(selectors: "var"): NodeListOf; + querySelectorAll(selectors: "video"): NodeListOf; + querySelectorAll(selectors: "view"): NodeListOf; + querySelectorAll(selectors: "wbr"): NodeListOf; + querySelectorAll(selectors: "x-ms-webview"): NodeListOf; + querySelectorAll(selectors: "xmp"): NodeListOf; querySelectorAll(selectors: string): NodeListOf; } @@ -13605,18 +13959,21 @@ interface WindowSessionStorage { interface WindowTimers extends Object, WindowTimersExtension { clearInterval(handle: number): void; clearTimeout(handle: number): void; + setInterval(handler: (...args: any[]) => void, timeout: number): number; setInterval(handler: any, timeout?: any, ...args: any[]): number; + setTimeout(handler: (...args: any[]) => void, timeout: number): number; setTimeout(handler: any, timeout?: any, ...args: any[]): number; } interface WindowTimersExtension { clearImmediate(handle: number): void; - setImmediate(expression: any, ...args: any[]): number; + setImmediate(handler: (...args: any[]) => void): number; + setImmediate(handler: any, ...args: any[]): number; } interface XMLHttpRequestEventTarget { onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; onloadstart: (ev: Event) => any; @@ -13640,6 +13997,13 @@ interface StorageEventInit extends EventInit { storageArea?: Storage; } +interface Canvas2DContextAttributes { + alpha?: boolean; + willReadFrequently?: boolean; + storage?: boolean; + [attribute: string]: boolean | string | undefined; +} + interface NodeListOf extends NodeList { length: number; item(index: number): TNode; @@ -13689,6 +14053,177 @@ interface ClipboardEventInit extends EventInit { interface IDBArrayKey extends Array { } +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: AlgorithmIdentifier; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: AlgorithmIdentifier; +} + +interface RsaHashedImportParams { + hash: AlgorithmIdentifier; +} + +interface RsaPssParams { + saltLength: number; +} + +interface RsaOaepParams extends Algorithm { + label?: BufferSource; +} + +interface EcdsaParams extends Algorithm { + hash: AlgorithmIdentifier; +} + +interface EcKeyGenParams extends Algorithm { + typedCurve: string; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + typedCurve: string; +} + +interface EcKeyImportParams { + namedCurve: string; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesCbcParams extends Algorithm { + iv: BufferSource; +} + +interface AesCmacParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + iv: BufferSource; + additionalData?: BufferSource; + tagLength?: number; +} + +interface AesCfbParams extends Algorithm { + iv: BufferSource; +} + +interface HmacImportParams extends Algorithm { + hash?: AlgorithmIdentifier; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: AlgorithmIdentifier; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: AlgorithmIdentifier; + length?: number; +} + +interface DhKeyGenParams extends Algorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface DhKeyAlgorithm extends KeyAlgorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface DhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface DhImportKeyParams extends Algorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface ConcatParams extends Algorithm { + hash?: AlgorithmIdentifier; + algorithmId: Uint8Array; + partyUInfo: Uint8Array; + partyVInfo: Uint8Array; + publicInfo?: Uint8Array; + privateInfo?: Uint8Array; +} + +interface HkdfCtrParams extends Algorithm { + hash: AlgorithmIdentifier; + label: BufferSource; + context: BufferSource; +} + +interface Pbkdf2Params extends Algorithm { + salt: BufferSource; + iterations: number; + hash: AlgorithmIdentifier; +} + +interface RsaOtherPrimesInfo { + r: string; + d: string; + t: string; +} + +interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + kid?: string; + x5u?: string; + x5c?: string; + x5t?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { @@ -13762,7 +14297,7 @@ declare var msCredentials: MSCredentials; declare var name: string; declare var navigator: Navigator; declare var offscreenBuffering: string | boolean; -declare var onabort: (ev: Event) => any; +declare var onabort: (ev: UIEvent) => any; declare var onafterprint: (ev: Event) => any; declare var onbeforeprint: (ev: Event) => any; declare var onbeforeunload: (ev: BeforeUnloadEvent) => any; @@ -13912,10 +14447,13 @@ declare function dispatchEvent(evt: Event): boolean; declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; declare function clearInterval(handle: number): void; declare function clearTimeout(handle: number): void; +declare function setInterval(handler: (...args: any[]) => void, timeout: number): number; declare function setInterval(handler: any, timeout?: any, ...args: any[]): number; +declare function setTimeout(handler: (...args: any[]) => void, timeout: number): number; declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number; declare function clearImmediate(handle: number): void; -declare function setImmediate(expression: any, ...args: any[]): number; +declare function setImmediate(handler: (...args: any[]) => void): number; +declare function setImmediate(handler: any, ...args: any[]): number; declare var sessionStorage: Storage; declare var localStorage: Storage; declare var console: Console; @@ -14058,4 +14596,6 @@ type MSOutboundPayload = MSVideoSendPayload | MSAudioSendPayload; type RTCIceGatherCandidate = RTCIceCandidate | RTCIceCandidateComplete; type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; type payloadtype = number; -type IDBValidKey = number | string | Date | IDBArrayKey; \ No newline at end of file +type IDBValidKey = number | string | Date | IDBArrayKey; +type BufferSource = ArrayBuffer | ArrayBufferView; +type MouseWheelEvent = WheelEvent; \ No newline at end of file diff --git a/lib/lib.es2015.promise.d.ts b/lib/lib.es2015.promise.d.ts index 4817121154f..905cc13cba5 100644 --- a/lib/lib.es2015.promise.d.ts +++ b/lib/lib.es2015.promise.d.ts @@ -19,59 +19,149 @@ and limitations under the License. */ interface Promise { /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike): Promise; + + /** + * Creates a new Promise with the same internal state of this Promise. + * @returns A Promise. + */ + then(): Promise; /** * Attaches a callback for only the rejection of the Promise. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. */ - catch(onrejected?: (reason: any) => T | PromiseLike): Promise; - catch(onrejected?: (reason: any) => void): Promise; + catch(onrejected: (reason: any) => TResult | PromiseLike): Promise; + + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected: (reason: any) => T | PromiseLike): Promise; } interface PromiseConstructor { - /** - * A reference to the prototype. + /** + * A reference to the prototype. */ readonly prototype: Promise; /** * Creates a new Promise. - * @param executor A callback used to initialize the promise. This callback is passed two arguments: - * a resolve callback used resolve the promise with a value or the result of another promise, + * @param executor A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used resolve the promise with a value or the result of another promise, * and a reject callback used to reject the promise with a provided reason or error. */ new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises + * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: (T | PromiseLike)[]): Promise; + /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ - reject(reason: any): Promise; + reject(reason: any): Promise; /** * Creates a new rejected promise for the provided reason. diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 3b9e2d40fce..af497c972fb 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -1271,13 +1271,33 @@ declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | P interface PromiseLike { /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): PromiseLike; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): PromiseLike; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike): PromiseLike; + + /** + * Creates a new Promise with the same internal state of this Promise. + * @returns A Promise. + */ + then(): PromiseLike; } interface ArrayLike { @@ -1540,7 +1560,7 @@ interface Int8Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -1813,7 +1833,7 @@ interface Uint8Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2087,7 +2107,7 @@ interface Uint8ClampedArray { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2360,7 +2380,7 @@ interface Int16Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2634,7 +2654,7 @@ interface Uint16Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2907,7 +2927,7 @@ interface Int32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3180,7 +3200,7 @@ interface Uint32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3453,7 +3473,7 @@ interface Float32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3727,7 +3747,7 @@ interface Float64Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index a4b790b852b..c3b6555d1e8 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -1271,13 +1271,33 @@ declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | P interface PromiseLike { /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): PromiseLike; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): PromiseLike; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike): PromiseLike; + + /** + * Creates a new Promise with the same internal state of this Promise. + * @returns A Promise. + */ + then(): PromiseLike; } interface ArrayLike { @@ -1540,7 +1560,7 @@ interface Int8Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -1813,7 +1833,7 @@ interface Uint8Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2087,7 +2107,7 @@ interface Uint8ClampedArray { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2360,7 +2380,7 @@ interface Int16Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2634,7 +2654,7 @@ interface Uint16Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2907,7 +2927,7 @@ interface Int32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3180,7 +3200,7 @@ interface Uint32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3453,7 +3473,7 @@ interface Float32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3727,7 +3747,7 @@ interface Float64Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -5118,59 +5138,149 @@ interface Float64ArrayConstructor { */ interface Promise { /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike): Promise; + + /** + * Creates a new Promise with the same internal state of this Promise. + * @returns A Promise. + */ + then(): Promise; /** * Attaches a callback for only the rejection of the Promise. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. */ - catch(onrejected?: (reason: any) => T | PromiseLike): Promise; - catch(onrejected?: (reason: any) => void): Promise; + catch(onrejected: (reason: any) => TResult | PromiseLike): Promise; + + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected: (reason: any) => T | PromiseLike): Promise; } interface PromiseConstructor { - /** - * A reference to the prototype. + /** + * A reference to the prototype. */ readonly prototype: Promise; /** * Creates a new Promise. - * @param executor A callback used to initialize the promise. This callback is passed two arguments: - * a resolve callback used resolve the promise with a value or the result of another promise, + * @param executor A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used resolve the promise with a value or the result of another promise, * and a reject callback used to reject the promise with a provided reason or error. */ new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises + * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: (T | PromiseLike)[]): Promise; + /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ - reject(reason: any): Promise; + reject(reason: any): Promise; /** * Creates a new rejected promise for the provided reason. @@ -5596,7 +5706,7 @@ interface Float64Array { ///////////////////////////// interface Algorithm { - name?: string; + name: string; } interface AriaRequestEventInit extends EventInit { @@ -6443,6 +6553,7 @@ interface UIEventInit extends EventInit { } interface WebGLContextAttributes { + failIfMajorPerformanceCaveat?: boolean; alpha?: boolean; depth?: boolean; stencil?: boolean; @@ -6511,7 +6622,7 @@ interface ApplicationCache extends EventTarget { oncached: (ev: Event) => any; onchecking: (ev: Event) => any; ondownloading: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onnoupdate: (ev: Event) => any; onobsolete: (ev: Event) => any; onprogress: (ev: ProgressEvent) => any; @@ -7881,7 +7992,7 @@ declare var DeviceRotationRate: { interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent { /** - * Sets or gets the URL for the current document. + * Sets or gets the URL for the current document. */ readonly URL: string; /** @@ -7909,7 +8020,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ applets: HTMLCollectionOf; /** - * Deprecated. Sets or retrieves a value that indicates the background color behind the object. + * Deprecated. Sets or retrieves a value that indicates the background color behind the object. */ bgColor: string; /** @@ -7937,19 +8048,19 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ designMode: string; /** - * Sets or retrieves a value that indicates the reading order of the object. + * Sets or retrieves a value that indicates the reading order of the object. */ dir: string; /** - * Gets an object representing the document type declaration associated with the current document. + * Gets an object representing the document type declaration associated with the current document. */ readonly doctype: DocumentType; /** - * Gets a reference to the root node of the document. + * Gets a reference to the root node of the document. */ documentElement: HTMLElement; /** - * Sets or gets the security domain of the document. + * Sets or gets the security domain of the document. */ domain: string; /** @@ -7973,7 +8084,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ images: HTMLCollectionOf; /** - * Gets the implementation object of the current document. + * Gets the implementation object of the current document. */ readonly implementation: DOMImplementation; /** @@ -7981,11 +8092,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ readonly inputEncoding: string | null; /** - * Gets the date that the page was last modified, if the page supplies one. + * Gets the date that the page was last modified, if the page supplies one. */ readonly lastModified: string; /** - * Sets or gets the color of the document links. + * Sets or gets the color of the document links. */ linkColor: string; /** @@ -7993,7 +8104,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ links: HTMLCollectionOf; /** - * Contains information about the current URL. + * Contains information about the current URL. */ readonly location: Location; msCSSOMElementFloatMetrics: boolean; @@ -8002,7 +8113,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Fires when the user aborts the download. * @param ev The event. */ - onabort: (ev: Event) => any; + onabort: (ev: UIEvent) => any; /** * Fires when the object is set as the active element. * @param ev The event. @@ -8018,19 +8129,19 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param ev The event. */ onbeforedeactivate: (ev: UIEvent) => any; - /** - * Fires when the object loses the input focus. + /** + * Fires when the object loses the input focus. * @param ev The focus event. */ onblur: (ev: FocusEvent) => any; /** - * Occurs when playback is possible, but would require further buffering. + * Occurs when playback is possible, but would require further buffering. * @param ev The event. */ oncanplay: (ev: Event) => any; oncanplaythrough: (ev: Event) => any; /** - * Fires when the contents of the object or selection have changed. + * Fires when the contents of the object or selection have changed. * @param ev The event. */ onchange: (ev: Event) => any; @@ -8040,7 +8151,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onclick: (ev: MouseEvent) => any; /** - * Fires when the user clicks the right mouse button in the client area, opening the context menu. + * Fires when the user clicks the right mouse button in the client area, opening the context menu. * @param ev The mouse event. */ oncontextmenu: (ev: PointerEvent) => any; @@ -8064,12 +8175,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param ev The event. */ ondragend: (ev: DragEvent) => any; - /** + /** * Fires on the target element when the user drags the object to a valid drop target. * @param ev The drag event. */ ondragenter: (ev: DragEvent) => any; - /** + /** * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. * @param ev The drag event. */ @@ -8080,23 +8191,23 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ ondragover: (ev: DragEvent) => any; /** - * Fires on the source object when the user starts to drag a text selection or selected object. + * Fires on the source object when the user starts to drag a text selection or selected object. * @param ev The event. */ ondragstart: (ev: DragEvent) => any; ondrop: (ev: DragEvent) => any; /** - * Occurs when the duration attribute is updated. + * Occurs when the duration attribute is updated. * @param ev The event. */ ondurationchange: (ev: Event) => any; /** - * Occurs when the media element is reset to its initial state. + * Occurs when the media element is reset to its initial state. * @param ev The event. */ onemptied: (ev: Event) => any; /** - * Occurs when the end of playback is reached. + * Occurs when the end of playback is reached. * @param ev The event */ onended: (ev: MediaStreamErrorEvent) => any; @@ -8104,9 +8215,9 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Fires when an error occurs during object loading. * @param ev The event. */ - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; /** - * Fires when the object receives focus. + * Fires when the object receives focus. * @param ev The event. */ onfocus: (ev: FocusEvent) => any; @@ -8130,12 +8241,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onkeyup: (ev: KeyboardEvent) => any; /** - * Fires immediately after the browser loads the object. + * Fires immediately after the browser loads the object. * @param ev The event. */ onload: (ev: Event) => any; /** - * Occurs when media data is loaded at the current playback position. + * Occurs when media data is loaded at the current playback position. * @param ev The event. */ onloadeddata: (ev: Event) => any; @@ -8145,22 +8256,22 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onloadedmetadata: (ev: Event) => any; /** - * Occurs when Internet Explorer begins looking for media data. + * Occurs when Internet Explorer begins looking for media data. * @param ev The event. */ onloadstart: (ev: Event) => any; /** - * Fires when the user clicks the object with either mouse button. + * Fires when the user clicks the object with either mouse button. * @param ev The mouse event. */ onmousedown: (ev: MouseEvent) => any; /** - * Fires when the user moves the mouse over the object. + * Fires when the user moves the mouse over the object. * @param ev The mouse event. */ onmousemove: (ev: MouseEvent) => any; /** - * Fires when the user moves the mouse pointer outside the boundaries of the object. + * Fires when the user moves the mouse pointer outside the boundaries of the object. * @param ev The mouse event. */ onmouseout: (ev: MouseEvent) => any; @@ -8170,12 +8281,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onmouseover: (ev: MouseEvent) => any; /** - * Fires when the user releases a mouse button while the mouse is over the object. + * Fires when the user releases a mouse button while the mouse is over the object. * @param ev The mouse event. */ onmouseup: (ev: MouseEvent) => any; /** - * Fires when the wheel button is rotated. + * Fires when the wheel button is rotated. * @param ev The mouse event */ onmousewheel: (ev: WheelEvent) => any; @@ -8197,7 +8308,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onmspointerover: (ev: MSPointerEvent) => any; onmspointerup: (ev: MSPointerEvent) => any; /** - * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. + * Occurs when an item is removed from a Jump List of a webpage running in Site Mode. * @param ev The event. */ onmssitemodejumplistitemremoved: (ev: MSSiteModeEvent) => any; @@ -8212,24 +8323,24 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onpause: (ev: Event) => any; /** - * Occurs when the play method is requested. + * Occurs when the play method is requested. * @param ev The event. */ onplay: (ev: Event) => any; /** - * Occurs when the audio or video has started playing. + * Occurs when the audio or video has started playing. * @param ev The event. */ onplaying: (ev: Event) => any; onpointerlockchange: (ev: Event) => any; onpointerlockerror: (ev: Event) => any; /** - * Occurs to indicate progress while downloading media data. + * Occurs to indicate progress while downloading media data. * @param ev The event. */ onprogress: (ev: ProgressEvent) => any; /** - * Occurs when the playback rate is increased or decreased. + * Occurs when the playback rate is increased or decreased. * @param ev The event. */ onratechange: (ev: Event) => any; @@ -8239,22 +8350,22 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onreadystatechange: (ev: ProgressEvent) => any; /** - * Fires when the user resets a form. + * Fires when the user resets a form. * @param ev The event. */ onreset: (ev: Event) => any; /** - * Fires when the user repositions the scroll box in the scroll bar on the object. + * Fires when the user repositions the scroll box in the scroll bar on the object. * @param ev The event. */ onscroll: (ev: UIEvent) => any; /** - * Occurs when the seek operation ends. + * Occurs when the seek operation ends. * @param ev The event. */ onseeked: (ev: Event) => any; /** - * Occurs when the current playback position is moved. + * Occurs when the current playback position is moved. * @param ev The event. */ onseeking: (ev: Event) => any; @@ -8270,7 +8381,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onselectionchange: (ev: Event) => any; onselectstart: (ev: Event) => any; /** - * Occurs when the download has stopped. + * Occurs when the download has stopped. * @param ev The event. */ onstalled: (ev: Event) => any; @@ -8281,7 +8392,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven onstop: (ev: Event) => any; onsubmit: (ev: Event) => any; /** - * Occurs if the load operation has been intentionally halted. + * Occurs if the load operation has been intentionally halted. * @param ev The event. */ onsuspend: (ev: Event) => any; @@ -8300,7 +8411,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ onvolumechange: (ev: Event) => any; /** - * Occurs when playback stops because the next frame of a video resource is not available. + * Occurs when playback stops because the next frame of a video resource is not available. * @param ev The event. */ onwaiting: (ev: Event) => any; @@ -8334,7 +8445,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ title: string; readonly visibilityState: string; - /** + /** * Sets or gets the color of the links that the user has visited. */ vlinkColor: string; @@ -8524,7 +8635,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; createNSResolver(nodeResolver: Node): XPathNSResolver; /** - * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. + * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. * @param root The root element or node to start traversing on. * @param whatToShow The type of nodes or elements to appear in the node list * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter. @@ -8533,11 +8644,11 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator; createProcessingInstruction(target: string, data: string): ProcessingInstruction; /** - * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. + * Returns an empty range object that has both of its boundary points positioned at the beginning of the document. */ createRange(): Range; /** - * Creates a text string from the specified value. + * Creates a text string from the specified value. * @param data String that specifies the nodeValue property of the text node. */ createTextNode(data: string): Text; @@ -8552,7 +8663,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven */ createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker; /** - * Returns the element for the specified x coordinate and the specified y coordinate. + * Returns the element for the specified x coordinate and the specified y coordinate. * @param x The x-offset * @param y The y-offset */ @@ -8580,7 +8691,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * Returns a reference to the first object with the specified value of the ID or NAME attribute. * @param elementId String that specifies the ID value. Case-insensitive. */ - getElementById(elementId: string): HTMLElement; + getElementById(elementId: string): HTMLElement | null; getElementsByClassName(classNames: string): HTMLCollectionOf; /** * Gets a collection of objects based on the value of the NAME or ID attribute. @@ -8790,7 +8901,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven * @param replace Specifies whether the existing entry for the document is replaced in the history list. */ open(url?: string, name?: string, features?: string, replace?: boolean): Document; - /** + /** * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document. * @param commandId Specifies a command identifier. */ @@ -8812,7 +8923,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven queryCommandSupported(commandId: string): boolean; /** * Retrieves the string associated with a command. - * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. + * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers. */ queryCommandText(commandId: string): string; /** @@ -8828,12 +8939,12 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven webkitCancelFullScreen(): void; webkitExitFullscreen(): void; /** - * Writes one or more HTML expressions to a document in the specified window. + * Writes one or more HTML expressions to a document in the specified window. * @param content Specifies the text and HTML tags to write. */ write(...content: string[]): void; /** - * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. + * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. * @param content The text and HTML tags to write. */ writeln(...content: string[]): void; @@ -9055,7 +9166,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec readonly scrollWidth: number; readonly tagName: string; innerHTML: string; - getAttribute(name?: string): string | null; + getAttribute(name: string): string | null; getAttributeNS(namespaceURI: string, localName: string): string; getAttributeNode(name: string): Attr; getAttributeNodeNS(namespaceURI: string, localName: string): Attr; @@ -9265,6 +9376,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec webkitRequestFullscreen(): void; getElementsByClassName(classNames: string): NodeListOf; matches(selector: string): boolean; + closest(selector: string): Element | null; addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): void; @@ -9561,12 +9673,12 @@ interface HTMLAnchorElement extends HTMLElement { */ target: string; /** - * Retrieves or sets the text of the object as a string. + * Retrieves or sets the text of the object as a string. */ text: string; type: string; urn: string; - /** + /** * Returns a string representation of an object. */ toString(): string; @@ -9668,7 +9780,7 @@ interface HTMLAreaElement extends HTMLElement { */ host: string; /** - * Sets or retrieves the host name part of the location or URL. + * Sets or retrieves the host name part of the location or URL. */ hostname: string; /** @@ -9704,7 +9816,7 @@ interface HTMLAreaElement extends HTMLElement { * Sets or retrieves the window or frame at which to target content. */ target: string; - /** + /** * Returns a string representation of an object. */ toString(): string; @@ -9795,7 +9907,7 @@ interface HTMLBodyElement extends HTMLElement { onbeforeprint: (ev: Event) => any; onbeforeunload: (ev: BeforeUnloadEvent) => any; onblur: (ev: FocusEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onfocus: (ev: FocusEvent) => any; onhashchange: (ev: HashChangeEvent) => any; onload: (ev: Event) => any; @@ -9970,7 +10082,7 @@ interface HTMLButtonElement extends HTMLElement { * Overrides the target attribute on a form element. */ formTarget: string; - /** + /** * Sets or retrieves the name of the object. */ name: string; @@ -9987,7 +10099,7 @@ interface HTMLButtonElement extends HTMLElement { * Returns a ValidityState object that represents the validity states of an element. */ readonly validity: ValidityState; - /** + /** * Sets or retrieves the default or selected value of the control. */ value: string; @@ -10024,9 +10136,9 @@ interface HTMLCanvasElement extends HTMLElement { * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas. * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext("2d"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext("experimental-webgl"); */ - getContext(contextId: "2d"): CanvasRenderingContext2D; - getContext(contextId: "experimental-webgl"): WebGLRenderingContext; - getContext(contextId: string, ...args: any[]): CanvasRenderingContext2D | WebGLRenderingContext; + getContext(contextId: "2d", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null; + getContext(contextId: "webgl" | "experimental-webgl", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null; + getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null; /** * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing. */ @@ -10036,7 +10148,7 @@ interface HTMLCanvasElement extends HTMLElement { * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image. */ toDataURL(type?: string, ...args: any[]): string; - toBlob(): Blob; + toBlob(callback: (result: Blob | null) => void, ... arguments: any[]): void; } declare var HTMLCanvasElement: { @@ -10094,7 +10206,7 @@ declare var HTMLDirectoryElement: { interface HTMLDivElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. + * Sets or retrieves how the object is aligned with adjacent text. */ align: string; /** @@ -10134,7 +10246,7 @@ interface HTMLElement extends Element { readonly offsetParent: Element; readonly offsetTop: number; readonly offsetWidth: number; - onabort: (ev: Event) => any; + onabort: (ev: UIEvent) => any; onactivate: (ev: UIEvent) => any; onbeforeactivate: (ev: UIEvent) => any; onbeforecopy: (ev: ClipboardEvent) => any; @@ -10162,7 +10274,7 @@ interface HTMLElement extends Element { ondurationchange: (ev: Event) => any; onemptied: (ev: Event) => any; onended: (ev: MediaStreamErrorEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onfocus: (ev: FocusEvent) => any; oninput: (ev: Event) => any; oninvalid: (ev: Event) => any; @@ -10712,7 +10824,7 @@ interface HTMLFrameSetElement extends HTMLElement { * Fires when the object loses the input focus. */ onblur: (ev: FocusEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; /** * Fires when the object receives focus. */ @@ -11235,9 +11347,9 @@ interface HTMLInputElement extends HTMLElement { /** * Returns a FileList object on a file type input object. */ - readonly files: FileList; + readonly files: FileList | null; /** - * Retrieves a reference to the form that the object is embedded in. + * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement; /** @@ -11957,7 +12069,7 @@ interface HTMLMetaElement extends HTMLElement { */ scheme: string; /** - * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. + * Sets or retrieves the URL property that will be loaded after the specified time has elapsed. */ url: string; } @@ -12206,7 +12318,7 @@ declare var HTMLOptionElement: { create(): HTMLOptionElement; } -interface HTMLOptionsCollection extends HTMLCollection { +interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; selectedIndex: number; add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void; @@ -12220,7 +12332,7 @@ declare var HTMLOptionsCollection: { interface HTMLParagraphElement extends HTMLElement { /** - * Sets or retrieves how the object is aligned with adjacent text. + * Sets or retrieves how the object is aligned with adjacent text. */ align: string; clear: string; @@ -12322,10 +12434,10 @@ interface HTMLScriptElement extends HTMLElement { */ defer: boolean; /** - * Sets or retrieves the event for which the script is written. + * Sets or retrieves the event for which the script is written. */ event: string; - /** + /** * Sets or retrieves the object that is bound to the event script. */ htmlFor: string; @@ -12334,7 +12446,7 @@ interface HTMLScriptElement extends HTMLElement { */ src: string; /** - * Retrieves or sets the text of the object as a string. + * Retrieves or sets the text of the object as a string. */ text: string; /** @@ -12355,7 +12467,7 @@ interface HTMLSelectElement extends HTMLElement { autofocus: boolean; disabled: boolean; /** - * Retrieves a reference to the form that the object is embedded in. + * Retrieves a reference to the form that the object is embedded in. */ readonly form: HTMLFormElement; /** @@ -12370,7 +12482,7 @@ interface HTMLSelectElement extends HTMLElement { * Sets or retrieves the name of the object. */ name: string; - options: HTMLCollectionOf; + readonly options: HTMLOptionsCollection; /** * When present, marks an element that can't be submitted without a value. */ @@ -12381,7 +12493,7 @@ interface HTMLSelectElement extends HTMLElement { selectedIndex: number; selectedOptions: HTMLCollectionOf; /** - * Sets or retrieves the number of rows in the list box. + * Sets or retrieves the number of rows in the list box. */ size: number; /** @@ -12407,7 +12519,7 @@ interface HTMLSelectElement extends HTMLElement { /** * Adds an element to the areas, controlRange, or options collection. * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection. - * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. + * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection. */ add(element: HTMLElement, before?: HTMLElement | number): void; /** @@ -12602,7 +12714,7 @@ interface HTMLTableElement extends HTMLElement { */ border: string; /** - * Sets or retrieves the border color of the object. + * Sets or retrieves the border color of the object. */ borderColor: any; /** @@ -12897,7 +13009,7 @@ declare var HTMLTextAreaElement: { interface HTMLTitleElement extends HTMLElement { /** - * Retrieves or sets the text of the object as a string. + * Retrieves or sets the text of the object as a string. */ text: string; } @@ -13166,7 +13278,7 @@ interface IDBDatabase extends EventTarget { readonly name: string; readonly objectStoreNames: DOMStringList; onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; version: number; onversionchange: (ev: IDBVersionChangeEvent) => any; close(): void; @@ -13269,7 +13381,7 @@ declare var IDBOpenDBRequest: { interface IDBRequest extends EventTarget { readonly error: DOMError; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onsuccess: (ev: Event) => any; readonly readyState: string; readonly result: any; @@ -13291,7 +13403,7 @@ interface IDBTransaction extends EventTarget { readonly mode: string; onabort: (ev: Event) => any; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; abort(): void; objectStore(name: string): IDBObjectStore; readonly READ_ONLY: string; @@ -13434,7 +13546,7 @@ declare var MSApp: MSApp; interface MSAppAsyncOperation extends EventTarget { readonly error: DOMError; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; readonly readyState: number; readonly result: any; start(): void; @@ -13794,7 +13906,7 @@ declare var MSStreamReader: { interface MSWebViewAsyncOperation extends EventTarget { readonly error: DOMError; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; readonly readyState: number; readonly result: any; readonly target: MSHTMLWebViewElement; @@ -14330,7 +14442,7 @@ interface Node extends EventTarget { contains(child: Node): boolean; hasAttributes(): boolean; hasChildNodes(): boolean; - insertBefore(newChild: Node, refChild: Node): Node; + insertBefore(newChild: Node, refChild: Node | null): Node; isDefaultNamespace(namespaceURI: string | null): boolean; isEqualNode(arg: Node): boolean; isSameNode(other: Node): boolean; @@ -14339,7 +14451,6 @@ interface Node extends EventTarget { normalize(): void; removeChild(oldChild: Node): Node; replaceChild(newChild: Node, oldChild: Node): Node; - contains(node: Node): boolean; readonly ATTRIBUTE_NODE: number; readonly CDATA_SECTION_NODE: number; readonly COMMENT_NODE: number; @@ -14875,7 +14986,7 @@ declare var RTCDTMFToneChangeEvent: { interface RTCDtlsTransport extends RTCStatsProvider { ondtlsstatechange: ((ev: RTCDtlsTransportStateChangedEvent) => any) | null; - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; readonly state: string; readonly transport: RTCIceTransport; getLocalParameters(): RTCDtlsParameters; @@ -14930,7 +15041,7 @@ declare var RTCIceCandidatePairChangedEvent: { interface RTCIceGatherer extends RTCStatsProvider { readonly component: string; - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; onlocalcandidate: ((ev: RTCIceGathererEvent) => any) | null; createAssociatedGatherer(): RTCIceGatherer; getLocalCandidates(): RTCIceCandidate[]; @@ -14989,7 +15100,7 @@ declare var RTCIceTransportStateChangedEvent: { } interface RTCRtpReceiver extends RTCStatsProvider { - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack | null; readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport; @@ -15009,7 +15120,7 @@ declare var RTCRtpReceiver: { } interface RTCRtpSender extends RTCStatsProvider { - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; onssrcconflict: ((ev: RTCSsrcConflictEvent) => any) | null; readonly rtcpTransport: RTCDtlsTransport; readonly track: MediaStreamTrack; @@ -15030,7 +15141,7 @@ declare var RTCRtpSender: { } interface RTCSrtpSdesTransport extends EventTarget { - onerror: ((ev: Event) => any) | null; + onerror: ((ev: ErrorEvent) => any) | null; readonly transport: RTCIceTransport; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; @@ -17070,18 +17181,24 @@ declare var StyleSheetPageList: { } interface SubtleCrypto { - decrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): PromiseLike; - deriveBits(algorithm: string | Algorithm, baseKey: CryptoKey, length: number): PromiseLike; - deriveKey(algorithm: string | Algorithm, baseKey: CryptoKey, derivedKeyType: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; - digest(algorithm: string | Algorithm, data: ArrayBufferView): PromiseLike; - encrypt(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): PromiseLike; - exportKey(format: string, key: CryptoKey): PromiseLike; - generateKey(algorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike; - importKey(format: string, keyData: ArrayBufferView, algorithm: string | Algorithm | null, extractable: boolean, keyUsages: string[]): PromiseLike; - sign(algorithm: string | Algorithm, key: CryptoKey, data: ArrayBufferView): PromiseLike; - unwrapKey(format: string, wrappedKey: ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm | null, extractable: boolean, keyUsages: string[]): PromiseLike; - verify(algorithm: string | Algorithm, key: CryptoKey, signature: ArrayBufferView, data: ArrayBufferView): PromiseLike; - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike; + decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike; + deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + digest(algorithm: AlgorithmIdentifier, data: BufferSource): PromiseLike; + encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: BufferSource): PromiseLike; + exportKey(format: "jwk", key: CryptoKey): PromiseLike; + exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): PromiseLike; + exportKey(format: string, key: CryptoKey): PromiseLike; + generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike; + generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike; + importKey(format: "jwk", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; + importKey(format: "raw" | "pkcs8" | "spki", keyData: BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; + importKey(format: string, keyData: JsonWebKey | BufferSource, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable:boolean, keyUsages: string[]): PromiseLike; + sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: BufferSource): PromiseLike; + unwrapKey(format: string, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: string[]): PromiseLike; + verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: BufferSource, data: BufferSource): PromiseLike; + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier): PromiseLike; } declare var SubtleCrypto: { @@ -17149,7 +17266,7 @@ interface TextTrack extends EventTarget { readonly language: string; mode: any; oncuechange: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; readonly readyState: number; addCue(cue: TextTrackCue): void; @@ -17638,18 +17755,12 @@ interface WebGLRenderingContext { stencilMaskSeparate(face: number, mask: number): void; stencilOp(fail: number, zfail: number, zpass: number): void; stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void; - texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, image: HTMLImageElement): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, canvas: HTMLCanvasElement): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, video: HTMLVideoElement): void; - texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageData): void; + texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels?: ArrayBufferView): void; + texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels?: ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void; texParameterf(target: number, pname: number, param: number): void; texParameteri(target: number, pname: number, param: number): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, image: HTMLImageElement): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, canvas: HTMLCanvasElement): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, video: HTMLVideoElement): void; - texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageData): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels?: ArrayBufferView): void; + texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels?: ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void; uniform1f(location: WebGLUniformLocation | null, x: number): void; uniform1fv(location: WebGLUniformLocation, v: Float32Array | number[]): void; uniform1i(location: WebGLUniformLocation | null, x: number): void; @@ -18372,7 +18483,7 @@ interface WebSocket extends EventTarget { readonly bufferedAmount: number; readonly extensions: string; onclose: (ev: CloseEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onmessage: (ev: MessageEvent) => any; onopen: (ev: Event) => any; readonly protocol: string; @@ -18447,7 +18558,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window name: string; readonly navigator: Navigator; offscreenBuffering: string | boolean; - onabort: (ev: Event) => any; + onabort: (ev: UIEvent) => any; onafterprint: (ev: Event) => any; onbeforeprint: (ev: Event) => any; onbeforeunload: (ev: BeforeUnloadEvent) => any; @@ -18563,6 +18674,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window readonly top: Window; readonly window: Window; URL: typeof URL; + Blob: typeof Blob; alert(message?: any): void; blur(): void; cancelAnimationFrame(handle: number): void; @@ -18719,7 +18831,6 @@ declare var XMLDocument: { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - msCaching: string; onreadystatechange: (ev: ProgressEvent) => any; readonly readyState: number; readonly response: any; @@ -18731,6 +18842,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { timeout: number; readonly upload: XMLHttpRequestUpload; withCredentials: boolean; + msCaching?: string; abort(): void; getAllResponseHeaders(): string; getResponseHeader(header: string): string | null; @@ -18869,7 +18981,7 @@ declare var XSLTProcessor: { } interface AbstractWorker { - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -19028,7 +19140,7 @@ interface LinkStyle { interface MSBaseReader { onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; onloadstart: (ev: Event) => any; @@ -19093,7 +19205,359 @@ interface NavigatorUserMedia { } interface NodeSelector { + querySelector(selectors: "a"): HTMLAnchorElement; + querySelector(selectors: "abbr"): HTMLElement; + querySelector(selectors: "acronym"): HTMLElement; + querySelector(selectors: "address"): HTMLElement; + querySelector(selectors: "applet"): HTMLAppletElement; + querySelector(selectors: "area"): HTMLAreaElement; + querySelector(selectors: "article"): HTMLElement; + querySelector(selectors: "aside"): HTMLElement; + querySelector(selectors: "audio"): HTMLAudioElement; + querySelector(selectors: "b"): HTMLElement; + querySelector(selectors: "base"): HTMLBaseElement; + querySelector(selectors: "basefont"): HTMLBaseFontElement; + querySelector(selectors: "bdo"): HTMLElement; + querySelector(selectors: "big"): HTMLElement; + querySelector(selectors: "blockquote"): HTMLQuoteElement; + querySelector(selectors: "body"): HTMLBodyElement; + querySelector(selectors: "br"): HTMLBRElement; + querySelector(selectors: "button"): HTMLButtonElement; + querySelector(selectors: "canvas"): HTMLCanvasElement; + querySelector(selectors: "caption"): HTMLTableCaptionElement; + querySelector(selectors: "center"): HTMLElement; + querySelector(selectors: "circle"): SVGCircleElement; + querySelector(selectors: "cite"): HTMLElement; + querySelector(selectors: "clippath"): SVGClipPathElement; + querySelector(selectors: "code"): HTMLElement; + querySelector(selectors: "col"): HTMLTableColElement; + querySelector(selectors: "colgroup"): HTMLTableColElement; + querySelector(selectors: "datalist"): HTMLDataListElement; + querySelector(selectors: "dd"): HTMLElement; + querySelector(selectors: "defs"): SVGDefsElement; + querySelector(selectors: "del"): HTMLModElement; + querySelector(selectors: "desc"): SVGDescElement; + querySelector(selectors: "dfn"): HTMLElement; + querySelector(selectors: "dir"): HTMLDirectoryElement; + querySelector(selectors: "div"): HTMLDivElement; + querySelector(selectors: "dl"): HTMLDListElement; + querySelector(selectors: "dt"): HTMLElement; + querySelector(selectors: "ellipse"): SVGEllipseElement; + querySelector(selectors: "em"): HTMLElement; + querySelector(selectors: "embed"): HTMLEmbedElement; + querySelector(selectors: "feblend"): SVGFEBlendElement; + querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement; + querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement; + querySelector(selectors: "fecomposite"): SVGFECompositeElement; + querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement; + querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement; + querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement; + querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement; + querySelector(selectors: "feflood"): SVGFEFloodElement; + querySelector(selectors: "fefunca"): SVGFEFuncAElement; + querySelector(selectors: "fefuncb"): SVGFEFuncBElement; + querySelector(selectors: "fefuncg"): SVGFEFuncGElement; + querySelector(selectors: "fefuncr"): SVGFEFuncRElement; + querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement; + querySelector(selectors: "feimage"): SVGFEImageElement; + querySelector(selectors: "femerge"): SVGFEMergeElement; + querySelector(selectors: "femergenode"): SVGFEMergeNodeElement; + querySelector(selectors: "femorphology"): SVGFEMorphologyElement; + querySelector(selectors: "feoffset"): SVGFEOffsetElement; + querySelector(selectors: "fepointlight"): SVGFEPointLightElement; + querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement; + querySelector(selectors: "fespotlight"): SVGFESpotLightElement; + querySelector(selectors: "fetile"): SVGFETileElement; + querySelector(selectors: "feturbulence"): SVGFETurbulenceElement; + querySelector(selectors: "fieldset"): HTMLFieldSetElement; + querySelector(selectors: "figcaption"): HTMLElement; + querySelector(selectors: "figure"): HTMLElement; + querySelector(selectors: "filter"): SVGFilterElement; + querySelector(selectors: "font"): HTMLFontElement; + querySelector(selectors: "footer"): HTMLElement; + querySelector(selectors: "foreignobject"): SVGForeignObjectElement; + querySelector(selectors: "form"): HTMLFormElement; + querySelector(selectors: "frame"): HTMLFrameElement; + querySelector(selectors: "frameset"): HTMLFrameSetElement; + querySelector(selectors: "g"): SVGGElement; + querySelector(selectors: "h1"): HTMLHeadingElement; + querySelector(selectors: "h2"): HTMLHeadingElement; + querySelector(selectors: "h3"): HTMLHeadingElement; + querySelector(selectors: "h4"): HTMLHeadingElement; + querySelector(selectors: "h5"): HTMLHeadingElement; + querySelector(selectors: "h6"): HTMLHeadingElement; + querySelector(selectors: "head"): HTMLHeadElement; + querySelector(selectors: "header"): HTMLElement; + querySelector(selectors: "hgroup"): HTMLElement; + querySelector(selectors: "hr"): HTMLHRElement; + querySelector(selectors: "html"): HTMLHtmlElement; + querySelector(selectors: "i"): HTMLElement; + querySelector(selectors: "iframe"): HTMLIFrameElement; + querySelector(selectors: "image"): SVGImageElement; + querySelector(selectors: "img"): HTMLImageElement; + querySelector(selectors: "input"): HTMLInputElement; + querySelector(selectors: "ins"): HTMLModElement; + querySelector(selectors: "isindex"): HTMLUnknownElement; + querySelector(selectors: "kbd"): HTMLElement; + querySelector(selectors: "keygen"): HTMLElement; + querySelector(selectors: "label"): HTMLLabelElement; + querySelector(selectors: "legend"): HTMLLegendElement; + querySelector(selectors: "li"): HTMLLIElement; + querySelector(selectors: "line"): SVGLineElement; + querySelector(selectors: "lineargradient"): SVGLinearGradientElement; + querySelector(selectors: "link"): HTMLLinkElement; + querySelector(selectors: "listing"): HTMLPreElement; + querySelector(selectors: "map"): HTMLMapElement; + querySelector(selectors: "mark"): HTMLElement; + querySelector(selectors: "marker"): SVGMarkerElement; + querySelector(selectors: "marquee"): HTMLMarqueeElement; + querySelector(selectors: "mask"): SVGMaskElement; + querySelector(selectors: "menu"): HTMLMenuElement; + querySelector(selectors: "meta"): HTMLMetaElement; + querySelector(selectors: "metadata"): SVGMetadataElement; + querySelector(selectors: "meter"): HTMLMeterElement; + querySelector(selectors: "nav"): HTMLElement; + querySelector(selectors: "nextid"): HTMLUnknownElement; + querySelector(selectors: "nobr"): HTMLElement; + querySelector(selectors: "noframes"): HTMLElement; + querySelector(selectors: "noscript"): HTMLElement; + querySelector(selectors: "object"): HTMLObjectElement; + querySelector(selectors: "ol"): HTMLOListElement; + querySelector(selectors: "optgroup"): HTMLOptGroupElement; + querySelector(selectors: "option"): HTMLOptionElement; + querySelector(selectors: "p"): HTMLParagraphElement; + querySelector(selectors: "param"): HTMLParamElement; + querySelector(selectors: "path"): SVGPathElement; + querySelector(selectors: "pattern"): SVGPatternElement; + querySelector(selectors: "picture"): HTMLPictureElement; + querySelector(selectors: "plaintext"): HTMLElement; + querySelector(selectors: "polygon"): SVGPolygonElement; + querySelector(selectors: "polyline"): SVGPolylineElement; + querySelector(selectors: "pre"): HTMLPreElement; + querySelector(selectors: "progress"): HTMLProgressElement; + querySelector(selectors: "q"): HTMLQuoteElement; + querySelector(selectors: "radialgradient"): SVGRadialGradientElement; + querySelector(selectors: "rect"): SVGRectElement; + querySelector(selectors: "rt"): HTMLElement; + querySelector(selectors: "ruby"): HTMLElement; + querySelector(selectors: "s"): HTMLElement; + querySelector(selectors: "samp"): HTMLElement; + querySelector(selectors: "script"): HTMLScriptElement; + querySelector(selectors: "section"): HTMLElement; + querySelector(selectors: "select"): HTMLSelectElement; + querySelector(selectors: "small"): HTMLElement; + querySelector(selectors: "source"): HTMLSourceElement; + querySelector(selectors: "span"): HTMLSpanElement; + querySelector(selectors: "stop"): SVGStopElement; + querySelector(selectors: "strike"): HTMLElement; + querySelector(selectors: "strong"): HTMLElement; + querySelector(selectors: "style"): HTMLStyleElement; + querySelector(selectors: "sub"): HTMLElement; + querySelector(selectors: "sup"): HTMLElement; + querySelector(selectors: "svg"): SVGSVGElement; + querySelector(selectors: "switch"): SVGSwitchElement; + querySelector(selectors: "symbol"): SVGSymbolElement; + querySelector(selectors: "table"): HTMLTableElement; + querySelector(selectors: "tbody"): HTMLTableSectionElement; + querySelector(selectors: "td"): HTMLTableDataCellElement; + querySelector(selectors: "template"): HTMLTemplateElement; + querySelector(selectors: "text"): SVGTextElement; + querySelector(selectors: "textpath"): SVGTextPathElement; + querySelector(selectors: "textarea"): HTMLTextAreaElement; + querySelector(selectors: "tfoot"): HTMLTableSectionElement; + querySelector(selectors: "th"): HTMLTableHeaderCellElement; + querySelector(selectors: "thead"): HTMLTableSectionElement; + querySelector(selectors: "title"): HTMLTitleElement; + querySelector(selectors: "tr"): HTMLTableRowElement; + querySelector(selectors: "track"): HTMLTrackElement; + querySelector(selectors: "tspan"): SVGTSpanElement; + querySelector(selectors: "tt"): HTMLElement; + querySelector(selectors: "u"): HTMLElement; + querySelector(selectors: "ul"): HTMLUListElement; + querySelector(selectors: "use"): SVGUseElement; + querySelector(selectors: "var"): HTMLElement; + querySelector(selectors: "video"): HTMLVideoElement; + querySelector(selectors: "view"): SVGViewElement; + querySelector(selectors: "wbr"): HTMLElement; + querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement; + querySelector(selectors: "xmp"): HTMLPreElement; querySelector(selectors: string): Element; + querySelectorAll(selectors: "a"): NodeListOf; + querySelectorAll(selectors: "abbr"): NodeListOf; + querySelectorAll(selectors: "acronym"): NodeListOf; + querySelectorAll(selectors: "address"): NodeListOf; + querySelectorAll(selectors: "applet"): NodeListOf; + querySelectorAll(selectors: "area"): NodeListOf; + querySelectorAll(selectors: "article"): NodeListOf; + querySelectorAll(selectors: "aside"): NodeListOf; + querySelectorAll(selectors: "audio"): NodeListOf; + querySelectorAll(selectors: "b"): NodeListOf; + querySelectorAll(selectors: "base"): NodeListOf; + querySelectorAll(selectors: "basefont"): NodeListOf; + querySelectorAll(selectors: "bdo"): NodeListOf; + querySelectorAll(selectors: "big"): NodeListOf; + querySelectorAll(selectors: "blockquote"): NodeListOf; + querySelectorAll(selectors: "body"): NodeListOf; + querySelectorAll(selectors: "br"): NodeListOf; + querySelectorAll(selectors: "button"): NodeListOf; + querySelectorAll(selectors: "canvas"): NodeListOf; + querySelectorAll(selectors: "caption"): NodeListOf; + querySelectorAll(selectors: "center"): NodeListOf; + querySelectorAll(selectors: "circle"): NodeListOf; + querySelectorAll(selectors: "cite"): NodeListOf; + querySelectorAll(selectors: "clippath"): NodeListOf; + querySelectorAll(selectors: "code"): NodeListOf; + querySelectorAll(selectors: "col"): NodeListOf; + querySelectorAll(selectors: "colgroup"): NodeListOf; + querySelectorAll(selectors: "datalist"): NodeListOf; + querySelectorAll(selectors: "dd"): NodeListOf; + querySelectorAll(selectors: "defs"): NodeListOf; + querySelectorAll(selectors: "del"): NodeListOf; + querySelectorAll(selectors: "desc"): NodeListOf; + querySelectorAll(selectors: "dfn"): NodeListOf; + querySelectorAll(selectors: "dir"): NodeListOf; + querySelectorAll(selectors: "div"): NodeListOf; + querySelectorAll(selectors: "dl"): NodeListOf; + querySelectorAll(selectors: "dt"): NodeListOf; + querySelectorAll(selectors: "ellipse"): NodeListOf; + querySelectorAll(selectors: "em"): NodeListOf; + querySelectorAll(selectors: "embed"): NodeListOf; + querySelectorAll(selectors: "feblend"): NodeListOf; + querySelectorAll(selectors: "fecolormatrix"): NodeListOf; + querySelectorAll(selectors: "fecomponenttransfer"): NodeListOf; + querySelectorAll(selectors: "fecomposite"): NodeListOf; + querySelectorAll(selectors: "feconvolvematrix"): NodeListOf; + querySelectorAll(selectors: "fediffuselighting"): NodeListOf; + querySelectorAll(selectors: "fedisplacementmap"): NodeListOf; + querySelectorAll(selectors: "fedistantlight"): NodeListOf; + querySelectorAll(selectors: "feflood"): NodeListOf; + querySelectorAll(selectors: "fefunca"): NodeListOf; + querySelectorAll(selectors: "fefuncb"): NodeListOf; + querySelectorAll(selectors: "fefuncg"): NodeListOf; + querySelectorAll(selectors: "fefuncr"): NodeListOf; + querySelectorAll(selectors: "fegaussianblur"): NodeListOf; + querySelectorAll(selectors: "feimage"): NodeListOf; + querySelectorAll(selectors: "femerge"): NodeListOf; + querySelectorAll(selectors: "femergenode"): NodeListOf; + querySelectorAll(selectors: "femorphology"): NodeListOf; + querySelectorAll(selectors: "feoffset"): NodeListOf; + querySelectorAll(selectors: "fepointlight"): NodeListOf; + querySelectorAll(selectors: "fespecularlighting"): NodeListOf; + querySelectorAll(selectors: "fespotlight"): NodeListOf; + querySelectorAll(selectors: "fetile"): NodeListOf; + querySelectorAll(selectors: "feturbulence"): NodeListOf; + querySelectorAll(selectors: "fieldset"): NodeListOf; + querySelectorAll(selectors: "figcaption"): NodeListOf; + querySelectorAll(selectors: "figure"): NodeListOf; + querySelectorAll(selectors: "filter"): NodeListOf; + querySelectorAll(selectors: "font"): NodeListOf; + querySelectorAll(selectors: "footer"): NodeListOf; + querySelectorAll(selectors: "foreignobject"): NodeListOf; + querySelectorAll(selectors: "form"): NodeListOf; + querySelectorAll(selectors: "frame"): NodeListOf; + querySelectorAll(selectors: "frameset"): NodeListOf; + querySelectorAll(selectors: "g"): NodeListOf; + querySelectorAll(selectors: "h1"): NodeListOf; + querySelectorAll(selectors: "h2"): NodeListOf; + querySelectorAll(selectors: "h3"): NodeListOf; + querySelectorAll(selectors: "h4"): NodeListOf; + querySelectorAll(selectors: "h5"): NodeListOf; + querySelectorAll(selectors: "h6"): NodeListOf; + querySelectorAll(selectors: "head"): NodeListOf; + querySelectorAll(selectors: "header"): NodeListOf; + querySelectorAll(selectors: "hgroup"): NodeListOf; + querySelectorAll(selectors: "hr"): NodeListOf; + querySelectorAll(selectors: "html"): NodeListOf; + querySelectorAll(selectors: "i"): NodeListOf; + querySelectorAll(selectors: "iframe"): NodeListOf; + querySelectorAll(selectors: "image"): NodeListOf; + querySelectorAll(selectors: "img"): NodeListOf; + querySelectorAll(selectors: "input"): NodeListOf; + querySelectorAll(selectors: "ins"): NodeListOf; + querySelectorAll(selectors: "isindex"): NodeListOf; + querySelectorAll(selectors: "kbd"): NodeListOf; + querySelectorAll(selectors: "keygen"): NodeListOf; + querySelectorAll(selectors: "label"): NodeListOf; + querySelectorAll(selectors: "legend"): NodeListOf; + querySelectorAll(selectors: "li"): NodeListOf; + querySelectorAll(selectors: "line"): NodeListOf; + querySelectorAll(selectors: "lineargradient"): NodeListOf; + querySelectorAll(selectors: "link"): NodeListOf; + querySelectorAll(selectors: "listing"): NodeListOf; + querySelectorAll(selectors: "map"): NodeListOf; + querySelectorAll(selectors: "mark"): NodeListOf; + querySelectorAll(selectors: "marker"): NodeListOf; + querySelectorAll(selectors: "marquee"): NodeListOf; + querySelectorAll(selectors: "mask"): NodeListOf; + querySelectorAll(selectors: "menu"): NodeListOf; + querySelectorAll(selectors: "meta"): NodeListOf; + querySelectorAll(selectors: "metadata"): NodeListOf; + querySelectorAll(selectors: "meter"): NodeListOf; + querySelectorAll(selectors: "nav"): NodeListOf; + querySelectorAll(selectors: "nextid"): NodeListOf; + querySelectorAll(selectors: "nobr"): NodeListOf; + querySelectorAll(selectors: "noframes"): NodeListOf; + querySelectorAll(selectors: "noscript"): NodeListOf; + querySelectorAll(selectors: "object"): NodeListOf; + querySelectorAll(selectors: "ol"): NodeListOf; + querySelectorAll(selectors: "optgroup"): NodeListOf; + querySelectorAll(selectors: "option"): NodeListOf; + querySelectorAll(selectors: "p"): NodeListOf; + querySelectorAll(selectors: "param"): NodeListOf; + querySelectorAll(selectors: "path"): NodeListOf; + querySelectorAll(selectors: "pattern"): NodeListOf; + querySelectorAll(selectors: "picture"): NodeListOf; + querySelectorAll(selectors: "plaintext"): NodeListOf; + querySelectorAll(selectors: "polygon"): NodeListOf; + querySelectorAll(selectors: "polyline"): NodeListOf; + querySelectorAll(selectors: "pre"): NodeListOf; + querySelectorAll(selectors: "progress"): NodeListOf; + querySelectorAll(selectors: "q"): NodeListOf; + querySelectorAll(selectors: "radialgradient"): NodeListOf; + querySelectorAll(selectors: "rect"): NodeListOf; + querySelectorAll(selectors: "rt"): NodeListOf; + querySelectorAll(selectors: "ruby"): NodeListOf; + querySelectorAll(selectors: "s"): NodeListOf; + querySelectorAll(selectors: "samp"): NodeListOf; + querySelectorAll(selectors: "script"): NodeListOf; + querySelectorAll(selectors: "section"): NodeListOf; + querySelectorAll(selectors: "select"): NodeListOf; + querySelectorAll(selectors: "small"): NodeListOf; + querySelectorAll(selectors: "source"): NodeListOf; + querySelectorAll(selectors: "span"): NodeListOf; + querySelectorAll(selectors: "stop"): NodeListOf; + querySelectorAll(selectors: "strike"): NodeListOf; + querySelectorAll(selectors: "strong"): NodeListOf; + querySelectorAll(selectors: "style"): NodeListOf; + querySelectorAll(selectors: "sub"): NodeListOf; + querySelectorAll(selectors: "sup"): NodeListOf; + querySelectorAll(selectors: "svg"): NodeListOf; + querySelectorAll(selectors: "switch"): NodeListOf; + querySelectorAll(selectors: "symbol"): NodeListOf; + querySelectorAll(selectors: "table"): NodeListOf; + querySelectorAll(selectors: "tbody"): NodeListOf; + querySelectorAll(selectors: "td"): NodeListOf; + querySelectorAll(selectors: "template"): NodeListOf; + querySelectorAll(selectors: "text"): NodeListOf; + querySelectorAll(selectors: "textpath"): NodeListOf; + querySelectorAll(selectors: "textarea"): NodeListOf; + querySelectorAll(selectors: "tfoot"): NodeListOf; + querySelectorAll(selectors: "th"): NodeListOf; + querySelectorAll(selectors: "thead"): NodeListOf; + querySelectorAll(selectors: "title"): NodeListOf; + querySelectorAll(selectors: "tr"): NodeListOf; + querySelectorAll(selectors: "track"): NodeListOf; + querySelectorAll(selectors: "tspan"): NodeListOf; + querySelectorAll(selectors: "tt"): NodeListOf; + querySelectorAll(selectors: "u"): NodeListOf; + querySelectorAll(selectors: "ul"): NodeListOf; + querySelectorAll(selectors: "use"): NodeListOf; + querySelectorAll(selectors: "var"): NodeListOf; + querySelectorAll(selectors: "video"): NodeListOf; + querySelectorAll(selectors: "view"): NodeListOf; + querySelectorAll(selectors: "wbr"): NodeListOf; + querySelectorAll(selectors: "x-ms-webview"): NodeListOf; + querySelectorAll(selectors: "xmp"): NodeListOf; querySelectorAll(selectors: string): NodeListOf; } @@ -19181,18 +19645,21 @@ interface WindowSessionStorage { interface WindowTimers extends Object, WindowTimersExtension { clearInterval(handle: number): void; clearTimeout(handle: number): void; + setInterval(handler: (...args: any[]) => void, timeout: number): number; setInterval(handler: any, timeout?: any, ...args: any[]): number; + setTimeout(handler: (...args: any[]) => void, timeout: number): number; setTimeout(handler: any, timeout?: any, ...args: any[]): number; } interface WindowTimersExtension { clearImmediate(handle: number): void; - setImmediate(expression: any, ...args: any[]): number; + setImmediate(handler: (...args: any[]) => void): number; + setImmediate(handler: any, ...args: any[]): number; } interface XMLHttpRequestEventTarget { onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; onloadstart: (ev: Event) => any; @@ -19216,6 +19683,13 @@ interface StorageEventInit extends EventInit { storageArea?: Storage; } +interface Canvas2DContextAttributes { + alpha?: boolean; + willReadFrequently?: boolean; + storage?: boolean; + [attribute: string]: boolean | string | undefined; +} + interface NodeListOf extends NodeList { length: number; item(index: number): TNode; @@ -19265,6 +19739,177 @@ interface ClipboardEventInit extends EventInit { interface IDBArrayKey extends Array { } +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: AlgorithmIdentifier; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: AlgorithmIdentifier; +} + +interface RsaHashedImportParams { + hash: AlgorithmIdentifier; +} + +interface RsaPssParams { + saltLength: number; +} + +interface RsaOaepParams extends Algorithm { + label?: BufferSource; +} + +interface EcdsaParams extends Algorithm { + hash: AlgorithmIdentifier; +} + +interface EcKeyGenParams extends Algorithm { + typedCurve: string; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + typedCurve: string; +} + +interface EcKeyImportParams { + namedCurve: string; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesCbcParams extends Algorithm { + iv: BufferSource; +} + +interface AesCmacParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + iv: BufferSource; + additionalData?: BufferSource; + tagLength?: number; +} + +interface AesCfbParams extends Algorithm { + iv: BufferSource; +} + +interface HmacImportParams extends Algorithm { + hash?: AlgorithmIdentifier; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: AlgorithmIdentifier; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: AlgorithmIdentifier; + length?: number; +} + +interface DhKeyGenParams extends Algorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface DhKeyAlgorithm extends KeyAlgorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface DhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface DhImportKeyParams extends Algorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface ConcatParams extends Algorithm { + hash?: AlgorithmIdentifier; + algorithmId: Uint8Array; + partyUInfo: Uint8Array; + partyVInfo: Uint8Array; + publicInfo?: Uint8Array; + privateInfo?: Uint8Array; +} + +interface HkdfCtrParams extends Algorithm { + hash: AlgorithmIdentifier; + label: BufferSource; + context: BufferSource; +} + +interface Pbkdf2Params extends Algorithm { + salt: BufferSource; + iterations: number; + hash: AlgorithmIdentifier; +} + +interface RsaOtherPrimesInfo { + r: string; + d: string; + t: string; +} + +interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + kid?: string; + x5u?: string; + x5c?: string; + x5t?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { @@ -19338,7 +19983,7 @@ declare var msCredentials: MSCredentials; declare var name: string; declare var navigator: Navigator; declare var offscreenBuffering: string | boolean; -declare var onabort: (ev: Event) => any; +declare var onabort: (ev: UIEvent) => any; declare var onafterprint: (ev: Event) => any; declare var onbeforeprint: (ev: Event) => any; declare var onbeforeunload: (ev: BeforeUnloadEvent) => any; @@ -19488,10 +20133,13 @@ declare function dispatchEvent(evt: Event): boolean; declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void; declare function clearInterval(handle: number): void; declare function clearTimeout(handle: number): void; +declare function setInterval(handler: (...args: any[]) => void, timeout: number): number; declare function setInterval(handler: any, timeout?: any, ...args: any[]): number; +declare function setTimeout(handler: (...args: any[]) => void, timeout: number): number; declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number; declare function clearImmediate(handle: number): void; -declare function setImmediate(expression: any, ...args: any[]): number; +declare function setImmediate(handler: (...args: any[]) => void): number; +declare function setImmediate(handler: any, ...args: any[]): number; declare var sessionStorage: Storage; declare var localStorage: Storage; declare var console: Console; @@ -19635,6 +20283,8 @@ type RTCIceGatherCandidate = RTCIceCandidate | RTCIceCandidateComplete; type RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport; type payloadtype = number; type IDBValidKey = number | string | Date | IDBArrayKey; +type BufferSource = ArrayBuffer | ArrayBufferView; +type MouseWheelEvent = WheelEvent; ///////////////////////////// /// WorkerGlobalScope APIs ///////////////////////////// diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index cf5ce7e81d8..fcff4b9eacd 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -19,6 +19,10 @@ and limitations under the License. /// IE Worker APIs ///////////////////////////// +interface Algorithm { + name: string; +} + interface EventInit { bubbles?: boolean; cancelable?: boolean; @@ -34,6 +38,10 @@ interface IDBObjectStoreParameters { keyPath?: IDBKeyPath; } +interface KeyAlgorithm { + name?: string; +} + interface EventListener { (evt: Event): void; } @@ -123,6 +131,18 @@ declare var Coordinates: { new(): Coordinates; } +interface CryptoKey { + readonly algorithm: KeyAlgorithm; + readonly extractable: boolean; + readonly type: string; + readonly usages: string[]; +} + +declare var CryptoKey: { + prototype: CryptoKey; + new(): CryptoKey; +} + interface DOMError { readonly name: string; toString(): string; @@ -339,7 +359,7 @@ interface IDBDatabase extends EventTarget { readonly name: string; readonly objectStoreNames: DOMStringList; onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; version: number; onversionchange: (ev: IDBVersionChangeEvent) => any; close(): void; @@ -442,7 +462,7 @@ declare var IDBOpenDBRequest: { interface IDBRequest extends EventTarget { readonly error: DOMError; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onsuccess: (ev: Event) => any; readonly readyState: string; readonly result: any; @@ -464,7 +484,7 @@ interface IDBTransaction extends EventTarget { readonly mode: string; onabort: (ev: Event) => any; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; abort(): void; objectStore(name: string): IDBObjectStore; readonly READ_ONLY: string; @@ -532,7 +552,7 @@ declare var MSApp: MSApp; interface MSAppAsyncOperation extends EventTarget { readonly error: DOMError; oncomplete: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; readonly readyState: number; readonly result: any; start(): void; @@ -681,7 +701,7 @@ interface WebSocket extends EventTarget { readonly bufferedAmount: number; readonly extensions: string; onclose: (ev: CloseEvent) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onmessage: (ev: MessageEvent) => any; onopen: (ev: Event) => any; readonly protocol: string; @@ -724,7 +744,6 @@ declare var Worker: { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - msCaching: string; onreadystatechange: (ev: ProgressEvent) => any; readonly readyState: number; readonly response: any; @@ -736,6 +755,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { timeout: number; readonly upload: XMLHttpRequestUpload; withCredentials: boolean; + msCaching?: string; abort(): void; getAllResponseHeaders(): string; getResponseHeader(header: string): string | null; @@ -782,14 +802,14 @@ declare var XMLHttpRequestUpload: { } interface AbstractWorker { - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } interface MSBaseReader { onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; onloadstart: (ev: Event) => any; @@ -835,7 +855,7 @@ interface WindowConsole { interface XMLHttpRequestEventTarget { onabort: (ev: Event) => any; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; onload: (ev: Event) => any; onloadend: (ev: ProgressEvent) => any; onloadstart: (ev: Event) => any; @@ -865,7 +885,7 @@ declare var FileReaderSync: { interface WorkerGlobalScope extends EventTarget, WorkerUtils, DedicatedWorkerGlobalScope, WindowConsole { readonly location: WorkerLocation; - onerror: (ev: Event) => any; + onerror: (ev: ErrorEvent) => any; readonly self: WorkerGlobalScope; close(): void; msWriteProfilerMark(profilerMarkName: string): void; @@ -921,8 +941,11 @@ interface WorkerUtils extends Object, WindowBase64 { clearInterval(handle: number): void; clearTimeout(handle: number): void; importScripts(...urls: string[]): void; + setImmediate(handler: (...args: any[]) => void): number; setImmediate(handler: any, ...args: any[]): number; + setInterval(handler: (...args: any[]) => void, timeout: number): number; setInterval(handler: any, timeout?: any, ...args: any[]): number; + setTimeout(handler: (...args: any[]) => void, timeout: number): number; setTimeout(handler: any, timeout?: any, ...args: any[]): number; } @@ -958,6 +981,177 @@ interface ProgressEventInit extends EventInit { interface IDBArrayKey extends Array { } +interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: AlgorithmIdentifier; +} + +interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: Uint8Array; +} + +interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: AlgorithmIdentifier; +} + +interface RsaHashedImportParams { + hash: AlgorithmIdentifier; +} + +interface RsaPssParams { + saltLength: number; +} + +interface RsaOaepParams extends Algorithm { + label?: BufferSource; +} + +interface EcdsaParams extends Algorithm { + hash: AlgorithmIdentifier; +} + +interface EcKeyGenParams extends Algorithm { + typedCurve: string; +} + +interface EcKeyAlgorithm extends KeyAlgorithm { + typedCurve: string; +} + +interface EcKeyImportParams { + namedCurve: string; +} + +interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; +} + +interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; +} + +interface AesKeyGenParams extends Algorithm { + length: number; +} + +interface AesDerivedKeyParams extends Algorithm { + length: number; +} + +interface AesCbcParams extends Algorithm { + iv: BufferSource; +} + +interface AesCmacParams extends Algorithm { + length: number; +} + +interface AesGcmParams extends Algorithm { + iv: BufferSource; + additionalData?: BufferSource; + tagLength?: number; +} + +interface AesCfbParams extends Algorithm { + iv: BufferSource; +} + +interface HmacImportParams extends Algorithm { + hash?: AlgorithmIdentifier; + length?: number; +} + +interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: AlgorithmIdentifier; + length: number; +} + +interface HmacKeyGenParams extends Algorithm { + hash: AlgorithmIdentifier; + length?: number; +} + +interface DhKeyGenParams extends Algorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface DhKeyAlgorithm extends KeyAlgorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface DhKeyDeriveParams extends Algorithm { + public: CryptoKey; +} + +interface DhImportKeyParams extends Algorithm { + prime: Uint8Array; + generator: Uint8Array; +} + +interface ConcatParams extends Algorithm { + hash?: AlgorithmIdentifier; + algorithmId: Uint8Array; + partyUInfo: Uint8Array; + partyVInfo: Uint8Array; + publicInfo?: Uint8Array; + privateInfo?: Uint8Array; +} + +interface HkdfCtrParams extends Algorithm { + hash: AlgorithmIdentifier; + label: BufferSource; + context: BufferSource; +} + +interface Pbkdf2Params extends Algorithm { + salt: BufferSource; + iterations: number; + hash: AlgorithmIdentifier; +} + +interface RsaOtherPrimesInfo { + r: string; + d: string; + t: string; +} + +interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + kid?: string; + x5u?: string; + x5c?: string; + x5t?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface ErrorEventHandler { @@ -991,7 +1185,7 @@ interface FunctionStringCallback { (data: string): void; } declare var location: WorkerLocation; -declare var onerror: (ev: Event) => any; +declare var onerror: (ev: ErrorEvent) => any; declare var self: WorkerGlobalScope; declare function close(): void; declare function msWriteProfilerMark(profilerMarkName: string): void; @@ -1006,8 +1200,11 @@ declare function clearImmediate(handle: number): void; declare function clearInterval(handle: number): void; declare function clearTimeout(handle: number): void; declare function importScripts(...urls: string[]): void; +declare function setImmediate(handler: (...args: any[]) => void): number; declare function setImmediate(handler: any, ...args: any[]): number; +declare function setInterval(handler: (...args: any[]) => void, timeout: number): number; declare function setInterval(handler: any, timeout?: any, ...args: any[]): number; +declare function setTimeout(handler: (...args: any[]) => void, timeout: number): number; declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number; declare function atob(encodedString: string): string; declare function btoa(rawString: string): string; @@ -1017,5 +1214,7 @@ declare var console: Console; declare function addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; +type AlgorithmIdentifier = string | Algorithm; type IDBKeyPath = string; -type IDBValidKey = number | string | Date | IDBArrayKey; \ No newline at end of file +type IDBValidKey = number | string | Date | IDBArrayKey; +type BufferSource = ArrayBuffer | ArrayBufferView; \ No newline at end of file diff --git a/lib/tsc.js b/lib/tsc.js index a53870ecffe..1c6d5b8f47a 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -142,6 +142,15 @@ var ts; return -1; } ts.indexOf = indexOf; + function indexOfAnyCharCode(text, charCodes, start) { + for (var i = start || 0, len = text.length; i < len; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; + } + ts.indexOfAnyCharCode = indexOfAnyCharCode; function countWhere(array, predicate) { var count = 0; if (array) { @@ -169,12 +178,24 @@ var ts; return result; } ts.filter = filter; + function filterMutate(array, f) { + var outIndex = 0; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + if (f(item)) { + array[outIndex] = item; + outIndex++; + } + } + array.length = outIndex; + } + ts.filterMutate = filterMutate; function map(array, f) { var result; if (array) { result = []; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; result.push(f(v)); } } @@ -193,8 +214,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var item = array_6[_i]; if (!contains(result, item, areEqual)) { result.push(item); } @@ -205,8 +226,8 @@ var ts; ts.deduplicate = deduplicate; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var v = array_7[_i]; result += v[prop]; } return result; @@ -500,6 +521,30 @@ var ts; return a < b ? -1 : 1; } ts.compareValues = compareValues; + function compareStrings(a, b, ignoreCase) { + if (a === b) + return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + if (ignoreCase) { + if (String.prototype.localeCompare) { + var result = a.localeCompare(b, undefined, { usage: "sort", sensitivity: "accent" }); + return result < 0 ? -1 : result > 0 ? 1 : 0; + } + a = a.toUpperCase(); + b = b.toUpperCase(); + if (a === b) + return 0; + } + return a < b ? -1 : 1; + } + ts.compareStrings = compareStrings; + function compareStringsCaseInsensitive(a, b) { + return compareStrings(a, b, true); + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; function getDiagnosticFileName(diagnostic) { return diagnostic.file ? diagnostic.file.fileName : undefined; } @@ -722,12 +767,220 @@ var ts; return path1 + ts.directorySeparator + path2; } ts.combinePaths = combinePaths; + function removeTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) === ts.directorySeparator) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) !== ts.directorySeparator) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (a === b) + return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + a = removeTrailingDirectorySeparator(a); + b = removeTrailingDirectorySeparator(b); + var aComponents = getNormalizedPathComponents(a, currentDirectory); + var bComponents = getNormalizedPathComponents(b, currentDirectory); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 0; i < sharedLength; i++) { + var result = compareStrings(aComponents[i], bComponents[i], ignoreCase); + if (result !== 0) { + return result; + } + } + return compareValues(aComponents.length, bComponents.length); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + parent = removeTrailingDirectorySeparator(parent); + child = removeTrailingDirectorySeparator(child); + if (parent === child) + return true; + var parentComponents = getNormalizedPathComponents(parent, currentDirectory); + var childComponents = getNormalizedPathComponents(child, currentDirectory); + if (childComponents.length < parentComponents.length) { + return false; + } + for (var i = 0; i < parentComponents.length; i++) { + var result = compareStrings(parentComponents[i], childComponents[i], ignoreCase); + if (result !== 0) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; function fileExtensionIs(path, extension) { var pathLen = path.length; var extLen = extension.length; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsAny(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsAny = fileExtensionIsAny; + var reservedCharacterPattern = /[^\w\s\/]/g; + var wildcardCharCodes = [42, 63]; + function getRegularExpressionForWildcard(specs, basePath, usage) { + if (specs === undefined || specs.length === 0) { + return undefined; + } + var pattern = ""; + var hasWrittenSubpattern = false; + spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { + var spec = specs_1[_i]; + if (!spec) { + continue; + } + var subpattern = ""; + var hasRecursiveDirectoryWildcard = false; + var hasWrittenComponent = false; + var components = getNormalizedPathComponents(spec, basePath); + if (usage !== "exclude" && components[components.length - 1] === "**") { + continue spec; + } + components[0] = removeTrailingDirectorySeparator(components[0]); + var optionalCount = 0; + for (var _a = 0, components_1 = components; _a < components_1.length; _a++) { + var component = components_1[_a]; + if (component === "**") { + if (hasRecursiveDirectoryWildcard) { + continue spec; + } + subpattern += "(/.+?)?"; + hasRecursiveDirectoryWildcard = true; + hasWrittenComponent = true; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + hasWrittenComponent = true; + } + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + if (hasWrittenSubpattern) { + pattern += "|"; + } + pattern += "(" + subpattern + ")"; + hasWrittenSubpattern = true; + } + if (!pattern) { + return undefined; + } + return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); + } + ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function replaceWildcardCharacter(match) { + return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; + } + function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + }; + } + ts.getFileMatcherPatterns = getFileMatcherPatterns; + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, getFileSystemEntries) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var patterns = getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + var regexFlag = useCaseSensitiveFileNames ? "" : "i"; + var includeFileRegex = patterns.includeFilePattern && new RegExp(patterns.includeFilePattern, regexFlag); + var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); + var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); + var result = []; + for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { + var basePath = _a[_i]; + visitDirectory(basePath, combinePaths(currentDirectory, basePath)); + } + return result; + function visitDirectory(path, absolutePath) { + var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var current = files_1[_i]; + var name_1 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!extensions || fileExtensionIsAny(name_1, extensions)) && + (!includeFileRegex || includeFileRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + result.push(name_1); + } + } + for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { + var current = directories_1[_b]; + var name_2 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name_2, absoluteName); + } + } + } + } + ts.matchFiles = matchFiles; + function getBasePaths(path, includes, useCaseSensitiveFileNames) { + var basePaths = [path]; + if (includes) { + var includeBasePaths = []; + for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { + var include = includes_1[_i]; + if (isRootedDiskPath(include)) { + var wildcardOffset = indexOfAnyCharCode(include, wildcardCharCodes); + var includeBasePath = wildcardOffset < 0 + ? removeTrailingDirectorySeparator(getDirectoryPath(include)) + : include.substring(0, include.lastIndexOf(ts.directorySeparator, wildcardOffset)); + includeBasePaths.push(includeBasePath); + } + } + includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); + include: for (var i = 0; i < includeBasePaths.length; i++) { + var includeBasePath = includeBasePaths[i]; + for (var j = 0; j < basePaths.length; j++) { + if (containsPath(basePaths[j], includeBasePath, path, !useCaseSensitiveFileNames)) { + continue include; + } + } + basePaths.push(includeBasePath); + } + } + return basePaths; + } function ensureScriptKind(fileName, scriptKind) { return (scriptKind || getScriptKindFromFileName(fileName)) || 3; } @@ -768,6 +1021,36 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + function getExtensionPriority(path, supportedExtensions) { + for (var i = supportedExtensions.length - 1; i >= 0; i--) { + if (fileExtensionIs(path, supportedExtensions[i])) { + return adjustExtensionPriority(i); + } + } + return 0; + } + ts.getExtensionPriority = getExtensionPriority; + function adjustExtensionPriority(extensionPriority) { + if (extensionPriority < 2) { + return 0; + } + else if (extensionPriority < 5) { + return 2; + } + else { + return 5; + } + } + ts.adjustExtensionPriority = adjustExtensionPriority; + function getNextLowestExtensionPriority(extensionPriority) { + if (extensionPriority < 2) { + return 2; + } + else { + return 5; + } + } + ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { @@ -788,6 +1071,10 @@ var ts; return ext === ".jsx" || ext === ".tsx"; } ts.isJsxOrTsxExtension = isJsxOrTsxExtension; + function changeExtension(path, newExtension) { + return (removeFileExtension(path) + newExtension); + } + ts.changeExtension = changeExtension; function Symbol(flags, name) { this.flags = flags; this.name = name; @@ -858,6 +1145,7 @@ var ts; ts.sys = (function () { function getWScriptSystem() { var fso = new ActiveXObject("Scripting.FileSystemObject"); + var shell = new ActiveXObject("WScript.Shell"); var fileStream = new ActiveXObject("ADODB.Stream"); fileStream.Type = 2; var binaryStream = new ActiveXObject("ADODB.Stream"); @@ -912,9 +1200,6 @@ var ts; fileStream.Close(); } } - function getCanonicalPath(path) { - return path.toLowerCase(); - } function getNames(collection) { var result = []; for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { @@ -926,30 +1211,19 @@ var ts; var folder = fso.GetFolder(path); return getNames(folder.subfolders); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { + function getAccessibleFileSystemEntries(path) { + try { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var current = files_1[_i]; - var name_1 = ts.combinePaths(path, current); - if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { - result.push(name_1); - } - } - var subfolders = getNames(folder.subfolders); - for (var _a = 0, subfolders_1 = subfolders; _a < subfolders_1.length; _a++) { - var current = subfolders_1[_a]; - var name_2 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_2))) { - visitDirectory(name_2); - } - } + var directories = getNames(folder.subfolders); + return { files: files, directories: directories }; } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } return { args: args, @@ -978,7 +1252,7 @@ var ts; return WScript.ScriptFullName; }, getCurrentDirectory: function () { - return new ActiveXObject("WScript.Shell").CurrentDirectory; + return shell.CurrentDirectory; }, getDirectories: getDirectories, readDirectory: readDirectory, @@ -1107,8 +1381,39 @@ var ts; } } } - function getCanonicalPath(path) { - return useCaseSensitiveFileNames ? path : path.toLowerCase(); + function getAccessibleFileSystemEntries(path) { + try { + var entries = _fs.readdirSync(path || ".").sort(); + var files = []; + var directories = []; + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var entry = entries_1[_i]; + if (entry === "." || entry === "..") { + continue; + } + var name_3 = ts.combinePaths(path, entry); + var stat = void 0; + try { + stat = _fs.statSync(name_3); + } + catch (e) { + continue; + } + if (stat.isFile()) { + files.push(entry); + } + else if (stat.isDirectory()) { + directories.push(entry); + } + } + return { files: files, directories: directories }; + } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); } function fileSystemEntryExists(path, entryKind) { try { @@ -1131,38 +1436,6 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); }); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { - var files = _fs.readdirSync(path || ".").sort(); - var directories = []; - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var current = files_2[_i]; - if (current === "." || current === "..") { - continue; - } - var name_3 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_3))) { - var stat = _fs.statSync(name_3); - if (stat.isFile()) { - if (!extension || ts.fileExtensionIs(name_3, extension)) { - result.push(name_3); - } - } - else if (stat.isDirectory()) { - directories.push(name_3); - } - } - } - for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { - var current = directories_1[_a]; - visitDirectory(current); - } - } - } return { args: process.argv.slice(2), newLine: _os.EOL, @@ -1244,6 +1517,16 @@ var ts; } return process.memoryUsage().heapUsed; }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch (e) { } + return 0; + }, exit: function (exitCode) { process.exit(exitCode); }, @@ -1275,7 +1558,10 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, - readDirectory: ChakraHost.readDirectory, + readDirectory: function (path, extensions, excludes, includes) { + var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); + }, exit: ChakraHost.quit, realpath: realpath }; @@ -1440,7 +1726,7 @@ var ts; Modifiers_cannot_appear_here: { code: 1184, category: ts.DiagnosticCategory.Error, key: "Modifiers_cannot_appear_here_1184", message: "Modifiers cannot appear here." }, Merge_conflict_marker_encountered: { code: 1185, category: ts.DiagnosticCategory.Error, key: "Merge_conflict_marker_encountered_1185", message: "Merge conflict marker encountered." }, A_rest_element_cannot_have_an_initializer: { code: 1186, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_have_an_initializer_1186", message: "A rest element cannot have an initializer." }, - A_parameter_property_may_not_be_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_a_binding_pattern_1187", message: "A parameter property may not be a binding pattern." }, + A_parameter_property_may_not_be_declared_using_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", message: "A parameter property may not be declared using a binding pattern." }, Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: { code: 1188, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", message: "Only a single variable declaration is allowed in a 'for...of' statement." }, The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: { code: 1189, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", message: "The variable declaration of a 'for...in' statement cannot have an initializer." }, The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: { code: 1190, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", message: "The variable declaration of a 'for...of' statement cannot have an initializer." }, @@ -1456,7 +1742,6 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, - Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower: { code: 1204, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower_1204", message: "Cannot compile modules into 'es2015' when targeting 'ES5' or lower." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -1511,6 +1796,7 @@ var ts; Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, Global_module_exports_may_only_appear_in_declaration_files: { code: 1315, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_declaration_files_1315", message: "Global module exports may only appear in declaration files." }, Global_module_exports_may_only_appear_at_top_level: { code: 1316, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_at_top_level_1316", message: "Global module exports may only appear at top level." }, + A_parameter_property_cannot_be_declared_using_a_rest_parameter: { code: 1317, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", message: "A parameter property cannot be declared using a rest parameter." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, @@ -1781,6 +2067,8 @@ var ts; The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, + Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, + Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -1854,6 +2142,8 @@ var ts; Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, + File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { code: 5011, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", message: "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'." }, Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot_read_file_0_Colon_1_5012", message: "Cannot read file '{0}': {1}" }, Unsupported_file_encoding: { code: 5013, category: ts.DiagnosticCategory.Error, key: "Unsupported_file_encoding_5013", message: "Unsupported file encoding." }, Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed_to_parse_file_0_Colon_1_5014", message: "Failed to parse file '{0}': {1}." }, @@ -2027,7 +2317,6 @@ var ts; types_can_only_be_used_in_a_ts_file: { code: 8010, category: ts.DiagnosticCategory.Error, key: "types_can_only_be_used_in_a_ts_file_8010", message: "'types' can only be used in a .ts file." }, type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: ts.DiagnosticCategory.Error, key: "type_arguments_can_only_be_used_in_a_ts_file_8011", message: "'type arguments' can only be used in a .ts file." }, parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: ts.DiagnosticCategory.Error, key: "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", message: "'parameter modifiers' can only be used in a .ts file." }, - property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "property_declarations_can_only_be_used_in_a_ts_file_8014", message: "'property declarations' can only be used in a .ts file." }, enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "enum_declarations_can_only_be_used_in_a_ts_file_8015", message: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, @@ -3807,6 +4096,10 @@ var ts; (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isShorthandAmbientModule(node) { + return node.kind === 225 && (!node.body); + } + ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 || node.kind === 225 || @@ -4194,6 +4487,7 @@ var ts; case 157: return true; } + return false; } ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { @@ -4571,6 +4865,14 @@ var ts; return charCode === 39 || charCode === 34; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isDeclarationOfFunctionExpression(s) { + if (s.valueDeclaration && s.valueDeclaration.kind === 218) { + var declaration = s.valueDeclaration; + return declaration.initializer && declaration.initializer.kind === 179; + } + return false; + } + ts.isDeclarationOfFunctionExpression = isDeclarationOfFunctionExpression; function getSpecialPropertyAssignmentKind(expression) { if (!isInJavaScriptFile(expression)) { return 0; @@ -5462,7 +5764,9 @@ var ts; ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); + var commonSourceDirectory = host.getCommonSourceDirectory(); + var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; return ts.combinePaths(newDirPath, sourceFilePath); } ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; @@ -5776,6 +6080,10 @@ var ts; return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -6159,7 +6467,6 @@ var ts; return visitNodes(cbNodes, node.properties); case 172: return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); case 173: return visitNode(cbNode, node.expression) || @@ -6910,6 +7217,7 @@ var ts; return token === 19 || token === 15 || token === 37 + || token === 22 || isLiteralPropertyName(); } function nextTokenIsClassOrFunction() { @@ -8417,7 +8725,7 @@ var ts; } var node = createNode(172, expression.pos); node.expression = expression; - node.dotToken = parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); return finishNode(node); } @@ -8605,7 +8913,6 @@ var ts; if (dotToken) { var propertyAccess = createNode(172, expression.pos); propertyAccess.expression = expression; - propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); continue; @@ -9793,7 +10100,12 @@ var ts; else { node.name = parseLiteralNode(true); } - node.body = parseModuleBlock(); + if (token === 15) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { @@ -10729,8 +11041,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var node = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -10802,8 +11114,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -10983,7 +11295,8 @@ var ts; return state_1; } else if (node.kind === 225) { - return getModuleInstanceState(node.body); + var body = node.body; + return body ? getModuleInstanceState(body) : 1; } else { return 1; @@ -11352,11 +11665,6 @@ var ts; break; } } - function isNarrowableReference(expr) { - return expr.kind === 69 || - expr.kind === 97 || - expr.kind === 172 && isNarrowableReference(expr.expression); - } function isNarrowingExpression(expr) { switch (expr.kind) { case 69: @@ -11364,7 +11672,7 @@ var ts; case 172: return isNarrowableReference(expr); case 174: - return true; + return hasNarrowableArgument(expr); case 178: return isNarrowingExpression(expr.expression); case 187: @@ -11374,6 +11682,35 @@ var ts; } return false; } + function isNarrowableReference(expr) { + return expr.kind === 69 || + expr.kind === 97 || + expr.kind === 172 && isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 172 && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingNullCheckOperands(expr1, expr2) { + return (expr1.kind === 93 || expr1.kind === 69 && expr1.text === "undefined") && isNarrowableOperand(expr2); + } + function isNarrowingTypeofOperands(expr1, expr2) { + return expr1.kind === 182 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + } + function isNarrowingDiscriminant(expr) { + return expr.kind === 172 && isNarrowableReference(expr.expression); + } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56: @@ -11382,20 +11719,34 @@ var ts; case 31: case 32: case 33: - if (isNarrowingExpression(expr.left) && (expr.right.kind === 93 || expr.right.kind === 69)) { - return true; - } - if (expr.left.kind === 182 && isNarrowingExpression(expr.left.expression) && expr.right.kind === 9) { - return true; - } - return false; + return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || + isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); case 91: - return isNarrowingExpression(expr.left); + return isNarrowableOperand(expr.left); case 24: return isNarrowingExpression(expr.right); } return false; } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 178: + return isNarrowableOperand(expr.expression); + case 187: + switch (expr.operatorToken.kind) { + case 56: + return isNarrowableOperand(expr.left); + case 24: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function isNarrowingSwitchStatement(switchStatement) { + var expr = switchStatement.expression; + return expr.kind === 172 && isNarrowableReference(expr.expression); + } function createBranchLabel() { return { flags: 4, @@ -11409,7 +11760,7 @@ var ts; }; } function setFlowNodeReferenced(flow) { - flow.flags |= flow.flags & 128 ? 256 : 128; + flow.flags |= flow.flags & 256 ? 512 : 256; } function addAntecedent(label, antecedent) { if (!(antecedent.flags & 1) && !ts.contains(label.antecedents, antecedent)) { @@ -11434,8 +11785,21 @@ var ts; setFlowNodeReferenced(antecedent); return { flags: flags, - antecedent: antecedent, - expression: expression + expression: expression, + antecedent: antecedent + }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingSwitchStatement(switchStatement)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: 128, + switchStatement: switchStatement, + clauseStart: clauseStart, + clauseEnd: clauseEnd, + antecedent: antecedent }; } function createFlowAssignment(antecedent, node) { @@ -11645,9 +12009,10 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasNonEmptyDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250 && c.statements.length; }); - if (!hasNonEmptyDefault) { - addAntecedent(postSwitchLabel, preSwitchCaseFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250; }); + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); } currentBreakTarget = saveBreakTarget; preSwitchCaseFlow = savePreSwitchCaseFlow; @@ -11655,25 +12020,22 @@ var ts; } function bindCaseBlock(node) { var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { - var clause = clauses[i]; - if (clause.statements.length) { - if (currentFlow.flags & 1) { - currentFlow = preSwitchCaseFlow; - } - else { - var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, preSwitchCaseFlow); - addAntecedent(preCaseLabel, currentFlow); - currentFlow = finishFlowLabel(preCaseLabel); - } - bind(clause); - if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; } - else { - bind(clause); + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); } } } @@ -11938,7 +12300,7 @@ var ts; } function hasExportDeclarations(node) { var body = node.kind === 256 ? node : node.body; - if (body.kind === 256 || body.kind === 226) { + if (body && (body.kind === 256 || body.kind === 226)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; if (stat.kind === 236 || stat.kind === 235) { @@ -12458,7 +12820,7 @@ var ts; constructorFunction.parent = classPrototype; classPrototype.parent = leftSideOfAssignment; var funcSymbol = container.locals[constructorFunction.text]; - if (!funcSymbol || !(funcSymbol.flags & 16)) { + if (!funcSymbol || !(funcSymbol.flags & 16 || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return; } if (!funcSymbol.members) { @@ -13043,7 +13405,8 @@ var ts; var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { - if (modulekind || (!compilerOptions.outFile && !compilerOptions.out)) { + if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out)) { return true; } var sourceFiles = host.getSourceFiles(); @@ -13240,7 +13603,8 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg)) { + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -13296,6 +13660,29 @@ var ts; } return false; } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var parentClassExpression = errorLocation; + while (parentClassExpression) { + var kind = parentClassExpression.kind; + if (kind === 69 || kind === 172) { + parentClassExpression = parentClassExpression.parent; + continue; + } + if (kind === 194) { + break; + } + return false; + } + if (!parentClassExpression) { + return false; + } + var expression = parentClassExpression.expression; + if (resolveEntityName(expression, 64, true)) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; + } + return false; + } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); @@ -13338,9 +13725,11 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = moduleSymbol.exports["export="] ? - getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : - resolveSymbol(moduleSymbol.exports["default"]); + var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? + moduleSymbol : + moduleSymbol.exports["export="] ? + getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : + resolveSymbol(moduleSymbol.exports["default"]); if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } @@ -13391,6 +13780,9 @@ var ts; if (targetSymbol) { var name_10 = specifier.propertyName || specifier.name; if (name_10.text) { + if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { + return moduleSymbol; + } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_10.text); @@ -14739,6 +15131,9 @@ var ts; function isTypeAny(type) { return type && (type.flags & 1) !== 0; } + function isTypeNever(type) { + return type && (type.flags & 134217728) !== 0; + } function getTypeForBindingElementParent(node) { var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); @@ -14990,18 +15385,21 @@ var ts; if (declaration.kind === 235) { return links.type = checkExpression(declaration.expression); } - if (declaration.kind === 187) { - return links.type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); - } - if (declaration.kind === 172) { - if (declaration.parent.kind === 187) { - return links.type = checkExpressionCached(declaration.parent.right); - } - } if (!pushTypeResolution(symbol, 0)) { return unknownType; } - var type = getWidenedTypeForVariableLikeDeclaration(declaration, true); + var type = undefined; + if (declaration.kind === 187) { + type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); + } + else if (declaration.kind === 172) { + if (declaration.parent.kind === 187) { + type = checkExpressionCached(declaration.parent.right); + } + } + if (type === undefined) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, true); + } if (!popTypeResolution()) { if (symbol.valueDeclaration.type) { type = unknownType; @@ -15089,9 +15487,14 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var type = createObjectType(65536, symbol); - links.type = strictNullChecks && symbol.flags & 536870912 ? - addTypeKind(type, 32) : type; + if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { + links.type = anyType; + } + else { + var type = createObjectType(65536, symbol); + links.type = strictNullChecks && symbol.flags & 536870912 ? + addTypeKind(type, 32) : type; + } } return links.type; } @@ -16042,7 +16445,7 @@ var ts; } return result; } - function isOptionalParameter(node) { + function isJSDocOptionalParameter(node) { if (node.flags & 134217728) { if (node.type && node.type.kind === 268) { return true; @@ -16057,7 +16460,9 @@ var ts; } } } - if (ts.hasQuestionToken(node)) { + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { return true; } if (node.initializer) { @@ -16112,7 +16517,7 @@ var ts; if (param.type && param.type.kind === 166) { hasStringLiterals = true; } - if (param.initializer || param.questionToken || param.dotDotDotToken) { + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { minArgumentCount = i - (hasThisParameter ? 1 : 0); } @@ -17109,6 +17514,9 @@ var ts; function isTypeComparableTo(source, target) { return checkTypeComparableTo(source, target, undefined); } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); } @@ -18047,8 +18455,10 @@ var ts; function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isStringLiteralType(type) { - return type.flags & 256; + function isStringLiteralUnionType(type) { + return type.flags & 256 ? true : + type.flags & 16384 ? ts.forEach(type.types, isStringLiteralUnionType) : + false; } function isTupleType(type) { return !!(type.flags & 8192); @@ -18778,6 +19188,29 @@ var ts; } return node; } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 249) { + var expr = clause.expression; + return expr.kind === 9 ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); + } + return undefined; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); + links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256; }) ? types : emptyArray; + } + return links.switchTypes; + } + function eachTypeContainedIn(source, types) { + return source.flags & 16384 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function filterType(type, f) { + return type.flags & 16384 ? + getUnionType(ts.filter(type.types, f)) : + f(type) ? type : neverType; + } function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { var key; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175)) { @@ -18793,7 +19226,7 @@ var ts; return result; function getTypeAtFlowNode(flow) { while (true) { - if (flow.flags & 256) { + if (flow.flags & 512) { for (var i = visitedFlowStart; i < visitedFlowCount; i++) { if (visitedFlowNodes[i] === flow) { return visitedFlowTypes[i]; @@ -18811,6 +19244,9 @@ var ts; else if (flow.flags & 96) { type = getTypeAtFlowCondition(flow); } + else if (flow.flags & 128) { + type = getTypeAtSwitchClause(flow); + } else if (flow.flags & 12) { if (flow.antecedents.length === 1) { flow = flow.antecedents[0]; @@ -18831,7 +19267,7 @@ var ts; else { type = declaredType; } - if (flow.flags & 256) { + if (flow.flags & 512) { visitedFlowNodes[visitedFlowCount] = flow; visitedFlowTypes[visitedFlowCount] = type; visitedFlowCount++; @@ -18869,6 +19305,10 @@ var ts; } return type; } + function getTypeAtSwitchClause(flow) { + var type = getTypeAtFlowNode(flow.antecedent); + return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { @@ -18929,11 +19369,26 @@ var ts; case 31: case 32: case 33: - if (isNullOrUndefinedLiteral(expr.right)) { - return narrowTypeByNullCheck(type, expr, assumeTrue); + var left = expr.left; + var operator = expr.operatorToken.kind; + var right = expr.right; + if (isNullOrUndefinedLiteral(right)) { + return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); } - if (expr.left.kind === 182 && expr.right.kind === 9) { - return narrowTypeByTypeof(type, expr, assumeTrue); + if (isNullOrUndefinedLiteral(left)) { + return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); + } + if (left.kind === 182 && right.kind === 9) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); + } + if (right.kind === 182 && left.kind === 9) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); + } + if (left.kind === 172) { + return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); + } + if (right.kind === 172) { + return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); } break; case 91: @@ -18943,46 +19398,91 @@ var ts; } return type; } - function narrowTypeByNullCheck(type, expr, assumeTrue) { - var operator = expr.operatorToken.kind; + function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } - if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(expr.left))) { + if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { return type; } var doubleEquals = operator === 30 || operator === 31; var facts = doubleEquals ? assumeTrue ? 65536 : 524288 : - expr.right.kind === 93 ? + literal.kind === 93 ? assumeTrue ? 32768 : 262144 : assumeTrue ? 16384 : 131072; return getTypeWithFacts(type, facts); } - function narrowTypeByTypeof(type, expr, assumeTrue) { - var left = getReferenceFromExpression(expr.left.expression); - var right = expr.right; - if (!isMatchingReference(reference, left)) { - if (containsMatchingReference(reference, left)) { + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + var target = getReferenceFromExpression(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { + if (containsMatchingReference(reference, target)) { return declaredType; } return type; } - if (expr.operatorToken.kind === 31 || - expr.operatorToken.kind === 33) { + if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } if (assumeTrue && !(type.flags & 16384)) { - var targetType = ts.getProperty(typeofTypesByName, right.text); + var targetType = ts.getProperty(typeofTypesByName, literal.text); if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - ts.getProperty(typeofEQFacts, right.text) || 64 : - ts.getProperty(typeofNEFacts, right.text) || 8192; + ts.getProperty(typeofEQFacts, literal.text) || 64 : + ts.getProperty(typeofNEFacts, literal.text) || 8192; return getTypeWithFacts(type, facts); } + function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { + if (!isMatchingReference(reference, propAccess.expression)) { + return type; + } + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var discriminantType = value.kind === 9 ? getStringLiteralTypeForText(value.text) : checkExpression(value); + if (!isStringLiteralUnionType(discriminantType)) { + return type; + } + if (operator === 31 || operator === 33) { + assumeTrue = !assumeTrue; + } + if (assumeTrue) { + return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); + } + if (discriminantType.flags & 256) { + return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); + } + return type; + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + if (!isMatchingReference(reference, switchStatement.expression.expression)) { + return type; + } + var propName = switchStatement.expression.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); + var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; + var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; + var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); + return caseType ? getUnionType([caseType, defaultType]) : defaultType; + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceFromExpression(expr.left); if (!isMatchingReference(reference, left)) { @@ -19681,9 +20181,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } - function contextualTypeIsStringLiteralType(type) { - return !!(type.flags & 16384 ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type)); - } function contextualTypeIsTupleLikeType(type) { return !!(type.flags & 16384 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } @@ -20450,7 +20947,7 @@ var ts; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { - if (right.text) { + if (right.text && !checkAndReportErrorForExtendingInterface(node)) { error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 ? apparentType : type)); } return unknownType; @@ -21370,8 +21867,10 @@ var ts; declaration.kind !== 152 && declaration.kind !== 157 && !ts.isJSDocConstructSignature(declaration)) { - var funcSymbol = checkExpression(node.expression).symbol; - if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16)) { + var funcSymbol = node.expression.kind === 69 ? + getResolvedSymbol(node.expression) : + checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return getInferredClassType(funcSymbol); } else if (compilerOptions.noImplicitAny) { @@ -21390,6 +21889,7 @@ var ts; } function checkAssertion(node) { var exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + checkSourceElement(node.type); var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { var widenedType = getWidenedType(exprType); @@ -21473,6 +21973,14 @@ var ts; } return emptyObjectType; } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return unknownType; + } + return promiseType; + } function getReturnTypeFromBody(func, contextualMapper) { var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { @@ -21502,18 +22010,10 @@ var ts; else { types = checkAndAggregateReturnExpressionTypes(func, contextualMapper); if (!types) { - return neverType; + return isAsync ? createPromiseReturnType(func, neverType) : neverType; } if (types.length === 0) { - if (isAsync) { - var promiseType = createPromiseType(voidType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - return voidType; + return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); @@ -21524,7 +22024,7 @@ var ts; } else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return getUnionType(types); + return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); } } if (funcIsGenerator) { @@ -21535,17 +22035,7 @@ var ts; reportErrorsFromWidening(func, type); } var widenedType = getWidenedType(type); - if (isAsync) { - var promiseType = createPromiseType(widenedType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - else { - return widenedType; - } + return isAsync ? createPromiseReturnType(func, widenedType) : widenedType; } function checkAndAggregateYieldOperandTypes(func, contextualMapper) { var aggregatedTypes = []; @@ -21563,10 +22053,40 @@ var ts; }); return aggregatedTypes; } + function isExhaustiveSwitchStatement(node) { + var expr = node.expression; + if (!node.possiblyExhaustive || expr.kind !== 172) { + return false; + } + var type = checkExpression(expr.expression); + if (!(type.flags & 16384)) { + return false; + } + var propName = expr.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length) { + return false; + } + return eachTypeContainedIn(propType, switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 32768)) { + return false; + } + var lastStatement = ts.lastOrUndefined(func.body.statements); + if (lastStatement && lastStatement.kind === 213 && isExhaustiveSwitchStatement(lastStatement)) { + return false; + } + return true; + } function checkAndAggregateReturnExpressionTypes(func, contextualMapper) { var isAsync = ts.isAsyncFunctionLike(func); var aggregatedTypes = []; - var hasReturnWithNoExpression = !!(func.flags & 32768); + var hasReturnWithNoExpression = functionHasImplicitReturn(func); var hasReturnOfTypeNever = false; ts.forEachReturnStatement(func.body, function (returnStatement) { var expr = returnStatement.expression; @@ -21604,7 +22124,7 @@ var ts; if (returnType && maybeTypeOfKind(returnType, 1 | 16)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !(func.flags & 32768)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 65536; @@ -22115,7 +22635,7 @@ var ts; case 90: return checkInExpression(left, right, leftType, rightType); case 51: - return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 126) : rightType; + return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112) : rightType; case 52: return getUnionType([getNonNullableType(leftType), rightType]); case 56: @@ -22215,7 +22735,7 @@ var ts; } function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); - if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { + if (contextualType && isStringLiteralUnionType(contextualType)) { return getStringLiteralTypeForText(node.text); } return stringType; @@ -22964,7 +23484,6 @@ var ts; } } } - var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & 1536; var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { @@ -22989,7 +23508,7 @@ var ts; duplicateFunctionDeclaration = true; } } - else if (!isExportSymbolInsideModule && previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { reportImplementationExpectedError(previousDeclaration); } if (ts.nodeIsPresent(node.body)) { @@ -23016,7 +23535,7 @@ var ts; error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); }); } - if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && !(lastSeenNonAmbientDeclaration.flags & 128) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } @@ -23107,7 +23626,7 @@ var ts; } function checkNonThenableType(type, location, message) { type = getWidenedType(type); - if (!isTypeAny(type) && isTypeAssignableTo(type, getGlobalThenableType())) { + if (!isTypeAny(type) && !isTypeNever(type) && isTypeAssignableTo(type, getGlobalThenableType())) { if (location) { if (!message) { message = ts.Diagnostics.Operand_for_await_does_not_have_a_valid_callable_then_member; @@ -23119,37 +23638,39 @@ var ts; return type; } function getPromisedType(promise) { - if (promise.flags & 1) { + if (isTypeAny(promise)) { return undefined; } - if ((promise.flags & 4096) && promise.target === tryGetGlobalPromiseType()) { - return promise.typeArguments[0]; + if (promise.flags & 4096) { + if (promise.target === tryGetGlobalPromiseType() + || promise.target === getGlobalPromiseLikeType()) { + return promise.typeArguments[0]; + } } var globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType(); if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) { return undefined; } var thenFunction = getTypeOfPropertyOfType(promise, "then"); - if (thenFunction && (thenFunction.flags & 1)) { + if (!thenFunction || isTypeAny(thenFunction)) { return undefined; } - var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0) : emptyArray; + var thenSignatures = getSignaturesOfType(thenFunction, 0); if (thenSignatures.length === 0) { return undefined; } var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072); - if (onfulfilledParameterType.flags & 1) { + if (isTypeAny(onfulfilledParameterType)) { return undefined; } var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0); if (onfulfilledParameterSignatures.length === 0) { return undefined; } - var valueParameterType = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); - return valueParameterType; + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); } function getTypeOfFirstParameterOfSignature(signature) { - return getTypeAtPosition(signature, 0); + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; } function getAwaitedType(type) { return checkAwaitedType(type, undefined, undefined); @@ -24691,7 +25212,7 @@ var ts; if (isAmbientExternalModule) { if (ts.isExternalModuleAugmentation(node)) { var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432); - if (checkBody) { + if (checkBody && node.body) { for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { var statement = _a[_i]; checkModuleAugmentationElement(statement, isGlobalAugmentation); @@ -24716,7 +25237,12 @@ var ts; } } } - checkSourceElement(node.body); + if (compilerOptions.noImplicitAny && !node.body) { + reportImplicitAnyError(node, anyType); + } + if (node.body) { + checkSourceElement(node.body); + } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { @@ -26276,7 +26802,10 @@ var ts; return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } else if (node.kind === 142 && (flags & 92) && ts.isBindingPattern(node.name)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 142 && (flags & 92) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256) { return checkGrammarAsyncModifier(node, lastAsync); @@ -27930,21 +28459,26 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body.kind !== 226) { + while (node.body && node.body.kind !== 226) { node = node.body; write("."); writeTextOfNode(currentText, node.name); } var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; + if (node.body) { + enclosingDeclaration = node; + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.body.statements); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + else { + write(";"); + } } function writeTypeAliasDeclaration(node) { var prevEnclosingDeclaration = enclosingDeclaration; @@ -30245,7 +30779,6 @@ var ts; function createPropertyAccessExpression(expression, name) { var result = ts.createSynthesizedNode(172); result.expression = parenthesizeForAccess(expression); - result.dotToken = ts.createSynthesizedNode(21); result.name = name; return result; } @@ -30291,9 +30824,9 @@ var ts; emitTrailingCommentsOfPosition(node.initializer.pos); emit(node.initializer); } - function isNamespaceExportReference(node) { + function isExportReference(node) { var container = resolver.getReferencedExportContainer(node); - return container && container.kind !== 256; + return !!container; } function isImportedReference(node) { var declaration = resolver.getReferencedImportDeclaration(node); @@ -30301,9 +30834,9 @@ var ts; } function emitShorthandPropertyAssignment(node) { writeTextOfNode(currentText, node.name); - if (languageVersion < 2 || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isNamespaceExportReference(node.name)) { + if (languageVersion < 2 || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isExportReference(node.name)) { write(": "); - emit(node.name); + emitExpressionIdentifier(node.name); } if (languageVersion >= 2 && node.objectAssignmentInitializer) { write(" = "); @@ -30358,7 +30891,10 @@ var ts; return; } emit(node.expression); - var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); + var dotRangeStart = ts.nodeIsSynthesized(node.expression) ? -1 : node.expression.end; + var dotRangeEnd = ts.nodeIsSynthesized(node.expression) ? -1 : ts.skipTrivia(currentText, node.expression.end) + 1; + var dotToken = { pos: dotRangeStart, end: dotRangeEnd }; + var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, dotToken); var shouldEmitSpace = false; if (!indentedBeforeDot) { if (node.expression.kind === 8) { @@ -30376,7 +30912,7 @@ var ts; else { write("."); } - var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); + var indentedAfterDot = indentIfOnDifferentLines(node, dotToken, node.name); emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); } @@ -30749,7 +31285,6 @@ var ts; synthesizedLHS = ts.createSynthesizedNode(172, false); var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); synthesizedLHS.expression = identifier; - synthesizedLHS.dotToken = leftHandSideExpression.dotToken; synthesizedLHS.name = leftHandSideExpression.name; write(", "); } @@ -32821,7 +33356,11 @@ var ts; } } function emitClassLikeDeclarationBelowES6(node) { + var isES6ExportedClass = isES6ExportedDeclaration(node); if (node.kind === 221) { + if (isES6ExportedClass && !(node.flags & 512)) { + write("export "); + } if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); } @@ -32885,9 +33424,15 @@ var ts; write(";"); } emitEnd(node); - if (node.kind === 221) { + if (node.kind === 221 && !isES6ExportedClass) { emitExportMemberAssignment(node); } + else if (isES6ExportedClass && (node.flags & 512)) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); @@ -33183,10 +33728,10 @@ var ts; } if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 160) { + if (parameterType && parameterType.kind === 160) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 155 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType && parameterType.kind === 155 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { @@ -33203,9 +33748,15 @@ var ts; } } function emitSerializedReturnTypeOfNode(node) { - if (node && ts.isFunctionLike(node) && node.type) { - emitSerializedTypeNode(node.type); - return; + if (node && ts.isFunctionLike(node)) { + if (node.type) { + emitSerializedTypeNode(node.type); + return; + } + else if (ts.isAsyncFunctionLike(node)) { + write("Promise"); + return; + } } write("void 0"); } @@ -33338,7 +33889,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 225) { + if (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -33379,6 +33930,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); + ts.Debug.assert(node.body !== undefined); if (node.body.kind === 226) { var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; @@ -34946,13 +35498,9 @@ var ts; ts.emitTime = 0; ts.ioReadTime = 0; ts.ioWriteTime = 0; - var emptyArray = []; - var defaultLibrarySearchPaths = [ - "types/", - "node_modules/", - "node_modules/@types/", - ]; ts.version = "1.9.0"; + var emptyArray = []; + var defaultTypeRoots = ["node_modules/@types"]; function findConfigFile(searchPath, fileExists) { while (true) { var fileName = ts.combinePaths(searchPath, "tsconfig.json"); @@ -35080,6 +35628,10 @@ var ts; return undefined; } var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + return options.typeRoots || + ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(), d); }); + } function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); var moduleResolutionState = { @@ -35088,35 +35640,34 @@ var ts; skipTsx: true, traceEnabled: traceEnabled }; - var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : (host.getCurrentDirectory && host.getCurrentDirectory())); + var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); } } else { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } } var failedLookupLocations = []; - if (rootDir !== undefined) { - var effectivePrimarySearchPaths = options.typesSearchPaths || defaultLibrarySearchPaths; - for (var _i = 0, effectivePrimarySearchPaths_1 = effectivePrimarySearchPaths; _i < effectivePrimarySearchPaths_1.length; _i++) { - var searchPath = effectivePrimarySearchPaths_1[_i]; - var primaryPath = ts.combinePaths(rootDir, searchPath); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, primaryPath); - } - var candidate = ts.combinePaths(primaryPath, typeReferenceDirectiveName); + if (typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); if (resolvedFile_1) { @@ -35140,9 +35691,6 @@ var ts; if (containingFile) { initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); } - else { - initialLocationForSecondaryLookup = rootDir; - } if (initialLocationForSecondaryLookup !== undefined) { if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); @@ -35635,25 +36183,12 @@ var ts; } } } - function getDefaultTypeDirectiveNames(rootPath) { - var localTypes = ts.combinePaths(rootPath, "types"); - var npmTypes = ts.combinePaths(rootPath, "node_modules/@types"); - var result = []; - if (ts.sys.directoryExists(localTypes)) { - result = result.concat(ts.sys.getDirectories(localTypes)); - } - if (ts.sys.directoryExists(npmTypes)) { - result = result.concat(ts.sys.getDirectories(npmTypes)); - } - return result; - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); } var newLine = ts.getNewLineCharacter(options); var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); return { - getDefaultTypeDirectiveNames: getDefaultTypeDirectiveNames, getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -35666,6 +36201,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, + getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; } @@ -35721,19 +36257,26 @@ var ts; } return resolutions; } - function getDefaultTypeDirectiveNames(options, rootFiles, host) { + function getInferredTypesRoot(options, rootFiles, host) { + return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + function getAutomaticTypeDirectiveNames(options, rootFiles, host) { if (options.types) { return options.types; } - if (host && host.getDefaultTypeDirectiveNames) { - var commonRoot = computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); - if (commonRoot) { - return host.getDefaultTypeDirectiveNames(commonRoot); + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + result = result.concat(host.getDirectories(root)); + } } } - return undefined; + return result; } - ts.getDefaultTypeDirectiveNames = getDefaultTypeDirectiveNames; + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -35770,9 +36313,11 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - var typeReferences = getDefaultTypeDirectiveNames(options, rootNames, host); + var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); if (typeReferences) { - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, undefined); + var inferredRoot = getInferredTypesRoot(options, rootNames, host); + var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); } @@ -35835,8 +36380,8 @@ var ts; if (!classifiableNames) { getTypeChecker(); classifiableNames = {}; - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var sourceFile = files_3[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } @@ -35855,10 +36400,9 @@ var ts; (oldOptions.jsx !== options.jsx) || (oldOptions.allowJs !== options.allowJs) || (oldOptions.rootDir !== options.rootDir) || - (oldOptions.typesSearchPaths !== options.typesSearchPaths) || (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || - (oldOptions.typesRoot !== options.typesRoot) || + !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { return false; @@ -36150,8 +36694,20 @@ var ts; } break; case 145: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); - return true; + var propertyDeclaration = node; + if (propertyDeclaration.modifiers) { + for (var _i = 0, _a = propertyDeclaration.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 113) { + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + } + } + } + if (checkTypeAnnotation(node.type)) { + return true; + } + break; case 224: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return true; @@ -36283,9 +36839,12 @@ var ts; (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - collectModuleReferences(statement, true); + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, true); + } } } } @@ -36432,7 +36991,7 @@ var ts; } } else { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_name_0, typeReferenceDirective)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); } if (saveResolution) { resolvedTypeReferenceDirectives[typeReferenceDirective] = resolvedTypeReferenceDirective; @@ -36597,9 +37156,6 @@ var ts; var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } - if (options.module === ts.ModuleKind.ES6 && languageVersion < 2) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); - } if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); @@ -36985,8 +37541,13 @@ var ts; } }, { - name: "typesRoot", - type: "string" + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + } }, { name: "types", @@ -37052,6 +37613,10 @@ var ts; }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, + { + name: "disableProjectSizeLimit", + type: "boolean" + }, { name: "strictNullChecks", type: "boolean", @@ -37117,7 +37682,15 @@ var ts; } ts.parseCustomTypeOption = parseCustomTypeOption; function parseListTypeOption(opt, value, errors) { - var values = trimString((value || "")).split(","); + if (value === void 0) { value = ""; } + value = trimString(value); + if (ts.startsWith(value, "-")) { + return undefined; + } + if (value === "") { + return []; + } + var values = value.split(","); switch (opt.element.type) { case "number": return ts.map(values, parseInt); @@ -37174,8 +37747,11 @@ var ts; i++; break; case "list": - options[opt.name] = parseListTypeOption(opt, args[i], errors); - i++; + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } break; default: options[opt.name] = parseCustomTypeOption(opt, args[i], errors); @@ -37267,7 +37843,7 @@ var ts; } return output; } - var IgnoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; + var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { if (existingOptions === void 0) { existingOptions = {}; } var errors = []; @@ -37275,66 +37851,57 @@ var ts; var options = ts.extend(existingOptions, compilerOptions); var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); options.configFilePath = configFileName; - var fileNames = getFileNames(errors); + var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, - errors: errors + errors: errors, + wildcardDirectories: wildcardDirectories }; function getFileNames(errors) { - var fileNames = []; + var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { - fileNames = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); + fileNames = json["files"]; } else { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); } } - else { - var filesSeen = {}; - var exclude = []; - if (ts.isArray(json["exclude"])) { - exclude = json["exclude"]; + var includeSpecs; + if (ts.hasProperty(json, "include")) { + if (ts.isArray(json["include"])) { + includeSpecs = json["include"]; } else { - exclude = ["node_modules", "bower_components", "jspm_packages"]; - } - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; - if (outDir) { - exclude.push(outDir); - } - exclude = ts.map(exclude, function (e) { return ts.getNormalizedAbsolutePath(e, basePath); }); - var supportedExtensions = ts.getSupportedExtensions(options); - ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); - for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { - var extension = supportedExtensions_1[_i]; - var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); - for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { - var fileName = filesInDirWithExtension_1[_a]; - if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { - continue; - } - if (IgnoreFileNamePattern.test(fileName)) { - continue; - } - if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { - var baseName = fileName.substr(0, fileName.length - extension.length); - if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { - continue; - } - } - filesSeen[fileName] = true; - fileNames.push(fileName); - } + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array")); } } - if (ts.hasProperty(json, "excludes") && !ts.hasProperty(json, "exclude")) { + var excludeSpecs; + if (ts.hasProperty(json, "exclude")) { + if (ts.isArray(json["exclude"])) { + excludeSpecs = json["exclude"]; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); + } + } + else if (ts.hasProperty(json, "excludes")) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } - return fileNames; + else { + excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; + } + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + excludeSpecs.push(outDir); + } + if (fileNames === undefined && includeSpecs === undefined) { + includeSpecs = ["**/*"]; + } + return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; @@ -37416,6 +37983,139 @@ var ts; function trimString(s) { return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); } + var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + var invalidMultipleRecursionPatterns = /(^|\/)\*\*\/(.*\/)?\*\*($|\/)/; + var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + basePath = ts.normalizePath(basePath); + var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; + var literalFileMap = {}; + var wildcardFileMap = {}; + if (include) { + include = validateSpecs(include, errors, false); + } + if (exclude) { + exclude = validateSpecs(exclude, errors, true); + } + var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); + var supportedExtensions = ts.getSupportedExtensions(options); + if (fileNames) { + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; + var file = ts.combinePaths(basePath, fileName); + literalFileMap[keyMapper(file)] = file; + } + } + if (include && include.length > 0) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include); _a < _b.length; _a++) { + var file = _b[_a]; + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + continue; + } + if (ignoreFileNamePattern.test(file)) { + continue; + } + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file); + if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { + wildcardFileMap[key] = file; + } + } + } + var literalFiles = ts.reduceProperties(literalFileMap, addFileToOutput, []); + var wildcardFiles = ts.reduceProperties(wildcardFileMap, addFileToOutput, []); + wildcardFiles.sort(host.useCaseSensitiveFileNames ? ts.compareStrings : ts.compareStringsCaseInsensitive); + return { + fileNames: literalFiles.concat(wildcardFiles), + wildcardDirectories: wildcardDirectories + }; + } + function validateSpecs(specs, errors, allowTrailingRecursion) { + var validSpecs = []; + for (var _i = 0, specs_2 = specs; _i < specs_2.length; _i++) { + var spec = specs_2[_i]; + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + } + else if (invalidMultipleRecursionPatterns.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); + } + else { + validSpecs.push(spec); + } + } + return validSpecs; + } + function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); + var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + var wildcardDirectories = {}; + if (include !== undefined) { + var recursiveKeys = []; + for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { + var file = include_1[_i]; + var name_35 = ts.combinePaths(path, file); + if (excludeRegex && excludeRegex.test(name_35)) { + continue; + } + var match = wildcardDirectoryPattern.exec(name_35); + if (match) { + var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); + var flags = watchRecursivePattern.test(name_35) ? 1 : 0; + var existingFlags = ts.getProperty(wildcardDirectories, key); + if (existingFlags === undefined || existingFlags < flags) { + wildcardDirectories[key] = flags; + if (flags === 1) { + recursiveKeys.push(key); + } + } + } + } + for (var key in wildcardDirectories) { + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } + } + } + } + } + return wildcardDirectories; + } + function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); + for (var i = 0; i < adjustedExtensionPriority; i++) { + var higherPriorityExtension = extensions[i]; + var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); + if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { + return true; + } + } + return false; + } + function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority); + for (var i = nextExtensionPriority; i < extensions.length; i++) { + var lowerPriorityExtension = extensions[i]; + var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); + delete wildcardFiles[lowerPriorityPath]; + } + } + function addFileToOutput(output, file) { + output.push(file); + return output; + } + function caseSensitiveKeyMapper(key) { + return key; + } + function caseInsensitiveKeyMapper(key) { + return key.toLowerCase(); + } })(ts || (ts = {})); var ts; (function (ts) { @@ -37431,8 +38131,8 @@ var ts; return; } var currentDir = ts.sys.getCurrentDirectory(); - for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { - var file = files_4[_i]; + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var file = files_3[_i]; var filepath = ts.getNormalizedAbsolutePath(file, currentDir); ts.sys.write("TSFILE: " + filepath + ts.sys.newLine); } @@ -38019,10 +38719,10 @@ var ts; function serializeCompilerOptions(options) { var result = {}; var optionsNameMap = ts.getOptionNameMap().optionNameMap; - for (var name_35 in options) { - if (ts.hasProperty(options, name_35)) { - var value = options[name_35]; - switch (name_35) { + for (var name_36 in options) { + if (ts.hasProperty(options, name_36)) { + var value = options[name_36]; + switch (name_36) { case "init": case "watch": case "version": @@ -38030,17 +38730,17 @@ var ts; case "project": break; default: - var optionDefinition = optionsNameMap[name_35.toLowerCase()]; + var optionDefinition = optionsNameMap[name_36.toLowerCase()]; if (optionDefinition) { if (typeof optionDefinition.type === "string") { - result[name_35] = value; + result[name_36] = value; } else { var typeMap = optionDefinition.type; for (var key in typeMap) { if (ts.hasProperty(typeMap, key)) { if (typeMap[key] === value) - result[name_35] = key; + result[name_36] = key; } } } diff --git a/lib/tsserver.js b/lib/tsserver.js index 6565ba47042..bd80f9f800e 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -147,6 +147,15 @@ var ts; return -1; } ts.indexOf = indexOf; + function indexOfAnyCharCode(text, charCodes, start) { + for (var i = start || 0, len = text.length; i < len; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; + } + ts.indexOfAnyCharCode = indexOfAnyCharCode; function countWhere(array, predicate) { var count = 0; if (array) { @@ -174,12 +183,24 @@ var ts; return result; } ts.filter = filter; + function filterMutate(array, f) { + var outIndex = 0; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + if (f(item)) { + array[outIndex] = item; + outIndex++; + } + } + array.length = outIndex; + } + ts.filterMutate = filterMutate; function map(array, f) { var result; if (array) { result = []; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; result.push(f(v)); } } @@ -198,8 +219,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var item = array_6[_i]; if (!contains(result, item, areEqual)) { result.push(item); } @@ -210,8 +231,8 @@ var ts; ts.deduplicate = deduplicate; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var v = array_7[_i]; result += v[prop]; } return result; @@ -505,6 +526,30 @@ var ts; return a < b ? -1 : 1; } ts.compareValues = compareValues; + function compareStrings(a, b, ignoreCase) { + if (a === b) + return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + if (ignoreCase) { + if (String.prototype.localeCompare) { + var result = a.localeCompare(b, undefined, { usage: "sort", sensitivity: "accent" }); + return result < 0 ? -1 : result > 0 ? 1 : 0; + } + a = a.toUpperCase(); + b = b.toUpperCase(); + if (a === b) + return 0; + } + return a < b ? -1 : 1; + } + ts.compareStrings = compareStrings; + function compareStringsCaseInsensitive(a, b) { + return compareStrings(a, b, true); + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; function getDiagnosticFileName(diagnostic) { return diagnostic.file ? diagnostic.file.fileName : undefined; } @@ -727,12 +772,220 @@ var ts; return path1 + ts.directorySeparator + path2; } ts.combinePaths = combinePaths; + function removeTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) === ts.directorySeparator) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) !== ts.directorySeparator) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (a === b) + return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + a = removeTrailingDirectorySeparator(a); + b = removeTrailingDirectorySeparator(b); + var aComponents = getNormalizedPathComponents(a, currentDirectory); + var bComponents = getNormalizedPathComponents(b, currentDirectory); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 0; i < sharedLength; i++) { + var result = compareStrings(aComponents[i], bComponents[i], ignoreCase); + if (result !== 0) { + return result; + } + } + return compareValues(aComponents.length, bComponents.length); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + parent = removeTrailingDirectorySeparator(parent); + child = removeTrailingDirectorySeparator(child); + if (parent === child) + return true; + var parentComponents = getNormalizedPathComponents(parent, currentDirectory); + var childComponents = getNormalizedPathComponents(child, currentDirectory); + if (childComponents.length < parentComponents.length) { + return false; + } + for (var i = 0; i < parentComponents.length; i++) { + var result = compareStrings(parentComponents[i], childComponents[i], ignoreCase); + if (result !== 0) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; function fileExtensionIs(path, extension) { var pathLen = path.length; var extLen = extension.length; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsAny(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsAny = fileExtensionIsAny; + var reservedCharacterPattern = /[^\w\s\/]/g; + var wildcardCharCodes = [42, 63]; + function getRegularExpressionForWildcard(specs, basePath, usage) { + if (specs === undefined || specs.length === 0) { + return undefined; + } + var pattern = ""; + var hasWrittenSubpattern = false; + spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { + var spec = specs_1[_i]; + if (!spec) { + continue; + } + var subpattern = ""; + var hasRecursiveDirectoryWildcard = false; + var hasWrittenComponent = false; + var components = getNormalizedPathComponents(spec, basePath); + if (usage !== "exclude" && components[components.length - 1] === "**") { + continue spec; + } + components[0] = removeTrailingDirectorySeparator(components[0]); + var optionalCount = 0; + for (var _a = 0, components_1 = components; _a < components_1.length; _a++) { + var component = components_1[_a]; + if (component === "**") { + if (hasRecursiveDirectoryWildcard) { + continue spec; + } + subpattern += "(/.+?)?"; + hasRecursiveDirectoryWildcard = true; + hasWrittenComponent = true; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + hasWrittenComponent = true; + } + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + if (hasWrittenSubpattern) { + pattern += "|"; + } + pattern += "(" + subpattern + ")"; + hasWrittenSubpattern = true; + } + if (!pattern) { + return undefined; + } + return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); + } + ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function replaceWildcardCharacter(match) { + return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; + } + function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + }; + } + ts.getFileMatcherPatterns = getFileMatcherPatterns; + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, getFileSystemEntries) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var patterns = getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + var regexFlag = useCaseSensitiveFileNames ? "" : "i"; + var includeFileRegex = patterns.includeFilePattern && new RegExp(patterns.includeFilePattern, regexFlag); + var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); + var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); + var result = []; + for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { + var basePath = _a[_i]; + visitDirectory(basePath, combinePaths(currentDirectory, basePath)); + } + return result; + function visitDirectory(path, absolutePath) { + var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var current = files_1[_i]; + var name_1 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!extensions || fileExtensionIsAny(name_1, extensions)) && + (!includeFileRegex || includeFileRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + result.push(name_1); + } + } + for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { + var current = directories_1[_b]; + var name_2 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name_2, absoluteName); + } + } + } + } + ts.matchFiles = matchFiles; + function getBasePaths(path, includes, useCaseSensitiveFileNames) { + var basePaths = [path]; + if (includes) { + var includeBasePaths = []; + for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { + var include = includes_1[_i]; + if (isRootedDiskPath(include)) { + var wildcardOffset = indexOfAnyCharCode(include, wildcardCharCodes); + var includeBasePath = wildcardOffset < 0 + ? removeTrailingDirectorySeparator(getDirectoryPath(include)) + : include.substring(0, include.lastIndexOf(ts.directorySeparator, wildcardOffset)); + includeBasePaths.push(includeBasePath); + } + } + includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); + include: for (var i = 0; i < includeBasePaths.length; i++) { + var includeBasePath = includeBasePaths[i]; + for (var j = 0; j < basePaths.length; j++) { + if (containsPath(basePaths[j], includeBasePath, path, !useCaseSensitiveFileNames)) { + continue include; + } + } + basePaths.push(includeBasePath); + } + } + return basePaths; + } function ensureScriptKind(fileName, scriptKind) { return (scriptKind || getScriptKindFromFileName(fileName)) || 3; } @@ -773,6 +1026,36 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + function getExtensionPriority(path, supportedExtensions) { + for (var i = supportedExtensions.length - 1; i >= 0; i--) { + if (fileExtensionIs(path, supportedExtensions[i])) { + return adjustExtensionPriority(i); + } + } + return 0; + } + ts.getExtensionPriority = getExtensionPriority; + function adjustExtensionPriority(extensionPriority) { + if (extensionPriority < 2) { + return 0; + } + else if (extensionPriority < 5) { + return 2; + } + else { + return 5; + } + } + ts.adjustExtensionPriority = adjustExtensionPriority; + function getNextLowestExtensionPriority(extensionPriority) { + if (extensionPriority < 2) { + return 2; + } + else { + return 5; + } + } + ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { @@ -793,6 +1076,10 @@ var ts; return ext === ".jsx" || ext === ".tsx"; } ts.isJsxOrTsxExtension = isJsxOrTsxExtension; + function changeExtension(path, newExtension) { + return (removeFileExtension(path) + newExtension); + } + ts.changeExtension = changeExtension; function Symbol(flags, name) { this.flags = flags; this.name = name; @@ -863,6 +1150,7 @@ var ts; ts.sys = (function () { function getWScriptSystem() { var fso = new ActiveXObject("Scripting.FileSystemObject"); + var shell = new ActiveXObject("WScript.Shell"); var fileStream = new ActiveXObject("ADODB.Stream"); fileStream.Type = 2; var binaryStream = new ActiveXObject("ADODB.Stream"); @@ -917,9 +1205,6 @@ var ts; fileStream.Close(); } } - function getCanonicalPath(path) { - return path.toLowerCase(); - } function getNames(collection) { var result = []; for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { @@ -931,30 +1216,19 @@ var ts; var folder = fso.GetFolder(path); return getNames(folder.subfolders); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { + function getAccessibleFileSystemEntries(path) { + try { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var current = files_1[_i]; - var name_1 = ts.combinePaths(path, current); - if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { - result.push(name_1); - } - } - var subfolders = getNames(folder.subfolders); - for (var _a = 0, subfolders_1 = subfolders; _a < subfolders_1.length; _a++) { - var current = subfolders_1[_a]; - var name_2 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_2))) { - visitDirectory(name_2); - } - } + var directories = getNames(folder.subfolders); + return { files: files, directories: directories }; } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } return { args: args, @@ -983,7 +1257,7 @@ var ts; return WScript.ScriptFullName; }, getCurrentDirectory: function () { - return new ActiveXObject("WScript.Shell").CurrentDirectory; + return shell.CurrentDirectory; }, getDirectories: getDirectories, readDirectory: readDirectory, @@ -1112,8 +1386,39 @@ var ts; } } } - function getCanonicalPath(path) { - return useCaseSensitiveFileNames ? path : path.toLowerCase(); + function getAccessibleFileSystemEntries(path) { + try { + var entries = _fs.readdirSync(path || ".").sort(); + var files = []; + var directories = []; + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var entry = entries_1[_i]; + if (entry === "." || entry === "..") { + continue; + } + var name_3 = ts.combinePaths(path, entry); + var stat = void 0; + try { + stat = _fs.statSync(name_3); + } + catch (e) { + continue; + } + if (stat.isFile()) { + files.push(entry); + } + else if (stat.isDirectory()) { + directories.push(entry); + } + } + return { files: files, directories: directories }; + } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); } function fileSystemEntryExists(path, entryKind) { try { @@ -1136,38 +1441,6 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); }); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { - var files = _fs.readdirSync(path || ".").sort(); - var directories = []; - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var current = files_2[_i]; - if (current === "." || current === "..") { - continue; - } - var name_3 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_3))) { - var stat = _fs.statSync(name_3); - if (stat.isFile()) { - if (!extension || ts.fileExtensionIs(name_3, extension)) { - result.push(name_3); - } - } - else if (stat.isDirectory()) { - directories.push(name_3); - } - } - } - for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { - var current = directories_1[_a]; - visitDirectory(current); - } - } - } return { args: process.argv.slice(2), newLine: _os.EOL, @@ -1249,6 +1522,16 @@ var ts; } return process.memoryUsage().heapUsed; }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch (e) { } + return 0; + }, exit: function (exitCode) { process.exit(exitCode); }, @@ -1280,7 +1563,10 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, - readDirectory: ChakraHost.readDirectory, + readDirectory: function (path, extensions, excludes, includes) { + var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); + }, exit: ChakraHost.quit, realpath: realpath }; @@ -1445,7 +1731,7 @@ var ts; Modifiers_cannot_appear_here: { code: 1184, category: ts.DiagnosticCategory.Error, key: "Modifiers_cannot_appear_here_1184", message: "Modifiers cannot appear here." }, Merge_conflict_marker_encountered: { code: 1185, category: ts.DiagnosticCategory.Error, key: "Merge_conflict_marker_encountered_1185", message: "Merge conflict marker encountered." }, A_rest_element_cannot_have_an_initializer: { code: 1186, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_have_an_initializer_1186", message: "A rest element cannot have an initializer." }, - A_parameter_property_may_not_be_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_a_binding_pattern_1187", message: "A parameter property may not be a binding pattern." }, + A_parameter_property_may_not_be_declared_using_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", message: "A parameter property may not be declared using a binding pattern." }, Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: { code: 1188, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", message: "Only a single variable declaration is allowed in a 'for...of' statement." }, The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: { code: 1189, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", message: "The variable declaration of a 'for...in' statement cannot have an initializer." }, The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: { code: 1190, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", message: "The variable declaration of a 'for...of' statement cannot have an initializer." }, @@ -1461,7 +1747,6 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, - Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower: { code: 1204, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower_1204", message: "Cannot compile modules into 'es2015' when targeting 'ES5' or lower." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -1516,6 +1801,7 @@ var ts; Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, Global_module_exports_may_only_appear_in_declaration_files: { code: 1315, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_declaration_files_1315", message: "Global module exports may only appear in declaration files." }, Global_module_exports_may_only_appear_at_top_level: { code: 1316, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_at_top_level_1316", message: "Global module exports may only appear at top level." }, + A_parameter_property_cannot_be_declared_using_a_rest_parameter: { code: 1317, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", message: "A parameter property cannot be declared using a rest parameter." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, @@ -1786,6 +2072,8 @@ var ts; The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, + Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, + Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -1859,6 +2147,8 @@ var ts; Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, + File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { code: 5011, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", message: "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'." }, Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot_read_file_0_Colon_1_5012", message: "Cannot read file '{0}': {1}" }, Unsupported_file_encoding: { code: 5013, category: ts.DiagnosticCategory.Error, key: "Unsupported_file_encoding_5013", message: "Unsupported file encoding." }, Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed_to_parse_file_0_Colon_1_5014", message: "Failed to parse file '{0}': {1}." }, @@ -2032,7 +2322,6 @@ var ts; types_can_only_be_used_in_a_ts_file: { code: 8010, category: ts.DiagnosticCategory.Error, key: "types_can_only_be_used_in_a_ts_file_8010", message: "'types' can only be used in a .ts file." }, type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: ts.DiagnosticCategory.Error, key: "type_arguments_can_only_be_used_in_a_ts_file_8011", message: "'type arguments' can only be used in a .ts file." }, parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: ts.DiagnosticCategory.Error, key: "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", message: "'parameter modifiers' can only be used in a .ts file." }, - property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "property_declarations_can_only_be_used_in_a_ts_file_8014", message: "'property declarations' can only be used in a .ts file." }, enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "enum_declarations_can_only_be_used_in_a_ts_file_8015", message: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, @@ -3861,8 +4150,13 @@ var ts; } }, { - name: "typesRoot", - type: "string" + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + } }, { name: "types", @@ -3928,6 +4222,10 @@ var ts; }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, + { + name: "disableProjectSizeLimit", + type: "boolean" + }, { name: "strictNullChecks", type: "boolean", @@ -3993,7 +4291,15 @@ var ts; } ts.parseCustomTypeOption = parseCustomTypeOption; function parseListTypeOption(opt, value, errors) { - var values = trimString((value || "")).split(","); + if (value === void 0) { value = ""; } + value = trimString(value); + if (ts.startsWith(value, "-")) { + return undefined; + } + if (value === "") { + return []; + } + var values = value.split(","); switch (opt.element.type) { case "number": return ts.map(values, parseInt); @@ -4050,8 +4356,11 @@ var ts; i++; break; case "list": - options[opt.name] = parseListTypeOption(opt, args[i], errors); - i++; + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } break; default: options[opt.name] = parseCustomTypeOption(opt, args[i], errors); @@ -4143,7 +4452,7 @@ var ts; } return output; } - var IgnoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; + var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { if (existingOptions === void 0) { existingOptions = {}; } var errors = []; @@ -4151,66 +4460,57 @@ var ts; var options = ts.extend(existingOptions, compilerOptions); var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); options.configFilePath = configFileName; - var fileNames = getFileNames(errors); + var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, - errors: errors + errors: errors, + wildcardDirectories: wildcardDirectories }; function getFileNames(errors) { - var fileNames = []; + var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { - fileNames = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); + fileNames = json["files"]; } else { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); } } - else { - var filesSeen = {}; - var exclude = []; - if (ts.isArray(json["exclude"])) { - exclude = json["exclude"]; + var includeSpecs; + if (ts.hasProperty(json, "include")) { + if (ts.isArray(json["include"])) { + includeSpecs = json["include"]; } else { - exclude = ["node_modules", "bower_components", "jspm_packages"]; - } - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; - if (outDir) { - exclude.push(outDir); - } - exclude = ts.map(exclude, function (e) { return ts.getNormalizedAbsolutePath(e, basePath); }); - var supportedExtensions = ts.getSupportedExtensions(options); - ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); - for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { - var extension = supportedExtensions_1[_i]; - var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); - for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { - var fileName = filesInDirWithExtension_1[_a]; - if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { - continue; - } - if (IgnoreFileNamePattern.test(fileName)) { - continue; - } - if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { - var baseName = fileName.substr(0, fileName.length - extension.length); - if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { - continue; - } - } - filesSeen[fileName] = true; - fileNames.push(fileName); - } + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array")); } } - if (ts.hasProperty(json, "excludes") && !ts.hasProperty(json, "exclude")) { + var excludeSpecs; + if (ts.hasProperty(json, "exclude")) { + if (ts.isArray(json["exclude"])) { + excludeSpecs = json["exclude"]; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); + } + } + else if (ts.hasProperty(json, "excludes")) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } - return fileNames; + else { + excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; + } + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + excludeSpecs.push(outDir); + } + if (fileNames === undefined && includeSpecs === undefined) { + includeSpecs = ["**/*"]; + } + return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; @@ -4292,6 +4592,139 @@ var ts; function trimString(s) { return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); } + var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + var invalidMultipleRecursionPatterns = /(^|\/)\*\*\/(.*\/)?\*\*($|\/)/; + var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + basePath = ts.normalizePath(basePath); + var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; + var literalFileMap = {}; + var wildcardFileMap = {}; + if (include) { + include = validateSpecs(include, errors, false); + } + if (exclude) { + exclude = validateSpecs(exclude, errors, true); + } + var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); + var supportedExtensions = ts.getSupportedExtensions(options); + if (fileNames) { + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; + var file = ts.combinePaths(basePath, fileName); + literalFileMap[keyMapper(file)] = file; + } + } + if (include && include.length > 0) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include); _a < _b.length; _a++) { + var file = _b[_a]; + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + continue; + } + if (ignoreFileNamePattern.test(file)) { + continue; + } + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file); + if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { + wildcardFileMap[key] = file; + } + } + } + var literalFiles = ts.reduceProperties(literalFileMap, addFileToOutput, []); + var wildcardFiles = ts.reduceProperties(wildcardFileMap, addFileToOutput, []); + wildcardFiles.sort(host.useCaseSensitiveFileNames ? ts.compareStrings : ts.compareStringsCaseInsensitive); + return { + fileNames: literalFiles.concat(wildcardFiles), + wildcardDirectories: wildcardDirectories + }; + } + function validateSpecs(specs, errors, allowTrailingRecursion) { + var validSpecs = []; + for (var _i = 0, specs_2 = specs; _i < specs_2.length; _i++) { + var spec = specs_2[_i]; + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + } + else if (invalidMultipleRecursionPatterns.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); + } + else { + validSpecs.push(spec); + } + } + return validSpecs; + } + function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); + var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + var wildcardDirectories = {}; + if (include !== undefined) { + var recursiveKeys = []; + for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { + var file = include_1[_i]; + var name_5 = ts.combinePaths(path, file); + if (excludeRegex && excludeRegex.test(name_5)) { + continue; + } + var match = wildcardDirectoryPattern.exec(name_5); + if (match) { + var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); + var flags = watchRecursivePattern.test(name_5) ? 1 : 0; + var existingFlags = ts.getProperty(wildcardDirectories, key); + if (existingFlags === undefined || existingFlags < flags) { + wildcardDirectories[key] = flags; + if (flags === 1) { + recursiveKeys.push(key); + } + } + } + } + for (var key in wildcardDirectories) { + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } + } + } + } + } + return wildcardDirectories; + } + function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); + for (var i = 0; i < adjustedExtensionPriority; i++) { + var higherPriorityExtension = extensions[i]; + var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); + if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { + return true; + } + } + return false; + } + function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority); + for (var i = nextExtensionPriority; i < extensions.length; i++) { + var lowerPriorityExtension = extensions[i]; + var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); + delete wildcardFiles[lowerPriorityPath]; + } + } + function addFileToOutput(output, file) { + output.push(file); + return output; + } + function caseSensitiveKeyMapper(key) { + return key; + } + function caseInsensitiveKeyMapper(key) { + return key.toLowerCase(); + } })(ts || (ts = {})); var ts; (function (ts) { @@ -4572,6 +5005,10 @@ var ts; (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isShorthandAmbientModule(node) { + return node.kind === 225 && (!node.body); + } + ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 || node.kind === 225 || @@ -4900,9 +5337,9 @@ var ts; return; default: if (isFunctionLike(node)) { - var name_5 = node.name; - if (name_5 && name_5.kind === 140) { - traverse(name_5.expression); + var name_6 = node.name; + if (name_6 && name_6.kind === 140) { + traverse(name_6.expression); return; } } @@ -4959,6 +5396,7 @@ var ts; case 157: return true; } + return false; } ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { @@ -5336,6 +5774,14 @@ var ts; return charCode === 39 || charCode === 34; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isDeclarationOfFunctionExpression(s) { + if (s.valueDeclaration && s.valueDeclaration.kind === 218) { + var declaration = s.valueDeclaration; + return declaration.initializer && declaration.initializer.kind === 179; + } + return false; + } + ts.isDeclarationOfFunctionExpression = isDeclarationOfFunctionExpression; function getSpecialPropertyAssignmentKind(expression) { if (!isInJavaScriptFile(expression)) { return 0; @@ -5483,8 +5929,8 @@ var ts; var tag = _b[_a]; if (tag.kind === 275) { var parameterTag = tag; - var name_6 = parameterTag.preParameterName || parameterTag.postParameterName; - if (name_6.text === parameterName) { + var name_7 = parameterTag.preParameterName || parameterTag.postParameterName; + if (name_7.text === parameterName) { return parameterTag; } } @@ -6227,7 +6673,9 @@ var ts; ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); + var commonSourceDirectory = host.getCommonSourceDirectory(); + var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; return ts.combinePaths(newDirPath, sourceFilePath); } ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; @@ -6541,6 +6989,10 @@ var ts; return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -6924,7 +7376,6 @@ var ts; return visitNodes(cbNodes, node.properties); case 172: return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); case 173: return visitNode(cbNode, node.expression) || @@ -7675,6 +8126,7 @@ var ts; return token === 19 || token === 15 || token === 37 + || token === 22 || isLiteralPropertyName(); } function nextTokenIsClassOrFunction() { @@ -9182,7 +9634,7 @@ var ts; } var node = createNode(172, expression.pos); node.expression = expression; - node.dotToken = parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); return finishNode(node); } @@ -9370,7 +9822,6 @@ var ts; if (dotToken) { var propertyAccess = createNode(172, expression.pos); propertyAccess.expression = expression; - propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); continue; @@ -10414,8 +10865,8 @@ var ts; return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { - var name_7 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_7, undefined); + var name_8 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_8, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } @@ -10558,7 +11009,12 @@ var ts; else { node.name = parseLiteralNode(true); } - node.body = parseModuleBlock(); + if (token === 15) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { @@ -11302,8 +11758,8 @@ var ts; if (typeExpression.type.kind === 267) { var jsDocTypeReference = typeExpression.type; if (jsDocTypeReference.name.kind === 69) { - var name_8 = jsDocTypeReference.name; - if (name_8.text === "Object") { + var name_9 = jsDocTypeReference.name; + if (name_9.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -11386,13 +11842,13 @@ var ts; var typeParameters = []; typeParameters.pos = scanner.getStartPos(); while (true) { - var name_9 = parseJSDocIdentifierName(); - if (!name_9) { + var name_10 = parseJSDocIdentifierName(); + if (!name_10) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141, name_9.pos); - typeParameter.name = name_9; + var typeParameter = createNode(141, name_10.pos); + typeParameter.name = name_10; finishNode(typeParameter); typeParameters.push(typeParameter); if (token === 24) { @@ -11494,8 +11950,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var node = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -11567,8 +12023,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -11748,7 +12204,8 @@ var ts; return state_1; } else if (node.kind === 225) { - return getModuleInstanceState(node.body); + var body = node.body; + return body ? getModuleInstanceState(body) : 1; } else { return 1; @@ -12117,11 +12574,6 @@ var ts; break; } } - function isNarrowableReference(expr) { - return expr.kind === 69 || - expr.kind === 97 || - expr.kind === 172 && isNarrowableReference(expr.expression); - } function isNarrowingExpression(expr) { switch (expr.kind) { case 69: @@ -12129,7 +12581,7 @@ var ts; case 172: return isNarrowableReference(expr); case 174: - return true; + return hasNarrowableArgument(expr); case 178: return isNarrowingExpression(expr.expression); case 187: @@ -12139,6 +12591,35 @@ var ts; } return false; } + function isNarrowableReference(expr) { + return expr.kind === 69 || + expr.kind === 97 || + expr.kind === 172 && isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 172 && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingNullCheckOperands(expr1, expr2) { + return (expr1.kind === 93 || expr1.kind === 69 && expr1.text === "undefined") && isNarrowableOperand(expr2); + } + function isNarrowingTypeofOperands(expr1, expr2) { + return expr1.kind === 182 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + } + function isNarrowingDiscriminant(expr) { + return expr.kind === 172 && isNarrowableReference(expr.expression); + } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56: @@ -12147,20 +12628,34 @@ var ts; case 31: case 32: case 33: - if (isNarrowingExpression(expr.left) && (expr.right.kind === 93 || expr.right.kind === 69)) { - return true; - } - if (expr.left.kind === 182 && isNarrowingExpression(expr.left.expression) && expr.right.kind === 9) { - return true; - } - return false; + return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || + isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); case 91: - return isNarrowingExpression(expr.left); + return isNarrowableOperand(expr.left); case 24: return isNarrowingExpression(expr.right); } return false; } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 178: + return isNarrowableOperand(expr.expression); + case 187: + switch (expr.operatorToken.kind) { + case 56: + return isNarrowableOperand(expr.left); + case 24: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function isNarrowingSwitchStatement(switchStatement) { + var expr = switchStatement.expression; + return expr.kind === 172 && isNarrowableReference(expr.expression); + } function createBranchLabel() { return { flags: 4, @@ -12174,7 +12669,7 @@ var ts; }; } function setFlowNodeReferenced(flow) { - flow.flags |= flow.flags & 128 ? 256 : 128; + flow.flags |= flow.flags & 256 ? 512 : 256; } function addAntecedent(label, antecedent) { if (!(antecedent.flags & 1) && !ts.contains(label.antecedents, antecedent)) { @@ -12199,8 +12694,21 @@ var ts; setFlowNodeReferenced(antecedent); return { flags: flags, - antecedent: antecedent, - expression: expression + expression: expression, + antecedent: antecedent + }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingSwitchStatement(switchStatement)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: 128, + switchStatement: switchStatement, + clauseStart: clauseStart, + clauseEnd: clauseEnd, + antecedent: antecedent }; } function createFlowAssignment(antecedent, node) { @@ -12410,9 +12918,10 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasNonEmptyDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250 && c.statements.length; }); - if (!hasNonEmptyDefault) { - addAntecedent(postSwitchLabel, preSwitchCaseFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250; }); + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); } currentBreakTarget = saveBreakTarget; preSwitchCaseFlow = savePreSwitchCaseFlow; @@ -12420,25 +12929,22 @@ var ts; } function bindCaseBlock(node) { var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { - var clause = clauses[i]; - if (clause.statements.length) { - if (currentFlow.flags & 1) { - currentFlow = preSwitchCaseFlow; - } - else { - var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, preSwitchCaseFlow); - addAntecedent(preCaseLabel, currentFlow); - currentFlow = finishFlowLabel(preCaseLabel); - } - bind(clause); - if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; } - else { - bind(clause); + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); } } } @@ -12703,7 +13209,7 @@ var ts; } function hasExportDeclarations(node) { var body = node.kind === 256 ? node : node.body; - if (body.kind === 256 || body.kind === 226) { + if (body && (body.kind === 256 || body.kind === 226)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; if (stat.kind === 236 || stat.kind === 235) { @@ -13223,7 +13729,7 @@ var ts; constructorFunction.parent = classPrototype; classPrototype.parent = leftSideOfAssignment; var funcSymbol = container.locals[constructorFunction.text]; - if (!funcSymbol || !(funcSymbol.flags & 16)) { + if (!funcSymbol || !(funcSymbol.flags & 16 || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return; } if (!funcSymbol.members) { @@ -13808,7 +14314,8 @@ var ts; var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { - if (modulekind || (!compilerOptions.outFile && !compilerOptions.out)) { + if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out)) { return true; } var sourceFiles = host.getSourceFiles(); @@ -14005,7 +14512,8 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg)) { + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -14061,6 +14569,29 @@ var ts; } return false; } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var parentClassExpression = errorLocation; + while (parentClassExpression) { + var kind = parentClassExpression.kind; + if (kind === 69 || kind === 172) { + parentClassExpression = parentClassExpression.parent; + continue; + } + if (kind === 194) { + break; + } + return false; + } + if (!parentClassExpression) { + return false; + } + var expression = parentClassExpression.expression; + if (resolveEntityName(expression, 64, true)) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; + } + return false; + } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); @@ -14103,9 +14634,11 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = moduleSymbol.exports["export="] ? - getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : - resolveSymbol(moduleSymbol.exports["default"]); + var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? + moduleSymbol : + moduleSymbol.exports["export="] ? + getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : + resolveSymbol(moduleSymbol.exports["default"]); if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } @@ -14154,22 +14687,25 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_10 = specifier.propertyName || specifier.name; - if (name_10.text) { + var name_11 = specifier.propertyName || specifier.name; + if (name_11.text) { + if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { + return moduleSymbol; + } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_10.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_11.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_10.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_11.text); } symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_10.text); + var symbolFromModule = getExportOfModule(targetSymbol, name_11.text); var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_10, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_10)); + error(name_11, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_11)); } return symbol; } @@ -15504,6 +16040,9 @@ var ts; function isTypeAny(type) { return type && (type.flags & 1) !== 0; } + function isTypeNever(type) { + return type && (type.flags & 134217728) !== 0; + } function getTypeForBindingElementParent(node) { var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); @@ -15539,19 +16078,19 @@ var ts; } var type; if (pattern.kind === 167) { - var name_11 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_11)) { + var name_12 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_12)) { return anyType; } if (declaration.initializer) { getContextualType(declaration.initializer); } - var text = getTextOfPropertyName(name_11); + var text = getTextOfPropertyName(name_12); type = getTypeOfPropertyOfType(parentType, text) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { - error(name_11, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_11)); + error(name_12, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_12)); return unknownType; } } @@ -15755,18 +16294,21 @@ var ts; if (declaration.kind === 235) { return links.type = checkExpression(declaration.expression); } - if (declaration.kind === 187) { - return links.type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); - } - if (declaration.kind === 172) { - if (declaration.parent.kind === 187) { - return links.type = checkExpressionCached(declaration.parent.right); - } - } if (!pushTypeResolution(symbol, 0)) { return unknownType; } - var type = getWidenedTypeForVariableLikeDeclaration(declaration, true); + var type = undefined; + if (declaration.kind === 187) { + type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); + } + else if (declaration.kind === 172) { + if (declaration.parent.kind === 187) { + type = checkExpressionCached(declaration.parent.right); + } + } + if (type === undefined) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, true); + } if (!popTypeResolution()) { if (symbol.valueDeclaration.type) { type = unknownType; @@ -15854,9 +16396,14 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var type = createObjectType(65536, symbol); - links.type = strictNullChecks && symbol.flags & 536870912 ? - addTypeKind(type, 32) : type; + if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { + links.type = anyType; + } + else { + var type = createObjectType(65536, symbol); + links.type = strictNullChecks && symbol.flags & 536870912 ? + addTypeKind(type, 32) : type; + } } return links.type; } @@ -16807,7 +17354,7 @@ var ts; } return result; } - function isOptionalParameter(node) { + function isJSDocOptionalParameter(node) { if (node.flags & 134217728) { if (node.type && node.type.kind === 268) { return true; @@ -16822,7 +17369,9 @@ var ts; } } } - if (ts.hasQuestionToken(node)) { + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { return true; } if (node.initializer) { @@ -16877,7 +17426,7 @@ var ts; if (param.type && param.type.kind === 166) { hasStringLiterals = true; } - if (param.initializer || param.questionToken || param.dotDotDotToken) { + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { minArgumentCount = i - (hasThisParameter ? 1 : 0); } @@ -17874,6 +18423,9 @@ var ts; function isTypeComparableTo(source, target) { return checkTypeComparableTo(source, target, undefined); } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); } @@ -18812,8 +19364,10 @@ var ts; function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isStringLiteralType(type) { - return type.flags & 256; + function isStringLiteralUnionType(type) { + return type.flags & 256 ? true : + type.flags & 16384 ? ts.forEach(type.types, isStringLiteralUnionType) : + false; } function isTupleType(type) { return !!(type.flags & 8192); @@ -19543,6 +20097,29 @@ var ts; } return node; } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 249) { + var expr = clause.expression; + return expr.kind === 9 ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); + } + return undefined; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); + links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256; }) ? types : emptyArray; + } + return links.switchTypes; + } + function eachTypeContainedIn(source, types) { + return source.flags & 16384 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function filterType(type, f) { + return type.flags & 16384 ? + getUnionType(ts.filter(type.types, f)) : + f(type) ? type : neverType; + } function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { var key; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175)) { @@ -19558,7 +20135,7 @@ var ts; return result; function getTypeAtFlowNode(flow) { while (true) { - if (flow.flags & 256) { + if (flow.flags & 512) { for (var i = visitedFlowStart; i < visitedFlowCount; i++) { if (visitedFlowNodes[i] === flow) { return visitedFlowTypes[i]; @@ -19576,6 +20153,9 @@ var ts; else if (flow.flags & 96) { type = getTypeAtFlowCondition(flow); } + else if (flow.flags & 128) { + type = getTypeAtSwitchClause(flow); + } else if (flow.flags & 12) { if (flow.antecedents.length === 1) { flow = flow.antecedents[0]; @@ -19596,7 +20176,7 @@ var ts; else { type = declaredType; } - if (flow.flags & 256) { + if (flow.flags & 512) { visitedFlowNodes[visitedFlowCount] = flow; visitedFlowTypes[visitedFlowCount] = type; visitedFlowCount++; @@ -19634,6 +20214,10 @@ var ts; } return type; } + function getTypeAtSwitchClause(flow) { + var type = getTypeAtFlowNode(flow.antecedent); + return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { @@ -19694,11 +20278,26 @@ var ts; case 31: case 32: case 33: - if (isNullOrUndefinedLiteral(expr.right)) { - return narrowTypeByNullCheck(type, expr, assumeTrue); + var left = expr.left; + var operator = expr.operatorToken.kind; + var right = expr.right; + if (isNullOrUndefinedLiteral(right)) { + return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); } - if (expr.left.kind === 182 && expr.right.kind === 9) { - return narrowTypeByTypeof(type, expr, assumeTrue); + if (isNullOrUndefinedLiteral(left)) { + return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); + } + if (left.kind === 182 && right.kind === 9) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); + } + if (right.kind === 182 && left.kind === 9) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); + } + if (left.kind === 172) { + return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); + } + if (right.kind === 172) { + return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); } break; case 91: @@ -19708,46 +20307,91 @@ var ts; } return type; } - function narrowTypeByNullCheck(type, expr, assumeTrue) { - var operator = expr.operatorToken.kind; + function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } - if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(expr.left))) { + if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { return type; } var doubleEquals = operator === 30 || operator === 31; var facts = doubleEquals ? assumeTrue ? 65536 : 524288 : - expr.right.kind === 93 ? + literal.kind === 93 ? assumeTrue ? 32768 : 262144 : assumeTrue ? 16384 : 131072; return getTypeWithFacts(type, facts); } - function narrowTypeByTypeof(type, expr, assumeTrue) { - var left = getReferenceFromExpression(expr.left.expression); - var right = expr.right; - if (!isMatchingReference(reference, left)) { - if (containsMatchingReference(reference, left)) { + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + var target = getReferenceFromExpression(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { + if (containsMatchingReference(reference, target)) { return declaredType; } return type; } - if (expr.operatorToken.kind === 31 || - expr.operatorToken.kind === 33) { + if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } if (assumeTrue && !(type.flags & 16384)) { - var targetType = ts.getProperty(typeofTypesByName, right.text); + var targetType = ts.getProperty(typeofTypesByName, literal.text); if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - ts.getProperty(typeofEQFacts, right.text) || 64 : - ts.getProperty(typeofNEFacts, right.text) || 8192; + ts.getProperty(typeofEQFacts, literal.text) || 64 : + ts.getProperty(typeofNEFacts, literal.text) || 8192; return getTypeWithFacts(type, facts); } + function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { + if (!isMatchingReference(reference, propAccess.expression)) { + return type; + } + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var discriminantType = value.kind === 9 ? getStringLiteralTypeForText(value.text) : checkExpression(value); + if (!isStringLiteralUnionType(discriminantType)) { + return type; + } + if (operator === 31 || operator === 33) { + assumeTrue = !assumeTrue; + } + if (assumeTrue) { + return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); + } + if (discriminantType.flags & 256) { + return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); + } + return type; + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + if (!isMatchingReference(reference, switchStatement.expression.expression)) { + return type; + } + var propName = switchStatement.expression.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); + var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; + var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; + var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); + return caseType ? getUnionType([caseType, defaultType]) : defaultType; + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceFromExpression(expr.left); if (!isMatchingReference(reference, left)) { @@ -20316,11 +20960,11 @@ var ts; } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_12 = declaration.propertyName || declaration.name; + var name_13 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_12)) { - var text = getTextOfPropertyName(name_12); + !ts.isBindingPattern(name_13)) { + var text = getTextOfPropertyName(name_13); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -20446,9 +21090,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } - function contextualTypeIsStringLiteralType(type) { - return !!(type.flags & 16384 ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type)); - } function contextualTypeIsTupleLikeType(type) { return !!(type.flags & 16384 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } @@ -21215,7 +21856,7 @@ var ts; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { - if (right.text) { + if (right.text && !checkAndReportErrorForExtendingInterface(node)) { error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 ? apparentType : type)); } return unknownType; @@ -21308,15 +21949,15 @@ var ts; return unknownType; } if (node.argumentExpression) { - var name_13 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_13 !== undefined) { - var prop = getPropertyOfType(objectType, name_13); + var name_14 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_14 !== undefined) { + var prop = getPropertyOfType(objectType, name_14); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_13, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_14, symbolToString(objectType.symbol)); return unknownType; } } @@ -22135,8 +22776,10 @@ var ts; declaration.kind !== 152 && declaration.kind !== 157 && !ts.isJSDocConstructSignature(declaration)) { - var funcSymbol = checkExpression(node.expression).symbol; - if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16)) { + var funcSymbol = node.expression.kind === 69 ? + getResolvedSymbol(node.expression) : + checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return getInferredClassType(funcSymbol); } else if (compilerOptions.noImplicitAny) { @@ -22155,6 +22798,7 @@ var ts; } function checkAssertion(node) { var exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + checkSourceElement(node.type); var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { var widenedType = getWidenedType(exprType); @@ -22238,6 +22882,14 @@ var ts; } return emptyObjectType; } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return unknownType; + } + return promiseType; + } function getReturnTypeFromBody(func, contextualMapper) { var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { @@ -22267,18 +22919,10 @@ var ts; else { types = checkAndAggregateReturnExpressionTypes(func, contextualMapper); if (!types) { - return neverType; + return isAsync ? createPromiseReturnType(func, neverType) : neverType; } if (types.length === 0) { - if (isAsync) { - var promiseType = createPromiseType(voidType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - return voidType; + return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); @@ -22289,7 +22933,7 @@ var ts; } else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return getUnionType(types); + return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); } } if (funcIsGenerator) { @@ -22300,17 +22944,7 @@ var ts; reportErrorsFromWidening(func, type); } var widenedType = getWidenedType(type); - if (isAsync) { - var promiseType = createPromiseType(widenedType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - else { - return widenedType; - } + return isAsync ? createPromiseReturnType(func, widenedType) : widenedType; } function checkAndAggregateYieldOperandTypes(func, contextualMapper) { var aggregatedTypes = []; @@ -22328,10 +22962,40 @@ var ts; }); return aggregatedTypes; } + function isExhaustiveSwitchStatement(node) { + var expr = node.expression; + if (!node.possiblyExhaustive || expr.kind !== 172) { + return false; + } + var type = checkExpression(expr.expression); + if (!(type.flags & 16384)) { + return false; + } + var propName = expr.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length) { + return false; + } + return eachTypeContainedIn(propType, switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 32768)) { + return false; + } + var lastStatement = ts.lastOrUndefined(func.body.statements); + if (lastStatement && lastStatement.kind === 213 && isExhaustiveSwitchStatement(lastStatement)) { + return false; + } + return true; + } function checkAndAggregateReturnExpressionTypes(func, contextualMapper) { var isAsync = ts.isAsyncFunctionLike(func); var aggregatedTypes = []; - var hasReturnWithNoExpression = !!(func.flags & 32768); + var hasReturnWithNoExpression = functionHasImplicitReturn(func); var hasReturnOfTypeNever = false; ts.forEachReturnStatement(func.body, function (returnStatement) { var expr = returnStatement.expression; @@ -22369,7 +23033,7 @@ var ts; if (returnType && maybeTypeOfKind(returnType, 1 | 16)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !(func.flags & 32768)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 65536; @@ -22662,14 +23326,14 @@ var ts; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { if (property.kind === 253 || property.kind === 254) { - var name_14 = property.name; - if (name_14.kind === 140) { - checkComputedPropertyName(name_14); + var name_15 = property.name; + if (name_15.kind === 140) { + checkComputedPropertyName(name_15); } - if (isComputedNonLiteralName(name_14)) { + if (isComputedNonLiteralName(name_15)) { return undefined; } - var text = getTextOfPropertyName(name_14); + var text = getTextOfPropertyName(name_15); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -22684,7 +23348,7 @@ var ts; } } else { - error(name_14, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_14)); + error(name_15, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_15)); } } else { @@ -22880,7 +23544,7 @@ var ts; case 90: return checkInExpression(left, right, leftType, rightType); case 51: - return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 126) : rightType; + return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112) : rightType; case 52: return getUnionType([getNonNullableType(leftType), rightType]); case 56: @@ -22980,7 +23644,7 @@ var ts; } function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); - if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { + if (contextualType && isStringLiteralUnionType(contextualType)) { return getStringLiteralTypeForText(node.text); } return stringType; @@ -23223,9 +23887,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_15 = _a[_i].name; - if (ts.isBindingPattern(name_15) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_15, parameterName, typePredicate.parameterName)) { + var name_16 = _a[_i].name; + if (ts.isBindingPattern(name_16) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_16, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -23253,15 +23917,15 @@ var ts; } function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var name_16 = _a[_i].name; - if (name_16.kind === 69 && - name_16.text === predicateVariableName) { + var name_17 = _a[_i].name; + if (name_17.kind === 69 && + name_17.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_16.kind === 168 || - name_16.kind === 167) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_16, predicateVariableNode, predicateVariableName)) { + else if (name_17.kind === 168 || + name_17.kind === 167) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_17, predicateVariableNode, predicateVariableName)) { return true; } } @@ -23729,7 +24393,6 @@ var ts; } } } - var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & 1536; var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { @@ -23754,7 +24417,7 @@ var ts; duplicateFunctionDeclaration = true; } } - else if (!isExportSymbolInsideModule && previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { reportImplementationExpectedError(previousDeclaration); } if (ts.nodeIsPresent(node.body)) { @@ -23781,7 +24444,7 @@ var ts; error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); }); } - if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && !(lastSeenNonAmbientDeclaration.flags & 128) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } @@ -23872,7 +24535,7 @@ var ts; } function checkNonThenableType(type, location, message) { type = getWidenedType(type); - if (!isTypeAny(type) && isTypeAssignableTo(type, getGlobalThenableType())) { + if (!isTypeAny(type) && !isTypeNever(type) && isTypeAssignableTo(type, getGlobalThenableType())) { if (location) { if (!message) { message = ts.Diagnostics.Operand_for_await_does_not_have_a_valid_callable_then_member; @@ -23884,37 +24547,39 @@ var ts; return type; } function getPromisedType(promise) { - if (promise.flags & 1) { + if (isTypeAny(promise)) { return undefined; } - if ((promise.flags & 4096) && promise.target === tryGetGlobalPromiseType()) { - return promise.typeArguments[0]; + if (promise.flags & 4096) { + if (promise.target === tryGetGlobalPromiseType() + || promise.target === getGlobalPromiseLikeType()) { + return promise.typeArguments[0]; + } } var globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType(); if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) { return undefined; } var thenFunction = getTypeOfPropertyOfType(promise, "then"); - if (thenFunction && (thenFunction.flags & 1)) { + if (!thenFunction || isTypeAny(thenFunction)) { return undefined; } - var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0) : emptyArray; + var thenSignatures = getSignaturesOfType(thenFunction, 0); if (thenSignatures.length === 0) { return undefined; } var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072); - if (onfulfilledParameterType.flags & 1) { + if (isTypeAny(onfulfilledParameterType)) { return undefined; } var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0); if (onfulfilledParameterSignatures.length === 0) { return undefined; } - var valueParameterType = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); - return valueParameterType; + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); } function getTypeOfFirstParameterOfSignature(signature) { - return getTypeAtPosition(signature, 0); + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; } function getAwaitedType(type) { return checkAwaitedType(type, undefined, undefined); @@ -24255,8 +24920,8 @@ var ts; container.kind === 225 || container.kind === 256); if (!namesShareScope) { - var name_17 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_17, name_17); + var name_18 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_18, name_18); } } } @@ -24326,8 +24991,8 @@ var ts; } var parent_11 = node.parent.parent; var parentType = getTypeForBindingElementParent(parent_11); - var name_18 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_18)); + var name_19 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, getTextOfPropertyName(name_19)); if (parent_11.initializer && property && getParentOfSymbol(property)) { checkClassPropertyAccess(parent_11, parent_11.initializer, parentType, property); } @@ -25456,7 +26121,7 @@ var ts; if (isAmbientExternalModule) { if (ts.isExternalModuleAugmentation(node)) { var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432); - if (checkBody) { + if (checkBody && node.body) { for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { var statement = _a[_i]; checkModuleAugmentationElement(statement, isGlobalAugmentation); @@ -25481,7 +26146,12 @@ var ts; } } } - checkSourceElement(node.body); + if (compilerOptions.noImplicitAny && !node.body) { + reportImplicitAnyError(node, anyType); + } + if (node.body) { + checkSourceElement(node.body); + } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { @@ -25501,9 +26171,9 @@ var ts; break; case 169: case 218: - var name_19 = node.name; - if (ts.isBindingPattern(name_19)) { - for (var _b = 0, _c = name_19.elements; _b < _c.length; _b++) { + var name_20 = node.name; + if (ts.isBindingPattern(name_20)) { + for (var _b = 0, _c = name_20.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -26338,9 +27008,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols_3 = []; - var name_20 = symbol.name; + var name_21 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_20); + var symbol = getPropertyOfType(t, name_21); if (symbol) { symbols_3.push(symbol); } @@ -27041,7 +27711,10 @@ var ts; return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } else if (node.kind === 142 && (flags & 92) && ts.isBindingPattern(node.name)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 142 && (flags & 92) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256) { return checkGrammarAsyncModifier(node, lastAsync); @@ -27285,10 +27958,10 @@ var ts; var SetAccessor = 4; var GetOrSetAccessor = GetAccessor | SetAccessor; var _loop_1 = function(prop) { - var name_21 = prop.name; + var name_22 = prop.name; if (prop.kind === 193 || - name_21.kind === 140) { - checkGrammarComputedPropertyName(name_21); + name_22.kind === 140) { + checkGrammarComputedPropertyName(name_22); } if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; @@ -27301,8 +27974,8 @@ var ts; var currentKind = void 0; if (prop.kind === 253 || prop.kind === 254) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_21.kind === 8) { - checkGrammarNumericLiteral(name_21); + if (name_22.kind === 8) { + checkGrammarNumericLiteral(name_22); } currentKind = Property; } @@ -27318,7 +27991,7 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_21); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_22); if (effectiveName === undefined) { return "continue"; } @@ -27328,18 +28001,18 @@ var ts; else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_21, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_21)); + grammarErrorOnNode(name_22, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_22)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return { value: grammarErrorOnNode(name_21, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; + return { value: grammarErrorOnNode(name_22, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; } } else { - return { value: grammarErrorOnNode(name_21, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; + return { value: grammarErrorOnNode(name_22, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; } } }; @@ -27357,12 +28030,12 @@ var ts; continue; } var jsxAttr = attr; - var name_22 = jsxAttr.name; - if (!ts.hasProperty(seen, name_22.text)) { - seen[name_22.text] = true; + var name_23 = jsxAttr.name; + if (!ts.hasProperty(seen, name_23.text)) { + seen[name_23.text] = true; } else { - return grammarErrorOnNode(name_22, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_23, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; if (initializer && initializer.kind === 248 && !initializer.expression) { @@ -28425,9 +29098,9 @@ var ts; var count = 0; while (true) { count++; - var name_23 = baseName + "_" + count; - if (!ts.hasProperty(currentIdentifiers, name_23)) { - return name_23; + var name_24 = baseName + "_" + count; + if (!ts.hasProperty(currentIdentifiers, name_24)) { + return name_24; } } } @@ -28695,21 +29368,26 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body.kind !== 226) { + while (node.body && node.body.kind !== 226) { node = node.body; write("."); writeTextOfNode(currentText, node.name); } var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; + if (node.body) { + enclosingDeclaration = node; + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.body.statements); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + else { + write(";"); + } } function writeTypeAliasDeclaration(node) { var prevEnclosingDeclaration = enclosingDeclaration; @@ -29909,19 +30587,19 @@ var ts; } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_24 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_24)) { + var name_25 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_25)) { tempFlags |= flags; - return name_24; + return name_25; } } while (true) { var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name_25 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_25)) { - return name_25; + var name_26 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); + if (isUniqueName(name_26)) { + return name_26; } } } @@ -30617,8 +31295,8 @@ var ts; } else if (declaration.kind === 234) { write(getGeneratedNameForNode(declaration.parent.parent.parent)); - var name_26 = declaration.propertyName || declaration.name; - var identifier = ts.getTextOfNodeFromSourceText(currentText, name_26); + var name_27 = declaration.propertyName || declaration.name; + var identifier = ts.getTextOfNodeFromSourceText(currentText, name_27); if (languageVersion === 0 && identifier === "default") { write('["default"]'); } @@ -30671,8 +31349,8 @@ var ts; function emitIdentifier(node) { if (convertedLoopState) { if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { - var name_27 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); - write(name_27); + var name_28 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); + write(name_28); return; } } @@ -31010,7 +31688,6 @@ var ts; function createPropertyAccessExpression(expression, name) { var result = ts.createSynthesizedNode(172); result.expression = parenthesizeForAccess(expression); - result.dotToken = ts.createSynthesizedNode(21); result.name = name; return result; } @@ -31056,9 +31733,9 @@ var ts; emitTrailingCommentsOfPosition(node.initializer.pos); emit(node.initializer); } - function isNamespaceExportReference(node) { + function isExportReference(node) { var container = resolver.getReferencedExportContainer(node); - return container && container.kind !== 256; + return !!container; } function isImportedReference(node) { var declaration = resolver.getReferencedImportDeclaration(node); @@ -31066,9 +31743,9 @@ var ts; } function emitShorthandPropertyAssignment(node) { writeTextOfNode(currentText, node.name); - if (languageVersion < 2 || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isNamespaceExportReference(node.name)) { + if (languageVersion < 2 || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isExportReference(node.name)) { write(": "); - emit(node.name); + emitExpressionIdentifier(node.name); } if (languageVersion >= 2 && node.objectAssignmentInitializer) { write(" = "); @@ -31117,13 +31794,16 @@ var ts; if (languageVersion === 2 && node.expression.kind === 95 && isInAsyncMethodWithSuperInES6(node)) { - var name_28 = ts.createSynthesizedNode(9); - name_28.text = node.name.text; - emitSuperAccessInAsyncMethod(node.expression, name_28); + var name_29 = ts.createSynthesizedNode(9); + name_29.text = node.name.text; + emitSuperAccessInAsyncMethod(node.expression, name_29); return; } emit(node.expression); - var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); + var dotRangeStart = ts.nodeIsSynthesized(node.expression) ? -1 : node.expression.end; + var dotRangeEnd = ts.nodeIsSynthesized(node.expression) ? -1 : ts.skipTrivia(currentText, node.expression.end) + 1; + var dotToken = { pos: dotRangeStart, end: dotRangeEnd }; + var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, dotToken); var shouldEmitSpace = false; if (!indentedBeforeDot) { if (node.expression.kind === 8) { @@ -31141,7 +31821,7 @@ var ts; else { write("."); } - var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); + var indentedAfterDot = indentIfOnDifferentLines(node, dotToken, node.name); emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); } @@ -31514,7 +32194,6 @@ var ts; synthesizedLHS = ts.createSynthesizedNode(172, false); var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); synthesizedLHS.expression = identifier; - synthesizedLHS.dotToken = leftHandSideExpression.dotToken; synthesizedLHS.name = leftHandSideExpression.name; write(", "); } @@ -32790,12 +33469,12 @@ var ts; function emitParameter(node) { if (languageVersion < 2) { if (ts.isBindingPattern(node.name)) { - var name_29 = createTempVariable(0); + var name_30 = createTempVariable(0); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_29); - emit(name_29); + tempParameters.push(name_30); + emit(name_30); } else { emit(node.name); @@ -33586,7 +34265,11 @@ var ts; } } function emitClassLikeDeclarationBelowES6(node) { + var isES6ExportedClass = isES6ExportedDeclaration(node); if (node.kind === 221) { + if (isES6ExportedClass && !(node.flags & 512)) { + write("export "); + } if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); } @@ -33650,9 +34333,15 @@ var ts; write(";"); } emitEnd(node); - if (node.kind === 221) { + if (node.kind === 221 && !isES6ExportedClass) { emitExportMemberAssignment(node); } + else if (isES6ExportedClass && (node.flags & 512)) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); @@ -33948,10 +34637,10 @@ var ts; } if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 160) { + if (parameterType && parameterType.kind === 160) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 155 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType && parameterType.kind === 155 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { @@ -33968,9 +34657,15 @@ var ts; } } function emitSerializedReturnTypeOfNode(node) { - if (node && ts.isFunctionLike(node) && node.type) { - emitSerializedTypeNode(node.type); - return; + if (node && ts.isFunctionLike(node)) { + if (node.type) { + emitSerializedTypeNode(node.type); + return; + } + else if (ts.isAsyncFunctionLike(node)) { + write("Promise"); + return; + } } write("void 0"); } @@ -34103,7 +34798,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 225) { + if (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -34144,6 +34839,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); + ts.Debug.assert(node.body !== undefined); if (node.body.kind === 226) { var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; @@ -34523,8 +35219,8 @@ var ts; else { for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { var specifier = _d[_c]; - var name_30 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_30] || (exportSpecifiers[name_30] = [])).push(specifier); + var name_31 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_31] || (exportSpecifiers[name_31] = [])).push(specifier); } } break; @@ -34562,9 +35258,9 @@ var ts; } function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { if (emitRelativePathAsModuleName) { - var name_31 = getExternalModuleNameFromDeclaration(host, resolver, importNode); - if (name_31) { - return "\"" + name_31 + "\""; + var name_32 = getExternalModuleNameFromDeclaration(host, resolver, importNode); + if (name_32) { + return "\"" + name_32 + "\""; } } var moduleName = ts.getExternalModuleName(importNode); @@ -34710,11 +35406,11 @@ var ts; var seen = {}; for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; - var name_32 = local.kind === 69 + var name_33 = local.kind === 69 ? local : local.name; - if (name_32) { - var text = ts.unescapeIdentifier(name_32.text); + if (name_33) { + var text = ts.unescapeIdentifier(name_33.text); if (ts.hasProperty(seen, text)) { continue; } @@ -34793,15 +35489,15 @@ var ts; } if (node.kind === 218 || node.kind === 169) { if (shouldHoistVariable(node, false)) { - var name_33 = node.name; - if (name_33.kind === 69) { + var name_34 = node.name; + if (name_34.kind === 69) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_33); + hoistedVars.push(name_34); } else { - ts.forEachChild(name_33, visit); + ts.forEachChild(name_34, visit); } } return; @@ -35711,13 +36407,9 @@ var ts; ts.emitTime = 0; ts.ioReadTime = 0; ts.ioWriteTime = 0; - var emptyArray = []; - var defaultLibrarySearchPaths = [ - "types/", - "node_modules/", - "node_modules/@types/", - ]; ts.version = "1.9.0"; + var emptyArray = []; + var defaultTypeRoots = ["node_modules/@types"]; function findConfigFile(searchPath, fileExists) { while (true) { var fileName = ts.combinePaths(searchPath, "tsconfig.json"); @@ -35845,6 +36537,10 @@ var ts; return undefined; } var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + return options.typeRoots || + ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(), d); }); + } function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); var moduleResolutionState = { @@ -35853,35 +36549,34 @@ var ts; skipTsx: true, traceEnabled: traceEnabled }; - var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : (host.getCurrentDirectory && host.getCurrentDirectory())); + var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); } } else { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } } var failedLookupLocations = []; - if (rootDir !== undefined) { - var effectivePrimarySearchPaths = options.typesSearchPaths || defaultLibrarySearchPaths; - for (var _i = 0, effectivePrimarySearchPaths_1 = effectivePrimarySearchPaths; _i < effectivePrimarySearchPaths_1.length; _i++) { - var searchPath = effectivePrimarySearchPaths_1[_i]; - var primaryPath = ts.combinePaths(rootDir, searchPath); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, primaryPath); - } - var candidate = ts.combinePaths(primaryPath, typeReferenceDirectiveName); + if (typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); if (resolvedFile_1) { @@ -35905,9 +36600,6 @@ var ts; if (containingFile) { initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); } - else { - initialLocationForSecondaryLookup = rootDir; - } if (initialLocationForSecondaryLookup !== undefined) { if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); @@ -36400,25 +37092,12 @@ var ts; } } } - function getDefaultTypeDirectiveNames(rootPath) { - var localTypes = ts.combinePaths(rootPath, "types"); - var npmTypes = ts.combinePaths(rootPath, "node_modules/@types"); - var result = []; - if (ts.sys.directoryExists(localTypes)) { - result = result.concat(ts.sys.getDirectories(localTypes)); - } - if (ts.sys.directoryExists(npmTypes)) { - result = result.concat(ts.sys.getDirectories(npmTypes)); - } - return result; - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); } var newLine = ts.getNewLineCharacter(options); var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); return { - getDefaultTypeDirectiveNames: getDefaultTypeDirectiveNames, getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -36431,6 +37110,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, + getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; } @@ -36473,32 +37153,39 @@ var ts; var resolutions = []; var cache = {}; for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_34 = names_1[_i]; + var name_35 = names_1[_i]; var result = void 0; - if (ts.hasProperty(cache, name_34)) { - result = cache[name_34]; + if (ts.hasProperty(cache, name_35)) { + result = cache[name_35]; } else { - result = loader(name_34, containingFile); - cache[name_34] = result; + result = loader(name_35, containingFile); + cache[name_35] = result; } resolutions.push(result); } return resolutions; } - function getDefaultTypeDirectiveNames(options, rootFiles, host) { + function getInferredTypesRoot(options, rootFiles, host) { + return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + function getAutomaticTypeDirectiveNames(options, rootFiles, host) { if (options.types) { return options.types; } - if (host && host.getDefaultTypeDirectiveNames) { - var commonRoot = computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); - if (commonRoot) { - return host.getDefaultTypeDirectiveNames(commonRoot); + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + result = result.concat(host.getDirectories(root)); + } } } - return undefined; + return result; } - ts.getDefaultTypeDirectiveNames = getDefaultTypeDirectiveNames; + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -36535,9 +37222,11 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - var typeReferences = getDefaultTypeDirectiveNames(options, rootNames, host); + var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); if (typeReferences) { - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, undefined); + var inferredRoot = getInferredTypesRoot(options, rootNames, host); + var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); } @@ -36600,8 +37289,8 @@ var ts; if (!classifiableNames) { getTypeChecker(); classifiableNames = {}; - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var sourceFile = files_3[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } @@ -36620,10 +37309,9 @@ var ts; (oldOptions.jsx !== options.jsx) || (oldOptions.allowJs !== options.allowJs) || (oldOptions.rootDir !== options.rootDir) || - (oldOptions.typesSearchPaths !== options.typesSearchPaths) || (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || - (oldOptions.typesRoot !== options.typesRoot) || + !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { return false; @@ -36915,8 +37603,20 @@ var ts; } break; case 145: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); - return true; + var propertyDeclaration = node; + if (propertyDeclaration.modifiers) { + for (var _i = 0, _a = propertyDeclaration.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 113) { + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + } + } + } + if (checkTypeAnnotation(node.type)) { + return true; + } + break; case 224: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return true; @@ -37048,9 +37748,12 @@ var ts; (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - collectModuleReferences(statement, true); + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, true); + } } } } @@ -37197,7 +37900,7 @@ var ts; } } else { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_name_0, typeReferenceDirective)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); } if (saveResolution) { resolvedTypeReferenceDirectives[typeReferenceDirective] = resolvedTypeReferenceDirective; @@ -37362,9 +38065,6 @@ var ts; var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } - if (options.module === ts.ModuleKind.ES6 && languageVersion < 2) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); - } if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); @@ -38069,10 +38769,10 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_35 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_35); + for (var name_36 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_36); if (declarations) { - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_35); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_36); if (!matches) { continue; } @@ -38083,14 +38783,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_35); + matches = patternMatcher.getMatches(containers, name_36); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_35, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_36, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -38220,622 +38920,539 @@ var ts; (function (ts) { var NavigationBar; (function (NavigationBar) { - function getNavigationBarItems(sourceFile, compilerOptions) { - if (ts.isSourceFileJavaScript(sourceFile)) { - return getJsNavigationBarItems(sourceFile, compilerOptions); + function getNavigationBarItems(sourceFile) { + curSourceFile = sourceFile; + var result = ts.map(topLevelItems(rootNavigationBarNode(sourceFile)), convertToTopLevelItem); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationBarItems = getNavigationBarItems; + var curSourceFile; + function nodeText(node) { + return node.getText(curSourceFile); + } + function navigationBarNodeKind(n) { + return n.node.kind; + } + function pushChild(parent, child) { + if (parent.children) { + parent.children.push(child); } - return getItemsWorker(getTopLevelNodes(sourceFile), createTopLevelItem); - function getIndent(node) { - var indent = 1; - var current = node.parent; - while (current) { - switch (current.kind) { - case 225: - do { - current = current.parent; - } while (current.kind === 225); - case 221: - case 224: - case 222: - case 220: - indent++; + else { + parent.children = [child]; + } + } + var parentsStack = []; + var parent; + function rootNavigationBarNode(sourceFile) { + ts.Debug.assert(!parentsStack.length); + var root = { node: sourceFile, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 }; + parent = root; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + addChildrenRecursively(statement); + } + endNode(); + ts.Debug.assert(!parent && !parentsStack.length); + return root; + } + function addLeafNode(node) { + pushChild(parent, emptyNavigationBarNode(node)); + } + function emptyNavigationBarNode(node) { + return { + node: node, + additionalNodes: undefined, + parent: parent, + children: undefined, + indent: parent.indent + 1 + }; + } + function startNode(node) { + var navNode = emptyNavigationBarNode(node); + pushChild(parent, navNode); + parentsStack.push(parent); + parent = navNode; + } + function endNode() { + if (parent.children) { + mergeChildren(parent.children); + sortChildren(parent.children); + } + parent = parentsStack.pop(); + } + function addNodeWithRecursiveChild(node, child) { + startNode(node); + addChildrenRecursively(child); + endNode(); + } + function addChildrenRecursively(node) { + if (!node || ts.isToken(node)) { + return; + } + switch (node.kind) { + case 148: + var ctr = node; + addNodeWithRecursiveChild(ctr, ctr.body); + for (var _i = 0, _a = ctr.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (ts.isParameterPropertyDeclaration(param)) { + addLeafNode(param); + } } - current = current.parent; - } - return indent; - } - function getChildNodes(nodes) { - var childNodes = []; - function visit(node) { - switch (node.kind) { - case 200: - ts.forEach(node.declarationList.declarations, visit); - break; - case 167: - case 168: - ts.forEach(node.elements, visit); - break; - case 236: - if (node.exportClause) { - ts.forEach(node.exportClause.elements, visit); + break; + case 147: + case 149: + case 150: + case 146: + if (!ts.hasDynamicName(node)) { + addNodeWithRecursiveChild(node, node.body); + } + break; + case 145: + case 144: + if (!ts.hasDynamicName(node)) { + addLeafNode(node); + } + break; + case 231: + var importClause = node; + if (importClause.name) { + addLeafNode(importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + if (namedBindings.kind === 232) { + addLeafNode(namedBindings); + } + else { + for (var _b = 0, _c = namedBindings.elements; _b < _c.length; _b++) { + var element = _c[_b]; + addLeafNode(element); } - break; - case 230: - var importClause = node.importClause; - if (importClause) { - if (importClause.name) { - childNodes.push(importClause); - } - if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 232) { - childNodes.push(importClause.namedBindings); - } - else { - ts.forEach(importClause.namedBindings.elements, visit); - } - } - } - break; - case 169: - case 218: - if (ts.isBindingPattern(node.name)) { - visit(node.name); - break; - } - case 221: - case 224: - case 222: - case 225: - case 220: - case 229: - case 234: - case 238: - case 223: - childNodes.push(node); - break; + } } - } - ts.forEach(nodes, visit); - return sortNodes(childNodes); - } - function getTopLevelNodes(node) { - var topLevelNodes = []; - topLevelNodes.push(node); - addTopLevelNodes(node.statements, topLevelNodes); - return topLevelNodes; - } - function sortNodes(nodes) { - return nodes.slice(0).sort(function (n1, n2) { - if (n1.name && n2.name) { - return localeCompareFix(ts.getPropertyNameForPropertyNameNode(n1.name), ts.getPropertyNameForPropertyNameNode(n2.name)); + break; + case 169: + case 218: + var decl = node; + var name_37 = decl.name; + if (ts.isBindingPattern(name_37)) { + addChildrenRecursively(name_37); } - else if (n1.name) { - return 1; - } - else if (n2.name) { - return -1; + else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { + addChildrenRecursively(decl.initializer); } else { - return n1.kind - n2.kind; + addNodeWithRecursiveChild(decl, decl.initializer); } - }); - function localeCompareFix(a, b) { - var cmp = a.toLowerCase().localeCompare(b.toLowerCase()); - if (cmp !== 0) - return cmp; - return a < b ? 1 : a > b ? -1 : 0; - } - } - function addTopLevelNodes(nodes, topLevelNodes) { - nodes = sortNodes(nodes); - for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { - var node = nodes_4[_i]; - switch (node.kind) { - case 221: - topLevelNodes.push(node); - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if (member.kind === 147 || member.kind === 148) { - if (member.body) { - if (hasNamedFunctionDeclarations(member.body.statements)) { - topLevelNodes.push(member); - } - addTopLevelNodes(member.body.statements, topLevelNodes); - } + break; + case 180: + case 220: + case 179: + addNodeWithRecursiveChild(node, node.body); + break; + case 224: + startNode(node); + for (var _d = 0, _e = node.members; _d < _e.length; _d++) { + var member = _e[_d]; + if (!isComputedProperty(member)) { + addLeafNode(member); + } + } + endNode(); + break; + case 221: + case 192: + case 222: + startNode(node); + for (var _f = 0, _g = node.members; _f < _g.length; _f++) { + var member = _g[_f]; + addChildrenRecursively(member); + } + endNode(); + break; + case 225: + addNodeWithRecursiveChild(node, getInteriorModule(node).body); + break; + case 238: + case 229: + case 153: + case 151: + case 152: + case 223: + addLeafNode(node); + break; + default: + if (node.jsDocComments) { + for (var _h = 0, _j = node.jsDocComments; _h < _j.length; _h++) { + var jsDocComment = _j[_h]; + for (var _k = 0, _l = jsDocComment.tags; _k < _l.length; _k++) { + var tag = _l[_k]; + if (tag.kind === 279) { + addLeafNode(tag); } } - break; - case 224: - case 222: - case 223: - topLevelNodes.push(node); - break; - case 225: - var moduleDeclaration = node; - topLevelNodes.push(node); - addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); - break; - case 220: - var functionDeclaration = node; - if (isTopLevelFunctionDeclaration(functionDeclaration)) { - topLevelNodes.push(node); - addTopLevelNodes(functionDeclaration.body.statements, topLevelNodes); - } - break; + } } - } + ts.forEachChild(node, addChildrenRecursively); } - function hasNamedFunctionDeclarations(nodes) { - for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { - var s = nodes_5[_i]; - if (s.kind === 220 && !isEmpty(s.name.text)) { + } + function mergeChildren(children) { + var nameToItems = {}; + ts.filterMutate(children, function (child) { + var decl = child.node; + var name = decl.name && nodeText(decl.name); + if (!name) { + return true; + } + var itemsWithSameName = ts.getProperty(nameToItems, name); + if (!itemsWithSameName) { + nameToItems[name] = child; + return true; + } + if (itemsWithSameName instanceof Array) { + for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { + var itemWithSameName = itemsWithSameName_1[_i]; + if (tryMerge(itemWithSameName, child)) { + return false; + } + } + itemsWithSameName.push(child); + return true; + } + else { + var itemWithSameName = itemsWithSameName; + if (tryMerge(itemWithSameName, child)) { + return false; + } + nameToItems[name] = [itemWithSameName, child]; + return true; + } + function tryMerge(a, b) { + if (shouldReallyMerge(a.node, b.node)) { + merge(a, b); return true; } + return false; } - return false; - } - function isTopLevelFunctionDeclaration(functionDeclaration) { - if (functionDeclaration.kind === 220) { - if (functionDeclaration.body && functionDeclaration.body.kind === 199) { - if (hasNamedFunctionDeclarations(functionDeclaration.body.statements)) { - return true; - } - if (!ts.isFunctionBlock(functionDeclaration.parent)) { - return true; - } - else { - var grandParentKind = functionDeclaration.parent.parent.kind; - if (grandParentKind === 147 || - grandParentKind === 148) { - return true; - } - } + }); + function shouldReallyMerge(a, b) { + return a.kind === b.kind && (a.kind !== 225 || areSameModule(a, b)); + function areSameModule(a, b) { + if (a.body.kind !== b.body.kind) { + return false; } - } - return false; - } - function getItemsWorker(nodes, createItem) { - var items = []; - var keyToItem = {}; - for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { - var child = nodes_6[_i]; - var item = createItem(child); - if (item !== undefined) { - if (item.text.length > 0) { - var key = item.text + "-" + item.kind + "-" + item.indent; - var itemWithSameName = keyToItem[key]; - if (itemWithSameName) { - merge(itemWithSameName, item); - } - else { - keyToItem[key] = item; - items.push(item); - } - } + if (a.body.kind !== 225) { + return true; } + return areSameModule(a.body, b.body); } - return items; } function merge(target, source) { - ts.addRange(target.spans, source.spans); - if (source.childItems) { - if (!target.childItems) { - target.childItems = []; - } - outer: for (var _i = 0, _a = source.childItems; _i < _a.length; _i++) { - var sourceChild = _a[_i]; - for (var _b = 0, _c = target.childItems; _b < _c.length; _b++) { - var targetChild = _c[_b]; - if (targetChild.text === sourceChild.text && targetChild.kind === sourceChild.kind) { - merge(targetChild, sourceChild); - continue outer; - } - } - target.childItems.push(sourceChild); - } + target.additionalNodes = target.additionalNodes || []; + target.additionalNodes.push(source.node); + if (source.additionalNodes) { + (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); + } + target.children = ts.concatenate(target.children, source.children); + if (target.children) { + mergeChildren(target.children); + sortChildren(target.children); + } + var _a; + } + } + function sortChildren(children) { + children.sort(compareChildren); + } + function compareChildren(child1, child2) { + var name1 = tryGetName(child1.node), name2 = tryGetName(child2.node); + if (name1 && name2) { + var cmp = localeCompareFix(name1, name2); + return cmp !== 0 ? cmp : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + } + else { + return name1 ? 1 : name2 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + } + } + var collator = typeof Intl === "undefined" ? undefined : new Intl.Collator(); + var localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; + var localeCompareFix = localeCompareIsCorrect ? collator.compare : function (a, b) { + for (var i = 0; i < Math.min(a.length, b.length); i++) { + var chA = a.charAt(i), chB = b.charAt(i); + if (chA === "\"" && chB === "'") { + return 1; + } + if (chA === "'" && chB === "\"") { + return -1; + } + var cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + if (cmp !== 0) { + return cmp; } } - function createChildItem(node) { - switch (node.kind) { - case 142: - if (ts.isBindingPattern(node.name)) { - break; - } - if ((node.flags & 1023) === 0) { - return undefined; - } - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 147: - case 146: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement); - case 149: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement); - case 150: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); - case 153: - return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - case 224: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.enumElement); - case 255: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 225: - return createItem(node, getModuleName(node), ts.ScriptElementKind.moduleElement); - case 222: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.interfaceElement); - case 223: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.typeElement); - case 151: - return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); - case 152: - return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); - case 145: - case 144: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 221: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.classElement); - case 220: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); - case 218: - case 169: - var variableDeclarationNode = void 0; - var name_36; - if (node.kind === 169) { - name_36 = node.name; - variableDeclarationNode = node; - while (variableDeclarationNode && variableDeclarationNode.kind !== 218) { - variableDeclarationNode = variableDeclarationNode.parent; - } - ts.Debug.assert(variableDeclarationNode !== undefined); - } - else { - ts.Debug.assert(!ts.isBindingPattern(node.name)); - variableDeclarationNode = node; - name_36 = node.name; - } - if (ts.isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.constElement); - } - else if (ts.isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.letElement); - } - else { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.variableElement); - } - case 148: - return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); - case 238: - case 234: - case 229: - case 231: - case 232: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); - } - return undefined; - function createItem(node, name, scriptElementKind) { - return getNavigationBarItem(name, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)]); - } + return a.length - b.length; + }; + function tryGetName(node) { + if (node.kind === 225) { + return getModuleName(node); } - function isEmpty(text) { - return !text || text.trim() === ""; + var decl = node; + if (decl.name) { + return ts.getPropertyNameForPropertyNameNode(decl.name); } - function getNavigationBarItem(text, kind, kindModifiers, spans, childItems, indent) { - if (childItems === void 0) { childItems = []; } - if (indent === void 0) { indent = 0; } - if (isEmpty(text)) { + switch (node.kind) { + case 179: + case 180: + case 192: + return getFunctionOrClassName(node); + case 279: + return getJSDocTypedefTagName(node); + default: return undefined; + } + } + function getItemName(node) { + if (node.kind === 225) { + return getModuleName(node); + } + var name = node.name; + if (name) { + var text = nodeText(name); + if (text.length > 0) { + return text; } + } + switch (node.kind) { + case 256: + var sourceFile = node; + return ts.isExternalModule(sourceFile) + ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" + : ""; + case 180: + case 220: + case 179: + case 221: + case 192: + if (node.flags & 512) { + return "default"; + } + return getFunctionOrClassName(node); + case 148: + return "constructor"; + case 152: + return "new()"; + case 151: + return "()"; + case 153: + return "[]"; + case 279: + return getJSDocTypedefTagName(node); + default: + ts.Debug.fail(); + return ""; + } + } + function getJSDocTypedefTagName(node) { + if (node.name) { + return node.name.text; + } + else { + var parentNode = node.parent && node.parent.parent; + if (parentNode && parentNode.kind === 200) { + if (parentNode.declarationList.declarations.length > 0) { + var nameIdentifier = parentNode.declarationList.declarations[0].name; + if (nameIdentifier.kind === 69) { + return nameIdentifier.text; + } + } + } + return ""; + } + } + function topLevelItems(root) { + var topLevel = []; + function recur(item) { + if (isTopLevel(item)) { + topLevel.push(item); + if (item.children) { + for (var _i = 0, _a = item.children; _i < _a.length; _i++) { + var child = _a[_i]; + recur(child); + } + } + } + } + recur(root); + return topLevel; + function isTopLevel(item) { + switch (navigationBarNodeKind(item)) { + case 221: + case 192: + case 224: + case 222: + case 225: + case 256: + case 223: + case 279: + return true; + case 148: + case 147: + case 149: + case 150: + return hasSomeImportantChild(item); + case 180: + case 220: + case 179: + return isTopLevelFunctionDeclaration(item); + default: + return false; + } + function isTopLevelFunctionDeclaration(item) { + if (!item.node.body) { + return false; + } + switch (navigationBarNodeKind(item.parent)) { + case 226: + case 256: + case 147: + case 148: + return true; + default: + return hasSomeImportantChild(item); + } + } + function hasSomeImportantChild(item) { + return ts.forEach(item.children, function (child) { + var childKind = navigationBarNodeKind(child); + return childKind !== 218 && childKind !== 169; + }); + } + } + } + var emptyChildItemArray = []; + function convertToTopLevelItem(n) { + return { + text: getItemName(n.node), + kind: nodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, + indent: n.indent, + bolded: false, + grayed: false + }; + function convertToChildItem(n) { return { - text: text, - kind: kind, - kindModifiers: kindModifiers, - spans: spans, - childItems: childItems, - indent: indent, + text: getItemName(n.node), + kind: nodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: emptyChildItemArray, + indent: 0, bolded: false, grayed: false }; } - function createTopLevelItem(node) { - switch (node.kind) { - case 256: - return createSourceFileItem(node); - case 221: - return createClassItem(node); - case 147: - case 148: - return createMemberFunctionLikeItem(node); - case 224: - return createEnumItem(node); - case 222: - return createInterfaceItem(node); - case 225: - return createModuleItem(node); - case 220: - return createFunctionItem(node); - case 223: - return createTypeAliasItem(node); - } - return undefined; - function createModuleItem(node) { - var moduleName = getModuleName(node); - var childItems = getItemsWorker(getChildNodes(getInnermostModule(node).body.statements), createChildItem); - return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createFunctionItem(node) { - if (node.body && node.body.kind === 199) { - var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); - return getNavigationBarItem(!node.name ? "default" : node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); } - return undefined; } - function createTypeAliasItem(node) { - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.typeElement, ts.getNodeModifiers(node), [getNodeSpan(node)], [], getIndent(node)); - } - function createMemberFunctionLikeItem(node) { - if (node.body && node.body.kind === 199) { - var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); - var scriptElementKind = void 0; - var memberFunctionName = void 0; - if (node.kind === 147) { - memberFunctionName = ts.getPropertyNameForPropertyNameNode(node.name); - scriptElementKind = ts.ScriptElementKind.memberFunctionElement; - } - else { - memberFunctionName = "constructor"; - scriptElementKind = ts.ScriptElementKind.constructorImplementationElement; - } - return getNavigationBarItem(memberFunctionName, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - return undefined; - } - function createSourceFileItem(node) { - var childItems = getItemsWorker(getChildNodes(node.statements), createChildItem); - var rootName = ts.isExternalModule(node) - ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(node.fileName)))) + "\"" - : ""; - return getNavigationBarItem(rootName, ts.ScriptElementKind.moduleElement, ts.ScriptElementKindModifier.none, [getNodeSpan(node)], childItems); - } - function createClassItem(node) { - var childItems; - if (node.members) { - var constructor = ts.forEach(node.members, function (member) { - return member.kind === 148 && member; - }); - var nodes = removeDynamicallyNamedProperties(node); - if (constructor) { - ts.addRange(nodes, ts.filter(constructor.parameters, function (p) { return !ts.isBindingPattern(p.name); })); - } - childItems = getItemsWorker(sortNodes(nodes), createChildItem); - } - var nodeName = !node.name ? "default" : node.name.text; - return getNavigationBarItem(nodeName, ts.ScriptElementKind.classElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createEnumItem(node) { - var childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem); - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.enumElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createInterfaceItem(node) { - var childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem); - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.interfaceElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - } - function getModuleName(moduleDeclaration) { - if (ts.isAmbientModule(moduleDeclaration)) { - return getTextOfNode(moduleDeclaration.name); - } - var result = []; - result.push(moduleDeclaration.name.text); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { - moduleDeclaration = moduleDeclaration.body; - result.push(moduleDeclaration.name.text); - } - return result.join("."); - } - function removeComputedProperties(node) { - return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 140; }); - } - function removeDynamicallyNamedProperties(node) { - return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); - } - function getInnermostModule(node) { - while (node.body.kind === 225) { - node = node.body; - } - return node; - } - function getNodeSpan(node) { - return node.kind === 256 - ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); - } - function getTextOfNode(node) { - return ts.getTextOfNodeFromSourceText(sourceFile.text, node); + return spans; } } - NavigationBar.getNavigationBarItems = getNavigationBarItems; - function getJsNavigationBarItems(sourceFile, compilerOptions) { - var anonFnText = ""; - var anonClassText = ""; - var indent = 0; - var rootName = ts.isExternalModule(sourceFile) ? - "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" - : ""; - var sourceFileItem = getNavBarItem(rootName, ts.ScriptElementKind.moduleElement, [getNodeSpan(sourceFile)]); - var topItem = sourceFileItem; - ts.forEachChild(sourceFile, visitNode); - function visitNode(node) { - var newItem = createNavBarItem(node); - if (newItem) { - topItem.childItems.push(newItem); - } - if (node.jsDocComments && node.jsDocComments.length > 0) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - visitNode(jsDocComment); - } - } - if (newItem && (ts.isFunctionLike(node) || ts.isClassLike(node))) { - var lastTop = topItem; - indent++; - topItem = newItem; - ts.forEachChild(node, visitNode); - topItem = lastTop; - indent--; - if (newItem && newItem.text === anonFnText && newItem.childItems.length === 0) { - topItem.childItems.pop(); - } - } - else { - ts.forEachChild(node, visitNode); - } - } - function createNavBarItem(node) { - switch (node.kind) { - case 218: - if (node.parent.parent - .parent.kind !== 256) { - return undefined; + function nodeKind(node) { + switch (node.kind) { + case 256: + return ts.ScriptElementKind.moduleElement; + case 255: + return ts.ScriptElementKind.memberVariableElement; + case 218: + case 169: + var variableDeclarationNode = void 0; + var name_38; + if (node.kind === 169) { + name_38 = node.name; + variableDeclarationNode = node; + while (variableDeclarationNode && variableDeclarationNode.kind !== 218) { + variableDeclarationNode = variableDeclarationNode.parent; } - var varDecl = node; - if (varDecl.initializer && (varDecl.initializer.kind === 179 || - varDecl.initializer.kind === 180 || - varDecl.initializer.kind === 192)) { - return undefined; - } - case 220: - case 221: - case 148: - case 149: - case 150: - var name_37 = node.flags && (node.flags & 512) && !node.name ? "default" : - node.kind === 148 ? "constructor" : - ts.declarationNameToString(node.name); - return getNavBarItem(name_37, getScriptKindForElementKind(node.kind), [getNodeSpan(node)]); - case 179: - case 180: - case 192: - return getDefineModuleItem(node) || getFunctionOrClassExpressionItem(node); - case 147: - var methodDecl = node; - return getNavBarItem(ts.declarationNameToString(methodDecl.name), ts.ScriptElementKind.memberFunctionElement, [getNodeSpan(node)]); - case 235: - return getNavBarItem("default", ts.ScriptElementKind.variableElement, [getNodeSpan(node)]); - case 231: - if (!node.name) { - return undefined; - } - case 234: - case 232: - case 238: - if (node.kind === 238) { - if (!node.parent.parent.moduleSpecifier && !node.propertyName) { - return undefined; - } - } - var decl = node; - if (!decl.name) { - return undefined; - } - var declName = ts.declarationNameToString(decl.name); - return getNavBarItem(declName, ts.ScriptElementKind.constElement, [getNodeSpan(node)]); - case 279: - if (node.name) { - return getNavBarItem(node.name.text, ts.ScriptElementKind.typeElement, [getNodeSpan(node)]); - } - else { - var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 200) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 69) { - return getNavBarItem(nameIdentifier.text, ts.ScriptElementKind.typeElement, [getNodeSpan(node)]); - } - } - } - } - default: - return undefined; - } - } - function getNavBarItem(text, kind, spans, kindModifiers) { - if (kindModifiers === void 0) { kindModifiers = ts.ScriptElementKindModifier.none; } - return { - text: text, kind: kind, kindModifiers: kindModifiers, spans: spans, childItems: [], indent: indent, bolded: false, grayed: false - }; - } - function getDefineModuleItem(node) { - if (node.kind !== 179 && node.kind !== 180) { - return undefined; - } - if (node.parent.kind !== 174) { - return undefined; - } - var callExpr = node.parent; - if (callExpr.expression.kind !== 69 || callExpr.expression.getText() !== "define") { - return undefined; - } - var defaultName = node.getSourceFile().fileName; - if (callExpr.arguments[0].kind === 9) { - defaultName = (callExpr.arguments[0]).text; - } - return getNavBarItem(defaultName, ts.ScriptElementKind.moduleElement, [getNodeSpan(node.parent)]); - } - function getFunctionOrClassExpressionItem(node) { - if (node.kind !== 179 && - node.kind !== 180 && - node.kind !== 192) { - return undefined; - } - var fnExpr = node; - var fnName; - if (fnExpr.name && ts.getFullWidth(fnExpr.name) > 0) { - fnName = ts.declarationNameToString(fnExpr.name); - } - else { - if (fnExpr.parent.kind === 218) { - fnName = ts.declarationNameToString(fnExpr.parent.name); - } - else if (fnExpr.parent.kind === 187 && - fnExpr.parent.operatorToken.kind === 56) { - fnName = fnExpr.parent.left.getText(); - } - else if (fnExpr.parent.kind === 253 && - fnExpr.parent.name) { - fnName = fnExpr.parent.name.getText(); + ts.Debug.assert(!!variableDeclarationNode); } else { - fnName = node.kind === 192 ? anonClassText : anonFnText; + ts.Debug.assert(!ts.isBindingPattern(node.name)); + variableDeclarationNode = node; + name_38 = node.name; } - } - var scriptKind = node.kind === 192 ? ts.ScriptElementKind.classElement : ts.ScriptElementKind.functionElement; - return getNavBarItem(fnName, scriptKind, [getNodeSpan(node)]); - } - function getNodeSpan(node) { - return node.kind === 256 - ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); - } - function getScriptKindForElementKind(kind) { - switch (kind) { - case 218: + if (ts.isConst(variableDeclarationNode)) { + return ts.ScriptElementKind.constElement; + } + else if (ts.isLet(variableDeclarationNode)) { + return ts.ScriptElementKind.letElement; + } + else { return ts.ScriptElementKind.variableElement; - case 220: - return ts.ScriptElementKind.functionElement; - case 221: - return ts.ScriptElementKind.classElement; - case 148: - return ts.ScriptElementKind.constructorImplementationElement; - case 149: - return ts.ScriptElementKind.memberGetAccessorElement; - case 150: - return ts.ScriptElementKind.memberSetAccessorElement; - default: - return "unknown"; - } + } + case 180: + return ts.ScriptElementKind.functionElement; + case 279: + return ts.ScriptElementKind.typeElement; + default: + return ts.getNodeKind(node); } - return sourceFileItem.childItems; } - NavigationBar.getJsNavigationBarItems = getJsNavigationBarItems; + function getModuleName(moduleDeclaration) { + if (ts.isAmbientModule(moduleDeclaration)) { + return ts.getTextOfNode(moduleDeclaration.name); + } + var result = []; + result.push(moduleDeclaration.name.text); + while (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { + moduleDeclaration = moduleDeclaration.body; + result.push(moduleDeclaration.name.text); + } + return result.join("."); + } + function getInteriorModule(decl) { + return decl.body.kind === 225 ? getInteriorModule(decl.body) : decl; + } + function isComputedProperty(member) { + return !member.name || member.name.kind === 140; + } + function getNodeSpan(node) { + return node.kind === 256 + ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) + : ts.createTextSpanFromBounds(node.getStart(curSourceFile), node.getEnd()); + } + function getFunctionOrClassName(node) { + if (node.name && ts.getFullWidth(node.name) > 0) { + return ts.declarationNameToString(node.name); + } + else if (node.parent.kind === 218) { + return ts.declarationNameToString(node.parent.name); + } + else if (node.parent.kind === 187 && + node.parent.operatorToken.kind === 56) { + return nodeText(node.parent.left); + } + else if (node.parent.kind === 253 && node.parent.name) { + return nodeText(node.parent.name); + } + else if (node.flags & 512) { + return "default"; + } + else { + return ts.isClassLike(node) ? "" : ""; + } + } + function isFunctionOrClassExpression(node) { + return node.kind === 179 || node.kind === 180 || node.kind === 192; + } })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); var ts; @@ -40372,9 +40989,9 @@ var ts; getTypingNamesFromNodeModuleFolder(nodeModulesPath); } getTypingNamesFromSourceFileNames(fileNames); - for (var name_38 in packageNameToTypingLocation) { - if (ts.hasProperty(inferredTypings, name_38) && !inferredTypings[name_38]) { - inferredTypings[name_38] = packageNameToTypingLocation[name_38]; + for (var name_39 in packageNameToTypingLocation) { + if (ts.hasProperty(inferredTypings, name_39) && !inferredTypings[name_39]) { + inferredTypings[name_39] = packageNameToTypingLocation[name_39]; } } for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { @@ -40442,9 +41059,9 @@ var ts; return; } var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, "*.json", undefined, 2); - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; + var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], undefined, undefined, 2); + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); if (ts.getBaseFileName(normalizedFileName) !== "package.json") { continue; @@ -41032,9 +41649,9 @@ var ts; } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_39 in o) { - if (o[name_39] === rule) { - return name_39; + for (var name_40 in o) { + if (o[name_40] === rule) { + return name_40; } } throw new Error("Unknown rule"); @@ -42880,8 +43497,8 @@ var ts; var list = createNode(282, nodes.pos, nodes.end, 0, this); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { - var node = nodes_7[_i]; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; if (pos < node.pos) { pos = this.addSyntheticNodes(list._children, pos, node.pos); } @@ -43007,7 +43624,7 @@ var ts; } addCommentParts(declaration.parent, sourceFileOfDeclaration, getCleanedParamJsDocComment); } - if (declaration.kind === 225 && declaration.body.kind === 225) { + if (declaration.kind === 225 && declaration.body && declaration.body.kind === 225) { return; } if ((declaration.kind === 179 || declaration.kind === 180) && @@ -43706,9 +44323,9 @@ var ts; sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - var commandLineOptions_stringToEnum; + var commandLineOptionsStringToEnum; function fixupCompilerOptions(options, diagnostics) { - commandLineOptions_stringToEnum = commandLineOptions_stringToEnum || ts.filter(ts.optionDeclarations, function (o) { + commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachValue(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); @@ -43726,8 +44343,8 @@ var ts; } } }; - for (var _i = 0, commandLineOptions_stringToEnum_1 = commandLineOptions_stringToEnum; _i < commandLineOptions_stringToEnum_1.length; _i++) { - var opt = commandLineOptions_stringToEnum_1[_i]; + for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { + var opt = commandLineOptionsStringToEnum_1[_i]; _loop_2(opt); } return options; @@ -43739,6 +44356,16 @@ var ts; options.suppressOutputPathCheck = true; options.allowNonTsExtensions = true; options.noLib = true; + options.lib = undefined; + options.types = undefined; + options.noEmit = undefined; + options.noEmitOnError = undefined; + options.paths = undefined; + options.rootDirs = undefined; + options.declaration = undefined; + options.declarationDir = undefined; + options.out = undefined; + options.outFile = undefined; options.noResolve = true; var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); var sourceFile = ts.createSourceFile(inputFileName, input, options.target); @@ -43768,7 +44395,8 @@ var ts; getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, readFile: function (fileName) { return ""; }, - directoryExists: function (directoryExists) { return true; } + directoryExists: function (directoryExists) { return true; }, + getDirectories: function (path) { return []; } }; var program = ts.createProgram([inputFileName], options, compilerHost); if (transpileOptions.reportDiagnostics) { @@ -43837,7 +44465,7 @@ var ts; var buckets = {}; var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyForCompilationSettings(settings) { - return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + settings.typesRoot + "|" + settings.typesSearchPaths + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); + return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = ts.lookUp(buckets, key); @@ -44487,7 +45115,8 @@ var ts; oldSettings.moduleResolution !== newSettings.moduleResolution || oldSettings.noResolve !== newSettings.noResolve || oldSettings.jsx !== newSettings.jsx || - oldSettings.allowJs !== newSettings.allowJs); + oldSettings.allowJs !== newSettings.allowJs || + oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit); var compilerHost = { getSourceFile: getOrCreateSourceFile, getSourceFileByPath: getOrCreateSourceFileByPath, @@ -44507,8 +45136,10 @@ var ts; return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); }, directoryExists: function (directoryName) { - ts.Debug.assert(!host.resolveModuleNames || !host.resolveTypeReferenceDirectives); return ts.directoryProbablyExists(directoryName, host); + }, + getDirectories: function (path) { + return host.getDirectories ? host.getDirectories(path) : []; } }; if (host.trace) { @@ -45164,8 +45795,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_40 = element.propertyName || element.name; - existingImportsOrExports[name_40.text] = true; + var name_41 = element.propertyName || element.name; + existingImportsOrExports[name_41.text] = true; } if (ts.isEmpty(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); @@ -45260,13 +45891,13 @@ var ts; var entries = []; var target = program.getCompilerOptions().target; var nameTable = getNameTable(sourceFile); - for (var name_41 in nameTable) { - if (nameTable[name_41] === position) { + for (var name_42 in nameTable) { + if (nameTable[name_42] === position) { continue; } - if (!uniqueNames[name_41]) { - uniqueNames[name_41] = name_41; - var displayName = getCompletionEntryDisplayName(name_41, target, true); + if (!uniqueNames[name_42]) { + uniqueNames[name_42] = name_42; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_42), target, true); if (displayName) { var entry = { name: displayName, @@ -45370,10 +46001,10 @@ var ts; var typeChecker = program.getTypeChecker(); var type = typeChecker.getContextualType(node); if (type) { - var entries_1 = []; - addStringLiteralCompletionsFromType(type, entries_1); - if (entries_1.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_1 }; + var entries_2 = []; + addStringLiteralCompletionsFromType(type, entries_2); + if (entries_2.length) { + return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -46572,7 +47203,8 @@ var ts; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference + isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference, + isDefinition: false }); } } @@ -46853,7 +47485,8 @@ var ts; references: [{ fileName: sourceFile.fileName, textSpan: ts.createTextSpan(position, searchText.length), - isWriteAccess: false + isWriteAccess: false, + isDefinition: false }] }); } @@ -47231,7 +47864,8 @@ var ts; return { fileName: node.getSourceFile().fileName, textSpan: ts.createTextSpanFromBounds(start, end), - isWriteAccess: isWriteAccess(node) + isWriteAccess: isWriteAccess(node), + isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node) }; } function isWriteAccess(node) { @@ -47452,7 +48086,7 @@ var ts; } function getNavigationBarItems(fileName) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile, host.getCompilationSettings()); + return ts.NavigationBar.getNavigationBarItems(sourceFile); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); @@ -47831,7 +48465,8 @@ var ts; return; case 142: if (token.parent.name === token) { - return 17; + var isThis = token.kind === 69 && token.originalKeywordKind === 97; + return isThis ? 3 : 17; } return; } @@ -49028,7 +49663,7 @@ var ts; Session.prototype.getDefinition = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49046,7 +49681,7 @@ var ts; Session.prototype.getTypeDefinition = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49064,7 +49699,7 @@ var ts; Session.prototype.getOccurrences = function (line, offset, fileName) { fileName = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(fileName); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49088,7 +49723,7 @@ var ts; Session.prototype.getDocumentHighlights = function (line, offset, fileName, filesToSearch) { fileName = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(fileName); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49115,8 +49750,12 @@ var ts; Session.prototype.getProjectInfo = function (fileName, needFileNameList) { fileName = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(fileName); + if (!project) { + throw Errors.NoProject; + } var projectInfo = { - configFileName: project.projectFilename + configFileName: project.projectFilename, + languageServiceDisabled: project.languageServiceDiabled }; if (needFileNameList) { projectInfo.fileNames = project.getFileNames(); @@ -49127,10 +49766,11 @@ var ts; var file = ts.normalizePath(fileName); var info = this.projectService.getScriptInfo(file); var projects = this.projectService.findReferencingProjects(info); - if (!projects.length) { + var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); + if (projectsWithLanguageServiceEnabeld.length === 0) { throw Errors.NoProject; } - var defaultProject = projects[0]; + var defaultProject = projectsWithLanguageServiceEnabeld[0]; var defaultProjectCompilerService = defaultProject.compilerService; var position = defaultProjectCompilerService.host.lineOffsetToPosition(file, line, offset); var renameInfo = defaultProjectCompilerService.languageService.getRenameInfo(file, position); @@ -49143,7 +49783,7 @@ var ts; locs: [] }; } - var fileSpans = server.combineProjectOutput(projects, function (project) { + var fileSpans = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { var compilerService = project.compilerService; var renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments); if (!renameLocations) { @@ -49195,10 +49835,11 @@ var ts; var file = ts.normalizePath(fileName); var info = this.projectService.getScriptInfo(file); var projects = this.projectService.findReferencingProjects(info); - if (!projects.length) { + var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); + if (projectsWithLanguageServiceEnabeld.length === 0) { throw Errors.NoProject; } - var defaultProject = projects[0]; + var defaultProject = projectsWithLanguageServiceEnabeld[0]; var position = defaultProject.compilerService.host.lineOffsetToPosition(file, line, offset); var nameInfo = defaultProject.compilerService.languageService.getQuickInfoAtPosition(file, position); if (!nameInfo) { @@ -49208,7 +49849,7 @@ var ts; var nameSpan = nameInfo.textSpan; var nameColStart = defaultProject.compilerService.host.positionToLineOffset(file, nameSpan.start).offset; var nameText = defaultProject.compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan)); - var refs = server.combineProjectOutput(projects, function (project) { + var refs = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { var compilerService = project.compilerService; var references = compilerService.languageService.getReferencesAtPosition(file, position); if (!references) { @@ -49224,7 +49865,8 @@ var ts; start: start, lineText: lineText, end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)), - isWriteAccess: ref.isWriteAccess + isWriteAccess: ref.isWriteAccess, + isDefinition: ref.isDefinition }; }); }, compareFileStart, areReferencesResponseItemsForTheSameLocation); @@ -49253,7 +49895,7 @@ var ts; Session.prototype.getQuickInfo = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49276,7 +49918,7 @@ var ts; Session.prototype.getFormattingEditsForRange = function (line, offset, endLine, endOffset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49297,7 +49939,7 @@ var ts; Session.prototype.getFormattingEditsAfterKeystroke = function (line, offset, key, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49360,7 +50002,7 @@ var ts; } var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49379,7 +50021,7 @@ var ts; Session.prototype.getCompletionEntryDetails = function (line, offset, entryNames, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49395,7 +50037,7 @@ var ts; Session.prototype.getSignatureHelpItems = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49422,7 +50064,7 @@ var ts; var checkList = fileNames.reduce(function (accum, fileName) { fileName = ts.normalizePath(fileName); var project = _this.projectService.getProjectForFile(fileName); - if (project) { + if (project && !project.languageServiceDiabled) { accum.push({ fileName: fileName, project: project }); } return accum; @@ -49435,7 +50077,7 @@ var ts; var _this = this; var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (project) { + if (project && !project.languageServiceDiabled) { var compilerService = project.compilerService; var start = compilerService.host.lineOffsetToPosition(file, line, offset); var end = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); @@ -49452,7 +50094,7 @@ var ts; var file = ts.normalizePath(fileName); var tmpfile = ts.normalizePath(tempFileName); var project = this.projectService.getProjectForFile(file); - if (project) { + if (project && !project.languageServiceDiabled) { this.changeSeq++; project.compilerService.host.reloadScript(file, tmpfile, function () { _this.output(undefined, CommandNames.Reload, reqSeq); @@ -49463,7 +50105,7 @@ var ts; var file = ts.normalizePath(fileName); var tmpfile = ts.normalizePath(tempFileName); var project = this.projectService.getProjectForFile(file); - if (project) { + if (project && !project.languageServiceDiabled) { project.compilerService.host.saveTo(file, tmpfile); } }; @@ -49474,7 +50116,7 @@ var ts; var file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); }; - Session.prototype.decorateNavigationBarItem = function (project, fileName, items) { + Session.prototype.decorateNavigationBarItem = function (project, fileName, items, lineIndex) { var _this = this; if (!items) { return undefined; @@ -49485,17 +50127,17 @@ var ts; kind: item.kind, kindModifiers: item.kindModifiers, spans: item.spans.map(function (span) { return ({ - start: compilerService.host.positionToLineOffset(fileName, span.start), - end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span)) + start: compilerService.host.positionToLineOffset(fileName, span.start, lineIndex), + end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span), lineIndex) }); }), - childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems), + childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems, lineIndex), indent: item.indent }); }); }; Session.prototype.getNavigationBarItems = function (fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49503,17 +50145,17 @@ var ts; if (!items) { return undefined; } - return this.decorateNavigationBarItem(project, fileName, items); + return this.decorateNavigationBarItem(project, fileName, items, compilerService.host.getLineIndex(fileName)); }; Session.prototype.getNavigateToItems = function (searchValue, fileName, maxResultCount) { var file = ts.normalizePath(fileName); var info = this.projectService.getScriptInfo(file); var projects = this.projectService.findReferencingProjects(info); - var defaultProject = projects[0]; - if (!defaultProject) { + var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); + if (projectsWithLanguageServiceEnabeld.length === 0) { throw Errors.NoProject; } - var allNavToItems = server.combineProjectOutput(projects, function (project) { + var allNavToItems = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { var compilerService = project.compilerService; var navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount); if (!navItems) { @@ -49557,7 +50199,7 @@ var ts; Session.prototype.getBraceMatching = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49573,7 +50215,10 @@ var ts; }; Session.prototype.getDiagnosticsForProject = function (delay, fileName) { var _this = this; - var fileNames = this.getProjectInfo(fileName, true).fileNames; + var _a = this.getProjectInfo(fileName, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; + if (languageServiceDisabled) { + return; + } var fileNamesInProject = fileNames.filter(function (value, index, array) { return value.indexOf("lib.d.ts") < 0; }); var highPriorityFiles = []; var mediumPriorityFiles = []; @@ -49683,6 +50328,7 @@ var ts; } }); } + server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; var ScriptInfo = (function () { function ScriptInfo(host, fileName, content, isOpen) { if (isOpen === void 0) { isOpen = false; } @@ -49752,17 +50398,17 @@ var ts; var resolvedModules = []; var compilerOptions = this.getCompilationSettings(); for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_42 = names_2[_i]; - var resolution = ts.lookUp(newResolutions, name_42); + var name_43 = names_2[_i]; + var resolution = ts.lookUp(newResolutions, name_43); if (!resolution) { - var existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, name_42); + var existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, name_43); if (moduleResolutionIsValid(existingResolution)) { resolution = existingResolution; } else { - resolution = loader(name_42, containingFile, compilerOptions, this.moduleResolutionHost); + resolution = loader(name_43, containingFile, compilerOptions, this.moduleResolutionHost); resolution.lastCheckTime = Date.now(); - newResolutions[name_42] = resolution; + newResolutions[name_43] = resolution; } } ts.Debug.assert(resolution !== undefined); @@ -49898,6 +50544,9 @@ var ts; LSHost.prototype.directoryExists = function (path) { return this.host.directoryExists(path); }; + LSHost.prototype.getDirectories = function (path) { + return this.host.getDirectories(path); + }; LSHost.prototype.lineToTextSpan = function (filename, line) { var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); var script = this.filenameToScript.get(path); @@ -49920,20 +50569,25 @@ var ts; var lineInfo = index.lineNumberToInfo(line); return (lineInfo.offset + offset - 1); }; - LSHost.prototype.positionToLineOffset = function (filename, position) { + LSHost.prototype.positionToLineOffset = function (filename, position, lineIndex) { + lineIndex = lineIndex || this.getLineIndex(filename); + var lineOffset = lineIndex.charOffsetToLineNumberAndPos(position); + return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + }; + LSHost.prototype.getLineIndex = function (filename) { var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); var script = this.filenameToScript.get(path); - var index = script.snap().index; - var lineOffset = index.charOffsetToLineNumberAndPos(position); - return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + return script.snap().index; }; return LSHost; }()); server.LSHost = LSHost; var Project = (function () { - function Project(projectService, projectOptions) { + function Project(projectService, projectOptions, languageServiceDiabled) { + if (languageServiceDiabled === void 0) { languageServiceDiabled = false; } this.projectService = projectService; this.projectOptions = projectOptions; + this.languageServiceDiabled = languageServiceDiabled; this.directoriesWatchedForTsconfig = []; this.filenameToSourceFile = {}; this.updateGraphSeq = 0; @@ -49941,8 +50595,19 @@ var ts; if (projectOptions && projectOptions.files) { projectOptions.compilerOptions.allowNonTsExtensions = true; } - this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions); + if (!languageServiceDiabled) { + this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions); + } } + Project.prototype.enableLanguageService = function () { + if (this.languageServiceDiabled) { + this.compilerService = new CompilerService(this, this.projectOptions && this.projectOptions.compilerOptions); + } + this.languageServiceDiabled = false; + }; + Project.prototype.disableLanguageService = function () { + this.languageServiceDiabled = true; + }; Project.prototype.addOpenRef = function () { this.openRefCount++; }; @@ -49954,16 +50619,36 @@ var ts; return this.projectService.openFile(filename, false); }; Project.prototype.getRootFiles = function () { + if (this.languageServiceDiabled) { + return this.projectOptions ? this.projectOptions.files : undefined; + } return this.compilerService.host.roots.map(function (info) { return info.fileName; }); }; Project.prototype.getFileNames = function () { + if (this.languageServiceDiabled) { + if (!this.projectOptions) { + return undefined; + } + var fileNames = []; + if (this.projectOptions && this.projectOptions.compilerOptions) { + fileNames.push(ts.getDefaultLibFilePath(this.projectOptions.compilerOptions)); + } + ts.addRange(fileNames, this.projectOptions.files); + return fileNames; + } var sourceFiles = this.program.getSourceFiles(); return sourceFiles.map(function (sourceFile) { return sourceFile.fileName; }); }; Project.prototype.getSourceFile = function (info) { + if (this.languageServiceDiabled) { + return undefined; + } return this.filenameToSourceFile[info.fileName]; }; Project.prototype.getSourceFileFromName = function (filename, requireOpen) { + if (this.languageServiceDiabled) { + return undefined; + } var info = this.projectService.getScriptInfo(filename); if (info) { if ((!requireOpen) || info.isOpen) { @@ -49972,13 +50657,22 @@ var ts; } }; Project.prototype.isRoot = function (info) { + if (this.languageServiceDiabled) { + return undefined; + } return this.compilerService.host.roots.some(function (root) { return root === info; }); }; Project.prototype.removeReferencedFile = function (info) { + if (this.languageServiceDiabled) { + return; + } this.compilerService.host.removeReferencedFile(info); this.updateGraph(); }; Project.prototype.updateFileMap = function () { + if (this.languageServiceDiabled) { + return; + } this.filenameToSourceFile = {}; var sourceFiles = this.program.getSourceFiles(); for (var i = 0, len = sourceFiles.length; i < len; i++) { @@ -49987,10 +50681,16 @@ var ts; } }; Project.prototype.finishGraph = function () { + if (this.languageServiceDiabled) { + return; + } this.updateGraph(); this.compilerService.languageService.getNavigateToItems(".*"); }; Project.prototype.updateGraph = function () { + if (this.languageServiceDiabled) { + return; + } this.program = this.compilerService.languageService.getProgram(); this.updateFileMap(); }; @@ -49998,12 +50698,25 @@ var ts; return this.projectFilename; }; Project.prototype.addRoot = function (info) { + if (this.languageServiceDiabled) { + return; + } this.compilerService.host.addRoot(info); }; Project.prototype.removeRoot = function (info) { + if (this.languageServiceDiabled) { + return; + } this.compilerService.host.removeRoot(info); }; Project.prototype.filesToString = function () { + if (this.languageServiceDiabled) { + if (this.projectOptions) { + var strBuilder_1 = ""; + ts.forEach(this.projectOptions.files, function (file) { strBuilder_1 += file + "\n"; }); + return strBuilder_1; + } + } var strBuilder = ""; ts.forEachValue(this.filenameToSourceFile, function (sourceFile) { strBuilder += sourceFile.fileName + "\n"; }); return strBuilder; @@ -50012,7 +50725,9 @@ var ts; this.projectOptions = projectOptions; if (projectOptions.compilerOptions) { projectOptions.compilerOptions.allowNonTsExtensions = true; - this.compilerService.setCompilerOptions(projectOptions.compilerOptions); + if (!this.languageServiceDiabled) { + this.compilerService.setCompilerOptions(projectOptions.compilerOptions); + } } }; return Project; @@ -50222,6 +50937,8 @@ var ts; if (project.isConfiguredProject()) { project.projectFileWatcher.close(); project.directoryWatcher.close(); + ts.forEachValue(project.directoriesWatchedForWildcards, function (watcher) { watcher.close(); }); + delete project.directoriesWatchedForWildcards; this.configuredProjects = copyListRemovingItem(project, this.configuredProjects); } else { @@ -50237,8 +50954,8 @@ var ts; this.inferredProjects = copyListRemovingItem(project, this.inferredProjects); } var fileNames = project.getFileNames(); - for (var _b = 0, fileNames_2 = fileNames; _b < fileNames_2.length; _b++) { - var fileName = fileNames_2[_b]; + for (var _b = 0, fileNames_3 = fileNames; _b < fileNames_3.length; _b++) { + var fileName = fileNames_3[_b]; var info = this.getScriptInfo(fileName); if (info.defaultProject == project) { info.defaultProject = undefined; @@ -50263,6 +50980,7 @@ var ts; else { this.findReferencingProjects(info); if (info.defaultProject) { + info.defaultProject.addOpenRef(); this.openFilesReferenced.push(info); } else { @@ -50615,12 +51333,30 @@ var ts; else { var projectOptions = { files: parsedCommandLine.fileNames, + wildcardDirectories: parsedCommandLine.wildcardDirectories, compilerOptions: parsedCommandLine.options }; return { succeeded: true, projectOptions: projectOptions }; } } }; + ProjectService.prototype.exceedTotalNonTsFileSizeLimit = function (fileNames) { + var totalNonTsFileSize = 0; + if (!this.host.getFileSize) { + return false; + } + for (var _i = 0, fileNames_4 = fileNames; _i < fileNames_4.length; _i++) { + var fileName = fileNames_4[_i]; + if (ts.hasTypeScriptFileExtension(fileName)) { + continue; + } + totalNonTsFileSize += this.host.getFileSize(fileName); + if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { + return true; + } + } + return false; + }; ProjectService.prototype.openConfigFile = function (configFilename, clientFileName) { var _this = this; var _a = this.configFileToProjectOptions(configFilename), succeeded = _a.succeeded, projectOptions = _a.projectOptions, errors = _a.errors; @@ -50628,23 +51364,39 @@ var ts; return { success: false, errors: errors }; } else { - var project_1 = this.createProject(configFilename, projectOptions); + if (!projectOptions.compilerOptions.disableSizeLimit && projectOptions.compilerOptions.allowJs) { + if (this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { + var project_1 = this.createProject(configFilename, projectOptions, true); + project_1.projectFileWatcher = this.host.watchFile(ts.toPath(configFilename, configFilename, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); + return { success: true, project: project_1 }; + } + } + var project_2 = this.createProject(configFilename, projectOptions); var errors_1; for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { var rootFilename = _b[_i]; if (this.host.fileExists(rootFilename)) { var info = this.openFile(rootFilename, clientFileName == rootFilename); - project_1.addRoot(info); + project_2.addRoot(info); } else { (errors_1 || (errors_1 = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, rootFilename)); } } - project_1.finishGraph(); - project_1.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); - this.log("Add recursive watcher for: " + ts.getDirectoryPath(configFilename)); - project_1.directoryWatcher = this.host.watchDirectory(ts.getDirectoryPath(configFilename), function (path) { return _this.directoryWatchedForSourceFilesChanged(project_1, path); }, true); - return { success: true, project: project_1, errors: errors_1 }; + project_2.finishGraph(); + project_2.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project_2); }); + var configDirectoryPath_1 = ts.getDirectoryPath(configFilename); + this.log("Add recursive watcher for: " + configDirectoryPath_1); + project_2.directoryWatcher = this.host.watchDirectory(configDirectoryPath_1, function (path) { return _this.directoryWatchedForSourceFilesChanged(project_2, path); }, true); + project_2.directoriesWatchedForWildcards = ts.reduceProperties(projectOptions.wildcardDirectories, function (watchers, flag, directory) { + if (ts.comparePaths(configDirectoryPath_1, directory, ".", !_this.host.useCaseSensitiveFileNames) !== 0) { + var recursive = (flag & 1) !== 0; + _this.log("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); + watchers[directory] = _this.host.watchDirectory(directory, function (path) { return _this.directoryWatchedForSourceFilesChanged(project_2, path); }, recursive); + } + return watchers; + }, {}); + return { success: true, project: project_2, errors: errors_1 }; } }; ProjectService.prototype.updateConfiguredProject = function (project) { @@ -50659,19 +51411,45 @@ var ts; return errors; } else { - var oldFileNames_1 = project.compilerService.host.roots.map(function (info) { return info.fileName; }); + if (projectOptions.compilerOptions && !projectOptions.compilerOptions.disableSizeLimit && this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { + project.setProjectOptions(projectOptions); + if (project.languageServiceDiabled) { + return; + } + project.disableLanguageService(); + if (project.directoryWatcher) { + project.directoryWatcher.close(); + project.directoryWatcher = undefined; + } + return; + } + if (project.languageServiceDiabled) { + project.setProjectOptions(projectOptions); + project.enableLanguageService(); + project.directoryWatcher = this.host.watchDirectory(ts.getDirectoryPath(project.projectFilename), function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); + for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { + var rootFilename = _b[_i]; + if (this.host.fileExists(rootFilename)) { + var info = this.openFile(rootFilename, false); + project.addRoot(info); + } + } + project.finishGraph(); + return; + } + var oldFileNames_1 = project.projectOptions ? project.projectOptions.files : project.compilerService.host.roots.map(function (info) { return info.fileName; }); var newFileNames_1 = ts.filter(projectOptions.files, function (f) { return _this.host.fileExists(f); }); var fileNamesToRemove = oldFileNames_1.filter(function (f) { return newFileNames_1.indexOf(f) < 0; }); var fileNamesToAdd = newFileNames_1.filter(function (f) { return oldFileNames_1.indexOf(f) < 0; }); - for (var _i = 0, fileNamesToRemove_1 = fileNamesToRemove; _i < fileNamesToRemove_1.length; _i++) { - var fileName = fileNamesToRemove_1[_i]; + for (var _c = 0, fileNamesToRemove_1 = fileNamesToRemove; _c < fileNamesToRemove_1.length; _c++) { + var fileName = fileNamesToRemove_1[_c]; var info = this.getScriptInfo(fileName); if (info) { project.removeRoot(info); } } - for (var _b = 0, fileNamesToAdd_1 = fileNamesToAdd; _b < fileNamesToAdd_1.length; _b++) { - var fileName = fileNamesToAdd_1[_b]; + for (var _d = 0, fileNamesToAdd_1 = fileNamesToAdd; _d < fileNamesToAdd_1.length; _d++) { + var fileName = fileNamesToAdd_1[_d]; var info = this.getScriptInfo(fileName); if (!info) { info = this.openFile(fileName, false); @@ -50698,8 +51476,8 @@ var ts; } } }; - ProjectService.prototype.createProject = function (projectFilename, projectOptions) { - var project = new Project(this, projectOptions); + ProjectService.prototype.createProject = function (projectFilename, projectOptions, languageServiceDisabled) { + var project = new Project(this, projectOptions, languageServiceDisabled); project.projectFilename = projectFilename; return project; }; @@ -51986,6 +52764,7 @@ var ts; function CoreServicesShimHostAdapter(shimHost) { var _this = this; this.shimHost = shimHost; + this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; if ("directoryExists" in this.shimHost) { this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; } @@ -51993,15 +52772,24 @@ var ts; this.realpath = function (path) { return _this.shimHost.realpath(path); }; } } - CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extension, exclude, depth) { - var encoded; + CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { try { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude), depth); + var pattern = ts.getFileMatcherPatterns(rootDir, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); } catch (e) { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); + var results = []; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + for (var _a = 0, _b = this.readDirectoryFallback(rootDir, extension, exclude); _a < _b.length; _a++) { + var file = _b[_a]; + if (!ts.contains(results, file)) { + results.push(file); + } + } + } + return results; } - return JSON.parse(encoded); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { return this.shimHost.fileExists(fileName); @@ -52009,6 +52797,9 @@ var ts; CoreServicesShimHostAdapter.prototype.readFile = function (fileName) { return this.shimHost.readFile(fileName); }; + CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { + return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); + }; return CoreServicesShimHostAdapter; }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index e8eae372528..aef7909bd45 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -704,7 +704,6 @@ declare namespace ts { } interface PropertyAccessExpression extends MemberExpression, Declaration { expression: LeftHandSideExpression; - dotToken: Node; name: Identifier; } type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression; @@ -835,6 +834,7 @@ declare namespace ts { interface SwitchStatement extends Statement { expression: Expression; caseBlock: CaseBlock; + possiblyExhaustive?: boolean; } interface CaseBlock extends Node { clauses: NodeArray; @@ -910,7 +910,7 @@ declare namespace ts { type ModuleBody = ModuleBlock | ModuleDeclaration; interface ModuleDeclaration extends DeclarationStatement { name: Identifier | LiteralExpression; - body: ModuleBlock | ModuleDeclaration; + body?: ModuleBlock | ModuleDeclaration; } interface ModuleBlock extends Node, Statement { statements: NodeArray; @@ -1066,8 +1066,9 @@ declare namespace ts { Assignment = 16, TrueCondition = 32, FalseCondition = 64, - Referenced = 128, - Shared = 256, + SwitchClause = 128, + Referenced = 256, + Shared = 512, Label = 12, Condition = 96, } @@ -1089,6 +1090,12 @@ declare namespace ts { expression: Expression; antecedent: FlowNode; } + interface FlowSwitchClause extends FlowNode { + switchStatement: SwitchStatement; + clauseStart: number; + clauseEnd: number; + antecedent: FlowNode; + } interface AmdDependency { path: string; name: string; @@ -1132,7 +1139,9 @@ declare namespace ts { getCurrentDirectory(): string; } interface ParseConfigHost { - readDirectory(rootDir: string, extension: string, exclude: string[]): string[]; + useCaseSensitiveFileNames: boolean; + readDirectory(rootDir: string, extensions: string[], excludes: string[], includes: string[]): string[]; + fileExists(path: string): boolean; } interface WriteFileCallback { (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void; @@ -1504,6 +1513,7 @@ declare namespace ts { resolvedJsxType?: Type; hasSuperCall?: boolean; superCall?: ExpressionStatement; + switchTypes?: Type[]; } const enum TypeFlags { Any = 1, @@ -1535,7 +1545,7 @@ declare namespace ts { ObjectLiteralPatternWithComputedProperties = 67108864, Never = 134217728, Nullable = 96, - Falsy = 126, + Falsy = 112, Intrinsic = 150995071, Primitive = 16777726, StringLike = 258, @@ -1772,8 +1782,9 @@ declare namespace ts { suppressOutputPathCheck?: boolean; target?: ScriptTarget; traceResolution?: boolean; + disableSizeLimit?: boolean; types?: string[]; - typesRoot?: string; + typeRoots?: string[]; typesSearchPaths?: string[]; version?: boolean; watch?: boolean; @@ -1843,6 +1854,15 @@ declare namespace ts { fileNames: string[]; raw?: any; errors: Diagnostic[]; + wildcardDirectories?: Map; + } + const enum WatchDirectoryFlags { + None = 0, + Recursive = 1, + } + interface ExpandResult { + fileNames: string[]; + wildcardDirectories: Map; } interface CommandLineOptionBase { name: string; @@ -2027,6 +2047,7 @@ declare namespace ts { getDefaultTypeDirectiveNames?(rootPath: string): string[]; writeFile: WriteFileCallback; getCurrentDirectory(): string; + getDirectories(path: string): string[]; getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; @@ -2068,8 +2089,10 @@ declare namespace ts { function forEach(array: T[], callback: (element: T, index: number) => U): U; function contains(array: T[], value: T, areEqual?: (a: T, b: T) => boolean): boolean; function indexOf(array: T[], value: T): number; + function indexOfAnyCharCode(text: string, charCodes: number[], start?: number): number; function countWhere(array: T[], predicate: (x: T) => boolean): number; function filter(array: T[], f: (x: T) => boolean): T[]; + function filterMutate(array: T[], f: (x: T) => boolean): void; function map(array: T[], f: (x: T) => U): U[]; function concatenate(array1: T[], array2: T[]): T[]; function deduplicate(array: T[], areEqual?: (a: T, b: T) => boolean): T[]; @@ -2104,6 +2127,8 @@ declare namespace ts { function chainDiagnosticMessages(details: DiagnosticMessageChain, message: DiagnosticMessage, ...args: any[]): DiagnosticMessageChain; function concatenateDiagnosticMessageChains(headChain: DiagnosticMessageChain, tailChain: DiagnosticMessageChain): DiagnosticMessageChain; function compareValues(a: T, b: T): Comparison; + function compareStrings(a: string, b: string, ignoreCase?: boolean): Comparison; + function compareStringsCaseInsensitive(a: string, b: string): Comparison; function compareDiagnostics(d1: Diagnostic, d2: Diagnostic): Comparison; function sortAndDeduplicateDiagnostics(diagnostics: Diagnostic[]): Diagnostic[]; function deduplicateSortedDiagnostics(diagnostics: Diagnostic[]): Diagnostic[]; @@ -2121,16 +2146,45 @@ declare namespace ts { function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: (fileName: string) => string, isAbsolutePathAnUrl: boolean): string; function getBaseFileName(path: string): string; function combinePaths(path1: string, path2: string): string; + function removeTrailingDirectorySeparator(path: string): string; + function ensureTrailingDirectorySeparator(path: string): string; + function comparePaths(a: string, b: string, currentDirectory: string, ignoreCase?: boolean): Comparison; + function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean): boolean; function fileExtensionIs(path: string, extension: string): boolean; + function fileExtensionIsAny(path: string, extensions: string[]): boolean; + function getRegularExpressionForWildcard(specs: string[], basePath: string, usage: "files" | "directories" | "exclude"): string; + interface FileSystemEntries { + files: string[]; + directories: string[]; + } + interface FileMatcherPatterns { + includeFilePattern: string; + includeDirectoryPattern: string; + excludePattern: string; + basePaths: string[]; + } + function getFileMatcherPatterns(path: string, extensions: string[], excludes: string[], includes: string[], useCaseSensitiveFileNames: boolean, currentDirectory: string): FileMatcherPatterns; + function matchFiles(path: string, extensions: string[], excludes: string[], includes: string[], useCaseSensitiveFileNames: boolean, currentDirectory: string, getFileSystemEntries: (path: string) => FileSystemEntries): string[]; function ensureScriptKind(fileName: string, scriptKind?: ScriptKind): ScriptKind; function getScriptKindFromFileName(fileName: string): ScriptKind; const supportedTypeScriptExtensions: string[]; const supportedJavascriptExtensions: string[]; function getSupportedExtensions(options?: CompilerOptions): string[]; function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions): boolean; + const enum ExtensionPriority { + TypeScriptFiles = 0, + DeclarationAndJavaScriptFiles = 2, + Limit = 5, + Highest = 0, + Lowest = 2, + } + function getExtensionPriority(path: string, supportedExtensions: string[]): ExtensionPriority; + function adjustExtensionPriority(extensionPriority: ExtensionPriority): ExtensionPriority; + function getNextLowestExtensionPriority(extensionPriority: ExtensionPriority): ExtensionPriority; function removeFileExtension(path: string): string; function tryRemoveExtension(path: string, extension: string): string; function isJsxOrTsxExtension(ext: string): boolean; + function changeExtension(path: T, newExtension: string): T; interface ObjectAllocator { getNodeConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Node; getSourceFileConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => SourceFile; @@ -2167,6 +2221,7 @@ declare namespace ts { useCaseSensitiveFileNames: boolean; write(s: string): void; readFile(path: string, encoding?: string): string; + getFileSize?(path: string): number; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; watchFile?(path: string, callback: FileWatcherCallback): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; @@ -2177,7 +2232,7 @@ declare namespace ts { getExecutingFilePath(): string; getCurrentDirectory(): string; getDirectories(path: string): string[]; - readDirectory(path: string, extension?: string, exclude?: string[]): string[]; + readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; getModifiedTime?(path: string): Date; createHash?(data: string): string; getMemoryUsage?(): number; @@ -3053,7 +3108,7 @@ declare namespace ts { key: string; message: string; }; - A_parameter_property_may_not_be_a_binding_pattern: { + A_parameter_property_may_not_be_declared_using_a_binding_pattern: { code: number; category: DiagnosticCategory; key: string; @@ -3149,12 +3204,6 @@ declare namespace ts { key: string; message: string; }; - Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; Decorators_are_not_valid_here: { code: number; category: DiagnosticCategory; @@ -3479,6 +3528,12 @@ declare namespace ts { key: string; message: string; }; + A_parameter_property_cannot_be_declared_using_a_rest_parameter: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Duplicate_identifier_0: { code: number; category: DiagnosticCategory; @@ -5099,6 +5154,18 @@ declare namespace ts { key: string; message: string; }; + Cannot_find_type_definition_file_for_0: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Cannot_extend_an_interface_0_Did_you_mean_implements: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Import_declaration_0_is_using_private_name_1: { code: number; category: DiagnosticCategory; @@ -5537,6 +5604,18 @@ declare namespace ts { key: string; message: string; }; + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Cannot_read_file_0_Colon_1: { code: number; category: DiagnosticCategory; @@ -6575,12 +6654,6 @@ declare namespace ts { key: string; message: string; }; - property_declarations_can_only_be_used_in_a_ts_file: { - code: number; - category: DiagnosticCategory; - key: string; - message: string; - }; enum_declarations_can_only_be_used_in_a_ts_file: { code: number; category: DiagnosticCategory; @@ -6742,7 +6815,7 @@ declare namespace ts { function getOptionNameMap(): OptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt: CommandLineOptionOfCustomType): Diagnostic; function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]): number | string; - function parseListTypeOption(opt: CommandLineOptionOfListType, value: string, errors: Diagnostic[]): (string | number)[]; + function parseListTypeOption(opt: CommandLineOptionOfListType, value: string, errors: Diagnostic[]): (string | number)[] | undefined; function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine; function readConfigFile(fileName: string, readFile: (path: string) => string): { config?: any; @@ -6818,6 +6891,7 @@ declare namespace ts { function makeIdentifierFromModuleName(moduleName: string): string; function isBlockOrCatchScoped(declaration: Declaration): boolean; function isAmbientModule(node: Node): boolean; + function isShorthandAmbientModule(node: Node): boolean; function isBlockScopedContainerTopLevel(node: Node): boolean; function isGlobalScopeAugmentation(module: ModuleDeclaration): boolean; function isExternalModuleAugmentation(node: Node): boolean; @@ -6880,6 +6954,7 @@ declare namespace ts { function isInJavaScriptFile(node: Node): boolean; function isRequireCall(expression: Node, checkArgumentIsStringLiteral: boolean): expression is CallExpression; function isSingleOrDoubleQuote(charCode: number): boolean; + function isDeclarationOfFunctionExpression(s: Symbol): boolean; function getSpecialPropertyAssignmentKind(expression: Node): SpecialPropertyAssignmentKind; function getExternalModuleName(node: Node): Expression; function hasQuestionToken(node: Node): boolean; @@ -6994,6 +7069,7 @@ declare namespace ts { function isEmptyObjectLiteralOrArrayLiteral(expression: Node): boolean; function getLocalSymbolForExportDefault(symbol: Symbol): Symbol; function hasJavaScriptFileExtension(fileName: string): boolean; + function hasTypeScriptFileExtension(fileName: string): boolean; const stringify: (value: any) => string; function convertToBase64(input: string): string; function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string; @@ -7105,7 +7181,7 @@ declare namespace ts { function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; - function getDefaultTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; + function getAutomaticTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts.BreakpointResolver { @@ -7118,8 +7194,7 @@ declare namespace ts.NavigateTo { function getNavigateToItems(program: Program, checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number): NavigateToItem[]; } declare namespace ts.NavigationBar { - function getNavigationBarItems(sourceFile: SourceFile, compilerOptions: CompilerOptions): ts.NavigationBarItem[]; - function getJsNavigationBarItems(sourceFile: SourceFile, compilerOptions: CompilerOptions): NavigationBarItem[]; + function getNavigationBarItems(sourceFile: SourceFile): NavigationBarItem[]; } declare namespace ts { enum PatternMatchKind { @@ -7229,7 +7304,7 @@ declare namespace ts.JsTyping { directoryExists: (path: string) => boolean; fileExists: (fileName: string) => boolean; readFile: (path: string, encoding?: string) => string; - readDirectory: (path: string, extension?: string, exclude?: string[], depth?: number) => string[]; + readDirectory: (rootDir: string, extensions: string[], excludes: string[], includes: string[], depth?: number) => string[]; } function discoverTypings(host: TypingResolutionHost, fileNames: string[], projectRootPath: Path, safeListPath: Path, packageNameToTypingLocation: Map, typingOptions: TypingOptions, compilerOptions: CompilerOptions): { cachedTypingPaths: string[]; @@ -7716,6 +7791,7 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists?(directoryName: string): boolean; + getDirectories?(directoryName: string): string[]; } interface LanguageService { cleanupSemanticCache(): void; @@ -7799,6 +7875,7 @@ declare namespace ts { textSpan: TextSpan; fileName: string; isWriteAccess: boolean; + isDefinition: boolean; } interface DocumentHighlights { fileName: string; @@ -8216,7 +8293,7 @@ declare namespace ts.server { private reload(fileName, tempFileName, reqSeq?); private saveToTmp(fileName, tempFileName); private closeClientFile(fileName); - private decorateNavigationBarItem(project, fileName, items); + private decorateNavigationBarItem(project, fileName, items, lineIndex); private getNavigationBarItems(fileName); private getNavigateToItems(searchValue, fileName, maxResultCount?); private getBraceMatching(line, offset, fileName); @@ -8246,6 +8323,7 @@ declare namespace ts.server { endGroup(): void; msg(s: string, type?: string): void; } + const maxProgramSizeForNonTsFiles: number; class ScriptInfo { private host; fileName: string; @@ -8304,27 +8382,34 @@ declare namespace ts.server { resolvePath(path: string): string; fileExists(path: string): boolean; directoryExists(path: string): boolean; + getDirectories(path: string): string[]; lineToTextSpan(filename: string, line: number): ts.TextSpan; lineOffsetToPosition(filename: string, line: number, offset: number): number; - positionToLineOffset(filename: string, position: number): ILineInfo; + positionToLineOffset(filename: string, position: number, lineIndex?: LineIndex): ILineInfo; + getLineIndex(filename: string): LineIndex; } interface ProjectOptions { files?: string[]; + wildcardDirectories?: ts.Map; compilerOptions?: ts.CompilerOptions; } class Project { projectService: ProjectService; projectOptions?: ProjectOptions; + languageServiceDiabled: boolean; compilerService: CompilerService; projectFilename: string; projectFileWatcher: FileWatcher; directoryWatcher: FileWatcher; + directoriesWatchedForWildcards: Map; directoriesWatchedForTsconfig: string[]; program: ts.Program; filenameToSourceFile: ts.Map; updateGraphSeq: number; openRefCount: number; - constructor(projectService: ProjectService, projectOptions?: ProjectOptions); + constructor(projectService: ProjectService, projectOptions?: ProjectOptions, languageServiceDiabled?: boolean); + enableLanguageService(): void; + disableLanguageService(): void; addOpenRef(): void; deleteOpenRef(): number; openReferencedFile(filename: string): ScriptInfo; @@ -8415,13 +8500,14 @@ declare namespace ts.server { projectOptions?: ProjectOptions; errors?: Diagnostic[]; }; + private exceedTotalNonTsFileSizeLimit(fileNames); openConfigFile(configFilename: string, clientFileName?: string): { success: boolean; project?: Project; errors?: Diagnostic[]; }; updateConfiguredProject(project: Project): Diagnostic[]; - createProject(projectFilename: string, projectOptions?: ProjectOptions): Project; + createProject(projectFilename: string, projectOptions?: ProjectOptions, languageServiceDisabled?: boolean): Project; } class CompilerService { project: Project; @@ -8592,7 +8678,9 @@ declare namespace ts { directoryExists(directoryName: string): boolean; } interface CoreServicesShimHost extends Logger, ModuleResolutionHost { - readDirectory(rootDir: string, extension: string, exclude?: string, depth?: number): string; + readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string; + useCaseSensitiveFileNames?(): boolean; + getCurrentDirectory(): string; trace(s: string): void; } interface IFileReference { @@ -8685,10 +8773,12 @@ declare namespace ts { private shimHost; directoryExists: (directoryName: string) => boolean; realpath: (path: string) => string; + useCaseSensitiveFileNames: boolean; constructor(shimHost: CoreServicesShimHost); - readDirectory(rootDir: string, extension: string, exclude: string[], depth?: number): string[]; + readDirectory(rootDir: string, extensions: string[], exclude: string[], include: string[], depth?: number): string[]; fileExists(fileName: string): boolean; readFile(fileName: string): string; + private readDirectoryFallback(rootDir, extension, exclude); } function realizeDiagnostics(diagnostics: Diagnostic[], newLine: string): { message: string; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 2da5d67be8a..22a420c25e4 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -147,6 +147,15 @@ var ts; return -1; } ts.indexOf = indexOf; + function indexOfAnyCharCode(text, charCodes, start) { + for (var i = start || 0, len = text.length; i < len; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; + } + ts.indexOfAnyCharCode = indexOfAnyCharCode; function countWhere(array, predicate) { var count = 0; if (array) { @@ -174,12 +183,24 @@ var ts; return result; } ts.filter = filter; + function filterMutate(array, f) { + var outIndex = 0; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + if (f(item)) { + array[outIndex] = item; + outIndex++; + } + } + array.length = outIndex; + } + ts.filterMutate = filterMutate; function map(array, f) { var result; if (array) { result = []; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; result.push(f(v)); } } @@ -198,8 +219,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var item = array_6[_i]; if (!contains(result, item, areEqual)) { result.push(item); } @@ -210,8 +231,8 @@ var ts; ts.deduplicate = deduplicate; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var v = array_7[_i]; result += v[prop]; } return result; @@ -505,6 +526,30 @@ var ts; return a < b ? -1 : 1; } ts.compareValues = compareValues; + function compareStrings(a, b, ignoreCase) { + if (a === b) + return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + if (ignoreCase) { + if (String.prototype.localeCompare) { + var result = a.localeCompare(b, undefined, { usage: "sort", sensitivity: "accent" }); + return result < 0 ? -1 : result > 0 ? 1 : 0; + } + a = a.toUpperCase(); + b = b.toUpperCase(); + if (a === b) + return 0; + } + return a < b ? -1 : 1; + } + ts.compareStrings = compareStrings; + function compareStringsCaseInsensitive(a, b) { + return compareStrings(a, b, true); + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; function getDiagnosticFileName(diagnostic) { return diagnostic.file ? diagnostic.file.fileName : undefined; } @@ -727,12 +772,220 @@ var ts; return path1 + ts.directorySeparator + path2; } ts.combinePaths = combinePaths; + function removeTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) === ts.directorySeparator) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) !== ts.directorySeparator) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (a === b) + return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + a = removeTrailingDirectorySeparator(a); + b = removeTrailingDirectorySeparator(b); + var aComponents = getNormalizedPathComponents(a, currentDirectory); + var bComponents = getNormalizedPathComponents(b, currentDirectory); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 0; i < sharedLength; i++) { + var result = compareStrings(aComponents[i], bComponents[i], ignoreCase); + if (result !== 0) { + return result; + } + } + return compareValues(aComponents.length, bComponents.length); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + parent = removeTrailingDirectorySeparator(parent); + child = removeTrailingDirectorySeparator(child); + if (parent === child) + return true; + var parentComponents = getNormalizedPathComponents(parent, currentDirectory); + var childComponents = getNormalizedPathComponents(child, currentDirectory); + if (childComponents.length < parentComponents.length) { + return false; + } + for (var i = 0; i < parentComponents.length; i++) { + var result = compareStrings(parentComponents[i], childComponents[i], ignoreCase); + if (result !== 0) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; function fileExtensionIs(path, extension) { var pathLen = path.length; var extLen = extension.length; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsAny(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsAny = fileExtensionIsAny; + var reservedCharacterPattern = /[^\w\s\/]/g; + var wildcardCharCodes = [42, 63]; + function getRegularExpressionForWildcard(specs, basePath, usage) { + if (specs === undefined || specs.length === 0) { + return undefined; + } + var pattern = ""; + var hasWrittenSubpattern = false; + spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { + var spec = specs_1[_i]; + if (!spec) { + continue; + } + var subpattern = ""; + var hasRecursiveDirectoryWildcard = false; + var hasWrittenComponent = false; + var components = getNormalizedPathComponents(spec, basePath); + if (usage !== "exclude" && components[components.length - 1] === "**") { + continue spec; + } + components[0] = removeTrailingDirectorySeparator(components[0]); + var optionalCount = 0; + for (var _a = 0, components_1 = components; _a < components_1.length; _a++) { + var component = components_1[_a]; + if (component === "**") { + if (hasRecursiveDirectoryWildcard) { + continue spec; + } + subpattern += "(/.+?)?"; + hasRecursiveDirectoryWildcard = true; + hasWrittenComponent = true; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + hasWrittenComponent = true; + } + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + if (hasWrittenSubpattern) { + pattern += "|"; + } + pattern += "(" + subpattern + ")"; + hasWrittenSubpattern = true; + } + if (!pattern) { + return undefined; + } + return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); + } + ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function replaceWildcardCharacter(match) { + return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; + } + function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + }; + } + ts.getFileMatcherPatterns = getFileMatcherPatterns; + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, getFileSystemEntries) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var patterns = getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + var regexFlag = useCaseSensitiveFileNames ? "" : "i"; + var includeFileRegex = patterns.includeFilePattern && new RegExp(patterns.includeFilePattern, regexFlag); + var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); + var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); + var result = []; + for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { + var basePath = _a[_i]; + visitDirectory(basePath, combinePaths(currentDirectory, basePath)); + } + return result; + function visitDirectory(path, absolutePath) { + var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var current = files_1[_i]; + var name_1 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!extensions || fileExtensionIsAny(name_1, extensions)) && + (!includeFileRegex || includeFileRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + result.push(name_1); + } + } + for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { + var current = directories_1[_b]; + var name_2 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name_2, absoluteName); + } + } + } + } + ts.matchFiles = matchFiles; + function getBasePaths(path, includes, useCaseSensitiveFileNames) { + var basePaths = [path]; + if (includes) { + var includeBasePaths = []; + for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { + var include = includes_1[_i]; + if (isRootedDiskPath(include)) { + var wildcardOffset = indexOfAnyCharCode(include, wildcardCharCodes); + var includeBasePath = wildcardOffset < 0 + ? removeTrailingDirectorySeparator(getDirectoryPath(include)) + : include.substring(0, include.lastIndexOf(ts.directorySeparator, wildcardOffset)); + includeBasePaths.push(includeBasePath); + } + } + includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); + include: for (var i = 0; i < includeBasePaths.length; i++) { + var includeBasePath = includeBasePaths[i]; + for (var j = 0; j < basePaths.length; j++) { + if (containsPath(basePaths[j], includeBasePath, path, !useCaseSensitiveFileNames)) { + continue include; + } + } + basePaths.push(includeBasePath); + } + } + return basePaths; + } function ensureScriptKind(fileName, scriptKind) { return (scriptKind || getScriptKindFromFileName(fileName)) || 3; } @@ -773,6 +1026,36 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + function getExtensionPriority(path, supportedExtensions) { + for (var i = supportedExtensions.length - 1; i >= 0; i--) { + if (fileExtensionIs(path, supportedExtensions[i])) { + return adjustExtensionPriority(i); + } + } + return 0; + } + ts.getExtensionPriority = getExtensionPriority; + function adjustExtensionPriority(extensionPriority) { + if (extensionPriority < 2) { + return 0; + } + else if (extensionPriority < 5) { + return 2; + } + else { + return 5; + } + } + ts.adjustExtensionPriority = adjustExtensionPriority; + function getNextLowestExtensionPriority(extensionPriority) { + if (extensionPriority < 2) { + return 2; + } + else { + return 5; + } + } + ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { @@ -793,6 +1076,10 @@ var ts; return ext === ".jsx" || ext === ".tsx"; } ts.isJsxOrTsxExtension = isJsxOrTsxExtension; + function changeExtension(path, newExtension) { + return (removeFileExtension(path) + newExtension); + } + ts.changeExtension = changeExtension; function Symbol(flags, name) { this.flags = flags; this.name = name; @@ -863,6 +1150,7 @@ var ts; ts.sys = (function () { function getWScriptSystem() { var fso = new ActiveXObject("Scripting.FileSystemObject"); + var shell = new ActiveXObject("WScript.Shell"); var fileStream = new ActiveXObject("ADODB.Stream"); fileStream.Type = 2; var binaryStream = new ActiveXObject("ADODB.Stream"); @@ -917,9 +1205,6 @@ var ts; fileStream.Close(); } } - function getCanonicalPath(path) { - return path.toLowerCase(); - } function getNames(collection) { var result = []; for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { @@ -931,30 +1216,19 @@ var ts; var folder = fso.GetFolder(path); return getNames(folder.subfolders); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { + function getAccessibleFileSystemEntries(path) { + try { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var current = files_1[_i]; - var name_1 = ts.combinePaths(path, current); - if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { - result.push(name_1); - } - } - var subfolders = getNames(folder.subfolders); - for (var _a = 0, subfolders_1 = subfolders; _a < subfolders_1.length; _a++) { - var current = subfolders_1[_a]; - var name_2 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_2))) { - visitDirectory(name_2); - } - } + var directories = getNames(folder.subfolders); + return { files: files, directories: directories }; } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } return { args: args, @@ -983,7 +1257,7 @@ var ts; return WScript.ScriptFullName; }, getCurrentDirectory: function () { - return new ActiveXObject("WScript.Shell").CurrentDirectory; + return shell.CurrentDirectory; }, getDirectories: getDirectories, readDirectory: readDirectory, @@ -1112,8 +1386,39 @@ var ts; } } } - function getCanonicalPath(path) { - return useCaseSensitiveFileNames ? path : path.toLowerCase(); + function getAccessibleFileSystemEntries(path) { + try { + var entries = _fs.readdirSync(path || ".").sort(); + var files = []; + var directories = []; + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var entry = entries_1[_i]; + if (entry === "." || entry === "..") { + continue; + } + var name_3 = ts.combinePaths(path, entry); + var stat = void 0; + try { + stat = _fs.statSync(name_3); + } + catch (e) { + continue; + } + if (stat.isFile()) { + files.push(entry); + } + else if (stat.isDirectory()) { + directories.push(entry); + } + } + return { files: files, directories: directories }; + } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); } function fileSystemEntryExists(path, entryKind) { try { @@ -1136,38 +1441,6 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1); }); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { - var files = _fs.readdirSync(path || ".").sort(); - var directories = []; - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var current = files_2[_i]; - if (current === "." || current === "..") { - continue; - } - var name_3 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_3))) { - var stat = _fs.statSync(name_3); - if (stat.isFile()) { - if (!extension || ts.fileExtensionIs(name_3, extension)) { - result.push(name_3); - } - } - else if (stat.isDirectory()) { - directories.push(name_3); - } - } - } - for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { - var current = directories_1[_a]; - visitDirectory(current); - } - } - } return { args: process.argv.slice(2), newLine: _os.EOL, @@ -1249,6 +1522,16 @@ var ts; } return process.memoryUsage().heapUsed; }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch (e) { } + return 0; + }, exit: function (exitCode) { process.exit(exitCode); }, @@ -1280,7 +1563,10 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, - readDirectory: ChakraHost.readDirectory, + readDirectory: function (path, extensions, excludes, includes) { + var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); + }, exit: ChakraHost.quit, realpath: realpath }; @@ -1445,7 +1731,7 @@ var ts; Modifiers_cannot_appear_here: { code: 1184, category: ts.DiagnosticCategory.Error, key: "Modifiers_cannot_appear_here_1184", message: "Modifiers cannot appear here." }, Merge_conflict_marker_encountered: { code: 1185, category: ts.DiagnosticCategory.Error, key: "Merge_conflict_marker_encountered_1185", message: "Merge conflict marker encountered." }, A_rest_element_cannot_have_an_initializer: { code: 1186, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_have_an_initializer_1186", message: "A rest element cannot have an initializer." }, - A_parameter_property_may_not_be_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_a_binding_pattern_1187", message: "A parameter property may not be a binding pattern." }, + A_parameter_property_may_not_be_declared_using_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", message: "A parameter property may not be declared using a binding pattern." }, Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: { code: 1188, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", message: "Only a single variable declaration is allowed in a 'for...of' statement." }, The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: { code: 1189, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", message: "The variable declaration of a 'for...in' statement cannot have an initializer." }, The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: { code: 1190, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", message: "The variable declaration of a 'for...of' statement cannot have an initializer." }, @@ -1461,7 +1747,6 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, - Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower: { code: 1204, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower_1204", message: "Cannot compile modules into 'es2015' when targeting 'ES5' or lower." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -1516,6 +1801,7 @@ var ts; Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, Global_module_exports_may_only_appear_in_declaration_files: { code: 1315, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_declaration_files_1315", message: "Global module exports may only appear in declaration files." }, Global_module_exports_may_only_appear_at_top_level: { code: 1316, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_at_top_level_1316", message: "Global module exports may only appear at top level." }, + A_parameter_property_cannot_be_declared_using_a_rest_parameter: { code: 1317, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", message: "A parameter property cannot be declared using a rest parameter." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, @@ -1786,6 +2072,8 @@ var ts; The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, + Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, + Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -1859,6 +2147,8 @@ var ts; Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, + File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { code: 5011, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", message: "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'." }, Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot_read_file_0_Colon_1_5012", message: "Cannot read file '{0}': {1}" }, Unsupported_file_encoding: { code: 5013, category: ts.DiagnosticCategory.Error, key: "Unsupported_file_encoding_5013", message: "Unsupported file encoding." }, Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed_to_parse_file_0_Colon_1_5014", message: "Failed to parse file '{0}': {1}." }, @@ -2032,7 +2322,6 @@ var ts; types_can_only_be_used_in_a_ts_file: { code: 8010, category: ts.DiagnosticCategory.Error, key: "types_can_only_be_used_in_a_ts_file_8010", message: "'types' can only be used in a .ts file." }, type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: ts.DiagnosticCategory.Error, key: "type_arguments_can_only_be_used_in_a_ts_file_8011", message: "'type arguments' can only be used in a .ts file." }, parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: ts.DiagnosticCategory.Error, key: "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", message: "'parameter modifiers' can only be used in a .ts file." }, - property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "property_declarations_can_only_be_used_in_a_ts_file_8014", message: "'property declarations' can only be used in a .ts file." }, enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "enum_declarations_can_only_be_used_in_a_ts_file_8015", message: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, @@ -3861,8 +4150,13 @@ var ts; } }, { - name: "typesRoot", - type: "string" + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + } }, { name: "types", @@ -3928,6 +4222,10 @@ var ts; }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, + { + name: "disableProjectSizeLimit", + type: "boolean" + }, { name: "strictNullChecks", type: "boolean", @@ -3993,7 +4291,15 @@ var ts; } ts.parseCustomTypeOption = parseCustomTypeOption; function parseListTypeOption(opt, value, errors) { - var values = trimString((value || "")).split(","); + if (value === void 0) { value = ""; } + value = trimString(value); + if (ts.startsWith(value, "-")) { + return undefined; + } + if (value === "") { + return []; + } + var values = value.split(","); switch (opt.element.type) { case "number": return ts.map(values, parseInt); @@ -4050,8 +4356,11 @@ var ts; i++; break; case "list": - options[opt.name] = parseListTypeOption(opt, args[i], errors); - i++; + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } break; default: options[opt.name] = parseCustomTypeOption(opt, args[i], errors); @@ -4143,7 +4452,7 @@ var ts; } return output; } - var IgnoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; + var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName) { if (existingOptions === void 0) { existingOptions = {}; } var errors = []; @@ -4151,66 +4460,57 @@ var ts; var options = ts.extend(existingOptions, compilerOptions); var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); options.configFilePath = configFileName; - var fileNames = getFileNames(errors); + var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, - errors: errors + errors: errors, + wildcardDirectories: wildcardDirectories }; function getFileNames(errors) { - var fileNames = []; + var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { - fileNames = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); + fileNames = json["files"]; } else { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); } } - else { - var filesSeen = {}; - var exclude = []; - if (ts.isArray(json["exclude"])) { - exclude = json["exclude"]; + var includeSpecs; + if (ts.hasProperty(json, "include")) { + if (ts.isArray(json["include"])) { + includeSpecs = json["include"]; } else { - exclude = ["node_modules", "bower_components", "jspm_packages"]; - } - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; - if (outDir) { - exclude.push(outDir); - } - exclude = ts.map(exclude, function (e) { return ts.getNormalizedAbsolutePath(e, basePath); }); - var supportedExtensions = ts.getSupportedExtensions(options); - ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); - for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { - var extension = supportedExtensions_1[_i]; - var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); - for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { - var fileName = filesInDirWithExtension_1[_a]; - if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { - continue; - } - if (IgnoreFileNamePattern.test(fileName)) { - continue; - } - if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { - var baseName = fileName.substr(0, fileName.length - extension.length); - if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { - continue; - } - } - filesSeen[fileName] = true; - fileNames.push(fileName); - } + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array")); } } - if (ts.hasProperty(json, "excludes") && !ts.hasProperty(json, "exclude")) { + var excludeSpecs; + if (ts.hasProperty(json, "exclude")) { + if (ts.isArray(json["exclude"])) { + excludeSpecs = json["exclude"]; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); + } + } + else if (ts.hasProperty(json, "excludes")) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } - return fileNames; + else { + excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; + } + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + excludeSpecs.push(outDir); + } + if (fileNames === undefined && includeSpecs === undefined) { + includeSpecs = ["**/*"]; + } + return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; @@ -4292,6 +4592,139 @@ var ts; function trimString(s) { return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); } + var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + var invalidMultipleRecursionPatterns = /(^|\/)\*\*\/(.*\/)?\*\*($|\/)/; + var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + basePath = ts.normalizePath(basePath); + var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; + var literalFileMap = {}; + var wildcardFileMap = {}; + if (include) { + include = validateSpecs(include, errors, false); + } + if (exclude) { + exclude = validateSpecs(exclude, errors, true); + } + var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); + var supportedExtensions = ts.getSupportedExtensions(options); + if (fileNames) { + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; + var file = ts.combinePaths(basePath, fileName); + literalFileMap[keyMapper(file)] = file; + } + } + if (include && include.length > 0) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include); _a < _b.length; _a++) { + var file = _b[_a]; + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + continue; + } + if (ignoreFileNamePattern.test(file)) { + continue; + } + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file); + if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { + wildcardFileMap[key] = file; + } + } + } + var literalFiles = ts.reduceProperties(literalFileMap, addFileToOutput, []); + var wildcardFiles = ts.reduceProperties(wildcardFileMap, addFileToOutput, []); + wildcardFiles.sort(host.useCaseSensitiveFileNames ? ts.compareStrings : ts.compareStringsCaseInsensitive); + return { + fileNames: literalFiles.concat(wildcardFiles), + wildcardDirectories: wildcardDirectories + }; + } + function validateSpecs(specs, errors, allowTrailingRecursion) { + var validSpecs = []; + for (var _i = 0, specs_2 = specs; _i < specs_2.length; _i++) { + var spec = specs_2[_i]; + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + } + else if (invalidMultipleRecursionPatterns.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); + } + else { + validSpecs.push(spec); + } + } + return validSpecs; + } + function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); + var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + var wildcardDirectories = {}; + if (include !== undefined) { + var recursiveKeys = []; + for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { + var file = include_1[_i]; + var name_5 = ts.combinePaths(path, file); + if (excludeRegex && excludeRegex.test(name_5)) { + continue; + } + var match = wildcardDirectoryPattern.exec(name_5); + if (match) { + var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); + var flags = watchRecursivePattern.test(name_5) ? 1 : 0; + var existingFlags = ts.getProperty(wildcardDirectories, key); + if (existingFlags === undefined || existingFlags < flags) { + wildcardDirectories[key] = flags; + if (flags === 1) { + recursiveKeys.push(key); + } + } + } + } + for (var key in wildcardDirectories) { + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } + } + } + } + } + return wildcardDirectories; + } + function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); + for (var i = 0; i < adjustedExtensionPriority; i++) { + var higherPriorityExtension = extensions[i]; + var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); + if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { + return true; + } + } + return false; + } + function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority); + for (var i = nextExtensionPriority; i < extensions.length; i++) { + var lowerPriorityExtension = extensions[i]; + var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); + delete wildcardFiles[lowerPriorityPath]; + } + } + function addFileToOutput(output, file) { + output.push(file); + return output; + } + function caseSensitiveKeyMapper(key) { + return key; + } + function caseInsensitiveKeyMapper(key) { + return key.toLowerCase(); + } })(ts || (ts = {})); var ts; (function (ts) { @@ -4572,6 +5005,10 @@ var ts; (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isShorthandAmbientModule(node) { + return node.kind === 225 && (!node.body); + } + ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 || node.kind === 225 || @@ -4900,9 +5337,9 @@ var ts; return; default: if (isFunctionLike(node)) { - var name_5 = node.name; - if (name_5 && name_5.kind === 140) { - traverse(name_5.expression); + var name_6 = node.name; + if (name_6 && name_6.kind === 140) { + traverse(name_6.expression); return; } } @@ -4959,6 +5396,7 @@ var ts; case 157: return true; } + return false; } ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { @@ -5336,6 +5774,14 @@ var ts; return charCode === 39 || charCode === 34; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isDeclarationOfFunctionExpression(s) { + if (s.valueDeclaration && s.valueDeclaration.kind === 218) { + var declaration = s.valueDeclaration; + return declaration.initializer && declaration.initializer.kind === 179; + } + return false; + } + ts.isDeclarationOfFunctionExpression = isDeclarationOfFunctionExpression; function getSpecialPropertyAssignmentKind(expression) { if (!isInJavaScriptFile(expression)) { return 0; @@ -5483,8 +5929,8 @@ var ts; var tag = _b[_a]; if (tag.kind === 275) { var parameterTag = tag; - var name_6 = parameterTag.preParameterName || parameterTag.postParameterName; - if (name_6.text === parameterName) { + var name_7 = parameterTag.preParameterName || parameterTag.postParameterName; + if (name_7.text === parameterName) { return parameterTag; } } @@ -6227,7 +6673,9 @@ var ts; ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); + var commonSourceDirectory = host.getCommonSourceDirectory(); + var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; return ts.combinePaths(newDirPath, sourceFilePath); } ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; @@ -6541,6 +6989,10 @@ var ts; return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function getExpandedCharCodes(input) { var output = []; var length = input.length; @@ -6924,7 +7376,6 @@ var ts; return visitNodes(cbNodes, node.properties); case 172: return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); case 173: return visitNode(cbNode, node.expression) || @@ -7675,6 +8126,7 @@ var ts; return token === 19 || token === 15 || token === 37 + || token === 22 || isLiteralPropertyName(); } function nextTokenIsClassOrFunction() { @@ -9182,7 +9634,7 @@ var ts; } var node = createNode(172, expression.pos); node.expression = expression; - node.dotToken = parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(21, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(true); return finishNode(node); } @@ -9370,7 +9822,6 @@ var ts; if (dotToken) { var propertyAccess = createNode(172, expression.pos); propertyAccess.expression = expression; - propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(true); expression = finishNode(propertyAccess); continue; @@ -10414,8 +10865,8 @@ var ts; return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { - var name_7 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_7, undefined); + var name_8 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_8, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } @@ -10558,7 +11009,12 @@ var ts; else { node.name = parseLiteralNode(true); } - node.body = parseModuleBlock(); + if (token === 15) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { @@ -11302,8 +11758,8 @@ var ts; if (typeExpression.type.kind === 267) { var jsDocTypeReference = typeExpression.type; if (jsDocTypeReference.name.kind === 69) { - var name_8 = jsDocTypeReference.name; - if (name_8.text === "Object") { + var name_9 = jsDocTypeReference.name; + if (name_9.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -11386,13 +11842,13 @@ var ts; var typeParameters = []; typeParameters.pos = scanner.getStartPos(); while (true) { - var name_9 = parseJSDocIdentifierName(); - if (!name_9) { + var name_10 = parseJSDocIdentifierName(); + if (!name_10) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141, name_9.pos); - typeParameter.name = name_9; + var typeParameter = createNode(141, name_10.pos); + typeParameter.name = name_10; finishNode(typeParameter); typeParameters.push(typeParameter); if (token === 24) { @@ -11494,8 +11950,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var node = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -11567,8 +12023,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -11748,7 +12204,8 @@ var ts; return state_1; } else if (node.kind === 225) { - return getModuleInstanceState(node.body); + var body = node.body; + return body ? getModuleInstanceState(body) : 1; } else { return 1; @@ -12117,11 +12574,6 @@ var ts; break; } } - function isNarrowableReference(expr) { - return expr.kind === 69 || - expr.kind === 97 || - expr.kind === 172 && isNarrowableReference(expr.expression); - } function isNarrowingExpression(expr) { switch (expr.kind) { case 69: @@ -12129,7 +12581,7 @@ var ts; case 172: return isNarrowableReference(expr); case 174: - return true; + return hasNarrowableArgument(expr); case 178: return isNarrowingExpression(expr.expression); case 187: @@ -12139,6 +12591,35 @@ var ts; } return false; } + function isNarrowableReference(expr) { + return expr.kind === 69 || + expr.kind === 97 || + expr.kind === 172 && isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 172 && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingNullCheckOperands(expr1, expr2) { + return (expr1.kind === 93 || expr1.kind === 69 && expr1.text === "undefined") && isNarrowableOperand(expr2); + } + function isNarrowingTypeofOperands(expr1, expr2) { + return expr1.kind === 182 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + } + function isNarrowingDiscriminant(expr) { + return expr.kind === 172 && isNarrowableReference(expr.expression); + } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56: @@ -12147,20 +12628,34 @@ var ts; case 31: case 32: case 33: - if (isNarrowingExpression(expr.left) && (expr.right.kind === 93 || expr.right.kind === 69)) { - return true; - } - if (expr.left.kind === 182 && isNarrowingExpression(expr.left.expression) && expr.right.kind === 9) { - return true; - } - return false; + return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || + isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); case 91: - return isNarrowingExpression(expr.left); + return isNarrowableOperand(expr.left); case 24: return isNarrowingExpression(expr.right); } return false; } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 178: + return isNarrowableOperand(expr.expression); + case 187: + switch (expr.operatorToken.kind) { + case 56: + return isNarrowableOperand(expr.left); + case 24: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function isNarrowingSwitchStatement(switchStatement) { + var expr = switchStatement.expression; + return expr.kind === 172 && isNarrowableReference(expr.expression); + } function createBranchLabel() { return { flags: 4, @@ -12174,7 +12669,7 @@ var ts; }; } function setFlowNodeReferenced(flow) { - flow.flags |= flow.flags & 128 ? 256 : 128; + flow.flags |= flow.flags & 256 ? 512 : 256; } function addAntecedent(label, antecedent) { if (!(antecedent.flags & 1) && !ts.contains(label.antecedents, antecedent)) { @@ -12199,8 +12694,21 @@ var ts; setFlowNodeReferenced(antecedent); return { flags: flags, - antecedent: antecedent, - expression: expression + expression: expression, + antecedent: antecedent + }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingSwitchStatement(switchStatement)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: 128, + switchStatement: switchStatement, + clauseStart: clauseStart, + clauseEnd: clauseEnd, + antecedent: antecedent }; } function createFlowAssignment(antecedent, node) { @@ -12410,9 +12918,10 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasNonEmptyDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250 && c.statements.length; }); - if (!hasNonEmptyDefault) { - addAntecedent(postSwitchLabel, preSwitchCaseFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250; }); + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); } currentBreakTarget = saveBreakTarget; preSwitchCaseFlow = savePreSwitchCaseFlow; @@ -12420,25 +12929,22 @@ var ts; } function bindCaseBlock(node) { var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { - var clause = clauses[i]; - if (clause.statements.length) { - if (currentFlow.flags & 1) { - currentFlow = preSwitchCaseFlow; - } - else { - var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, preSwitchCaseFlow); - addAntecedent(preCaseLabel, currentFlow); - currentFlow = finishFlowLabel(preCaseLabel); - } - bind(clause); - if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; } - else { - bind(clause); + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); } } } @@ -12703,7 +13209,7 @@ var ts; } function hasExportDeclarations(node) { var body = node.kind === 256 ? node : node.body; - if (body.kind === 256 || body.kind === 226) { + if (body && (body.kind === 256 || body.kind === 226)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; if (stat.kind === 236 || stat.kind === 235) { @@ -13223,7 +13729,7 @@ var ts; constructorFunction.parent = classPrototype; classPrototype.parent = leftSideOfAssignment; var funcSymbol = container.locals[constructorFunction.text]; - if (!funcSymbol || !(funcSymbol.flags & 16)) { + if (!funcSymbol || !(funcSymbol.flags & 16 || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return; } if (!funcSymbol.members) { @@ -13808,7 +14314,8 @@ var ts; var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { - if (modulekind || (!compilerOptions.outFile && !compilerOptions.out)) { + if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out)) { return true; } var sourceFiles = host.getSourceFiles(); @@ -14005,7 +14512,8 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg)) { + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -14061,6 +14569,29 @@ var ts; } return false; } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var parentClassExpression = errorLocation; + while (parentClassExpression) { + var kind = parentClassExpression.kind; + if (kind === 69 || kind === 172) { + parentClassExpression = parentClassExpression.parent; + continue; + } + if (kind === 194) { + break; + } + return false; + } + if (!parentClassExpression) { + return false; + } + var expression = parentClassExpression.expression; + if (resolveEntityName(expression, 64, true)) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; + } + return false; + } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2) !== 0); var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) ? d : undefined; }); @@ -14103,9 +14634,11 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = moduleSymbol.exports["export="] ? - getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : - resolveSymbol(moduleSymbol.exports["default"]); + var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? + moduleSymbol : + moduleSymbol.exports["export="] ? + getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : + resolveSymbol(moduleSymbol.exports["default"]); if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } @@ -14154,22 +14687,25 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_10 = specifier.propertyName || specifier.name; - if (name_10.text) { + var name_11 = specifier.propertyName || specifier.name; + if (name_11.text) { + if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { + return moduleSymbol; + } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_10.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_11.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_10.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_11.text); } symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_10.text); + var symbolFromModule = getExportOfModule(targetSymbol, name_11.text); var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_10, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_10)); + error(name_11, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_11)); } return symbol; } @@ -15504,6 +16040,9 @@ var ts; function isTypeAny(type) { return type && (type.flags & 1) !== 0; } + function isTypeNever(type) { + return type && (type.flags & 134217728) !== 0; + } function getTypeForBindingElementParent(node) { var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); @@ -15539,19 +16078,19 @@ var ts; } var type; if (pattern.kind === 167) { - var name_11 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_11)) { + var name_12 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_12)) { return anyType; } if (declaration.initializer) { getContextualType(declaration.initializer); } - var text = getTextOfPropertyName(name_11); + var text = getTextOfPropertyName(name_12); type = getTypeOfPropertyOfType(parentType, text) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { - error(name_11, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_11)); + error(name_12, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_12)); return unknownType; } } @@ -15755,18 +16294,21 @@ var ts; if (declaration.kind === 235) { return links.type = checkExpression(declaration.expression); } - if (declaration.kind === 187) { - return links.type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); - } - if (declaration.kind === 172) { - if (declaration.parent.kind === 187) { - return links.type = checkExpressionCached(declaration.parent.right); - } - } if (!pushTypeResolution(symbol, 0)) { return unknownType; } - var type = getWidenedTypeForVariableLikeDeclaration(declaration, true); + var type = undefined; + if (declaration.kind === 187) { + type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); + } + else if (declaration.kind === 172) { + if (declaration.parent.kind === 187) { + type = checkExpressionCached(declaration.parent.right); + } + } + if (type === undefined) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, true); + } if (!popTypeResolution()) { if (symbol.valueDeclaration.type) { type = unknownType; @@ -15854,9 +16396,14 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var type = createObjectType(65536, symbol); - links.type = strictNullChecks && symbol.flags & 536870912 ? - addTypeKind(type, 32) : type; + if (symbol.valueDeclaration.kind === 225 && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { + links.type = anyType; + } + else { + var type = createObjectType(65536, symbol); + links.type = strictNullChecks && symbol.flags & 536870912 ? + addTypeKind(type, 32) : type; + } } return links.type; } @@ -16807,7 +17354,7 @@ var ts; } return result; } - function isOptionalParameter(node) { + function isJSDocOptionalParameter(node) { if (node.flags & 134217728) { if (node.type && node.type.kind === 268) { return true; @@ -16822,7 +17369,9 @@ var ts; } } } - if (ts.hasQuestionToken(node)) { + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { return true; } if (node.initializer) { @@ -16877,7 +17426,7 @@ var ts; if (param.type && param.type.kind === 166) { hasStringLiterals = true; } - if (param.initializer || param.questionToken || param.dotDotDotToken) { + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { minArgumentCount = i - (hasThisParameter ? 1 : 0); } @@ -17874,6 +18423,9 @@ var ts; function isTypeComparableTo(source, target) { return checkTypeComparableTo(source, target, undefined); } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); } @@ -18812,8 +19364,10 @@ var ts; function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isStringLiteralType(type) { - return type.flags & 256; + function isStringLiteralUnionType(type) { + return type.flags & 256 ? true : + type.flags & 16384 ? ts.forEach(type.types, isStringLiteralUnionType) : + false; } function isTupleType(type) { return !!(type.flags & 8192); @@ -19543,6 +20097,29 @@ var ts; } return node; } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 249) { + var expr = clause.expression; + return expr.kind === 9 ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); + } + return undefined; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); + links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256; }) ? types : emptyArray; + } + return links.switchTypes; + } + function eachTypeContainedIn(source, types) { + return source.flags & 16384 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function filterType(type, f) { + return type.flags & 16384 ? + getUnionType(ts.filter(type.types, f)) : + f(type) ? type : neverType; + } function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { var key; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175)) { @@ -19558,7 +20135,7 @@ var ts; return result; function getTypeAtFlowNode(flow) { while (true) { - if (flow.flags & 256) { + if (flow.flags & 512) { for (var i = visitedFlowStart; i < visitedFlowCount; i++) { if (visitedFlowNodes[i] === flow) { return visitedFlowTypes[i]; @@ -19576,6 +20153,9 @@ var ts; else if (flow.flags & 96) { type = getTypeAtFlowCondition(flow); } + else if (flow.flags & 128) { + type = getTypeAtSwitchClause(flow); + } else if (flow.flags & 12) { if (flow.antecedents.length === 1) { flow = flow.antecedents[0]; @@ -19596,7 +20176,7 @@ var ts; else { type = declaredType; } - if (flow.flags & 256) { + if (flow.flags & 512) { visitedFlowNodes[visitedFlowCount] = flow; visitedFlowTypes[visitedFlowCount] = type; visitedFlowCount++; @@ -19634,6 +20214,10 @@ var ts; } return type; } + function getTypeAtSwitchClause(flow) { + var type = getTypeAtFlowNode(flow.antecedent); + return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { @@ -19694,11 +20278,26 @@ var ts; case 31: case 32: case 33: - if (isNullOrUndefinedLiteral(expr.right)) { - return narrowTypeByNullCheck(type, expr, assumeTrue); + var left = expr.left; + var operator = expr.operatorToken.kind; + var right = expr.right; + if (isNullOrUndefinedLiteral(right)) { + return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); } - if (expr.left.kind === 182 && expr.right.kind === 9) { - return narrowTypeByTypeof(type, expr, assumeTrue); + if (isNullOrUndefinedLiteral(left)) { + return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); + } + if (left.kind === 182 && right.kind === 9) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); + } + if (right.kind === 182 && left.kind === 9) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); + } + if (left.kind === 172) { + return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); + } + if (right.kind === 172) { + return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); } break; case 91: @@ -19708,46 +20307,91 @@ var ts; } return type; } - function narrowTypeByNullCheck(type, expr, assumeTrue) { - var operator = expr.operatorToken.kind; + function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } - if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(expr.left))) { + if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { return type; } var doubleEquals = operator === 30 || operator === 31; var facts = doubleEquals ? assumeTrue ? 65536 : 524288 : - expr.right.kind === 93 ? + literal.kind === 93 ? assumeTrue ? 32768 : 262144 : assumeTrue ? 16384 : 131072; return getTypeWithFacts(type, facts); } - function narrowTypeByTypeof(type, expr, assumeTrue) { - var left = getReferenceFromExpression(expr.left.expression); - var right = expr.right; - if (!isMatchingReference(reference, left)) { - if (containsMatchingReference(reference, left)) { + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + var target = getReferenceFromExpression(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { + if (containsMatchingReference(reference, target)) { return declaredType; } return type; } - if (expr.operatorToken.kind === 31 || - expr.operatorToken.kind === 33) { + if (operator === 31 || operator === 33) { assumeTrue = !assumeTrue; } if (assumeTrue && !(type.flags & 16384)) { - var targetType = ts.getProperty(typeofTypesByName, right.text); + var targetType = ts.getProperty(typeofTypesByName, literal.text); if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - ts.getProperty(typeofEQFacts, right.text) || 64 : - ts.getProperty(typeofNEFacts, right.text) || 8192; + ts.getProperty(typeofEQFacts, literal.text) || 64 : + ts.getProperty(typeofNEFacts, literal.text) || 8192; return getTypeWithFacts(type, facts); } + function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { + if (!isMatchingReference(reference, propAccess.expression)) { + return type; + } + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var discriminantType = value.kind === 9 ? getStringLiteralTypeForText(value.text) : checkExpression(value); + if (!isStringLiteralUnionType(discriminantType)) { + return type; + } + if (operator === 31 || operator === 33) { + assumeTrue = !assumeTrue; + } + if (assumeTrue) { + return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); + } + if (discriminantType.flags & 256) { + return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); + } + return type; + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + if (!isMatchingReference(reference, switchStatement.expression.expression)) { + return type; + } + var propName = switchStatement.expression.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); + var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; + var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; + var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); + return caseType ? getUnionType([caseType, defaultType]) : defaultType; + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceFromExpression(expr.left); if (!isMatchingReference(reference, left)) { @@ -20316,11 +20960,11 @@ var ts; } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_12 = declaration.propertyName || declaration.name; + var name_13 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_12)) { - var text = getTextOfPropertyName(name_12); + !ts.isBindingPattern(name_13)) { + var text = getTextOfPropertyName(name_13); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -20446,9 +21090,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } - function contextualTypeIsStringLiteralType(type) { - return !!(type.flags & 16384 ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type)); - } function contextualTypeIsTupleLikeType(type) { return !!(type.flags & 16384 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } @@ -21215,7 +21856,7 @@ var ts; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { - if (right.text) { + if (right.text && !checkAndReportErrorForExtendingInterface(node)) { error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 ? apparentType : type)); } return unknownType; @@ -21308,15 +21949,15 @@ var ts; return unknownType; } if (node.argumentExpression) { - var name_13 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_13 !== undefined) { - var prop = getPropertyOfType(objectType, name_13); + var name_14 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_14 !== undefined) { + var prop = getPropertyOfType(objectType, name_14); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_13, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_14, symbolToString(objectType.symbol)); return unknownType; } } @@ -22135,8 +22776,10 @@ var ts; declaration.kind !== 152 && declaration.kind !== 157 && !ts.isJSDocConstructSignature(declaration)) { - var funcSymbol = checkExpression(node.expression).symbol; - if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16)) { + var funcSymbol = node.expression.kind === 69 ? + getResolvedSymbol(node.expression) : + checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return getInferredClassType(funcSymbol); } else if (compilerOptions.noImplicitAny) { @@ -22155,6 +22798,7 @@ var ts; } function checkAssertion(node) { var exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + checkSourceElement(node.type); var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { var widenedType = getWidenedType(exprType); @@ -22238,6 +22882,14 @@ var ts; } return emptyObjectType; } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return unknownType; + } + return promiseType; + } function getReturnTypeFromBody(func, contextualMapper) { var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { @@ -22267,18 +22919,10 @@ var ts; else { types = checkAndAggregateReturnExpressionTypes(func, contextualMapper); if (!types) { - return neverType; + return isAsync ? createPromiseReturnType(func, neverType) : neverType; } if (types.length === 0) { - if (isAsync) { - var promiseType = createPromiseType(voidType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - return voidType; + return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } type = contextualSignature ? getUnionType(types) : getCommonSupertype(types); @@ -22289,7 +22933,7 @@ var ts; } else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); - return getUnionType(types); + return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); } } if (funcIsGenerator) { @@ -22300,17 +22944,7 @@ var ts; reportErrorsFromWidening(func, type); } var widenedType = getWidenedType(type); - if (isAsync) { - var promiseType = createPromiseType(widenedType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - else { - return widenedType; - } + return isAsync ? createPromiseReturnType(func, widenedType) : widenedType; } function checkAndAggregateYieldOperandTypes(func, contextualMapper) { var aggregatedTypes = []; @@ -22328,10 +22962,40 @@ var ts; }); return aggregatedTypes; } + function isExhaustiveSwitchStatement(node) { + var expr = node.expression; + if (!node.possiblyExhaustive || expr.kind !== 172) { + return false; + } + var type = checkExpression(expr.expression); + if (!(type.flags & 16384)) { + return false; + } + var propName = expr.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length) { + return false; + } + return eachTypeContainedIn(propType, switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 32768)) { + return false; + } + var lastStatement = ts.lastOrUndefined(func.body.statements); + if (lastStatement && lastStatement.kind === 213 && isExhaustiveSwitchStatement(lastStatement)) { + return false; + } + return true; + } function checkAndAggregateReturnExpressionTypes(func, contextualMapper) { var isAsync = ts.isAsyncFunctionLike(func); var aggregatedTypes = []; - var hasReturnWithNoExpression = !!(func.flags & 32768); + var hasReturnWithNoExpression = functionHasImplicitReturn(func); var hasReturnOfTypeNever = false; ts.forEachReturnStatement(func.body, function (returnStatement) { var expr = returnStatement.expression; @@ -22369,7 +23033,7 @@ var ts; if (returnType && maybeTypeOfKind(returnType, 1 | 16)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !(func.flags & 32768)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 65536; @@ -22662,14 +23326,14 @@ var ts; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { if (property.kind === 253 || property.kind === 254) { - var name_14 = property.name; - if (name_14.kind === 140) { - checkComputedPropertyName(name_14); + var name_15 = property.name; + if (name_15.kind === 140) { + checkComputedPropertyName(name_15); } - if (isComputedNonLiteralName(name_14)) { + if (isComputedNonLiteralName(name_15)) { return undefined; } - var text = getTextOfPropertyName(name_14); + var text = getTextOfPropertyName(name_15); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -22684,7 +23348,7 @@ var ts; } } else { - error(name_14, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_14)); + error(name_15, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_15)); } } else { @@ -22880,7 +23544,7 @@ var ts; case 90: return checkInExpression(left, right, leftType, rightType); case 51: - return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 126) : rightType; + return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112) : rightType; case 52: return getUnionType([getNonNullableType(leftType), rightType]); case 56: @@ -22980,7 +23644,7 @@ var ts; } function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); - if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { + if (contextualType && isStringLiteralUnionType(contextualType)) { return getStringLiteralTypeForText(node.text); } return stringType; @@ -23223,9 +23887,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_15 = _a[_i].name; - if (ts.isBindingPattern(name_15) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_15, parameterName, typePredicate.parameterName)) { + var name_16 = _a[_i].name; + if (ts.isBindingPattern(name_16) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_16, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -23253,15 +23917,15 @@ var ts; } function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var name_16 = _a[_i].name; - if (name_16.kind === 69 && - name_16.text === predicateVariableName) { + var name_17 = _a[_i].name; + if (name_17.kind === 69 && + name_17.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_16.kind === 168 || - name_16.kind === 167) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_16, predicateVariableNode, predicateVariableName)) { + else if (name_17.kind === 168 || + name_17.kind === 167) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_17, predicateVariableNode, predicateVariableName)) { return true; } } @@ -23729,7 +24393,6 @@ var ts; } } } - var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & 1536; var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { @@ -23754,7 +24417,7 @@ var ts; duplicateFunctionDeclaration = true; } } - else if (!isExportSymbolInsideModule && previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { reportImplementationExpectedError(previousDeclaration); } if (ts.nodeIsPresent(node.body)) { @@ -23781,7 +24444,7 @@ var ts; error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); }); } - if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && !(lastSeenNonAmbientDeclaration.flags & 128) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } @@ -23872,7 +24535,7 @@ var ts; } function checkNonThenableType(type, location, message) { type = getWidenedType(type); - if (!isTypeAny(type) && isTypeAssignableTo(type, getGlobalThenableType())) { + if (!isTypeAny(type) && !isTypeNever(type) && isTypeAssignableTo(type, getGlobalThenableType())) { if (location) { if (!message) { message = ts.Diagnostics.Operand_for_await_does_not_have_a_valid_callable_then_member; @@ -23884,37 +24547,39 @@ var ts; return type; } function getPromisedType(promise) { - if (promise.flags & 1) { + if (isTypeAny(promise)) { return undefined; } - if ((promise.flags & 4096) && promise.target === tryGetGlobalPromiseType()) { - return promise.typeArguments[0]; + if (promise.flags & 4096) { + if (promise.target === tryGetGlobalPromiseType() + || promise.target === getGlobalPromiseLikeType()) { + return promise.typeArguments[0]; + } } var globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType(); if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) { return undefined; } var thenFunction = getTypeOfPropertyOfType(promise, "then"); - if (thenFunction && (thenFunction.flags & 1)) { + if (!thenFunction || isTypeAny(thenFunction)) { return undefined; } - var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0) : emptyArray; + var thenSignatures = getSignaturesOfType(thenFunction, 0); if (thenSignatures.length === 0) { return undefined; } var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072); - if (onfulfilledParameterType.flags & 1) { + if (isTypeAny(onfulfilledParameterType)) { return undefined; } var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0); if (onfulfilledParameterSignatures.length === 0) { return undefined; } - var valueParameterType = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); - return valueParameterType; + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); } function getTypeOfFirstParameterOfSignature(signature) { - return getTypeAtPosition(signature, 0); + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; } function getAwaitedType(type) { return checkAwaitedType(type, undefined, undefined); @@ -24255,8 +24920,8 @@ var ts; container.kind === 225 || container.kind === 256); if (!namesShareScope) { - var name_17 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_17, name_17); + var name_18 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_18, name_18); } } } @@ -24326,8 +24991,8 @@ var ts; } var parent_11 = node.parent.parent; var parentType = getTypeForBindingElementParent(parent_11); - var name_18 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_18)); + var name_19 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, getTextOfPropertyName(name_19)); if (parent_11.initializer && property && getParentOfSymbol(property)) { checkClassPropertyAccess(parent_11, parent_11.initializer, parentType, property); } @@ -25456,7 +26121,7 @@ var ts; if (isAmbientExternalModule) { if (ts.isExternalModuleAugmentation(node)) { var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432); - if (checkBody) { + if (checkBody && node.body) { for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { var statement = _a[_i]; checkModuleAugmentationElement(statement, isGlobalAugmentation); @@ -25481,7 +26146,12 @@ var ts; } } } - checkSourceElement(node.body); + if (compilerOptions.noImplicitAny && !node.body) { + reportImplicitAnyError(node, anyType); + } + if (node.body) { + checkSourceElement(node.body); + } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { @@ -25501,9 +26171,9 @@ var ts; break; case 169: case 218: - var name_19 = node.name; - if (ts.isBindingPattern(name_19)) { - for (var _b = 0, _c = name_19.elements; _b < _c.length; _b++) { + var name_20 = node.name; + if (ts.isBindingPattern(name_20)) { + for (var _b = 0, _c = name_20.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -26338,9 +27008,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols_3 = []; - var name_20 = symbol.name; + var name_21 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_20); + var symbol = getPropertyOfType(t, name_21); if (symbol) { symbols_3.push(symbol); } @@ -27041,7 +27711,10 @@ var ts; return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } else if (node.kind === 142 && (flags & 92) && ts.isBindingPattern(node.name)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 142 && (flags & 92) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256) { return checkGrammarAsyncModifier(node, lastAsync); @@ -27285,10 +27958,10 @@ var ts; var SetAccessor = 4; var GetOrSetAccessor = GetAccessor | SetAccessor; var _loop_1 = function(prop) { - var name_21 = prop.name; + var name_22 = prop.name; if (prop.kind === 193 || - name_21.kind === 140) { - checkGrammarComputedPropertyName(name_21); + name_22.kind === 140) { + checkGrammarComputedPropertyName(name_22); } if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { return { value: grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment) }; @@ -27301,8 +27974,8 @@ var ts; var currentKind = void 0; if (prop.kind === 253 || prop.kind === 254) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_21.kind === 8) { - checkGrammarNumericLiteral(name_21); + if (name_22.kind === 8) { + checkGrammarNumericLiteral(name_22); } currentKind = Property; } @@ -27318,7 +27991,7 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_21); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_22); if (effectiveName === undefined) { return "continue"; } @@ -27328,18 +28001,18 @@ var ts; else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_21, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_21)); + grammarErrorOnNode(name_22, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_22)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return { value: grammarErrorOnNode(name_21, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; + return { value: grammarErrorOnNode(name_22, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name) }; } } else { - return { value: grammarErrorOnNode(name_21, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; + return { value: grammarErrorOnNode(name_22, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name) }; } } }; @@ -27357,12 +28030,12 @@ var ts; continue; } var jsxAttr = attr; - var name_22 = jsxAttr.name; - if (!ts.hasProperty(seen, name_22.text)) { - seen[name_22.text] = true; + var name_23 = jsxAttr.name; + if (!ts.hasProperty(seen, name_23.text)) { + seen[name_23.text] = true; } else { - return grammarErrorOnNode(name_22, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_23, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; if (initializer && initializer.kind === 248 && !initializer.expression) { @@ -28425,9 +29098,9 @@ var ts; var count = 0; while (true) { count++; - var name_23 = baseName + "_" + count; - if (!ts.hasProperty(currentIdentifiers, name_23)) { - return name_23; + var name_24 = baseName + "_" + count; + if (!ts.hasProperty(currentIdentifiers, name_24)) { + return name_24; } } } @@ -28695,21 +29368,26 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body.kind !== 226) { + while (node.body && node.body.kind !== 226) { node = node.body; write("."); writeTextOfNode(currentText, node.name); } var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; + if (node.body) { + enclosingDeclaration = node; + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.body.statements); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + else { + write(";"); + } } function writeTypeAliasDeclaration(node) { var prevEnclosingDeclaration = enclosingDeclaration; @@ -29909,19 +30587,19 @@ var ts; } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_24 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_24)) { + var name_25 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_25)) { tempFlags |= flags; - return name_24; + return name_25; } } while (true) { var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name_25 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_25)) { - return name_25; + var name_26 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); + if (isUniqueName(name_26)) { + return name_26; } } } @@ -30617,8 +31295,8 @@ var ts; } else if (declaration.kind === 234) { write(getGeneratedNameForNode(declaration.parent.parent.parent)); - var name_26 = declaration.propertyName || declaration.name; - var identifier = ts.getTextOfNodeFromSourceText(currentText, name_26); + var name_27 = declaration.propertyName || declaration.name; + var identifier = ts.getTextOfNodeFromSourceText(currentText, name_27); if (languageVersion === 0 && identifier === "default") { write('["default"]'); } @@ -30671,8 +31349,8 @@ var ts; function emitIdentifier(node) { if (convertedLoopState) { if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { - var name_27 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); - write(name_27); + var name_28 = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); + write(name_28); return; } } @@ -31010,7 +31688,6 @@ var ts; function createPropertyAccessExpression(expression, name) { var result = ts.createSynthesizedNode(172); result.expression = parenthesizeForAccess(expression); - result.dotToken = ts.createSynthesizedNode(21); result.name = name; return result; } @@ -31056,9 +31733,9 @@ var ts; emitTrailingCommentsOfPosition(node.initializer.pos); emit(node.initializer); } - function isNamespaceExportReference(node) { + function isExportReference(node) { var container = resolver.getReferencedExportContainer(node); - return container && container.kind !== 256; + return !!container; } function isImportedReference(node) { var declaration = resolver.getReferencedImportDeclaration(node); @@ -31066,9 +31743,9 @@ var ts; } function emitShorthandPropertyAssignment(node) { writeTextOfNode(currentText, node.name); - if (languageVersion < 2 || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isNamespaceExportReference(node.name)) { + if (languageVersion < 2 || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isExportReference(node.name)) { write(": "); - emit(node.name); + emitExpressionIdentifier(node.name); } if (languageVersion >= 2 && node.objectAssignmentInitializer) { write(" = "); @@ -31117,13 +31794,16 @@ var ts; if (languageVersion === 2 && node.expression.kind === 95 && isInAsyncMethodWithSuperInES6(node)) { - var name_28 = ts.createSynthesizedNode(9); - name_28.text = node.name.text; - emitSuperAccessInAsyncMethod(node.expression, name_28); + var name_29 = ts.createSynthesizedNode(9); + name_29.text = node.name.text; + emitSuperAccessInAsyncMethod(node.expression, name_29); return; } emit(node.expression); - var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); + var dotRangeStart = ts.nodeIsSynthesized(node.expression) ? -1 : node.expression.end; + var dotRangeEnd = ts.nodeIsSynthesized(node.expression) ? -1 : ts.skipTrivia(currentText, node.expression.end) + 1; + var dotToken = { pos: dotRangeStart, end: dotRangeEnd }; + var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, dotToken); var shouldEmitSpace = false; if (!indentedBeforeDot) { if (node.expression.kind === 8) { @@ -31141,7 +31821,7 @@ var ts; else { write("."); } - var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); + var indentedAfterDot = indentIfOnDifferentLines(node, dotToken, node.name); emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); } @@ -31514,7 +32194,6 @@ var ts; synthesizedLHS = ts.createSynthesizedNode(172, false); var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, false, false); synthesizedLHS.expression = identifier; - synthesizedLHS.dotToken = leftHandSideExpression.dotToken; synthesizedLHS.name = leftHandSideExpression.name; write(", "); } @@ -32790,12 +33469,12 @@ var ts; function emitParameter(node) { if (languageVersion < 2) { if (ts.isBindingPattern(node.name)) { - var name_29 = createTempVariable(0); + var name_30 = createTempVariable(0); if (!tempParameters) { tempParameters = []; } - tempParameters.push(name_29); - emit(name_29); + tempParameters.push(name_30); + emit(name_30); } else { emit(node.name); @@ -33586,7 +34265,11 @@ var ts; } } function emitClassLikeDeclarationBelowES6(node) { + var isES6ExportedClass = isES6ExportedDeclaration(node); if (node.kind === 221) { + if (isES6ExportedClass && !(node.flags & 512)) { + write("export "); + } if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); } @@ -33650,9 +34333,15 @@ var ts; write(";"); } emitEnd(node); - if (node.kind === 221) { + if (node.kind === 221 && !isES6ExportedClass) { emitExportMemberAssignment(node); } + else if (isES6ExportedClass && (node.flags & 512)) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); @@ -33948,10 +34637,10 @@ var ts; } if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 160) { + if (parameterType && parameterType.kind === 160) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 155 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType && parameterType.kind === 155 && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { @@ -33968,9 +34657,15 @@ var ts; } } function emitSerializedReturnTypeOfNode(node) { - if (node && ts.isFunctionLike(node) && node.type) { - emitSerializedTypeNode(node.type); - return; + if (node && ts.isFunctionLike(node)) { + if (node.type) { + emitSerializedTypeNode(node.type); + return; + } + else if (ts.isAsyncFunctionLike(node)) { + write("Promise"); + return; + } } write("void 0"); } @@ -34103,7 +34798,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 225) { + if (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -34144,6 +34839,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); + ts.Debug.assert(node.body !== undefined); if (node.body.kind === 226) { var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; @@ -34523,8 +35219,8 @@ var ts; else { for (var _c = 0, _d = node.exportClause.elements; _c < _d.length; _c++) { var specifier = _d[_c]; - var name_30 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_30] || (exportSpecifiers[name_30] = [])).push(specifier); + var name_31 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_31] || (exportSpecifiers[name_31] = [])).push(specifier); } } break; @@ -34562,9 +35258,9 @@ var ts; } function getExternalModuleNameText(importNode, emitRelativePathAsModuleName) { if (emitRelativePathAsModuleName) { - var name_31 = getExternalModuleNameFromDeclaration(host, resolver, importNode); - if (name_31) { - return "\"" + name_31 + "\""; + var name_32 = getExternalModuleNameFromDeclaration(host, resolver, importNode); + if (name_32) { + return "\"" + name_32 + "\""; } } var moduleName = ts.getExternalModuleName(importNode); @@ -34710,11 +35406,11 @@ var ts; var seen = {}; for (var i = 0; i < hoistedVars.length; i++) { var local = hoistedVars[i]; - var name_32 = local.kind === 69 + var name_33 = local.kind === 69 ? local : local.name; - if (name_32) { - var text = ts.unescapeIdentifier(name_32.text); + if (name_33) { + var text = ts.unescapeIdentifier(name_33.text); if (ts.hasProperty(seen, text)) { continue; } @@ -34793,15 +35489,15 @@ var ts; } if (node.kind === 218 || node.kind === 169) { if (shouldHoistVariable(node, false)) { - var name_33 = node.name; - if (name_33.kind === 69) { + var name_34 = node.name; + if (name_34.kind === 69) { if (!hoistedVars) { hoistedVars = []; } - hoistedVars.push(name_33); + hoistedVars.push(name_34); } else { - ts.forEachChild(name_33, visit); + ts.forEachChild(name_34, visit); } } return; @@ -35711,13 +36407,9 @@ var ts; ts.emitTime = 0; ts.ioReadTime = 0; ts.ioWriteTime = 0; - var emptyArray = []; - var defaultLibrarySearchPaths = [ - "types/", - "node_modules/", - "node_modules/@types/", - ]; ts.version = "1.9.0"; + var emptyArray = []; + var defaultTypeRoots = ["node_modules/@types"]; function findConfigFile(searchPath, fileExists) { while (true) { var fileName = ts.combinePaths(searchPath, "tsconfig.json"); @@ -35845,6 +36537,10 @@ var ts; return undefined; } var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + return options.typeRoots || + ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(), d); }); + } function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); var moduleResolutionState = { @@ -35853,35 +36549,34 @@ var ts; skipTsx: true, traceEnabled: traceEnabled }; - var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : (host.getCurrentDirectory && host.getCurrentDirectory())); + var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); } } else { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } } var failedLookupLocations = []; - if (rootDir !== undefined) { - var effectivePrimarySearchPaths = options.typesSearchPaths || defaultLibrarySearchPaths; - for (var _i = 0, effectivePrimarySearchPaths_1 = effectivePrimarySearchPaths; _i < effectivePrimarySearchPaths_1.length; _i++) { - var searchPath = effectivePrimarySearchPaths_1[_i]; - var primaryPath = ts.combinePaths(rootDir, searchPath); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, primaryPath); - } - var candidate = ts.combinePaths(primaryPath, typeReferenceDirectiveName); + if (typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); if (resolvedFile_1) { @@ -35905,9 +36600,6 @@ var ts; if (containingFile) { initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); } - else { - initialLocationForSecondaryLookup = rootDir; - } if (initialLocationForSecondaryLookup !== undefined) { if (traceEnabled) { trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); @@ -36400,25 +37092,12 @@ var ts; } } } - function getDefaultTypeDirectiveNames(rootPath) { - var localTypes = ts.combinePaths(rootPath, "types"); - var npmTypes = ts.combinePaths(rootPath, "node_modules/@types"); - var result = []; - if (ts.sys.directoryExists(localTypes)) { - result = result.concat(ts.sys.getDirectories(localTypes)); - } - if (ts.sys.directoryExists(npmTypes)) { - result = result.concat(ts.sys.getDirectories(npmTypes)); - } - return result; - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); } var newLine = ts.getNewLineCharacter(options); var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); return { - getDefaultTypeDirectiveNames: getDefaultTypeDirectiveNames, getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -36431,6 +37110,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, + getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; } @@ -36473,32 +37153,39 @@ var ts; var resolutions = []; var cache = {}; for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_34 = names_1[_i]; + var name_35 = names_1[_i]; var result = void 0; - if (ts.hasProperty(cache, name_34)) { - result = cache[name_34]; + if (ts.hasProperty(cache, name_35)) { + result = cache[name_35]; } else { - result = loader(name_34, containingFile); - cache[name_34] = result; + result = loader(name_35, containingFile); + cache[name_35] = result; } resolutions.push(result); } return resolutions; } - function getDefaultTypeDirectiveNames(options, rootFiles, host) { + function getInferredTypesRoot(options, rootFiles, host) { + return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + function getAutomaticTypeDirectiveNames(options, rootFiles, host) { if (options.types) { return options.types; } - if (host && host.getDefaultTypeDirectiveNames) { - var commonRoot = computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); - if (commonRoot) { - return host.getDefaultTypeDirectiveNames(commonRoot); + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + result = result.concat(host.getDirectories(root)); + } } } - return undefined; + return result; } - ts.getDefaultTypeDirectiveNames = getDefaultTypeDirectiveNames; + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -36535,9 +37222,11 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - var typeReferences = getDefaultTypeDirectiveNames(options, rootNames, host); + var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); if (typeReferences) { - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, undefined); + var inferredRoot = getInferredTypesRoot(options, rootNames, host); + var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); } @@ -36600,8 +37289,8 @@ var ts; if (!classifiableNames) { getTypeChecker(); classifiableNames = {}; - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var sourceFile = files_3[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } @@ -36620,10 +37309,9 @@ var ts; (oldOptions.jsx !== options.jsx) || (oldOptions.allowJs !== options.allowJs) || (oldOptions.rootDir !== options.rootDir) || - (oldOptions.typesSearchPaths !== options.typesSearchPaths) || (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || - (oldOptions.typesRoot !== options.typesRoot) || + !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { return false; @@ -36915,8 +37603,20 @@ var ts; } break; case 145: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); - return true; + var propertyDeclaration = node; + if (propertyDeclaration.modifiers) { + for (var _i = 0, _a = propertyDeclaration.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 113) { + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + } + } + } + if (checkTypeAnnotation(node.type)) { + return true; + } + break; case 224: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return true; @@ -37048,9 +37748,12 @@ var ts; (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { - for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - collectModuleReferences(statement, true); + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, true); + } } } } @@ -37197,7 +37900,7 @@ var ts; } } else { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_name_0, typeReferenceDirective)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); } if (saveResolution) { resolvedTypeReferenceDirectives[typeReferenceDirective] = resolvedTypeReferenceDirective; @@ -37362,9 +38065,6 @@ var ts; var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } - if (options.module === ts.ModuleKind.ES6 && languageVersion < 2) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); - } if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); @@ -38069,10 +38769,10 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_35 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_35); + for (var name_36 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_36); if (declarations) { - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_35); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_36); if (!matches) { continue; } @@ -38083,14 +38783,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_35); + matches = patternMatcher.getMatches(containers, name_36); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_35, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_36, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -38220,622 +38920,539 @@ var ts; (function (ts) { var NavigationBar; (function (NavigationBar) { - function getNavigationBarItems(sourceFile, compilerOptions) { - if (ts.isSourceFileJavaScript(sourceFile)) { - return getJsNavigationBarItems(sourceFile, compilerOptions); + function getNavigationBarItems(sourceFile) { + curSourceFile = sourceFile; + var result = ts.map(topLevelItems(rootNavigationBarNode(sourceFile)), convertToTopLevelItem); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationBarItems = getNavigationBarItems; + var curSourceFile; + function nodeText(node) { + return node.getText(curSourceFile); + } + function navigationBarNodeKind(n) { + return n.node.kind; + } + function pushChild(parent, child) { + if (parent.children) { + parent.children.push(child); } - return getItemsWorker(getTopLevelNodes(sourceFile), createTopLevelItem); - function getIndent(node) { - var indent = 1; - var current = node.parent; - while (current) { - switch (current.kind) { - case 225: - do { - current = current.parent; - } while (current.kind === 225); - case 221: - case 224: - case 222: - case 220: - indent++; + else { + parent.children = [child]; + } + } + var parentsStack = []; + var parent; + function rootNavigationBarNode(sourceFile) { + ts.Debug.assert(!parentsStack.length); + var root = { node: sourceFile, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 }; + parent = root; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + addChildrenRecursively(statement); + } + endNode(); + ts.Debug.assert(!parent && !parentsStack.length); + return root; + } + function addLeafNode(node) { + pushChild(parent, emptyNavigationBarNode(node)); + } + function emptyNavigationBarNode(node) { + return { + node: node, + additionalNodes: undefined, + parent: parent, + children: undefined, + indent: parent.indent + 1 + }; + } + function startNode(node) { + var navNode = emptyNavigationBarNode(node); + pushChild(parent, navNode); + parentsStack.push(parent); + parent = navNode; + } + function endNode() { + if (parent.children) { + mergeChildren(parent.children); + sortChildren(parent.children); + } + parent = parentsStack.pop(); + } + function addNodeWithRecursiveChild(node, child) { + startNode(node); + addChildrenRecursively(child); + endNode(); + } + function addChildrenRecursively(node) { + if (!node || ts.isToken(node)) { + return; + } + switch (node.kind) { + case 148: + var ctr = node; + addNodeWithRecursiveChild(ctr, ctr.body); + for (var _i = 0, _a = ctr.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (ts.isParameterPropertyDeclaration(param)) { + addLeafNode(param); + } } - current = current.parent; - } - return indent; - } - function getChildNodes(nodes) { - var childNodes = []; - function visit(node) { - switch (node.kind) { - case 200: - ts.forEach(node.declarationList.declarations, visit); - break; - case 167: - case 168: - ts.forEach(node.elements, visit); - break; - case 236: - if (node.exportClause) { - ts.forEach(node.exportClause.elements, visit); + break; + case 147: + case 149: + case 150: + case 146: + if (!ts.hasDynamicName(node)) { + addNodeWithRecursiveChild(node, node.body); + } + break; + case 145: + case 144: + if (!ts.hasDynamicName(node)) { + addLeafNode(node); + } + break; + case 231: + var importClause = node; + if (importClause.name) { + addLeafNode(importClause); + } + var namedBindings = importClause.namedBindings; + if (namedBindings) { + if (namedBindings.kind === 232) { + addLeafNode(namedBindings); + } + else { + for (var _b = 0, _c = namedBindings.elements; _b < _c.length; _b++) { + var element = _c[_b]; + addLeafNode(element); } - break; - case 230: - var importClause = node.importClause; - if (importClause) { - if (importClause.name) { - childNodes.push(importClause); - } - if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 232) { - childNodes.push(importClause.namedBindings); - } - else { - ts.forEach(importClause.namedBindings.elements, visit); - } - } - } - break; - case 169: - case 218: - if (ts.isBindingPattern(node.name)) { - visit(node.name); - break; - } - case 221: - case 224: - case 222: - case 225: - case 220: - case 229: - case 234: - case 238: - case 223: - childNodes.push(node); - break; + } } - } - ts.forEach(nodes, visit); - return sortNodes(childNodes); - } - function getTopLevelNodes(node) { - var topLevelNodes = []; - topLevelNodes.push(node); - addTopLevelNodes(node.statements, topLevelNodes); - return topLevelNodes; - } - function sortNodes(nodes) { - return nodes.slice(0).sort(function (n1, n2) { - if (n1.name && n2.name) { - return localeCompareFix(ts.getPropertyNameForPropertyNameNode(n1.name), ts.getPropertyNameForPropertyNameNode(n2.name)); + break; + case 169: + case 218: + var decl = node; + var name_37 = decl.name; + if (ts.isBindingPattern(name_37)) { + addChildrenRecursively(name_37); } - else if (n1.name) { - return 1; - } - else if (n2.name) { - return -1; + else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { + addChildrenRecursively(decl.initializer); } else { - return n1.kind - n2.kind; + addNodeWithRecursiveChild(decl, decl.initializer); } - }); - function localeCompareFix(a, b) { - var cmp = a.toLowerCase().localeCompare(b.toLowerCase()); - if (cmp !== 0) - return cmp; - return a < b ? 1 : a > b ? -1 : 0; - } - } - function addTopLevelNodes(nodes, topLevelNodes) { - nodes = sortNodes(nodes); - for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { - var node = nodes_4[_i]; - switch (node.kind) { - case 221: - topLevelNodes.push(node); - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if (member.kind === 147 || member.kind === 148) { - if (member.body) { - if (hasNamedFunctionDeclarations(member.body.statements)) { - topLevelNodes.push(member); - } - addTopLevelNodes(member.body.statements, topLevelNodes); - } + break; + case 180: + case 220: + case 179: + addNodeWithRecursiveChild(node, node.body); + break; + case 224: + startNode(node); + for (var _d = 0, _e = node.members; _d < _e.length; _d++) { + var member = _e[_d]; + if (!isComputedProperty(member)) { + addLeafNode(member); + } + } + endNode(); + break; + case 221: + case 192: + case 222: + startNode(node); + for (var _f = 0, _g = node.members; _f < _g.length; _f++) { + var member = _g[_f]; + addChildrenRecursively(member); + } + endNode(); + break; + case 225: + addNodeWithRecursiveChild(node, getInteriorModule(node).body); + break; + case 238: + case 229: + case 153: + case 151: + case 152: + case 223: + addLeafNode(node); + break; + default: + if (node.jsDocComments) { + for (var _h = 0, _j = node.jsDocComments; _h < _j.length; _h++) { + var jsDocComment = _j[_h]; + for (var _k = 0, _l = jsDocComment.tags; _k < _l.length; _k++) { + var tag = _l[_k]; + if (tag.kind === 279) { + addLeafNode(tag); } } - break; - case 224: - case 222: - case 223: - topLevelNodes.push(node); - break; - case 225: - var moduleDeclaration = node; - topLevelNodes.push(node); - addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); - break; - case 220: - var functionDeclaration = node; - if (isTopLevelFunctionDeclaration(functionDeclaration)) { - topLevelNodes.push(node); - addTopLevelNodes(functionDeclaration.body.statements, topLevelNodes); - } - break; + } } - } + ts.forEachChild(node, addChildrenRecursively); } - function hasNamedFunctionDeclarations(nodes) { - for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { - var s = nodes_5[_i]; - if (s.kind === 220 && !isEmpty(s.name.text)) { + } + function mergeChildren(children) { + var nameToItems = {}; + ts.filterMutate(children, function (child) { + var decl = child.node; + var name = decl.name && nodeText(decl.name); + if (!name) { + return true; + } + var itemsWithSameName = ts.getProperty(nameToItems, name); + if (!itemsWithSameName) { + nameToItems[name] = child; + return true; + } + if (itemsWithSameName instanceof Array) { + for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { + var itemWithSameName = itemsWithSameName_1[_i]; + if (tryMerge(itemWithSameName, child)) { + return false; + } + } + itemsWithSameName.push(child); + return true; + } + else { + var itemWithSameName = itemsWithSameName; + if (tryMerge(itemWithSameName, child)) { + return false; + } + nameToItems[name] = [itemWithSameName, child]; + return true; + } + function tryMerge(a, b) { + if (shouldReallyMerge(a.node, b.node)) { + merge(a, b); return true; } + return false; } - return false; - } - function isTopLevelFunctionDeclaration(functionDeclaration) { - if (functionDeclaration.kind === 220) { - if (functionDeclaration.body && functionDeclaration.body.kind === 199) { - if (hasNamedFunctionDeclarations(functionDeclaration.body.statements)) { - return true; - } - if (!ts.isFunctionBlock(functionDeclaration.parent)) { - return true; - } - else { - var grandParentKind = functionDeclaration.parent.parent.kind; - if (grandParentKind === 147 || - grandParentKind === 148) { - return true; - } - } + }); + function shouldReallyMerge(a, b) { + return a.kind === b.kind && (a.kind !== 225 || areSameModule(a, b)); + function areSameModule(a, b) { + if (a.body.kind !== b.body.kind) { + return false; } - } - return false; - } - function getItemsWorker(nodes, createItem) { - var items = []; - var keyToItem = {}; - for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { - var child = nodes_6[_i]; - var item = createItem(child); - if (item !== undefined) { - if (item.text.length > 0) { - var key = item.text + "-" + item.kind + "-" + item.indent; - var itemWithSameName = keyToItem[key]; - if (itemWithSameName) { - merge(itemWithSameName, item); - } - else { - keyToItem[key] = item; - items.push(item); - } - } + if (a.body.kind !== 225) { + return true; } + return areSameModule(a.body, b.body); } - return items; } function merge(target, source) { - ts.addRange(target.spans, source.spans); - if (source.childItems) { - if (!target.childItems) { - target.childItems = []; - } - outer: for (var _i = 0, _a = source.childItems; _i < _a.length; _i++) { - var sourceChild = _a[_i]; - for (var _b = 0, _c = target.childItems; _b < _c.length; _b++) { - var targetChild = _c[_b]; - if (targetChild.text === sourceChild.text && targetChild.kind === sourceChild.kind) { - merge(targetChild, sourceChild); - continue outer; - } - } - target.childItems.push(sourceChild); - } + target.additionalNodes = target.additionalNodes || []; + target.additionalNodes.push(source.node); + if (source.additionalNodes) { + (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); + } + target.children = ts.concatenate(target.children, source.children); + if (target.children) { + mergeChildren(target.children); + sortChildren(target.children); + } + var _a; + } + } + function sortChildren(children) { + children.sort(compareChildren); + } + function compareChildren(child1, child2) { + var name1 = tryGetName(child1.node), name2 = tryGetName(child2.node); + if (name1 && name2) { + var cmp = localeCompareFix(name1, name2); + return cmp !== 0 ? cmp : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + } + else { + return name1 ? 1 : name2 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + } + } + var collator = typeof Intl === "undefined" ? undefined : new Intl.Collator(); + var localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; + var localeCompareFix = localeCompareIsCorrect ? collator.compare : function (a, b) { + for (var i = 0; i < Math.min(a.length, b.length); i++) { + var chA = a.charAt(i), chB = b.charAt(i); + if (chA === "\"" && chB === "'") { + return 1; + } + if (chA === "'" && chB === "\"") { + return -1; + } + var cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + if (cmp !== 0) { + return cmp; } } - function createChildItem(node) { - switch (node.kind) { - case 142: - if (ts.isBindingPattern(node.name)) { - break; - } - if ((node.flags & 1023) === 0) { - return undefined; - } - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 147: - case 146: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement); - case 149: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement); - case 150: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); - case 153: - return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - case 224: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.enumElement); - case 255: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 225: - return createItem(node, getModuleName(node), ts.ScriptElementKind.moduleElement); - case 222: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.interfaceElement); - case 223: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.typeElement); - case 151: - return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); - case 152: - return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); - case 145: - case 144: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 221: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.classElement); - case 220: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); - case 218: - case 169: - var variableDeclarationNode = void 0; - var name_36; - if (node.kind === 169) { - name_36 = node.name; - variableDeclarationNode = node; - while (variableDeclarationNode && variableDeclarationNode.kind !== 218) { - variableDeclarationNode = variableDeclarationNode.parent; - } - ts.Debug.assert(variableDeclarationNode !== undefined); - } - else { - ts.Debug.assert(!ts.isBindingPattern(node.name)); - variableDeclarationNode = node; - name_36 = node.name; - } - if (ts.isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.constElement); - } - else if (ts.isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.letElement); - } - else { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.variableElement); - } - case 148: - return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); - case 238: - case 234: - case 229: - case 231: - case 232: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); - } - return undefined; - function createItem(node, name, scriptElementKind) { - return getNavigationBarItem(name, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)]); - } + return a.length - b.length; + }; + function tryGetName(node) { + if (node.kind === 225) { + return getModuleName(node); } - function isEmpty(text) { - return !text || text.trim() === ""; + var decl = node; + if (decl.name) { + return ts.getPropertyNameForPropertyNameNode(decl.name); } - function getNavigationBarItem(text, kind, kindModifiers, spans, childItems, indent) { - if (childItems === void 0) { childItems = []; } - if (indent === void 0) { indent = 0; } - if (isEmpty(text)) { + switch (node.kind) { + case 179: + case 180: + case 192: + return getFunctionOrClassName(node); + case 279: + return getJSDocTypedefTagName(node); + default: return undefined; + } + } + function getItemName(node) { + if (node.kind === 225) { + return getModuleName(node); + } + var name = node.name; + if (name) { + var text = nodeText(name); + if (text.length > 0) { + return text; } + } + switch (node.kind) { + case 256: + var sourceFile = node; + return ts.isExternalModule(sourceFile) + ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" + : ""; + case 180: + case 220: + case 179: + case 221: + case 192: + if (node.flags & 512) { + return "default"; + } + return getFunctionOrClassName(node); + case 148: + return "constructor"; + case 152: + return "new()"; + case 151: + return "()"; + case 153: + return "[]"; + case 279: + return getJSDocTypedefTagName(node); + default: + ts.Debug.fail(); + return ""; + } + } + function getJSDocTypedefTagName(node) { + if (node.name) { + return node.name.text; + } + else { + var parentNode = node.parent && node.parent.parent; + if (parentNode && parentNode.kind === 200) { + if (parentNode.declarationList.declarations.length > 0) { + var nameIdentifier = parentNode.declarationList.declarations[0].name; + if (nameIdentifier.kind === 69) { + return nameIdentifier.text; + } + } + } + return ""; + } + } + function topLevelItems(root) { + var topLevel = []; + function recur(item) { + if (isTopLevel(item)) { + topLevel.push(item); + if (item.children) { + for (var _i = 0, _a = item.children; _i < _a.length; _i++) { + var child = _a[_i]; + recur(child); + } + } + } + } + recur(root); + return topLevel; + function isTopLevel(item) { + switch (navigationBarNodeKind(item)) { + case 221: + case 192: + case 224: + case 222: + case 225: + case 256: + case 223: + case 279: + return true; + case 148: + case 147: + case 149: + case 150: + return hasSomeImportantChild(item); + case 180: + case 220: + case 179: + return isTopLevelFunctionDeclaration(item); + default: + return false; + } + function isTopLevelFunctionDeclaration(item) { + if (!item.node.body) { + return false; + } + switch (navigationBarNodeKind(item.parent)) { + case 226: + case 256: + case 147: + case 148: + return true; + default: + return hasSomeImportantChild(item); + } + } + function hasSomeImportantChild(item) { + return ts.forEach(item.children, function (child) { + var childKind = navigationBarNodeKind(child); + return childKind !== 218 && childKind !== 169; + }); + } + } + } + var emptyChildItemArray = []; + function convertToTopLevelItem(n) { + return { + text: getItemName(n.node), + kind: nodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, + indent: n.indent, + bolded: false, + grayed: false + }; + function convertToChildItem(n) { return { - text: text, - kind: kind, - kindModifiers: kindModifiers, - spans: spans, - childItems: childItems, - indent: indent, + text: getItemName(n.node), + kind: nodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: emptyChildItemArray, + indent: 0, bolded: false, grayed: false }; } - function createTopLevelItem(node) { - switch (node.kind) { - case 256: - return createSourceFileItem(node); - case 221: - return createClassItem(node); - case 147: - case 148: - return createMemberFunctionLikeItem(node); - case 224: - return createEnumItem(node); - case 222: - return createInterfaceItem(node); - case 225: - return createModuleItem(node); - case 220: - return createFunctionItem(node); - case 223: - return createTypeAliasItem(node); - } - return undefined; - function createModuleItem(node) { - var moduleName = getModuleName(node); - var childItems = getItemsWorker(getChildNodes(getInnermostModule(node).body.statements), createChildItem); - return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createFunctionItem(node) { - if (node.body && node.body.kind === 199) { - var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); - return getNavigationBarItem(!node.name ? "default" : node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); } - return undefined; } - function createTypeAliasItem(node) { - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.typeElement, ts.getNodeModifiers(node), [getNodeSpan(node)], [], getIndent(node)); - } - function createMemberFunctionLikeItem(node) { - if (node.body && node.body.kind === 199) { - var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); - var scriptElementKind = void 0; - var memberFunctionName = void 0; - if (node.kind === 147) { - memberFunctionName = ts.getPropertyNameForPropertyNameNode(node.name); - scriptElementKind = ts.ScriptElementKind.memberFunctionElement; - } - else { - memberFunctionName = "constructor"; - scriptElementKind = ts.ScriptElementKind.constructorImplementationElement; - } - return getNavigationBarItem(memberFunctionName, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - return undefined; - } - function createSourceFileItem(node) { - var childItems = getItemsWorker(getChildNodes(node.statements), createChildItem); - var rootName = ts.isExternalModule(node) - ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(node.fileName)))) + "\"" - : ""; - return getNavigationBarItem(rootName, ts.ScriptElementKind.moduleElement, ts.ScriptElementKindModifier.none, [getNodeSpan(node)], childItems); - } - function createClassItem(node) { - var childItems; - if (node.members) { - var constructor = ts.forEach(node.members, function (member) { - return member.kind === 148 && member; - }); - var nodes = removeDynamicallyNamedProperties(node); - if (constructor) { - ts.addRange(nodes, ts.filter(constructor.parameters, function (p) { return !ts.isBindingPattern(p.name); })); - } - childItems = getItemsWorker(sortNodes(nodes), createChildItem); - } - var nodeName = !node.name ? "default" : node.name.text; - return getNavigationBarItem(nodeName, ts.ScriptElementKind.classElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createEnumItem(node) { - var childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem); - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.enumElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createInterfaceItem(node) { - var childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem); - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.interfaceElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - } - function getModuleName(moduleDeclaration) { - if (ts.isAmbientModule(moduleDeclaration)) { - return getTextOfNode(moduleDeclaration.name); - } - var result = []; - result.push(moduleDeclaration.name.text); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { - moduleDeclaration = moduleDeclaration.body; - result.push(moduleDeclaration.name.text); - } - return result.join("."); - } - function removeComputedProperties(node) { - return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 140; }); - } - function removeDynamicallyNamedProperties(node) { - return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); - } - function getInnermostModule(node) { - while (node.body.kind === 225) { - node = node.body; - } - return node; - } - function getNodeSpan(node) { - return node.kind === 256 - ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); - } - function getTextOfNode(node) { - return ts.getTextOfNodeFromSourceText(sourceFile.text, node); + return spans; } } - NavigationBar.getNavigationBarItems = getNavigationBarItems; - function getJsNavigationBarItems(sourceFile, compilerOptions) { - var anonFnText = ""; - var anonClassText = ""; - var indent = 0; - var rootName = ts.isExternalModule(sourceFile) ? - "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" - : ""; - var sourceFileItem = getNavBarItem(rootName, ts.ScriptElementKind.moduleElement, [getNodeSpan(sourceFile)]); - var topItem = sourceFileItem; - ts.forEachChild(sourceFile, visitNode); - function visitNode(node) { - var newItem = createNavBarItem(node); - if (newItem) { - topItem.childItems.push(newItem); - } - if (node.jsDocComments && node.jsDocComments.length > 0) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - visitNode(jsDocComment); - } - } - if (newItem && (ts.isFunctionLike(node) || ts.isClassLike(node))) { - var lastTop = topItem; - indent++; - topItem = newItem; - ts.forEachChild(node, visitNode); - topItem = lastTop; - indent--; - if (newItem && newItem.text === anonFnText && newItem.childItems.length === 0) { - topItem.childItems.pop(); - } - } - else { - ts.forEachChild(node, visitNode); - } - } - function createNavBarItem(node) { - switch (node.kind) { - case 218: - if (node.parent.parent - .parent.kind !== 256) { - return undefined; + function nodeKind(node) { + switch (node.kind) { + case 256: + return ts.ScriptElementKind.moduleElement; + case 255: + return ts.ScriptElementKind.memberVariableElement; + case 218: + case 169: + var variableDeclarationNode = void 0; + var name_38; + if (node.kind === 169) { + name_38 = node.name; + variableDeclarationNode = node; + while (variableDeclarationNode && variableDeclarationNode.kind !== 218) { + variableDeclarationNode = variableDeclarationNode.parent; } - var varDecl = node; - if (varDecl.initializer && (varDecl.initializer.kind === 179 || - varDecl.initializer.kind === 180 || - varDecl.initializer.kind === 192)) { - return undefined; - } - case 220: - case 221: - case 148: - case 149: - case 150: - var name_37 = node.flags && (node.flags & 512) && !node.name ? "default" : - node.kind === 148 ? "constructor" : - ts.declarationNameToString(node.name); - return getNavBarItem(name_37, getScriptKindForElementKind(node.kind), [getNodeSpan(node)]); - case 179: - case 180: - case 192: - return getDefineModuleItem(node) || getFunctionOrClassExpressionItem(node); - case 147: - var methodDecl = node; - return getNavBarItem(ts.declarationNameToString(methodDecl.name), ts.ScriptElementKind.memberFunctionElement, [getNodeSpan(node)]); - case 235: - return getNavBarItem("default", ts.ScriptElementKind.variableElement, [getNodeSpan(node)]); - case 231: - if (!node.name) { - return undefined; - } - case 234: - case 232: - case 238: - if (node.kind === 238) { - if (!node.parent.parent.moduleSpecifier && !node.propertyName) { - return undefined; - } - } - var decl = node; - if (!decl.name) { - return undefined; - } - var declName = ts.declarationNameToString(decl.name); - return getNavBarItem(declName, ts.ScriptElementKind.constElement, [getNodeSpan(node)]); - case 279: - if (node.name) { - return getNavBarItem(node.name.text, ts.ScriptElementKind.typeElement, [getNodeSpan(node)]); - } - else { - var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 200) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 69) { - return getNavBarItem(nameIdentifier.text, ts.ScriptElementKind.typeElement, [getNodeSpan(node)]); - } - } - } - } - default: - return undefined; - } - } - function getNavBarItem(text, kind, spans, kindModifiers) { - if (kindModifiers === void 0) { kindModifiers = ts.ScriptElementKindModifier.none; } - return { - text: text, kind: kind, kindModifiers: kindModifiers, spans: spans, childItems: [], indent: indent, bolded: false, grayed: false - }; - } - function getDefineModuleItem(node) { - if (node.kind !== 179 && node.kind !== 180) { - return undefined; - } - if (node.parent.kind !== 174) { - return undefined; - } - var callExpr = node.parent; - if (callExpr.expression.kind !== 69 || callExpr.expression.getText() !== "define") { - return undefined; - } - var defaultName = node.getSourceFile().fileName; - if (callExpr.arguments[0].kind === 9) { - defaultName = (callExpr.arguments[0]).text; - } - return getNavBarItem(defaultName, ts.ScriptElementKind.moduleElement, [getNodeSpan(node.parent)]); - } - function getFunctionOrClassExpressionItem(node) { - if (node.kind !== 179 && - node.kind !== 180 && - node.kind !== 192) { - return undefined; - } - var fnExpr = node; - var fnName; - if (fnExpr.name && ts.getFullWidth(fnExpr.name) > 0) { - fnName = ts.declarationNameToString(fnExpr.name); - } - else { - if (fnExpr.parent.kind === 218) { - fnName = ts.declarationNameToString(fnExpr.parent.name); - } - else if (fnExpr.parent.kind === 187 && - fnExpr.parent.operatorToken.kind === 56) { - fnName = fnExpr.parent.left.getText(); - } - else if (fnExpr.parent.kind === 253 && - fnExpr.parent.name) { - fnName = fnExpr.parent.name.getText(); + ts.Debug.assert(!!variableDeclarationNode); } else { - fnName = node.kind === 192 ? anonClassText : anonFnText; + ts.Debug.assert(!ts.isBindingPattern(node.name)); + variableDeclarationNode = node; + name_38 = node.name; } - } - var scriptKind = node.kind === 192 ? ts.ScriptElementKind.classElement : ts.ScriptElementKind.functionElement; - return getNavBarItem(fnName, scriptKind, [getNodeSpan(node)]); - } - function getNodeSpan(node) { - return node.kind === 256 - ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); - } - function getScriptKindForElementKind(kind) { - switch (kind) { - case 218: + if (ts.isConst(variableDeclarationNode)) { + return ts.ScriptElementKind.constElement; + } + else if (ts.isLet(variableDeclarationNode)) { + return ts.ScriptElementKind.letElement; + } + else { return ts.ScriptElementKind.variableElement; - case 220: - return ts.ScriptElementKind.functionElement; - case 221: - return ts.ScriptElementKind.classElement; - case 148: - return ts.ScriptElementKind.constructorImplementationElement; - case 149: - return ts.ScriptElementKind.memberGetAccessorElement; - case 150: - return ts.ScriptElementKind.memberSetAccessorElement; - default: - return "unknown"; - } + } + case 180: + return ts.ScriptElementKind.functionElement; + case 279: + return ts.ScriptElementKind.typeElement; + default: + return ts.getNodeKind(node); } - return sourceFileItem.childItems; } - NavigationBar.getJsNavigationBarItems = getJsNavigationBarItems; + function getModuleName(moduleDeclaration) { + if (ts.isAmbientModule(moduleDeclaration)) { + return ts.getTextOfNode(moduleDeclaration.name); + } + var result = []; + result.push(moduleDeclaration.name.text); + while (moduleDeclaration.body && moduleDeclaration.body.kind === 225) { + moduleDeclaration = moduleDeclaration.body; + result.push(moduleDeclaration.name.text); + } + return result.join("."); + } + function getInteriorModule(decl) { + return decl.body.kind === 225 ? getInteriorModule(decl.body) : decl; + } + function isComputedProperty(member) { + return !member.name || member.name.kind === 140; + } + function getNodeSpan(node) { + return node.kind === 256 + ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) + : ts.createTextSpanFromBounds(node.getStart(curSourceFile), node.getEnd()); + } + function getFunctionOrClassName(node) { + if (node.name && ts.getFullWidth(node.name) > 0) { + return ts.declarationNameToString(node.name); + } + else if (node.parent.kind === 218) { + return ts.declarationNameToString(node.parent.name); + } + else if (node.parent.kind === 187 && + node.parent.operatorToken.kind === 56) { + return nodeText(node.parent.left); + } + else if (node.parent.kind === 253 && node.parent.name) { + return nodeText(node.parent.name); + } + else if (node.flags & 512) { + return "default"; + } + else { + return ts.isClassLike(node) ? "" : ""; + } + } + function isFunctionOrClassExpression(node) { + return node.kind === 179 || node.kind === 180 || node.kind === 192; + } })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); var ts; @@ -40372,9 +40989,9 @@ var ts; getTypingNamesFromNodeModuleFolder(nodeModulesPath); } getTypingNamesFromSourceFileNames(fileNames); - for (var name_38 in packageNameToTypingLocation) { - if (ts.hasProperty(inferredTypings, name_38) && !inferredTypings[name_38]) { - inferredTypings[name_38] = packageNameToTypingLocation[name_38]; + for (var name_39 in packageNameToTypingLocation) { + if (ts.hasProperty(inferredTypings, name_39) && !inferredTypings[name_39]) { + inferredTypings[name_39] = packageNameToTypingLocation[name_39]; } } for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { @@ -40442,9 +41059,9 @@ var ts; return; } var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, "*.json", undefined, 2); - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; + var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], undefined, undefined, 2); + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); if (ts.getBaseFileName(normalizedFileName) !== "package.json") { continue; @@ -41032,9 +41649,9 @@ var ts; } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_39 in o) { - if (o[name_39] === rule) { - return name_39; + for (var name_40 in o) { + if (o[name_40] === rule) { + return name_40; } } throw new Error("Unknown rule"); @@ -42880,8 +43497,8 @@ var ts; var list = createNode(282, nodes.pos, nodes.end, 0, this); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { - var node = nodes_7[_i]; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; if (pos < node.pos) { pos = this.addSyntheticNodes(list._children, pos, node.pos); } @@ -43007,7 +43624,7 @@ var ts; } addCommentParts(declaration.parent, sourceFileOfDeclaration, getCleanedParamJsDocComment); } - if (declaration.kind === 225 && declaration.body.kind === 225) { + if (declaration.kind === 225 && declaration.body && declaration.body.kind === 225) { return; } if ((declaration.kind === 179 || declaration.kind === 180) && @@ -43706,9 +44323,9 @@ var ts; sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - var commandLineOptions_stringToEnum; + var commandLineOptionsStringToEnum; function fixupCompilerOptions(options, diagnostics) { - commandLineOptions_stringToEnum = commandLineOptions_stringToEnum || ts.filter(ts.optionDeclarations, function (o) { + commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachValue(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); @@ -43726,8 +44343,8 @@ var ts; } } }; - for (var _i = 0, commandLineOptions_stringToEnum_1 = commandLineOptions_stringToEnum; _i < commandLineOptions_stringToEnum_1.length; _i++) { - var opt = commandLineOptions_stringToEnum_1[_i]; + for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { + var opt = commandLineOptionsStringToEnum_1[_i]; _loop_2(opt); } return options; @@ -43739,6 +44356,16 @@ var ts; options.suppressOutputPathCheck = true; options.allowNonTsExtensions = true; options.noLib = true; + options.lib = undefined; + options.types = undefined; + options.noEmit = undefined; + options.noEmitOnError = undefined; + options.paths = undefined; + options.rootDirs = undefined; + options.declaration = undefined; + options.declarationDir = undefined; + options.out = undefined; + options.outFile = undefined; options.noResolve = true; var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); var sourceFile = ts.createSourceFile(inputFileName, input, options.target); @@ -43768,7 +44395,8 @@ var ts; getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, readFile: function (fileName) { return ""; }, - directoryExists: function (directoryExists) { return true; } + directoryExists: function (directoryExists) { return true; }, + getDirectories: function (path) { return []; } }; var program = ts.createProgram([inputFileName], options, compilerHost); if (transpileOptions.reportDiagnostics) { @@ -43837,7 +44465,7 @@ var ts; var buckets = {}; var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyForCompilationSettings(settings) { - return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + settings.typesRoot + "|" + settings.typesSearchPaths + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); + return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = ts.lookUp(buckets, key); @@ -44487,7 +45115,8 @@ var ts; oldSettings.moduleResolution !== newSettings.moduleResolution || oldSettings.noResolve !== newSettings.noResolve || oldSettings.jsx !== newSettings.jsx || - oldSettings.allowJs !== newSettings.allowJs); + oldSettings.allowJs !== newSettings.allowJs || + oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit); var compilerHost = { getSourceFile: getOrCreateSourceFile, getSourceFileByPath: getOrCreateSourceFileByPath, @@ -44507,8 +45136,10 @@ var ts; return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); }, directoryExists: function (directoryName) { - ts.Debug.assert(!host.resolveModuleNames || !host.resolveTypeReferenceDirectives); return ts.directoryProbablyExists(directoryName, host); + }, + getDirectories: function (path) { + return host.getDirectories ? host.getDirectories(path) : []; } }; if (host.trace) { @@ -45164,8 +45795,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_40 = element.propertyName || element.name; - existingImportsOrExports[name_40.text] = true; + var name_41 = element.propertyName || element.name; + existingImportsOrExports[name_41.text] = true; } if (ts.isEmpty(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); @@ -45260,13 +45891,13 @@ var ts; var entries = []; var target = program.getCompilerOptions().target; var nameTable = getNameTable(sourceFile); - for (var name_41 in nameTable) { - if (nameTable[name_41] === position) { + for (var name_42 in nameTable) { + if (nameTable[name_42] === position) { continue; } - if (!uniqueNames[name_41]) { - uniqueNames[name_41] = name_41; - var displayName = getCompletionEntryDisplayName(name_41, target, true); + if (!uniqueNames[name_42]) { + uniqueNames[name_42] = name_42; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_42), target, true); if (displayName) { var entry = { name: displayName, @@ -45370,10 +46001,10 @@ var ts; var typeChecker = program.getTypeChecker(); var type = typeChecker.getContextualType(node); if (type) { - var entries_1 = []; - addStringLiteralCompletionsFromType(type, entries_1); - if (entries_1.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_1 }; + var entries_2 = []; + addStringLiteralCompletionsFromType(type, entries_2); + if (entries_2.length) { + return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -46572,7 +47203,8 @@ var ts; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference + isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference, + isDefinition: false }); } } @@ -46853,7 +47485,8 @@ var ts; references: [{ fileName: sourceFile.fileName, textSpan: ts.createTextSpan(position, searchText.length), - isWriteAccess: false + isWriteAccess: false, + isDefinition: false }] }); } @@ -47231,7 +47864,8 @@ var ts; return { fileName: node.getSourceFile().fileName, textSpan: ts.createTextSpanFromBounds(start, end), - isWriteAccess: isWriteAccess(node) + isWriteAccess: isWriteAccess(node), + isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node) }; } function isWriteAccess(node) { @@ -47452,7 +48086,7 @@ var ts; } function getNavigationBarItems(fileName) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile, host.getCompilationSettings()); + return ts.NavigationBar.getNavigationBarItems(sourceFile); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); @@ -47831,7 +48465,8 @@ var ts; return; case 142: if (token.parent.name === token) { - return 17; + var isThis = token.kind === 69 && token.originalKeywordKind === 97; + return isThis ? 3 : 17; } return; } @@ -49028,7 +49663,7 @@ var ts; Session.prototype.getDefinition = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49046,7 +49681,7 @@ var ts; Session.prototype.getTypeDefinition = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49064,7 +49699,7 @@ var ts; Session.prototype.getOccurrences = function (line, offset, fileName) { fileName = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(fileName); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49088,7 +49723,7 @@ var ts; Session.prototype.getDocumentHighlights = function (line, offset, fileName, filesToSearch) { fileName = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(fileName); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49115,8 +49750,12 @@ var ts; Session.prototype.getProjectInfo = function (fileName, needFileNameList) { fileName = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(fileName); + if (!project) { + throw Errors.NoProject; + } var projectInfo = { - configFileName: project.projectFilename + configFileName: project.projectFilename, + languageServiceDisabled: project.languageServiceDiabled }; if (needFileNameList) { projectInfo.fileNames = project.getFileNames(); @@ -49127,10 +49766,11 @@ var ts; var file = ts.normalizePath(fileName); var info = this.projectService.getScriptInfo(file); var projects = this.projectService.findReferencingProjects(info); - if (!projects.length) { + var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); + if (projectsWithLanguageServiceEnabeld.length === 0) { throw Errors.NoProject; } - var defaultProject = projects[0]; + var defaultProject = projectsWithLanguageServiceEnabeld[0]; var defaultProjectCompilerService = defaultProject.compilerService; var position = defaultProjectCompilerService.host.lineOffsetToPosition(file, line, offset); var renameInfo = defaultProjectCompilerService.languageService.getRenameInfo(file, position); @@ -49143,7 +49783,7 @@ var ts; locs: [] }; } - var fileSpans = server.combineProjectOutput(projects, function (project) { + var fileSpans = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { var compilerService = project.compilerService; var renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments); if (!renameLocations) { @@ -49195,10 +49835,11 @@ var ts; var file = ts.normalizePath(fileName); var info = this.projectService.getScriptInfo(file); var projects = this.projectService.findReferencingProjects(info); - if (!projects.length) { + var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); + if (projectsWithLanguageServiceEnabeld.length === 0) { throw Errors.NoProject; } - var defaultProject = projects[0]; + var defaultProject = projectsWithLanguageServiceEnabeld[0]; var position = defaultProject.compilerService.host.lineOffsetToPosition(file, line, offset); var nameInfo = defaultProject.compilerService.languageService.getQuickInfoAtPosition(file, position); if (!nameInfo) { @@ -49208,7 +49849,7 @@ var ts; var nameSpan = nameInfo.textSpan; var nameColStart = defaultProject.compilerService.host.positionToLineOffset(file, nameSpan.start).offset; var nameText = defaultProject.compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan)); - var refs = server.combineProjectOutput(projects, function (project) { + var refs = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { var compilerService = project.compilerService; var references = compilerService.languageService.getReferencesAtPosition(file, position); if (!references) { @@ -49224,7 +49865,8 @@ var ts; start: start, lineText: lineText, end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)), - isWriteAccess: ref.isWriteAccess + isWriteAccess: ref.isWriteAccess, + isDefinition: ref.isDefinition }; }); }, compareFileStart, areReferencesResponseItemsForTheSameLocation); @@ -49253,7 +49895,7 @@ var ts; Session.prototype.getQuickInfo = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49276,7 +49918,7 @@ var ts; Session.prototype.getFormattingEditsForRange = function (line, offset, endLine, endOffset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49297,7 +49939,7 @@ var ts; Session.prototype.getFormattingEditsAfterKeystroke = function (line, offset, key, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49360,7 +50002,7 @@ var ts; } var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49379,7 +50021,7 @@ var ts; Session.prototype.getCompletionEntryDetails = function (line, offset, entryNames, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49395,7 +50037,7 @@ var ts; Session.prototype.getSignatureHelpItems = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49422,7 +50064,7 @@ var ts; var checkList = fileNames.reduce(function (accum, fileName) { fileName = ts.normalizePath(fileName); var project = _this.projectService.getProjectForFile(fileName); - if (project) { + if (project && !project.languageServiceDiabled) { accum.push({ fileName: fileName, project: project }); } return accum; @@ -49435,7 +50077,7 @@ var ts; var _this = this; var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (project) { + if (project && !project.languageServiceDiabled) { var compilerService = project.compilerService; var start = compilerService.host.lineOffsetToPosition(file, line, offset); var end = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); @@ -49452,7 +50094,7 @@ var ts; var file = ts.normalizePath(fileName); var tmpfile = ts.normalizePath(tempFileName); var project = this.projectService.getProjectForFile(file); - if (project) { + if (project && !project.languageServiceDiabled) { this.changeSeq++; project.compilerService.host.reloadScript(file, tmpfile, function () { _this.output(undefined, CommandNames.Reload, reqSeq); @@ -49463,7 +50105,7 @@ var ts; var file = ts.normalizePath(fileName); var tmpfile = ts.normalizePath(tempFileName); var project = this.projectService.getProjectForFile(file); - if (project) { + if (project && !project.languageServiceDiabled) { project.compilerService.host.saveTo(file, tmpfile); } }; @@ -49474,7 +50116,7 @@ var ts; var file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); }; - Session.prototype.decorateNavigationBarItem = function (project, fileName, items) { + Session.prototype.decorateNavigationBarItem = function (project, fileName, items, lineIndex) { var _this = this; if (!items) { return undefined; @@ -49485,17 +50127,17 @@ var ts; kind: item.kind, kindModifiers: item.kindModifiers, spans: item.spans.map(function (span) { return ({ - start: compilerService.host.positionToLineOffset(fileName, span.start), - end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span)) + start: compilerService.host.positionToLineOffset(fileName, span.start, lineIndex), + end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span), lineIndex) }); }), - childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems), + childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems, lineIndex), indent: item.indent }); }); }; Session.prototype.getNavigationBarItems = function (fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49503,17 +50145,17 @@ var ts; if (!items) { return undefined; } - return this.decorateNavigationBarItem(project, fileName, items); + return this.decorateNavigationBarItem(project, fileName, items, compilerService.host.getLineIndex(fileName)); }; Session.prototype.getNavigateToItems = function (searchValue, fileName, maxResultCount) { var file = ts.normalizePath(fileName); var info = this.projectService.getScriptInfo(file); var projects = this.projectService.findReferencingProjects(info); - var defaultProject = projects[0]; - if (!defaultProject) { + var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); + if (projectsWithLanguageServiceEnabeld.length === 0) { throw Errors.NoProject; } - var allNavToItems = server.combineProjectOutput(projects, function (project) { + var allNavToItems = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { var compilerService = project.compilerService; var navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount); if (!navItems) { @@ -49557,7 +50199,7 @@ var ts; Session.prototype.getBraceMatching = function (line, offset, fileName) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); - if (!project) { + if (!project || project.languageServiceDiabled) { throw Errors.NoProject; } var compilerService = project.compilerService; @@ -49573,7 +50215,10 @@ var ts; }; Session.prototype.getDiagnosticsForProject = function (delay, fileName) { var _this = this; - var fileNames = this.getProjectInfo(fileName, true).fileNames; + var _a = this.getProjectInfo(fileName, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; + if (languageServiceDisabled) { + return; + } var fileNamesInProject = fileNames.filter(function (value, index, array) { return value.indexOf("lib.d.ts") < 0; }); var highPriorityFiles = []; var mediumPriorityFiles = []; @@ -49683,6 +50328,7 @@ var ts; } }); } + server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; var ScriptInfo = (function () { function ScriptInfo(host, fileName, content, isOpen) { if (isOpen === void 0) { isOpen = false; } @@ -49752,17 +50398,17 @@ var ts; var resolvedModules = []; var compilerOptions = this.getCompilationSettings(); for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_42 = names_2[_i]; - var resolution = ts.lookUp(newResolutions, name_42); + var name_43 = names_2[_i]; + var resolution = ts.lookUp(newResolutions, name_43); if (!resolution) { - var existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, name_42); + var existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, name_43); if (moduleResolutionIsValid(existingResolution)) { resolution = existingResolution; } else { - resolution = loader(name_42, containingFile, compilerOptions, this.moduleResolutionHost); + resolution = loader(name_43, containingFile, compilerOptions, this.moduleResolutionHost); resolution.lastCheckTime = Date.now(); - newResolutions[name_42] = resolution; + newResolutions[name_43] = resolution; } } ts.Debug.assert(resolution !== undefined); @@ -49898,6 +50544,9 @@ var ts; LSHost.prototype.directoryExists = function (path) { return this.host.directoryExists(path); }; + LSHost.prototype.getDirectories = function (path) { + return this.host.getDirectories(path); + }; LSHost.prototype.lineToTextSpan = function (filename, line) { var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); var script = this.filenameToScript.get(path); @@ -49920,20 +50569,25 @@ var ts; var lineInfo = index.lineNumberToInfo(line); return (lineInfo.offset + offset - 1); }; - LSHost.prototype.positionToLineOffset = function (filename, position) { + LSHost.prototype.positionToLineOffset = function (filename, position, lineIndex) { + lineIndex = lineIndex || this.getLineIndex(filename); + var lineOffset = lineIndex.charOffsetToLineNumberAndPos(position); + return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + }; + LSHost.prototype.getLineIndex = function (filename) { var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); var script = this.filenameToScript.get(path); - var index = script.snap().index; - var lineOffset = index.charOffsetToLineNumberAndPos(position); - return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + return script.snap().index; }; return LSHost; }()); server.LSHost = LSHost; var Project = (function () { - function Project(projectService, projectOptions) { + function Project(projectService, projectOptions, languageServiceDiabled) { + if (languageServiceDiabled === void 0) { languageServiceDiabled = false; } this.projectService = projectService; this.projectOptions = projectOptions; + this.languageServiceDiabled = languageServiceDiabled; this.directoriesWatchedForTsconfig = []; this.filenameToSourceFile = {}; this.updateGraphSeq = 0; @@ -49941,8 +50595,19 @@ var ts; if (projectOptions && projectOptions.files) { projectOptions.compilerOptions.allowNonTsExtensions = true; } - this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions); + if (!languageServiceDiabled) { + this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions); + } } + Project.prototype.enableLanguageService = function () { + if (this.languageServiceDiabled) { + this.compilerService = new CompilerService(this, this.projectOptions && this.projectOptions.compilerOptions); + } + this.languageServiceDiabled = false; + }; + Project.prototype.disableLanguageService = function () { + this.languageServiceDiabled = true; + }; Project.prototype.addOpenRef = function () { this.openRefCount++; }; @@ -49954,16 +50619,36 @@ var ts; return this.projectService.openFile(filename, false); }; Project.prototype.getRootFiles = function () { + if (this.languageServiceDiabled) { + return this.projectOptions ? this.projectOptions.files : undefined; + } return this.compilerService.host.roots.map(function (info) { return info.fileName; }); }; Project.prototype.getFileNames = function () { + if (this.languageServiceDiabled) { + if (!this.projectOptions) { + return undefined; + } + var fileNames = []; + if (this.projectOptions && this.projectOptions.compilerOptions) { + fileNames.push(ts.getDefaultLibFilePath(this.projectOptions.compilerOptions)); + } + ts.addRange(fileNames, this.projectOptions.files); + return fileNames; + } var sourceFiles = this.program.getSourceFiles(); return sourceFiles.map(function (sourceFile) { return sourceFile.fileName; }); }; Project.prototype.getSourceFile = function (info) { + if (this.languageServiceDiabled) { + return undefined; + } return this.filenameToSourceFile[info.fileName]; }; Project.prototype.getSourceFileFromName = function (filename, requireOpen) { + if (this.languageServiceDiabled) { + return undefined; + } var info = this.projectService.getScriptInfo(filename); if (info) { if ((!requireOpen) || info.isOpen) { @@ -49972,13 +50657,22 @@ var ts; } }; Project.prototype.isRoot = function (info) { + if (this.languageServiceDiabled) { + return undefined; + } return this.compilerService.host.roots.some(function (root) { return root === info; }); }; Project.prototype.removeReferencedFile = function (info) { + if (this.languageServiceDiabled) { + return; + } this.compilerService.host.removeReferencedFile(info); this.updateGraph(); }; Project.prototype.updateFileMap = function () { + if (this.languageServiceDiabled) { + return; + } this.filenameToSourceFile = {}; var sourceFiles = this.program.getSourceFiles(); for (var i = 0, len = sourceFiles.length; i < len; i++) { @@ -49987,10 +50681,16 @@ var ts; } }; Project.prototype.finishGraph = function () { + if (this.languageServiceDiabled) { + return; + } this.updateGraph(); this.compilerService.languageService.getNavigateToItems(".*"); }; Project.prototype.updateGraph = function () { + if (this.languageServiceDiabled) { + return; + } this.program = this.compilerService.languageService.getProgram(); this.updateFileMap(); }; @@ -49998,12 +50698,25 @@ var ts; return this.projectFilename; }; Project.prototype.addRoot = function (info) { + if (this.languageServiceDiabled) { + return; + } this.compilerService.host.addRoot(info); }; Project.prototype.removeRoot = function (info) { + if (this.languageServiceDiabled) { + return; + } this.compilerService.host.removeRoot(info); }; Project.prototype.filesToString = function () { + if (this.languageServiceDiabled) { + if (this.projectOptions) { + var strBuilder_1 = ""; + ts.forEach(this.projectOptions.files, function (file) { strBuilder_1 += file + "\n"; }); + return strBuilder_1; + } + } var strBuilder = ""; ts.forEachValue(this.filenameToSourceFile, function (sourceFile) { strBuilder += sourceFile.fileName + "\n"; }); return strBuilder; @@ -50012,7 +50725,9 @@ var ts; this.projectOptions = projectOptions; if (projectOptions.compilerOptions) { projectOptions.compilerOptions.allowNonTsExtensions = true; - this.compilerService.setCompilerOptions(projectOptions.compilerOptions); + if (!this.languageServiceDiabled) { + this.compilerService.setCompilerOptions(projectOptions.compilerOptions); + } } }; return Project; @@ -50222,6 +50937,8 @@ var ts; if (project.isConfiguredProject()) { project.projectFileWatcher.close(); project.directoryWatcher.close(); + ts.forEachValue(project.directoriesWatchedForWildcards, function (watcher) { watcher.close(); }); + delete project.directoriesWatchedForWildcards; this.configuredProjects = copyListRemovingItem(project, this.configuredProjects); } else { @@ -50237,8 +50954,8 @@ var ts; this.inferredProjects = copyListRemovingItem(project, this.inferredProjects); } var fileNames = project.getFileNames(); - for (var _b = 0, fileNames_2 = fileNames; _b < fileNames_2.length; _b++) { - var fileName = fileNames_2[_b]; + for (var _b = 0, fileNames_3 = fileNames; _b < fileNames_3.length; _b++) { + var fileName = fileNames_3[_b]; var info = this.getScriptInfo(fileName); if (info.defaultProject == project) { info.defaultProject = undefined; @@ -50263,6 +50980,7 @@ var ts; else { this.findReferencingProjects(info); if (info.defaultProject) { + info.defaultProject.addOpenRef(); this.openFilesReferenced.push(info); } else { @@ -50615,12 +51333,30 @@ var ts; else { var projectOptions = { files: parsedCommandLine.fileNames, + wildcardDirectories: parsedCommandLine.wildcardDirectories, compilerOptions: parsedCommandLine.options }; return { succeeded: true, projectOptions: projectOptions }; } } }; + ProjectService.prototype.exceedTotalNonTsFileSizeLimit = function (fileNames) { + var totalNonTsFileSize = 0; + if (!this.host.getFileSize) { + return false; + } + for (var _i = 0, fileNames_4 = fileNames; _i < fileNames_4.length; _i++) { + var fileName = fileNames_4[_i]; + if (ts.hasTypeScriptFileExtension(fileName)) { + continue; + } + totalNonTsFileSize += this.host.getFileSize(fileName); + if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { + return true; + } + } + return false; + }; ProjectService.prototype.openConfigFile = function (configFilename, clientFileName) { var _this = this; var _a = this.configFileToProjectOptions(configFilename), succeeded = _a.succeeded, projectOptions = _a.projectOptions, errors = _a.errors; @@ -50628,23 +51364,39 @@ var ts; return { success: false, errors: errors }; } else { - var project_1 = this.createProject(configFilename, projectOptions); + if (!projectOptions.compilerOptions.disableSizeLimit && projectOptions.compilerOptions.allowJs) { + if (this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { + var project_1 = this.createProject(configFilename, projectOptions, true); + project_1.projectFileWatcher = this.host.watchFile(ts.toPath(configFilename, configFilename, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); + return { success: true, project: project_1 }; + } + } + var project_2 = this.createProject(configFilename, projectOptions); var errors_1; for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { var rootFilename = _b[_i]; if (this.host.fileExists(rootFilename)) { var info = this.openFile(rootFilename, clientFileName == rootFilename); - project_1.addRoot(info); + project_2.addRoot(info); } else { (errors_1 || (errors_1 = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, rootFilename)); } } - project_1.finishGraph(); - project_1.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); - this.log("Add recursive watcher for: " + ts.getDirectoryPath(configFilename)); - project_1.directoryWatcher = this.host.watchDirectory(ts.getDirectoryPath(configFilename), function (path) { return _this.directoryWatchedForSourceFilesChanged(project_1, path); }, true); - return { success: true, project: project_1, errors: errors_1 }; + project_2.finishGraph(); + project_2.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project_2); }); + var configDirectoryPath_1 = ts.getDirectoryPath(configFilename); + this.log("Add recursive watcher for: " + configDirectoryPath_1); + project_2.directoryWatcher = this.host.watchDirectory(configDirectoryPath_1, function (path) { return _this.directoryWatchedForSourceFilesChanged(project_2, path); }, true); + project_2.directoriesWatchedForWildcards = ts.reduceProperties(projectOptions.wildcardDirectories, function (watchers, flag, directory) { + if (ts.comparePaths(configDirectoryPath_1, directory, ".", !_this.host.useCaseSensitiveFileNames) !== 0) { + var recursive = (flag & 1) !== 0; + _this.log("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); + watchers[directory] = _this.host.watchDirectory(directory, function (path) { return _this.directoryWatchedForSourceFilesChanged(project_2, path); }, recursive); + } + return watchers; + }, {}); + return { success: true, project: project_2, errors: errors_1 }; } }; ProjectService.prototype.updateConfiguredProject = function (project) { @@ -50659,19 +51411,45 @@ var ts; return errors; } else { - var oldFileNames_1 = project.compilerService.host.roots.map(function (info) { return info.fileName; }); + if (projectOptions.compilerOptions && !projectOptions.compilerOptions.disableSizeLimit && this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { + project.setProjectOptions(projectOptions); + if (project.languageServiceDiabled) { + return; + } + project.disableLanguageService(); + if (project.directoryWatcher) { + project.directoryWatcher.close(); + project.directoryWatcher = undefined; + } + return; + } + if (project.languageServiceDiabled) { + project.setProjectOptions(projectOptions); + project.enableLanguageService(); + project.directoryWatcher = this.host.watchDirectory(ts.getDirectoryPath(project.projectFilename), function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); + for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { + var rootFilename = _b[_i]; + if (this.host.fileExists(rootFilename)) { + var info = this.openFile(rootFilename, false); + project.addRoot(info); + } + } + project.finishGraph(); + return; + } + var oldFileNames_1 = project.projectOptions ? project.projectOptions.files : project.compilerService.host.roots.map(function (info) { return info.fileName; }); var newFileNames_1 = ts.filter(projectOptions.files, function (f) { return _this.host.fileExists(f); }); var fileNamesToRemove = oldFileNames_1.filter(function (f) { return newFileNames_1.indexOf(f) < 0; }); var fileNamesToAdd = newFileNames_1.filter(function (f) { return oldFileNames_1.indexOf(f) < 0; }); - for (var _i = 0, fileNamesToRemove_1 = fileNamesToRemove; _i < fileNamesToRemove_1.length; _i++) { - var fileName = fileNamesToRemove_1[_i]; + for (var _c = 0, fileNamesToRemove_1 = fileNamesToRemove; _c < fileNamesToRemove_1.length; _c++) { + var fileName = fileNamesToRemove_1[_c]; var info = this.getScriptInfo(fileName); if (info) { project.removeRoot(info); } } - for (var _b = 0, fileNamesToAdd_1 = fileNamesToAdd; _b < fileNamesToAdd_1.length; _b++) { - var fileName = fileNamesToAdd_1[_b]; + for (var _d = 0, fileNamesToAdd_1 = fileNamesToAdd; _d < fileNamesToAdd_1.length; _d++) { + var fileName = fileNamesToAdd_1[_d]; var info = this.getScriptInfo(fileName); if (!info) { info = this.openFile(fileName, false); @@ -50698,8 +51476,8 @@ var ts; } } }; - ProjectService.prototype.createProject = function (projectFilename, projectOptions) { - var project = new Project(this, projectOptions); + ProjectService.prototype.createProject = function (projectFilename, projectOptions, languageServiceDisabled) { + var project = new Project(this, projectOptions, languageServiceDisabled); project.projectFilename = projectFilename; return project; }; @@ -51752,6 +52530,7 @@ var ts; function CoreServicesShimHostAdapter(shimHost) { var _this = this; this.shimHost = shimHost; + this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; if ("directoryExists" in this.shimHost) { this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; } @@ -51759,15 +52538,24 @@ var ts; this.realpath = function (path) { return _this.shimHost.realpath(path); }; } } - CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extension, exclude, depth) { - var encoded; + CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { try { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude), depth); + var pattern = ts.getFileMatcherPatterns(rootDir, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); } catch (e) { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); + var results = []; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + for (var _a = 0, _b = this.readDirectoryFallback(rootDir, extension, exclude); _a < _b.length; _a++) { + var file = _b[_a]; + if (!ts.contains(results, file)) { + results.push(file); + } + } + } + return results; } - return JSON.parse(encoded); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { return this.shimHost.fileExists(fileName); @@ -51775,6 +52563,9 @@ var ts; CoreServicesShimHostAdapter.prototype.readFile = function (fileName) { return this.shimHost.readFile(fileName); }; + CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { + return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); + }; return CoreServicesShimHostAdapter; }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 533903795cf..73bf72e135e 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -713,7 +713,6 @@ declare namespace ts { } interface PropertyAccessExpression extends MemberExpression, Declaration { expression: LeftHandSideExpression; - dotToken: Node; name: Identifier; } type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression; @@ -844,6 +843,7 @@ declare namespace ts { interface SwitchStatement extends Statement { expression: Expression; caseBlock: CaseBlock; + possiblyExhaustive?: boolean; } interface CaseBlock extends Node { clauses: NodeArray; @@ -919,7 +919,7 @@ declare namespace ts { type ModuleBody = ModuleBlock | ModuleDeclaration; interface ModuleDeclaration extends DeclarationStatement { name: Identifier | LiteralExpression; - body: ModuleBlock | ModuleDeclaration; + body?: ModuleBlock | ModuleDeclaration; } interface ModuleBlock extends Node, Statement { statements: NodeArray; @@ -1075,8 +1075,9 @@ declare namespace ts { Assignment = 16, TrueCondition = 32, FalseCondition = 64, - Referenced = 128, - Shared = 256, + SwitchClause = 128, + Referenced = 256, + Shared = 512, Label = 12, Condition = 96, } @@ -1098,6 +1099,12 @@ declare namespace ts { expression: Expression; antecedent: FlowNode; } + interface FlowSwitchClause extends FlowNode { + switchStatement: SwitchStatement; + clauseStart: number; + clauseEnd: number; + antecedent: FlowNode; + } interface AmdDependency { path: string; name: string; @@ -1132,7 +1139,13 @@ declare namespace ts { getCurrentDirectory(): string; } interface ParseConfigHost { - readDirectory(rootDir: string, extension: string, exclude: string[]): string[]; + useCaseSensitiveFileNames: boolean; + readDirectory(rootDir: string, extensions: string[], excludes: string[], includes: string[]): string[]; + /** + * Gets a value indicating whether the specified path exists and is a file. + * @param path The path to test. + */ + fileExists(path: string): boolean; } interface WriteFileCallback { (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void; @@ -1412,7 +1425,6 @@ declare namespace ts { ThisType = 33554432, ObjectLiteralPatternWithComputedProperties = 67108864, Never = 134217728, - Falsy = 126, StringLike = 258, NumberLike = 132, ObjectType = 80896, @@ -1574,7 +1586,10 @@ declare namespace ts { suppressImplicitAnyIndexErrors?: boolean; target?: ScriptTarget; traceResolution?: boolean; + disableSizeLimit?: boolean; types?: string[]; + /** Paths used to used to compute primary types search locations */ + typeRoots?: string[]; typesSearchPaths?: string[]; [option: string]: CompilerOptionsValue | undefined; } @@ -1638,6 +1653,15 @@ declare namespace ts { fileNames: string[]; raw?: any; errors: Diagnostic[]; + wildcardDirectories?: Map; + } + enum WatchDirectoryFlags { + None = 0, + Recursive = 1, + } + interface ExpandResult { + fileNames: string[]; + wildcardDirectories: Map; } interface ModuleResolutionHost { fileExists(fileName: string): boolean; @@ -1672,6 +1696,7 @@ declare namespace ts { getDefaultTypeDirectiveNames?(rootPath: string): string[]; writeFile: WriteFileCallback; getCurrentDirectory(): string; + getDirectories(path: string): string[]; getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; @@ -1707,6 +1732,7 @@ declare namespace ts { useCaseSensitiveFileNames: boolean; write(s: string): void; readFile(path: string, encoding?: string): string; + getFileSize?(path: string): number; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; watchFile?(path: string, callback: FileWatcherCallback): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; @@ -1717,7 +1743,7 @@ declare namespace ts { getExecutingFilePath(): string; getCurrentDirectory(): string; getDirectories(path: string): string[]; - readDirectory(path: string, extension?: string, exclude?: string[]): string[]; + readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; getModifiedTime?(path: string): Date; createHash?(data: string): string; getMemoryUsage?(): number; @@ -1821,6 +1847,7 @@ declare namespace ts { function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { + /** The version of the TypeScript compiler release */ const version: string; function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string; function resolveTripleslashReference(moduleName: string, containingFile: string): string; @@ -1836,7 +1863,15 @@ declare namespace ts { function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; - function getDefaultTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; + /** + * Given a set of options and a set of root files, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { @@ -1978,6 +2013,7 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists?(directoryName: string): boolean; + getDirectories?(directoryName: string): string[]; } interface LanguageService { cleanupSemanticCache(): void; @@ -2068,6 +2104,7 @@ declare namespace ts { textSpan: TextSpan; fileName: string; isWriteAccess: boolean; + isDefinition: boolean; } interface DocumentHighlights { fileName: string; diff --git a/lib/typescript.js b/lib/typescript.js index 9e41f640305..30d49888df1 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -439,8 +439,9 @@ var ts; FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment"; FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; - FlowFlags[FlowFlags["Referenced"] = 128] = "Referenced"; - FlowFlags[FlowFlags["Shared"] = 256] = "Shared"; + FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; + FlowFlags[FlowFlags["Referenced"] = 256] = "Referenced"; + FlowFlags[FlowFlags["Shared"] = 512] = "Shared"; FlowFlags[FlowFlags["Label"] = 12] = "Label"; FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; })(ts.FlowFlags || (ts.FlowFlags = {})); @@ -654,7 +655,8 @@ var ts; TypeFlags[TypeFlags["Never"] = 134217728] = "Never"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 96] = "Nullable"; - TypeFlags[TypeFlags["Falsy"] = 126] = "Falsy"; + /* @internal */ + TypeFlags[TypeFlags["Falsy"] = 112] = "Falsy"; /* @internal */ TypeFlags[TypeFlags["Intrinsic"] = 150995071] = "Intrinsic"; /* @internal */ @@ -755,6 +757,11 @@ var ts; DiagnosticStyle[DiagnosticStyle["Pretty"] = 1] = "Pretty"; })(ts.DiagnosticStyle || (ts.DiagnosticStyle = {})); var DiagnosticStyle = ts.DiagnosticStyle; + (function (WatchDirectoryFlags) { + WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; + WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; + })(ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); + var WatchDirectoryFlags = ts.WatchDirectoryFlags; /* @internal */ (function (CharacterCodes) { CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; @@ -994,6 +1001,15 @@ var ts; return -1; } ts.indexOf = indexOf; + function indexOfAnyCharCode(text, charCodes, start) { + for (var i = start || 0, len = text.length; i < len; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; + } + ts.indexOfAnyCharCode = indexOfAnyCharCode; function countWhere(array, predicate) { var count = 0; if (array) { @@ -1021,12 +1037,24 @@ var ts; return result; } ts.filter = filter; + function filterMutate(array, f) { + var outIndex = 0; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + if (f(item)) { + array[outIndex] = item; + outIndex++; + } + } + array.length = outIndex; + } + ts.filterMutate = filterMutate; function map(array, f) { var result; if (array) { result = []; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; result.push(f(v)); } } @@ -1045,8 +1073,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var item = array_6[_i]; if (!contains(result, item, areEqual)) { result.push(item); } @@ -1057,8 +1085,8 @@ var ts; ts.deduplicate = deduplicate; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var v = array_7[_i]; result += v[prop]; } return result; @@ -1383,6 +1411,30 @@ var ts; return a < b ? -1 /* LessThan */ : 1 /* GreaterThan */; } ts.compareValues = compareValues; + function compareStrings(a, b, ignoreCase) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + if (ignoreCase) { + if (String.prototype.localeCompare) { + var result = a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" }); + return result < 0 ? -1 /* LessThan */ : result > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + a = a.toUpperCase(); + b = b.toUpperCase(); + if (a === b) + return 0 /* EqualTo */; + } + return a < b ? -1 /* LessThan */ : 1 /* GreaterThan */; + } + ts.compareStrings = compareStrings; + function compareStringsCaseInsensitive(a, b) { + return compareStrings(a, b, /*ignoreCase*/ true); + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; function getDiagnosticFileName(diagnostic) { return diagnostic.file ? diagnostic.file.fileName : undefined; } @@ -1637,12 +1689,242 @@ var ts; return path1 + ts.directorySeparator + path2; } ts.combinePaths = combinePaths; + /** + * Removes a trailing directory separator from a path. + * @param path The path. + */ + function removeTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) === ts.directorySeparator) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + /** + * Adds a trailing directory separator to a path, if it does not already have one. + * @param path The path. + */ + function ensureTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) !== ts.directorySeparator) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + a = removeTrailingDirectorySeparator(a); + b = removeTrailingDirectorySeparator(b); + var aComponents = getNormalizedPathComponents(a, currentDirectory); + var bComponents = getNormalizedPathComponents(b, currentDirectory); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 0; i < sharedLength; i++) { + var result = compareStrings(aComponents[i], bComponents[i], ignoreCase); + if (result !== 0 /* EqualTo */) { + return result; + } + } + return compareValues(aComponents.length, bComponents.length); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + parent = removeTrailingDirectorySeparator(parent); + child = removeTrailingDirectorySeparator(child); + if (parent === child) + return true; + var parentComponents = getNormalizedPathComponents(parent, currentDirectory); + var childComponents = getNormalizedPathComponents(child, currentDirectory); + if (childComponents.length < parentComponents.length) { + return false; + } + for (var i = 0; i < parentComponents.length; i++) { + var result = compareStrings(parentComponents[i], childComponents[i], ignoreCase); + if (result !== 0 /* EqualTo */) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; function fileExtensionIs(path, extension) { var pathLen = path.length; var extLen = extension.length; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsAny(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsAny = fileExtensionIsAny; + // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. + // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future + // proof. + var reservedCharacterPattern = /[^\w\s\/]/g; + var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; + function getRegularExpressionForWildcard(specs, basePath, usage) { + if (specs === undefined || specs.length === 0) { + return undefined; + } + var pattern = ""; + var hasWrittenSubpattern = false; + spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { + var spec = specs_1[_i]; + if (!spec) { + continue; + } + var subpattern = ""; + var hasRecursiveDirectoryWildcard = false; + var hasWrittenComponent = false; + var components = getNormalizedPathComponents(spec, basePath); + if (usage !== "exclude" && components[components.length - 1] === "**") { + continue spec; + } + // getNormalizedPathComponents includes the separator for the root component. + // We need to remove to create our regex correctly. + components[0] = removeTrailingDirectorySeparator(components[0]); + var optionalCount = 0; + for (var _a = 0, components_1 = components; _a < components_1.length; _a++) { + var component = components_1[_a]; + if (component === "**") { + if (hasRecursiveDirectoryWildcard) { + continue spec; + } + subpattern += "(/.+?)?"; + hasRecursiveDirectoryWildcard = true; + hasWrittenComponent = true; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + hasWrittenComponent = true; + } + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + if (hasWrittenSubpattern) { + pattern += "|"; + } + pattern += "(" + subpattern + ")"; + hasWrittenSubpattern = true; + } + if (!pattern) { + return undefined; + } + return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); + } + ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function replaceWildcardCharacter(match) { + return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; + } + function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + }; + } + ts.getFileMatcherPatterns = getFileMatcherPatterns; + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, getFileSystemEntries) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var patterns = getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + var regexFlag = useCaseSensitiveFileNames ? "" : "i"; + var includeFileRegex = patterns.includeFilePattern && new RegExp(patterns.includeFilePattern, regexFlag); + var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); + var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); + var result = []; + for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { + var basePath = _a[_i]; + visitDirectory(basePath, combinePaths(currentDirectory, basePath)); + } + return result; + function visitDirectory(path, absolutePath) { + var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var current = files_1[_i]; + var name_1 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!extensions || fileExtensionIsAny(name_1, extensions)) && + (!includeFileRegex || includeFileRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + result.push(name_1); + } + } + for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { + var current = directories_1[_b]; + var name_2 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name_2, absoluteName); + } + } + } + } + ts.matchFiles = matchFiles; + /** + * Computes the unique non-wildcard base paths amongst the provided include patterns. + */ + function getBasePaths(path, includes, useCaseSensitiveFileNames) { + // Storage for our results in the form of literal paths (e.g. the paths as written by the user). + var basePaths = [path]; + if (includes) { + // Storage for literal base paths amongst the include patterns. + var includeBasePaths = []; + for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { + var include = includes_1[_i]; + if (isRootedDiskPath(include)) { + var wildcardOffset = indexOfAnyCharCode(include, wildcardCharCodes); + var includeBasePath = wildcardOffset < 0 + ? removeTrailingDirectorySeparator(getDirectoryPath(include)) + : include.substring(0, include.lastIndexOf(ts.directorySeparator, wildcardOffset)); + // Append the literal and canonical candidate base paths. + includeBasePaths.push(includeBasePath); + } + } + // Sort the offsets array using either the literal or canonical path representations. + includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); + // Iterate over each include base path and include unique base paths that are not a + // subpath of an existing base path + include: for (var i = 0; i < includeBasePaths.length; i++) { + var includeBasePath = includeBasePaths[i]; + for (var j = 0; j < basePaths.length; j++) { + if (containsPath(basePaths[j], includeBasePath, path, !useCaseSensitiveFileNames)) { + continue include; + } + } + basePaths.push(includeBasePath); + } + } + return basePaths; + } function ensureScriptKind(fileName, scriptKind) { // Using scriptKind as a condition handles both: // - 'scriptKind' is unspecified and thus it is `undefined` @@ -1692,6 +1974,57 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + /** + * Extension boundaries by priority. Lower numbers indicate higher priorities, and are + * aligned to the offset of the highest priority extension in the + * allSupportedExtensions array. + */ + (function (ExtensionPriority) { + ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; + ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; + ExtensionPriority[ExtensionPriority["Limit"] = 5] = "Limit"; + ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; + ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; + })(ts.ExtensionPriority || (ts.ExtensionPriority = {})); + var ExtensionPriority = ts.ExtensionPriority; + function getExtensionPriority(path, supportedExtensions) { + for (var i = supportedExtensions.length - 1; i >= 0; i--) { + if (fileExtensionIs(path, supportedExtensions[i])) { + return adjustExtensionPriority(i); + } + } + // If its not in the list of supported extensions, this is likely a + // TypeScript file with a non-ts extension + return 0 /* Highest */; + } + ts.getExtensionPriority = getExtensionPriority; + /** + * Adjusts an extension priority to be the highest priority within the same range. + */ + function adjustExtensionPriority(extensionPriority) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 0 /* TypeScriptFiles */; + } + else if (extensionPriority < 5 /* Limit */) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return 5 /* Limit */; + } + } + ts.adjustExtensionPriority = adjustExtensionPriority; + /** + * Gets the next lowest extension priority for a given priority. + */ + function getNextLowestExtensionPriority(extensionPriority) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return 5 /* Limit */; + } + } + ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { @@ -1712,6 +2045,10 @@ var ts; return ext === ".jsx" || ext === ".tsx"; } ts.isJsxOrTsxExtension = isJsxOrTsxExtension; + function changeExtension(path, newExtension) { + return (removeFileExtension(path) + newExtension); + } + ts.changeExtension = changeExtension; function Symbol(flags, name) { this.flags = flags; this.name = name; @@ -1790,6 +2127,7 @@ var ts; ts.sys = (function () { function getWScriptSystem() { var fso = new ActiveXObject("Scripting.FileSystemObject"); + var shell = new ActiveXObject("WScript.Shell"); var fileStream = new ActiveXObject("ADODB.Stream"); fileStream.Type = 2 /*text*/; var binaryStream = new ActiveXObject("ADODB.Stream"); @@ -1851,9 +2189,6 @@ var ts; fileStream.Close(); } } - function getCanonicalPath(path) { - return path.toLowerCase(); - } function getNames(collection) { var result = []; for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { @@ -1865,30 +2200,19 @@ var ts; var folder = fso.GetFolder(path); return getNames(folder.subfolders); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { + function getAccessibleFileSystemEntries(path) { + try { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var current = files_1[_i]; - var name_1 = ts.combinePaths(path, current); - if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { - result.push(name_1); - } - } - var subfolders = getNames(folder.subfolders); - for (var _a = 0, subfolders_1 = subfolders; _a < subfolders_1.length; _a++) { - var current = subfolders_1[_a]; - var name_2 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_2))) { - visitDirectory(name_2); - } - } + var directories = getNames(folder.subfolders); + return { files: files, directories: directories }; } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } return { args: args, @@ -1917,7 +2241,7 @@ var ts; return WScript.ScriptFullName; }, getCurrentDirectory: function () { - return new ActiveXObject("WScript.Shell").CurrentDirectory; + return shell.CurrentDirectory; }, getDirectories: getDirectories, readDirectory: readDirectory, @@ -2056,8 +2380,41 @@ var ts; } } } - function getCanonicalPath(path) { - return useCaseSensitiveFileNames ? path : path.toLowerCase(); + function getAccessibleFileSystemEntries(path) { + try { + var entries = _fs.readdirSync(path || ".").sort(); + var files = []; + var directories = []; + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var entry = entries_1[_i]; + // This is necessary because on some file system node fails to exclude + // "." and "..". See https://github.com/nodejs/node/issues/4002 + if (entry === "." || entry === "..") { + continue; + } + var name_3 = ts.combinePaths(path, entry); + var stat = void 0; + try { + stat = _fs.statSync(name_3); + } + catch (e) { + continue; + } + if (stat.isFile()) { + files.push(entry); + } + else if (stat.isDirectory()) { + directories.push(entry); + } + } + return { files: files, directories: directories }; + } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); } var FileSystemEntryKind; (function (FileSystemEntryKind) { @@ -2085,40 +2442,6 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1 /* Directory */); }); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { - var files = _fs.readdirSync(path || ".").sort(); - var directories = []; - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var current = files_2[_i]; - // This is necessary because on some file system node fails to exclude - // "." and "..". See https://github.com/nodejs/node/issues/4002 - if (current === "." || current === "..") { - continue; - } - var name_3 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_3))) { - var stat = _fs.statSync(name_3); - if (stat.isFile()) { - if (!extension || ts.fileExtensionIs(name_3, extension)) { - result.push(name_3); - } - } - else if (stat.isDirectory()) { - directories.push(name_3); - } - } - } - for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { - var current = directories_1[_a]; - visitDirectory(current); - } - } - } return { args: process.argv.slice(2), newLine: _os.EOL, @@ -2206,6 +2529,16 @@ var ts; } return process.memoryUsage().heapUsed; }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch (e) { } + return 0; + }, exit: function (exitCode) { process.exit(exitCode); }, @@ -2239,7 +2572,10 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, - readDirectory: ChakraHost.readDirectory, + readDirectory: function (path, extensions, excludes, includes) { + var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); + }, exit: ChakraHost.quit, realpath: realpath }; @@ -2409,7 +2745,7 @@ var ts; Modifiers_cannot_appear_here: { code: 1184, category: ts.DiagnosticCategory.Error, key: "Modifiers_cannot_appear_here_1184", message: "Modifiers cannot appear here." }, Merge_conflict_marker_encountered: { code: 1185, category: ts.DiagnosticCategory.Error, key: "Merge_conflict_marker_encountered_1185", message: "Merge conflict marker encountered." }, A_rest_element_cannot_have_an_initializer: { code: 1186, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_have_an_initializer_1186", message: "A rest element cannot have an initializer." }, - A_parameter_property_may_not_be_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_a_binding_pattern_1187", message: "A parameter property may not be a binding pattern." }, + A_parameter_property_may_not_be_declared_using_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", message: "A parameter property may not be declared using a binding pattern." }, Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: { code: 1188, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", message: "Only a single variable declaration is allowed in a 'for...of' statement." }, The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: { code: 1189, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", message: "The variable declaration of a 'for...in' statement cannot have an initializer." }, The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: { code: 1190, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", message: "The variable declaration of a 'for...of' statement cannot have an initializer." }, @@ -2425,7 +2761,6 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, - Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower: { code: 1204, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower_1204", message: "Cannot compile modules into 'es2015' when targeting 'ES5' or lower." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -2480,6 +2815,7 @@ var ts; Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, Global_module_exports_may_only_appear_in_declaration_files: { code: 1315, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_declaration_files_1315", message: "Global module exports may only appear in declaration files." }, Global_module_exports_may_only_appear_at_top_level: { code: 1316, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_at_top_level_1316", message: "Global module exports may only appear at top level." }, + A_parameter_property_cannot_be_declared_using_a_rest_parameter: { code: 1317, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", message: "A parameter property cannot be declared using a rest parameter." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, @@ -2750,6 +3086,8 @@ var ts; The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, + Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, + Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -2823,6 +3161,8 @@ var ts; Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, + File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { code: 5011, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", message: "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'." }, Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot_read_file_0_Colon_1_5012", message: "Cannot read file '{0}': {1}" }, Unsupported_file_encoding: { code: 5013, category: ts.DiagnosticCategory.Error, key: "Unsupported_file_encoding_5013", message: "Unsupported file encoding." }, Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed_to_parse_file_0_Colon_1_5014", message: "Failed to parse file '{0}': {1}." }, @@ -2996,7 +3336,6 @@ var ts; types_can_only_be_used_in_a_ts_file: { code: 8010, category: ts.DiagnosticCategory.Error, key: "types_can_only_be_used_in_a_ts_file_8010", message: "'types' can only be used in a .ts file." }, type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: ts.DiagnosticCategory.Error, key: "type_arguments_can_only_be_used_in_a_ts_file_8011", message: "'type arguments' can only be used in a .ts file." }, parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: ts.DiagnosticCategory.Error, key: "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", message: "'parameter modifiers' can only be used in a .ts file." }, - property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "property_declarations_can_only_be_used_in_a_ts_file_8014", message: "'property declarations' can only be used in a .ts file." }, enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "enum_declarations_can_only_be_used_in_a_ts_file_8015", message: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, @@ -4985,6 +5324,11 @@ var ts; (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isShorthandAmbientModule(node) { + // The only kind of module that can be missing a body is a shorthand ambient module. + return node.kind === 225 /* ModuleDeclaration */ && (!node.body); + } + ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 /* SourceFile */ || node.kind === 225 /* ModuleDeclaration */ || @@ -5417,6 +5761,7 @@ var ts; case 157 /* ConstructorType */: return true; } + return false; } ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { @@ -5839,6 +6184,18 @@ var ts; return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + /** + * Returns true if the node is a variable declaration whose initializer is a function expression. + * This function does not test if the node is in a JavaScript file or not. + */ + function isDeclarationOfFunctionExpression(s) { + if (s.valueDeclaration && s.valueDeclaration.kind === 218 /* VariableDeclaration */) { + var declaration = s.valueDeclaration; + return declaration.initializer && declaration.initializer.kind === 179 /* FunctionExpression */; + } + return false; + } + ts.isDeclarationOfFunctionExpression = isDeclarationOfFunctionExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder function getSpecialPropertyAssignmentKind(expression) { @@ -6815,7 +7172,9 @@ var ts; ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); + var commonSourceDirectory = host.getCommonSourceDirectory(); + var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; return ts.combinePaths(newDirPath, sourceFilePath); } ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; @@ -7175,6 +7534,10 @@ var ts; return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -7679,7 +8042,6 @@ var ts; return visitNodes(cbNodes, node.properties); case 172 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); case 173 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || @@ -8602,6 +8964,7 @@ var ts; return token === 19 /* OpenBracketToken */ || token === 15 /* OpenBraceToken */ || token === 37 /* AsteriskToken */ + || token === 22 /* DotDotDotToken */ || isLiteralPropertyName(); } function nextTokenIsClassOrFunction() { @@ -10703,7 +11066,7 @@ var ts; // If it wasn't then just try to parse out a '.' and report an error. var node = createNode(172 /* PropertyAccessExpression */, expression.pos); node.expression = expression; - node.dotToken = parseExpectedToken(21 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(21 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } @@ -10905,7 +11268,6 @@ var ts; if (dotToken) { var propertyAccess = createNode(172 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; - propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); continue; @@ -12250,7 +12612,12 @@ var ts; else { node.name = parseLiteralNode(/*internName*/ true); } - node.body = parseModuleBlock(); + if (token === 15 /* OpenBraceToken */) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { @@ -13341,8 +13708,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var node = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -13479,8 +13846,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -13752,7 +14119,8 @@ var ts; return state_1; } else if (node.kind === 225 /* ModuleDeclaration */) { - return getModuleInstanceState(node.body); + var body = node.body; + return body ? getModuleInstanceState(body) : 1 /* Instantiated */; } else { return 1 /* Instantiated */; @@ -14232,11 +14600,6 @@ var ts; break; } } - function isNarrowableReference(expr) { - return expr.kind === 69 /* Identifier */ || - expr.kind === 97 /* ThisKeyword */ || - expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); - } function isNarrowingExpression(expr) { switch (expr.kind) { case 69 /* Identifier */: @@ -14244,7 +14607,7 @@ var ts; case 172 /* PropertyAccessExpression */: return isNarrowableReference(expr); case 174 /* CallExpression */: - return true; + return hasNarrowableArgument(expr); case 178 /* ParenthesizedExpression */: return isNarrowingExpression(expr.expression); case 187 /* BinaryExpression */: @@ -14254,6 +14617,35 @@ var ts; } return false; } + function isNarrowableReference(expr) { + return expr.kind === 69 /* Identifier */ || + expr.kind === 97 /* ThisKeyword */ || + expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 172 /* PropertyAccessExpression */ && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingNullCheckOperands(expr1, expr2) { + return (expr1.kind === 93 /* NullKeyword */ || expr1.kind === 69 /* Identifier */ && expr1.text === "undefined") && isNarrowableOperand(expr2); + } + function isNarrowingTypeofOperands(expr1, expr2) { + return expr1.kind === 182 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; + } + function isNarrowingDiscriminant(expr) { + return expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56 /* EqualsToken */: @@ -14262,20 +14654,34 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: - if (isNarrowingExpression(expr.left) && (expr.right.kind === 93 /* NullKeyword */ || expr.right.kind === 69 /* Identifier */)) { - return true; - } - if (expr.left.kind === 182 /* TypeOfExpression */ && isNarrowingExpression(expr.left.expression) && expr.right.kind === 9 /* StringLiteral */) { - return true; - } - return false; + return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || + isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); case 91 /* InstanceOfKeyword */: - return isNarrowingExpression(expr.left); + return isNarrowableOperand(expr.left); case 24 /* CommaToken */: return isNarrowingExpression(expr.right); } return false; } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 178 /* ParenthesizedExpression */: + return isNarrowableOperand(expr.expression); + case 187 /* BinaryExpression */: + switch (expr.operatorToken.kind) { + case 56 /* EqualsToken */: + return isNarrowableOperand(expr.left); + case 24 /* CommaToken */: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function isNarrowingSwitchStatement(switchStatement) { + var expr = switchStatement.expression; + return expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } function createBranchLabel() { return { flags: 4 /* BranchLabel */, @@ -14290,7 +14696,7 @@ var ts; } function setFlowNodeReferenced(flow) { // On first reference we set the Referenced flag, thereafter we set the Shared flag - flow.flags |= flow.flags & 128 /* Referenced */ ? 256 /* Shared */ : 128 /* Referenced */; + flow.flags |= flow.flags & 256 /* Referenced */ ? 512 /* Shared */ : 256 /* Referenced */; } function addAntecedent(label, antecedent) { if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { @@ -14315,8 +14721,21 @@ var ts; setFlowNodeReferenced(antecedent); return { flags: flags, - antecedent: antecedent, - expression: expression + expression: expression, + antecedent: antecedent + }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingSwitchStatement(switchStatement)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: 128 /* SwitchClause */, + switchStatement: switchStatement, + clauseStart: clauseStart, + clauseEnd: clauseEnd, + antecedent: antecedent }; } function createFlowAssignment(antecedent, node) { @@ -14527,9 +14946,12 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasNonEmptyDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250 /* DefaultClause */ && c.statements.length; }); - if (!hasNonEmptyDefault) { - addAntecedent(postSwitchLabel, preSwitchCaseFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250 /* DefaultClause */; }); + // We mark a switch statement as possibly exhaustive if it has no default clause and if all + // case clauses have unreachable end points (e.g. they all return). + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); } currentBreakTarget = saveBreakTarget; preSwitchCaseFlow = savePreSwitchCaseFlow; @@ -14537,25 +14959,22 @@ var ts; } function bindCaseBlock(node) { var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { - var clause = clauses[i]; - if (clause.statements.length) { - if (currentFlow.flags & 1 /* Unreachable */) { - currentFlow = preSwitchCaseFlow; - } - else { - var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, preSwitchCaseFlow); - addAntecedent(preCaseLabel, currentFlow); - currentFlow = finishFlowLabel(preCaseLabel); - } - bind(clause); - if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; } - else { - bind(clause); + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); } } } @@ -14855,7 +15274,7 @@ var ts; } function hasExportDeclarations(node) { var body = node.kind === 256 /* SourceFile */ ? node : node.body; - if (body.kind === 256 /* SourceFile */ || body.kind === 226 /* ModuleBlock */) { + if (body && (body.kind === 256 /* SourceFile */ || body.kind === 226 /* ModuleBlock */)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; if (stat.kind === 236 /* ExportDeclaration */ || stat.kind === 235 /* ExportAssignment */) { @@ -15471,7 +15890,7 @@ var ts; constructorFunction.parent = classPrototype; classPrototype.parent = leftSideOfAssignment; var funcSymbol = container.locals[constructorFunction.text]; - if (!funcSymbol || !(funcSymbol.flags & 16 /* Function */)) { + if (!funcSymbol || !(funcSymbol.flags & 16 /* Function */ || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return; } // Set up the members collection if it doesn't exist already @@ -16193,7 +16612,8 @@ var ts; var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { - if (modulekind || (!compilerOptions.outFile && !compilerOptions.out)) { + if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out)) { // nodes are in different files and order cannot be determines return true; } @@ -16458,7 +16878,8 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg)) { + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -16532,6 +16953,29 @@ var ts; } return false; } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var parentClassExpression = errorLocation; + while (parentClassExpression) { + var kind = parentClassExpression.kind; + if (kind === 69 /* Identifier */ || kind === 172 /* PropertyAccessExpression */) { + parentClassExpression = parentClassExpression.parent; + continue; + } + if (kind === 194 /* ExpressionWithTypeArguments */) { + break; + } + return false; + } + if (!parentClassExpression) { + return false; + } + var expression = parentClassExpression.expression; + if (resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; + } + return false; + } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2 /* BlockScopedVariable */) !== 0); // Block-scoped variables cannot be used before their definition @@ -16579,9 +17023,11 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = moduleSymbol.exports["export="] ? - getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : - resolveSymbol(moduleSymbol.exports["default"]); + var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? + moduleSymbol : + moduleSymbol.exports["export="] ? + getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : + resolveSymbol(moduleSymbol.exports["default"]); if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } @@ -16650,6 +17096,9 @@ var ts; if (targetSymbol) { var name_10 = specifier.propertyName || specifier.name; if (name_10.text) { + if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { + return moduleSymbol; + } var symbolFromVariable = void 0; // First check if module was specified with "export=". If so, get the member from the resolved type if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { @@ -18171,6 +18620,9 @@ var ts; function isTypeAny(type) { return type && (type.flags & 1 /* Any */) !== 0; } + function isTypeNever(type) { + return type && (type.flags & 134217728 /* Never */) !== 0; + } // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been // assigned by contextual typing. function getTypeForBindingElementParent(node) { @@ -18491,23 +18943,26 @@ var ts; if (declaration.kind === 235 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } - // Handle module.exports = expr - if (declaration.kind === 187 /* BinaryExpression */) { - return links.type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); - } - if (declaration.kind === 172 /* PropertyAccessExpression */) { - // Declarations only exist for property access expressions for certain - // special assignment kinds - if (declaration.parent.kind === 187 /* BinaryExpression */) { - // Handle exports.p = expr or this.p = expr or className.prototype.method = expr - return links.type = checkExpressionCached(declaration.parent.right); - } - } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; } - var type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); + var type = undefined; + // Handle module.exports = expr or this.p = expr + if (declaration.kind === 187 /* BinaryExpression */) { + type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); + } + else if (declaration.kind === 172 /* PropertyAccessExpression */) { + // Declarations only exist for property access expressions for certain + // special assignment kinds + if (declaration.parent.kind === 187 /* BinaryExpression */) { + // Handle exports.p = expr or className.prototype.method = expr + type = checkExpressionCached(declaration.parent.right); + } + } + if (type === undefined) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); + } if (!popTypeResolution()) { if (symbol.valueDeclaration.type) { // Variable has type annotation that circularly references the variable itself @@ -18600,9 +19055,14 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var type = createObjectType(65536 /* Anonymous */, symbol); - links.type = strictNullChecks && symbol.flags & 536870912 /* Optional */ ? - addTypeKind(type, 32 /* Undefined */) : type; + if (symbol.valueDeclaration.kind === 225 /* ModuleDeclaration */ && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { + links.type = anyType; + } + else { + var type = createObjectType(65536 /* Anonymous */, symbol); + links.type = strictNullChecks && symbol.flags & 536870912 /* Optional */ ? + addTypeKind(type, 32 /* Undefined */) : type; + } } return links.type; } @@ -19660,7 +20120,7 @@ var ts; } return result; } - function isOptionalParameter(node) { + function isJSDocOptionalParameter(node) { if (node.flags & 134217728 /* JavaScriptFile */) { if (node.type && node.type.kind === 268 /* JSDocOptionalType */) { return true; @@ -19675,7 +20135,9 @@ var ts; } } } - if (ts.hasQuestionToken(node)) { + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { return true; } if (node.initializer) { @@ -19734,7 +20196,7 @@ var ts; if (param.type && param.type.kind === 166 /* StringLiteralType */) { hasStringLiterals = true; } - if (param.initializer || param.questionToken || param.dotDotDotToken) { + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { minArgumentCount = i - (hasThisParameter ? 1 : 0); } @@ -20818,6 +21280,9 @@ var ts; function isTypeComparableTo(source, target) { return checkTypeComparableTo(source, target, /*errorNode*/ undefined); } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); } @@ -21897,8 +22362,10 @@ var ts; function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isStringLiteralType(type) { - return type.flags & 256 /* StringLiteral */; + function isStringLiteralUnionType(type) { + return type.flags & 256 /* StringLiteral */ ? true : + type.flags & 16384 /* Union */ ? ts.forEach(type.types, isStringLiteralUnionType) : + false; } /** * Check if a Type was written as a tuple type literal. @@ -22709,6 +23176,31 @@ var ts; } return node; } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 249 /* CaseClause */) { + var expr = clause.expression; + return expr.kind === 9 /* StringLiteral */ ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); + } + return undefined; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + // If all case clauses specify expressions that have unit types, we return an array + // of those unit types. Otherwise we return an empty array. + var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); + links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256 /* StringLiteral */; }) ? types : emptyArray; + } + return links.switchTypes; + } + function eachTypeContainedIn(source, types) { + return source.flags & 16384 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function filterType(type, f) { + return type.flags & 16384 /* Union */ ? + getUnionType(ts.filter(type.types, f)) : + f(type) ? type : neverType; + } function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { var key; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175 /* Narrowable */)) { @@ -22724,7 +23216,7 @@ var ts; return result; function getTypeAtFlowNode(flow) { while (true) { - if (flow.flags & 256 /* Shared */) { + if (flow.flags & 512 /* Shared */) { // We cache results of flow type resolution for shared nodes that were previously visited in // the same getFlowTypeOfReference invocation. A node is considered shared when it is the // antecedent of more than one node. @@ -22745,6 +23237,9 @@ var ts; else if (flow.flags & 96 /* Condition */) { type = getTypeAtFlowCondition(flow); } + else if (flow.flags & 128 /* SwitchClause */) { + type = getTypeAtSwitchClause(flow); + } else if (flow.flags & 12 /* Label */) { if (flow.antecedents.length === 1) { flow = flow.antecedents[0]; @@ -22769,7 +23264,7 @@ var ts; // simply return the declared type to reduce follow-on errors. type = declaredType; } - if (flow.flags & 256 /* Shared */) { + if (flow.flags & 512 /* Shared */) { // Record visited node and the associated type in the cache. visitedFlowNodes[visitedFlowCount] = flow; visitedFlowTypes[visitedFlowCount] = type; @@ -22825,6 +23320,10 @@ var ts; } return type; } + function getTypeAtSwitchClause(flow) { + var type = getTypeAtFlowNode(flow.antecedent); + return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { @@ -22903,11 +23402,26 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: - if (isNullOrUndefinedLiteral(expr.right)) { - return narrowTypeByNullCheck(type, expr, assumeTrue); + var left = expr.left; + var operator = expr.operatorToken.kind; + var right = expr.right; + if (isNullOrUndefinedLiteral(right)) { + return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); } - if (expr.left.kind === 182 /* TypeOfExpression */ && expr.right.kind === 9 /* StringLiteral */) { - return narrowTypeByTypeof(type, expr, assumeTrue); + if (isNullOrUndefinedLiteral(left)) { + return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); + } + if (left.kind === 182 /* TypeOfExpression */ && right.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); + } + if (right.kind === 182 /* TypeOfExpression */ && left.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); + } + if (left.kind === 172 /* PropertyAccessExpression */) { + return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); + } + if (right.kind === 172 /* PropertyAccessExpression */) { + return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); } break; case 91 /* InstanceOfKeyword */: @@ -22917,54 +23431,100 @@ var ts; } return type; } - function narrowTypeByNullCheck(type, expr, assumeTrue) { - // We have '==', '!=', '===', or '!==' operator with 'null' or 'undefined' on the right - var operator = expr.operatorToken.kind; + function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { + // We have '==', '!=', '===', or '!==' operator with 'null' or 'undefined' as value if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(expr.left))) { + if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { return type; } var doubleEquals = operator === 30 /* EqualsEqualsToken */ || operator === 31 /* ExclamationEqualsToken */; var facts = doubleEquals ? assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - expr.right.kind === 93 /* NullKeyword */ ? + literal.kind === 93 /* NullKeyword */ ? assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; return getTypeWithFacts(type, facts); } - function narrowTypeByTypeof(type, expr, assumeTrue) { - // We have '==', '!=', '====', or !==' operator with 'typeof xxx' on the left - // and string literal on the right - var left = getReferenceFromExpression(expr.left.expression); - var right = expr.right; - if (!isMatchingReference(reference, left)) { + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands + var target = getReferenceFromExpression(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, left)) { + if (containsMatchingReference(reference, target)) { return declaredType; } return type; } - if (expr.operatorToken.kind === 31 /* ExclamationEqualsToken */ || - expr.operatorToken.kind === 33 /* ExclamationEqualsEqualsToken */) { + if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } if (assumeTrue && !(type.flags & 16384 /* Union */)) { // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primtive type. For example, type 'any' can be narrowed // to one of the primitive types. - var targetType = ts.getProperty(typeofTypesByName, right.text); + var targetType = ts.getProperty(typeofTypesByName, literal.text); if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - ts.getProperty(typeofEQFacts, right.text) || 64 /* TypeofEQHostObject */ : - ts.getProperty(typeofNEFacts, right.text) || 8192 /* TypeofNEHostObject */; + ts.getProperty(typeofEQFacts, literal.text) || 64 /* TypeofEQHostObject */ : + ts.getProperty(typeofNEFacts, literal.text) || 8192 /* TypeofNEHostObject */; return getTypeWithFacts(type, facts); } + function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { + // We have '==', '!=', '===', or '!==' operator with property access as target + if (!isMatchingReference(reference, propAccess.expression)) { + return type; + } + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var discriminantType = value.kind === 9 /* StringLiteral */ ? getStringLiteralTypeForText(value.text) : checkExpression(value); + if (!isStringLiteralUnionType(discriminantType)) { + return type; + } + if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + if (assumeTrue) { + return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); + } + if (discriminantType.flags & 256 /* StringLiteral */) { + return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); + } + return type; + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + // We have switch statement with property access expression + if (!isMatchingReference(reference, switchStatement.expression.expression)) { + return type; + } + var propName = switchStatement.expression.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); + var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; + var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; + var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); + return caseType ? getUnionType([caseType, defaultType]) : defaultType; + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceFromExpression(expr.left); if (!isMatchingReference(reference, left)) { @@ -23836,9 +24396,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } - function contextualTypeIsStringLiteralType(type) { - return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type)); - } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); @@ -24839,7 +25396,7 @@ var ts; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { - if (right.text) { + if (right.text && !checkAndReportErrorForExtendingInterface(node)) { error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 /* ThisType */ ? apparentType : type)); } return unknownType; @@ -26126,8 +26683,12 @@ var ts; // When resolved signature is a call signature (and not a construct signature) the result type is any, unless // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations // in a JS file - var funcSymbol = checkExpression(node.expression).symbol; - if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 /* Function */)) { + // Note:JS inferred classes might come from a variable declaration instead of a function declaration. + // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. + var funcSymbol = node.expression.kind === 69 /* Identifier */ ? + getResolvedSymbol(node.expression) : + checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 /* Function */ || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return getInferredClassType(funcSymbol); } else if (compilerOptions.noImplicitAny) { @@ -26147,6 +26708,7 @@ var ts; } function checkAssertion(node) { var exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + checkSourceElement(node.type); var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { var widenedType = getWidenedType(exprType); @@ -26264,6 +26826,14 @@ var ts; } return emptyObjectType; } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return unknownType; + } + return promiseType; + } function getReturnTypeFromBody(func, contextualMapper) { var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { @@ -26297,19 +26867,12 @@ var ts; else { types = checkAndAggregateReturnExpressionTypes(func, contextualMapper); if (!types) { - return neverType; + // For an async function, the return type will not be never, but rather a Promise for never. + return isAsync ? createPromiseReturnType(func, neverType) : neverType; } if (types.length === 0) { - if (isAsync) { - // For an async function, the return type will not be void, but rather a Promise for void. - var promiseType = createPromiseType(voidType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - return voidType; + // For an async function, the return type will not be void, but rather a Promise for void. + return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } // When yield/return statements are contextually typed we allow the return type to be a union type. @@ -26323,7 +26886,7 @@ var ts; else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); // Defer to unioning the return types so we get a) downstream errors earlier and b) better Salsa experience - return getUnionType(types); + return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); } } if (funcIsGenerator) { @@ -26334,20 +26897,10 @@ var ts; reportErrorsFromWidening(func, type); } var widenedType = getWidenedType(type); - if (isAsync) { - // From within an async function you can return either a non-promise value or a promise. Any - // Promise/A+ compatible implementation will always assimilate any foreign promise, so the - // return type of the body is awaited type of the body, wrapped in a native Promise type. - var promiseType = createPromiseType(widenedType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - else { - return widenedType; - } + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body is awaited type of the body, wrapped in a native Promise type. + return isAsync ? createPromiseReturnType(func, widenedType) : widenedType; } function checkAndAggregateYieldOperandTypes(func, contextualMapper) { var aggregatedTypes = []; @@ -26366,10 +26919,40 @@ var ts; }); return aggregatedTypes; } + function isExhaustiveSwitchStatement(node) { + var expr = node.expression; + if (!node.possiblyExhaustive || expr.kind !== 172 /* PropertyAccessExpression */) { + return false; + } + var type = checkExpression(expr.expression); + if (!(type.flags & 16384 /* Union */)) { + return false; + } + var propName = expr.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length) { + return false; + } + return eachTypeContainedIn(propType, switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 32768 /* HasImplicitReturn */)) { + return false; + } + var lastStatement = ts.lastOrUndefined(func.body.statements); + if (lastStatement && lastStatement.kind === 213 /* SwitchStatement */ && isExhaustiveSwitchStatement(lastStatement)) { + return false; + } + return true; + } function checkAndAggregateReturnExpressionTypes(func, contextualMapper) { var isAsync = ts.isAsyncFunctionLike(func); var aggregatedTypes = []; - var hasReturnWithNoExpression = !!(func.flags & 32768 /* HasImplicitReturn */); + var hasReturnWithNoExpression = functionHasImplicitReturn(func); var hasReturnOfTypeNever = false; ts.forEachReturnStatement(func.body, function (returnStatement) { var expr = returnStatement.expression; @@ -26423,7 +27006,7 @@ var ts; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 /* Block */ || !(func.flags & 32768 /* HasImplicitReturn */)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 65536 /* HasExplicitReturn */; @@ -27016,7 +27599,7 @@ var ts; case 90 /* InKeyword */: return checkInExpression(left, right, leftType, rightType); case 51 /* AmpersandAmpersandToken */: - return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 126 /* Falsy */) : rightType; + return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112 /* Falsy */) : rightType; case 52 /* BarBarToken */: return getUnionType([getNonNullableType(leftType), rightType]); case 56 /* EqualsToken */: @@ -27132,7 +27715,7 @@ var ts; } function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); - if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { + if (contextualType && isStringLiteralUnionType(contextualType)) { return getStringLiteralTypeForText(node.text); } return stringType; @@ -27979,9 +28562,6 @@ var ts; } } } - // when checking exported function declarations across modules check only duplicate implementations - // names and consistency of modifiers are verified when we check local symbol - var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & 1536 /* Module */; var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { @@ -28013,7 +28593,7 @@ var ts; duplicateFunctionDeclaration = true; } } - else if (!isExportSymbolInsideModule && previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { reportImplementationExpectedError(previousDeclaration); } if (ts.nodeIsPresent(node.body)) { @@ -28041,7 +28621,7 @@ var ts; }); } // Abstract methods can't have an implementation -- in particular, they don't need one. - if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && !(lastSeenNonAmbientDeclaration.flags & 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } @@ -28142,7 +28722,7 @@ var ts; } function checkNonThenableType(type, location, message) { type = getWidenedType(type); - if (!isTypeAny(type) && isTypeAssignableTo(type, getGlobalThenableType())) { + if (!isTypeAny(type) && !isTypeNever(type) && isTypeAssignableTo(type, getGlobalThenableType())) { if (location) { if (!message) { message = ts.Diagnostics.Operand_for_await_does_not_have_a_valid_callable_then_member; @@ -28168,37 +28748,39 @@ var ts; // ): any; // } // - if (promise.flags & 1 /* Any */) { + if (isTypeAny(promise)) { return undefined; } - if ((promise.flags & 4096 /* Reference */) && promise.target === tryGetGlobalPromiseType()) { - return promise.typeArguments[0]; + if (promise.flags & 4096 /* Reference */) { + if (promise.target === tryGetGlobalPromiseType() + || promise.target === getGlobalPromiseLikeType()) { + return promise.typeArguments[0]; + } } var globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType(); if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) { return undefined; } var thenFunction = getTypeOfPropertyOfType(promise, "then"); - if (thenFunction && (thenFunction.flags & 1 /* Any */)) { + if (!thenFunction || isTypeAny(thenFunction)) { return undefined; } - var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : emptyArray; + var thenSignatures = getSignaturesOfType(thenFunction, 0 /* Call */); if (thenSignatures.length === 0) { return undefined; } var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072 /* NEUndefined */); - if (onfulfilledParameterType.flags & 1 /* Any */) { + if (isTypeAny(onfulfilledParameterType)) { return undefined; } var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */); if (onfulfilledParameterSignatures.length === 0) { return undefined; } - var valueParameterType = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); - return valueParameterType; + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); } function getTypeOfFirstParameterOfSignature(signature) { - return getTypeAtPosition(signature, 0); + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; } /** * Gets the "awaited type" of a type. @@ -30189,7 +30771,7 @@ var ts; // - augmentation for a global scope is always applied // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Merged */); - if (checkBody) { + if (checkBody && node.body) { // body of ambient external module is always a module block for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { var statement = _a[_i]; @@ -30217,7 +30799,13 @@ var ts; } } } - checkSourceElement(node.body); + if (compilerOptions.noImplicitAny && !node.body) { + // Ambient shorthand module is an implicit any + reportImplicitAnyError(node, anyType); + } + if (node.body) { + checkSourceElement(node.body); + } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { @@ -31982,7 +32570,10 @@ var ts; return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } else if (node.kind === 142 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 142 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { return checkGrammarAsyncModifier(node, lastAsync); @@ -33812,21 +34403,26 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body.kind !== 226 /* ModuleBlock */) { + while (node.body && node.body.kind !== 226 /* ModuleBlock */) { node = node.body; write("."); writeTextOfNode(currentText, node.name); } var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; + if (node.body) { + enclosingDeclaration = node; + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.body.statements); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + else { + write(";"); + } } function writeTypeAliasDeclaration(node) { var prevEnclosingDeclaration = enclosingDeclaration; @@ -36393,7 +36989,6 @@ var ts; function createPropertyAccessExpression(expression, name) { var result = ts.createSynthesizedNode(172 /* PropertyAccessExpression */); result.expression = parenthesizeForAccess(expression); - result.dotToken = ts.createSynthesizedNode(21 /* DotToken */); result.name = name; return result; } @@ -36457,9 +37052,9 @@ var ts; emit(node.initializer); } // Return true if identifier resolves to an exported member of a namespace - function isNamespaceExportReference(node) { + function isExportReference(node) { var container = resolver.getReferencedExportContainer(node); - return container && container.kind !== 256 /* SourceFile */; + return !!container; } // Return true if identifier resolves to an imported identifier function isImportedReference(node) { @@ -36490,10 +37085,10 @@ var ts; // const foo_1 = require('./foo'); // exports.baz = { foo: foo_1.foo }; // - if (languageVersion < 2 /* ES6 */ || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isNamespaceExportReference(node.name)) { + if (languageVersion < 2 /* ES6 */ || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isExportReference(node.name)) { // Emit identifier as an identifier write(": "); - emit(node.name); + emitExpressionIdentifier(node.name); } if (languageVersion >= 2 /* ES6 */ && node.objectAssignmentInitializer) { write(" = "); @@ -36552,7 +37147,10 @@ var ts; return; } emit(node.expression); - var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); + var dotRangeStart = ts.nodeIsSynthesized(node.expression) ? -1 : node.expression.end; + var dotRangeEnd = ts.nodeIsSynthesized(node.expression) ? -1 : ts.skipTrivia(currentText, node.expression.end) + 1; + var dotToken = { pos: dotRangeStart, end: dotRangeEnd }; + var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, dotToken); // 1 .toString is a valid property access, emit a space after the literal // Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal var shouldEmitSpace = false; @@ -36575,7 +37173,7 @@ var ts; else { write("."); } - var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); + var indentedAfterDot = indentIfOnDifferentLines(node, dotToken, node.name); emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); } @@ -37014,7 +37612,6 @@ var ts; synthesizedLHS = ts.createSynthesizedNode(172 /* PropertyAccessExpression */, /*startsOnNewLine*/ false); var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false); synthesizedLHS.expression = identifier; - synthesizedLHS.dotToken = leftHandSideExpression.dotToken; synthesizedLHS.name = leftHandSideExpression.name; write(", "); } @@ -39556,7 +40153,11 @@ var ts; } } function emitClassLikeDeclarationBelowES6(node) { + var isES6ExportedClass = isES6ExportedDeclaration(node); if (node.kind === 221 /* ClassDeclaration */) { + if (isES6ExportedClass && !(node.flags & 512 /* Default */)) { + write("export "); + } // source file level classes in system modules are hoisted so 'var's for them are already defined if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); @@ -39621,9 +40222,15 @@ var ts; write(";"); } emitEnd(node); - if (node.kind === 221 /* ClassDeclaration */) { + if (node.kind === 221 /* ClassDeclaration */ && !isES6ExportedClass) { emitExportMemberAssignment(node); } + else if (isES6ExportedClass && (node.flags & 512 /* Default */)) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); @@ -40000,10 +40607,10 @@ var ts; } if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 160 /* ArrayType */) { + if (parameterType && parameterType.kind === 160 /* ArrayType */) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 155 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType && parameterType.kind === 155 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { @@ -40021,9 +40628,15 @@ var ts; } /** Serializes the return type of function. Used by the __metadata decorator for a method. */ function emitSerializedReturnTypeOfNode(node) { - if (node && ts.isFunctionLike(node) && node.type) { - emitSerializedTypeNode(node.type); - return; + if (node && ts.isFunctionLike(node)) { + if (node.type) { + emitSerializedTypeNode(node.type); + return; + } + else if (ts.isAsyncFunctionLike(node)) { + write("Promise"); + return; + } } write("void 0"); } @@ -40162,7 +40775,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { + if (moduleDeclaration.body && moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -40204,6 +40817,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); + ts.Debug.assert(node.body !== undefined); // node.body must exist, as this is a non-ambient module if (node.body.kind === 226 /* ModuleBlock */) { var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; @@ -41998,13 +42612,9 @@ var ts; /* @internal */ ts.ioReadTime = 0; /* @internal */ ts.ioWriteTime = 0; /** The version of the TypeScript compiler release */ - var emptyArray = []; - var defaultLibrarySearchPaths = [ - "types/", - "node_modules/", - "node_modules/@types/", - ]; ts.version = "1.9.0"; + var emptyArray = []; + var defaultTypeRoots = ["node_modules/@types"]; function findConfigFile(searchPath, fileExists) { while (true) { var fileName = ts.combinePaths(searchPath, "tsconfig.json"); @@ -42144,6 +42754,10 @@ var ts; return undefined; } var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + return options.typeRoots || + ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(), d); }); + } /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups @@ -42157,37 +42771,35 @@ var ts; skipTsx: true, traceEnabled: traceEnabled }; - // use typesRoot and fallback to directory that contains tsconfig or current directory if typesRoot is not set - var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : (host.getCurrentDirectory && host.getCurrentDirectory())); + var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); } } else { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } } var failedLookupLocations = []; // Check primary library paths - if (rootDir !== undefined) { - var effectivePrimarySearchPaths = options.typesSearchPaths || defaultLibrarySearchPaths; - for (var _i = 0, effectivePrimarySearchPaths_1 = effectivePrimarySearchPaths; _i < effectivePrimarySearchPaths_1.length; _i++) { - var searchPath = effectivePrimarySearchPaths_1[_i]; - var primaryPath = ts.combinePaths(rootDir, searchPath); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, primaryPath); - } - var candidate = ts.combinePaths(primaryPath, typeReferenceDirectiveName); + if (typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); if (resolvedFile_1) { @@ -42211,9 +42823,6 @@ var ts; if (containingFile) { initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); } - else { - initialLocationForSecondaryLookup = rootDir; - } if (initialLocationForSecondaryLookup !== undefined) { // check secondary locations if (traceEnabled) { @@ -42808,25 +43417,12 @@ var ts; } } } - function getDefaultTypeDirectiveNames(rootPath) { - var localTypes = ts.combinePaths(rootPath, "types"); - var npmTypes = ts.combinePaths(rootPath, "node_modules/@types"); - var result = []; - if (ts.sys.directoryExists(localTypes)) { - result = result.concat(ts.sys.getDirectories(localTypes)); - } - if (ts.sys.directoryExists(npmTypes)) { - result = result.concat(ts.sys.getDirectories(npmTypes)); - } - return result; - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); } var newLine = ts.getNewLineCharacter(options); var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); return { - getDefaultTypeDirectiveNames: getDefaultTypeDirectiveNames, getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -42839,6 +43435,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, + getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; } @@ -42894,21 +43491,36 @@ var ts; } return resolutions; } - function getDefaultTypeDirectiveNames(options, rootFiles, host) { + function getInferredTypesRoot(options, rootFiles, host) { + return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + /** + * Given a set of options and a set of root files, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options, rootFiles, host) { // Use explicit type list from tsconfig.json if (options.types) { return options.types; } - // or load all types from the automatic type import fields - if (host && host.getDefaultTypeDirectiveNames) { - var commonRoot = computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); - if (commonRoot) { - return host.getDefaultTypeDirectiveNames(commonRoot); + // Walk the primary type lookup locations + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + result = result.concat(host.getDirectories(root)); + } } } - return undefined; + return result; } - ts.getDefaultTypeDirectiveNames = getDefaultTypeDirectiveNames; + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -42948,10 +43560,12 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); - // load type declarations specified via 'types' argument - var typeReferences = getDefaultTypeDirectiveNames(options, rootNames, host); + // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders + var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); if (typeReferences) { - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, /*containingFile*/ undefined); + var inferredRoot = getInferredTypesRoot(options, rootNames, host); + var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); } @@ -43026,8 +43640,8 @@ var ts; // Initialize a checker so that all our files are bound. getTypeChecker(); classifiableNames = {}; - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var sourceFile = files_3[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } @@ -43048,10 +43662,9 @@ var ts; (oldOptions.jsx !== options.jsx) || (oldOptions.allowJs !== options.allowJs) || (oldOptions.rootDir !== options.rootDir) || - (oldOptions.typesSearchPaths !== options.typesSearchPaths) || (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || - (oldOptions.typesRoot !== options.typesRoot) || + !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { return false; @@ -43383,8 +43996,20 @@ var ts; } break; case 145 /* PropertyDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); - return true; + var propertyDeclaration = node; + if (propertyDeclaration.modifiers) { + for (var _i = 0, _a = propertyDeclaration.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 113 /* StaticKeyword */) { + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + } + } + } + if (checkTypeAnnotation(node.type)) { + return true; + } + break; case 224 /* EnumDeclaration */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return true; @@ -43530,10 +44155,13 @@ var ts; // This type of declaration is permitted only in the global module. // The StringLiteral must specify a top - level external module name. // Relative external module names are not permitted - // NOTE: body of ambient module is always a module block - for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - collectModuleReferences(statement, /*inAmbientModule*/ true); + // NOTE: body of ambient module is always a module block, if it exists + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, /*inAmbientModule*/ true); + } } } } @@ -43696,7 +44324,7 @@ var ts; } } else { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_name_0, typeReferenceDirective)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); } if (saveResolution) { resolvedTypeReferenceDirectives[typeReferenceDirective] = resolvedTypeReferenceDirective; @@ -43868,10 +44496,6 @@ var ts; var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } - // Cannot specify module gen target of es6 when below es6 - if (options.module === ts.ModuleKind.ES6 && languageVersion < 2 /* ES6 */) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); - } // Cannot specify module gen that isn't amd or system with --out if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { @@ -44278,8 +44902,13 @@ var ts; } }, { - name: "typesRoot", - type: "string" + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + } }, { name: "types", @@ -44348,6 +44977,10 @@ var ts; }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, + { + name: "disableProjectSizeLimit", + type: "boolean" + }, { name: "strictNullChecks", type: "boolean", @@ -44418,7 +45051,15 @@ var ts; ts.parseCustomTypeOption = parseCustomTypeOption; /* @internal */ function parseListTypeOption(opt, value, errors) { - var values = trimString((value || "")).split(","); + if (value === void 0) { value = ""; } + value = trimString(value); + if (ts.startsWith(value, "-")) { + return undefined; + } + if (value === "") { + return []; + } + var values = value.split(","); switch (opt.element.type) { case "number": return ts.map(values, parseInt); @@ -44478,8 +45119,11 @@ var ts; i++; break; case "list": - options[opt.name] = parseListTypeOption(opt, args[i], errors); - i++; + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } break; // If not a primitive, the possible types are specified in what is effectively a map of options. default: @@ -44590,7 +45234,7 @@ var ts; } // Skip over any minified JavaScript files (ending in ".min.js") // Skip over dotted files and folders as well - var IgnoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; + var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -44605,72 +45249,59 @@ var ts; var options = ts.extend(existingOptions, compilerOptions); var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); options.configFilePath = configFileName; - var fileNames = getFileNames(errors); + var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, - errors: errors + errors: errors, + wildcardDirectories: wildcardDirectories }; function getFileNames(errors) { - var fileNames = []; + var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { - fileNames = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); + fileNames = json["files"]; } else { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); } } - else { - var filesSeen = {}; - var exclude = []; - if (ts.isArray(json["exclude"])) { - exclude = json["exclude"]; + var includeSpecs; + if (ts.hasProperty(json, "include")) { + if (ts.isArray(json["include"])) { + includeSpecs = json["include"]; } else { - // by default exclude node_modules, and any specificied output directory - exclude = ["node_modules", "bower_components", "jspm_packages"]; - } - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; - if (outDir) { - exclude.push(outDir); - } - exclude = ts.map(exclude, function (e) { return ts.getNormalizedAbsolutePath(e, basePath); }); - var supportedExtensions = ts.getSupportedExtensions(options); - ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); - // Get files of supported extensions in their order of resolution - for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { - var extension = supportedExtensions_1[_i]; - var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); - for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { - var fileName = filesInDirWithExtension_1[_a]; - // .ts extension would read the .d.ts extension files too but since .d.ts is lower priority extension, - // lets pick them when its turn comes up - if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { - continue; - } - if (IgnoreFileNamePattern.test(fileName)) { - continue; - } - // If this is one of the output extension (which would be .d.ts and .js if we are allowing compilation of js files) - // do not include this file if we included .ts or .tsx file with same base name as it could be output of the earlier compilation - if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { - var baseName = fileName.substr(0, fileName.length - extension.length); - if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { - continue; - } - } - filesSeen[fileName] = true; - fileNames.push(fileName); - } + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array")); } } - if (ts.hasProperty(json, "excludes") && !ts.hasProperty(json, "exclude")) { + var excludeSpecs; + if (ts.hasProperty(json, "exclude")) { + if (ts.isArray(json["exclude"])) { + excludeSpecs = json["exclude"]; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); + } + } + else if (ts.hasProperty(json, "excludes")) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } - return fileNames; + else { + // By default, exclude common package folders + excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; + } + // Always exclude the output directory unless explicitly included + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + excludeSpecs.push(outDir); + } + if (fileNames === undefined && includeSpecs === undefined) { + includeSpecs = ["**/*"]; + } + return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; @@ -44752,6 +45383,273 @@ var ts; function trimString(s) { return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); } + /** + * Tests for a path that ends in a recursive directory wildcard. + * Matches **, \**, **\, and \**\, but not a**b. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\* # matches the recursive directory wildcard "**". + * \/?$ # matches an optional trailing directory separator at the end of the string. + */ + var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + /** + * Tests for a path with multiple recursive directory wildcards. + * Matches **\** and **\a\**, but not **\a**b. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. + * (.*\/)? # optionally matches any number of characters followed by a directory separator. + * \*\* # matches a recursive directory wildcard "**" + * ($|\/) # matches either the end of the string or a directory separator. + */ + var invalidMultipleRecursionPatterns = /(^|\/)\*\*\/(.*\/)?\*\*($|\/)/; + /** + * Tests for a path containing a wildcard character in a directory component of the path. + * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * \/ # matches a directory separator. + * [^/]*? # matches any number of characters excluding directory separators (non-greedy). + * [*?] # matches either a wildcard character (* or ?) + * [^/]* # matches any number of characters excluding directory separators (greedy). + * \/ # matches a directory separator. + */ + var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + /** + * Matches the portion of a wildcard path that does not contain wildcards. + * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * ^ # matches the beginning of the string + * [^*?]* # matches any number of non-wildcard characters + * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by + * # a path component that contains at least one wildcard character (* or ?). + */ + var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; + /** + * Expands an array of file specifications. + * + * @param fileNames The literal file names to include. + * @param include The wildcard file specifications to include. + * @param exclude The wildcard file specifications to exclude. + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param errors An array for diagnostic reporting. + */ + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + basePath = ts.normalizePath(basePath); + // The exclude spec list is converted into a regular expression, which allows us to quickly + // test whether a file or directory should be excluded before recursively traversing the + // file system. + var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; + // Literal file names (provided via the "files" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map later when when including + // wildcard paths. + var literalFileMap = {}; + // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard, and to handle extension priority. + var wildcardFileMap = {}; + if (include) { + include = validateSpecs(include, errors, /*allowTrailingRecursion*/ false); + } + if (exclude) { + exclude = validateSpecs(exclude, errors, /*allowTrailingRecursion*/ true); + } + // Wildcard directories (provided as part of a wildcard path) are stored in a + // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), + // or a recursive directory. This information is used by filesystem watchers to monitor for + // new entries in these paths. + var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); + // Rather than requery this for each file and filespec, we query the supported extensions + // once and store it on the expansion context. + var supportedExtensions = ts.getSupportedExtensions(options); + // Literal files are always included verbatim. An "include" or "exclude" specification cannot + // remove a literal file. + if (fileNames) { + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; + var file = ts.combinePaths(basePath, fileName); + literalFileMap[keyMapper(file)] = file; + } + } + if (include && include.length > 0) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include); _a < _b.length; _a++) { + var file = _b[_a]; + // If we have already included a literal or wildcard path with a + // higher priority extension, we should skip this file. + // + // This handles cases where we may encounter both .ts and + // .d.ts (or .js if "allowJs" is enabled) in the same + // directory when they are compilation outputs. + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + continue; + } + if (ignoreFileNamePattern.test(file)) { + continue; + } + // We may have included a wildcard path with a lower priority + // extension due to the user-defined order of entries in the + // "include" array. If there is a lower priority extension in the + // same directory, we should remove it. + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file); + if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { + wildcardFileMap[key] = file; + } + } + } + var literalFiles = ts.reduceProperties(literalFileMap, addFileToOutput, []); + var wildcardFiles = ts.reduceProperties(wildcardFileMap, addFileToOutput, []); + wildcardFiles.sort(host.useCaseSensitiveFileNames ? ts.compareStrings : ts.compareStringsCaseInsensitive); + return { + fileNames: literalFiles.concat(wildcardFiles), + wildcardDirectories: wildcardDirectories + }; + } + function validateSpecs(specs, errors, allowTrailingRecursion) { + var validSpecs = []; + for (var _i = 0, specs_2 = specs; _i < specs_2.length; _i++) { + var spec = specs_2[_i]; + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + } + else if (invalidMultipleRecursionPatterns.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); + } + else { + validSpecs.push(spec); + } + } + return validSpecs; + } + /** + * Gets directories in a set of include patterns that should be watched for changes. + */ + function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + // We watch a directory recursively if it contains a wildcard anywhere in a directory segment + // of the pattern: + // + // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively + // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added + // + // We watch a directory without recursion if it contains a wildcard in the file segment of + // the pattern: + // + // /a/b/* - Watch /a/b directly to catch any new file + // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z + var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); + var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + var wildcardDirectories = {}; + if (include !== undefined) { + var recursiveKeys = []; + for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { + var file = include_1[_i]; + var name_35 = ts.combinePaths(path, file); + if (excludeRegex && excludeRegex.test(name_35)) { + continue; + } + var match = wildcardDirectoryPattern.exec(name_35); + if (match) { + var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); + var flags = watchRecursivePattern.test(name_35) ? 1 /* Recursive */ : 0 /* None */; + var existingFlags = ts.getProperty(wildcardDirectories, key); + if (existingFlags === undefined || existingFlags < flags) { + wildcardDirectories[key] = flags; + if (flags === 1 /* Recursive */) { + recursiveKeys.push(key); + } + } + } + } + // Remove any subpaths under an existing recursively watched directory. + for (var key in wildcardDirectories) { + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } + } + } + } + } + return wildcardDirectories; + } + /** + * Determines whether a literal or wildcard file has already been included that has a higher + * extension priority. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); + for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { + var higherPriorityExtension = extensions[i]; + var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); + if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { + return true; + } + } + return false; + } + /** + * Removes files included via wildcard expansion with a lower extension priority that have + * already been included. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority); + for (var i = nextExtensionPriority; i < extensions.length; i++) { + var lowerPriorityExtension = extensions[i]; + var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); + delete wildcardFiles[lowerPriorityPath]; + } + } + /** + * Adds a file to an array of files. + * + * @param output The output array. + * @param file The file path. + */ + function addFileToOutput(output, file) { + output.push(file); + return output; + } + /** + * Gets a case sensitive key. + * + * @param key The original key. + */ + function caseSensitiveKeyMapper(key) { + return key; + } + /** + * Gets a case insensitive key. + * + * @param key The original key. + */ + function caseInsensitiveKeyMapper(key) { + return key.toLowerCase(); + } })(ts || (ts = {})); /* @internal */ var ts; @@ -44929,12 +45827,12 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_35 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_35); + for (var name_36 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_36); if (declarations) { // First do a quick check to see if the name of the declaration matches the // last portion of the (possibly) dotted name they're searching for. - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_35); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_36); if (!matches) { continue; } @@ -44947,14 +45845,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_35); + matches = patternMatcher.getMatches(containers, name_36); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_35, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_36, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -45100,689 +45998,586 @@ var ts; (function (ts) { var NavigationBar; (function (NavigationBar) { - function getNavigationBarItems(sourceFile, compilerOptions) { - // TODO: Handle JS files differently in 'navbar' calls for now, but ideally we should unify - // the 'navbar' and 'navto' logic for TypeScript and JavaScript. - if (ts.isSourceFileJavaScript(sourceFile)) { - return getJsNavigationBarItems(sourceFile, compilerOptions); + function getNavigationBarItems(sourceFile) { + curSourceFile = sourceFile; + var result = ts.map(topLevelItems(rootNavigationBarNode(sourceFile)), convertToTopLevelItem); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationBarItems = getNavigationBarItems; + // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. + var curSourceFile; + function nodeText(node) { + return node.getText(curSourceFile); + } + function navigationBarNodeKind(n) { + return n.node.kind; + } + function pushChild(parent, child) { + if (parent.children) { + parent.children.push(child); } - return getItemsWorker(getTopLevelNodes(sourceFile), createTopLevelItem); - function getIndent(node) { - var indent = 1; // Global node is the only one with indent 0. - var current = node.parent; - while (current) { - switch (current.kind) { - case 225 /* ModuleDeclaration */: - // If we have a module declared as A.B.C, it is more "intuitive" - // to say it only has a single layer of depth - do { - current = current.parent; - } while (current.kind === 225 /* ModuleDeclaration */); - // fall through - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - case 222 /* InterfaceDeclaration */: - case 220 /* FunctionDeclaration */: - indent++; + else { + parent.children = [child]; + } + } + /* + For performance, we keep navigation bar parents on a stack rather than passing them through each recursion. + `parent` is the current parent and is *not* stored in parentsStack. + `startNode` sets a new parent and `endNode` returns to the previous parent. + */ + var parentsStack = []; + var parent; + function rootNavigationBarNode(sourceFile) { + ts.Debug.assert(!parentsStack.length); + var root = { node: sourceFile, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 }; + parent = root; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + addChildrenRecursively(statement); + } + endNode(); + ts.Debug.assert(!parent && !parentsStack.length); + return root; + } + function addLeafNode(node) { + pushChild(parent, emptyNavigationBarNode(node)); + } + function emptyNavigationBarNode(node) { + return { + node: node, + additionalNodes: undefined, + parent: parent, + children: undefined, + indent: parent.indent + 1 + }; + } + /** + * Add a new level of NavigationBarNodes. + * This pushes to the stack, so you must call `endNode` when you are done adding to this node. + */ + function startNode(node) { + var navNode = emptyNavigationBarNode(node); + pushChild(parent, navNode); + // Save the old parent + parentsStack.push(parent); + parent = navNode; + } + /** Call after calling `startNode` and adding children to it. */ + function endNode() { + if (parent.children) { + mergeChildren(parent.children); + sortChildren(parent.children); + } + parent = parentsStack.pop(); + } + function addNodeWithRecursiveChild(node, child) { + startNode(node); + addChildrenRecursively(child); + endNode(); + } + /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ + function addChildrenRecursively(node) { + if (!node || ts.isToken(node)) { + return; + } + switch (node.kind) { + case 148 /* Constructor */: + // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. + var ctr = node; + addNodeWithRecursiveChild(ctr, ctr.body); + // Parameter properties are children of the class, not the constructor. + for (var _i = 0, _a = ctr.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (ts.isParameterPropertyDeclaration(param)) { + addLeafNode(param); + } } - current = current.parent; - } - return indent; - } - function getChildNodes(nodes) { - var childNodes = []; - function visit(node) { - switch (node.kind) { - case 200 /* VariableStatement */: - ts.forEach(node.declarationList.declarations, visit); - break; - case 167 /* ObjectBindingPattern */: - case 168 /* ArrayBindingPattern */: - ts.forEach(node.elements, visit); - break; - case 236 /* ExportDeclaration */: - // Handle named exports case e.g.: - // export {a, b as B} from "mod"; - if (node.exportClause) { - ts.forEach(node.exportClause.elements, visit); + break; + case 147 /* MethodDeclaration */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 146 /* MethodSignature */: + if (!ts.hasDynamicName(node)) { + addNodeWithRecursiveChild(node, node.body); + } + break; + case 145 /* PropertyDeclaration */: + case 144 /* PropertySignature */: + if (!ts.hasDynamicName(node)) { + addLeafNode(node); + } + break; + case 231 /* ImportClause */: + var importClause = node; + // Handle default import case e.g.: + // import d from "mod"; + if (importClause.name) { + addLeafNode(importClause); + } + // Handle named bindings in imports e.g.: + // import * as NS from "mod"; + // import {a, b as B} from "mod"; + var namedBindings = importClause.namedBindings; + if (namedBindings) { + if (namedBindings.kind === 232 /* NamespaceImport */) { + addLeafNode(namedBindings); + } + else { + for (var _b = 0, _c = namedBindings.elements; _b < _c.length; _b++) { + var element = _c[_b]; + addLeafNode(element); } - break; - case 230 /* ImportDeclaration */: - var importClause = node.importClause; - if (importClause) { - // Handle default import case e.g.: - // import d from "mod"; - if (importClause.name) { - childNodes.push(importClause); - } - // Handle named bindings in imports e.g.: - // import * as NS from "mod"; - // import {a, b as B} from "mod"; - if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 232 /* NamespaceImport */) { - childNodes.push(importClause.namedBindings); - } - else { - ts.forEach(importClause.namedBindings.elements, visit); - } - } - } - break; - case 169 /* BindingElement */: - case 218 /* VariableDeclaration */: - if (ts.isBindingPattern(node.name)) { - visit(node.name); - break; - } - // Fall through - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - case 222 /* InterfaceDeclaration */: - case 225 /* ModuleDeclaration */: - case 220 /* FunctionDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 234 /* ImportSpecifier */: - case 238 /* ExportSpecifier */: - case 223 /* TypeAliasDeclaration */: - childNodes.push(node); - break; + } } - } - // for (let i = 0, n = nodes.length; i < n; i++) { - // let node = nodes[i]; - // if (node.kind === SyntaxKind.ClassDeclaration || - // node.kind === SyntaxKind.EnumDeclaration || - // node.kind === SyntaxKind.InterfaceDeclaration || - // node.kind === SyntaxKind.ModuleDeclaration || - // node.kind === SyntaxKind.FunctionDeclaration) { - // childNodes.push(node); - // } - // else if (node.kind === SyntaxKind.VariableStatement) { - // childNodes.push.apply(childNodes, (node).declarations); - // } - // } - ts.forEach(nodes, visit); - return sortNodes(childNodes); - } - function getTopLevelNodes(node) { - var topLevelNodes = []; - topLevelNodes.push(node); - addTopLevelNodes(node.statements, topLevelNodes); - return topLevelNodes; - } - function sortNodes(nodes) { - return nodes.slice(0).sort(function (n1, n2) { - if (n1.name && n2.name) { - return localeCompareFix(ts.getPropertyNameForPropertyNameNode(n1.name), ts.getPropertyNameForPropertyNameNode(n2.name)); + break; + case 169 /* BindingElement */: + case 218 /* VariableDeclaration */: + var decl = node; + var name_37 = decl.name; + if (ts.isBindingPattern(name_37)) { + addChildrenRecursively(name_37); } - else if (n1.name) { - return 1; - } - else if (n2.name) { - return -1; + else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { + // For `const x = function() {}`, just use the function node, not the const. + addChildrenRecursively(decl.initializer); } else { - return n1.kind - n2.kind; + addNodeWithRecursiveChild(decl, decl.initializer); } - }); - // node 0.10 treats "a" as greater than "B". - // For consistency, sort alphabetically, falling back to which is lower-case. - function localeCompareFix(a, b) { - var cmp = a.toLowerCase().localeCompare(b.toLowerCase()); - if (cmp !== 0) - return cmp; - // Return the *opposite* of the `<` operator, which works the same in node 0.10 and 6.0. - return a < b ? 1 : a > b ? -1 : 0; - } - } - function addTopLevelNodes(nodes, topLevelNodes) { - nodes = sortNodes(nodes); - for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { - var node = nodes_4[_i]; - switch (node.kind) { - case 221 /* ClassDeclaration */: - topLevelNodes.push(node); - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if (member.kind === 147 /* MethodDeclaration */ || member.kind === 148 /* Constructor */) { - if (member.body) { - // We do not include methods that does not have child functions in it, because of duplications. - if (hasNamedFunctionDeclarations(member.body.statements)) { - topLevelNodes.push(member); - } - addTopLevelNodes(member.body.statements, topLevelNodes); - } + break; + case 180 /* ArrowFunction */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + addNodeWithRecursiveChild(node, node.body); + break; + case 224 /* EnumDeclaration */: + startNode(node); + for (var _d = 0, _e = node.members; _d < _e.length; _d++) { + var member = _e[_d]; + if (!isComputedProperty(member)) { + addLeafNode(member); + } + } + endNode(); + break; + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + case 222 /* InterfaceDeclaration */: + startNode(node); + for (var _f = 0, _g = node.members; _f < _g.length; _f++) { + var member = _g[_f]; + addChildrenRecursively(member); + } + endNode(); + break; + case 225 /* ModuleDeclaration */: + addNodeWithRecursiveChild(node, getInteriorModule(node).body); + break; + case 238 /* ExportSpecifier */: + case 229 /* ImportEqualsDeclaration */: + case 153 /* IndexSignature */: + case 151 /* CallSignature */: + case 152 /* ConstructSignature */: + case 223 /* TypeAliasDeclaration */: + addLeafNode(node); + break; + default: + if (node.jsDocComments) { + for (var _h = 0, _j = node.jsDocComments; _h < _j.length; _h++) { + var jsDocComment = _j[_h]; + for (var _k = 0, _l = jsDocComment.tags; _k < _l.length; _k++) { + var tag = _l[_k]; + if (tag.kind === 279 /* JSDocTypedefTag */) { + addLeafNode(tag); } } - break; - case 224 /* EnumDeclaration */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: - topLevelNodes.push(node); - break; - case 225 /* ModuleDeclaration */: - var moduleDeclaration = node; - topLevelNodes.push(node); - addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); - break; - case 220 /* FunctionDeclaration */: - var functionDeclaration = node; - if (isTopLevelFunctionDeclaration(functionDeclaration)) { - topLevelNodes.push(node); - addTopLevelNodes(functionDeclaration.body.statements, topLevelNodes); - } - break; + } } - } + ts.forEachChild(node, addChildrenRecursively); } - function hasNamedFunctionDeclarations(nodes) { - for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { - var s = nodes_5[_i]; - if (s.kind === 220 /* FunctionDeclaration */ && !isEmpty(s.name.text)) { + } + /** Merge declarations of the same kind. */ + function mergeChildren(children) { + var nameToItems = {}; + ts.filterMutate(children, function (child) { + var decl = child.node; + var name = decl.name && nodeText(decl.name); + if (!name) { + // Anonymous items are never merged. + return true; + } + var itemsWithSameName = ts.getProperty(nameToItems, name); + if (!itemsWithSameName) { + nameToItems[name] = child; + return true; + } + if (itemsWithSameName instanceof Array) { + for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { + var itemWithSameName = itemsWithSameName_1[_i]; + if (tryMerge(itemWithSameName, child)) { + return false; + } + } + itemsWithSameName.push(child); + return true; + } + else { + var itemWithSameName = itemsWithSameName; + if (tryMerge(itemWithSameName, child)) { + return false; + } + nameToItems[name] = [itemWithSameName, child]; + return true; + } + function tryMerge(a, b) { + if (shouldReallyMerge(a.node, b.node)) { + merge(a, b); return true; } + return false; } - return false; - } - function isTopLevelFunctionDeclaration(functionDeclaration) { - if (functionDeclaration.kind === 220 /* FunctionDeclaration */) { - // A function declaration is 'top level' if it contains any function declarations - // within it. - if (functionDeclaration.body && functionDeclaration.body.kind === 199 /* Block */) { - // Proper function declarations can only have identifier names - if (hasNamedFunctionDeclarations(functionDeclaration.body.statements)) { - return true; - } - // Or if it is not parented by another function. I.e all functions at module scope are 'top level'. - if (!ts.isFunctionBlock(functionDeclaration.parent)) { - return true; - } - else { - // We have made sure that a grand parent node exists with 'isFunctionBlock()' above. - var grandParentKind = functionDeclaration.parent.parent.kind; - if (grandParentKind === 147 /* MethodDeclaration */ || - grandParentKind === 148 /* Constructor */) { - return true; - } - } + }); + /** a and b have the same name, but they may not be mergeable. */ + function shouldReallyMerge(a, b) { + return a.kind === b.kind && (a.kind !== 225 /* ModuleDeclaration */ || areSameModule(a, b)); + // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. + // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! + function areSameModule(a, b) { + if (a.body.kind !== b.body.kind) { + return false; } - } - return false; - } - function getItemsWorker(nodes, createItem) { - var items = []; - var keyToItem = {}; - for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { - var child = nodes_6[_i]; - var item = createItem(child); - if (item !== undefined) { - if (item.text.length > 0) { - var key = item.text + "-" + item.kind + "-" + item.indent; - var itemWithSameName = keyToItem[key]; - if (itemWithSameName) { - // We had an item with the same name. Merge these items together. - merge(itemWithSameName, item); - } - else { - keyToItem[key] = item; - items.push(item); - } - } + if (a.body.kind !== 225 /* ModuleDeclaration */) { + return true; } + return areSameModule(a.body, b.body); } - return items; } + /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { - // First, add any spans in the source to the target. - ts.addRange(target.spans, source.spans); - if (source.childItems) { - if (!target.childItems) { - target.childItems = []; - } - // Next, recursively merge or add any children in the source as appropriate. - outer: for (var _i = 0, _a = source.childItems; _i < _a.length; _i++) { - var sourceChild = _a[_i]; - for (var _b = 0, _c = target.childItems; _b < _c.length; _b++) { - var targetChild = _c[_b]; - if (targetChild.text === sourceChild.text && targetChild.kind === sourceChild.kind) { - // Found a match. merge them. - merge(targetChild, sourceChild); - continue outer; - } - } - // Didn't find a match, just add this child to the list. - target.childItems.push(sourceChild); - } + target.additionalNodes = target.additionalNodes || []; + target.additionalNodes.push(source.node); + if (source.additionalNodes) { + (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); + } + target.children = ts.concatenate(target.children, source.children); + if (target.children) { + mergeChildren(target.children); + sortChildren(target.children); + } + var _a; + } + } + /** Recursively ensure that each NavNode's children are in sorted order. */ + function sortChildren(children) { + children.sort(compareChildren); + } + function compareChildren(child1, child2) { + var name1 = tryGetName(child1.node), name2 = tryGetName(child2.node); + if (name1 && name2) { + var cmp = localeCompareFix(name1, name2); + return cmp !== 0 ? cmp : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + } + else { + return name1 ? 1 : name2 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + } + } + // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. + var collator = typeof Intl === "undefined" ? undefined : new Intl.Collator(); + // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B". + var localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; + var localeCompareFix = localeCompareIsCorrect ? collator.compare : function (a, b) { + // This isn't perfect, but it passes all of our tests. + for (var i = 0; i < Math.min(a.length, b.length); i++) { + var chA = a.charAt(i), chB = b.charAt(i); + if (chA === "\"" && chB === "'") { + return 1; + } + if (chA === "'" && chB === "\"") { + return -1; + } + var cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + if (cmp !== 0) { + return cmp; } } - function createChildItem(node) { - switch (node.kind) { - case 142 /* Parameter */: - if (ts.isBindingPattern(node.name)) { - break; - } - if ((node.flags & 1023 /* Modifier */) === 0) { - return undefined; - } - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement); - case 149 /* GetAccessor */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement); - case 150 /* SetAccessor */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); - case 153 /* IndexSignature */: - return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - case 224 /* EnumDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.enumElement); - case 255 /* EnumMember */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 225 /* ModuleDeclaration */: - return createItem(node, getModuleName(node), ts.ScriptElementKind.moduleElement); - case 222 /* InterfaceDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.interfaceElement); - case 223 /* TypeAliasDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.typeElement); - case 151 /* CallSignature */: - return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); - case 152 /* ConstructSignature */: - return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 221 /* ClassDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.classElement); - case 220 /* FunctionDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: - var variableDeclarationNode = void 0; - var name_36; - if (node.kind === 169 /* BindingElement */) { - name_36 = node.name; - variableDeclarationNode = node; - // binding elements are added only for variable declarations - // bubble up to the containing variable declaration - while (variableDeclarationNode && variableDeclarationNode.kind !== 218 /* VariableDeclaration */) { - variableDeclarationNode = variableDeclarationNode.parent; - } - ts.Debug.assert(variableDeclarationNode !== undefined); - } - else { - ts.Debug.assert(!ts.isBindingPattern(node.name)); - variableDeclarationNode = node; - name_36 = node.name; - } - if (ts.isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.constElement); - } - else if (ts.isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.letElement); - } - else { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.variableElement); - } - case 148 /* Constructor */: - return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); - case 238 /* ExportSpecifier */: - case 234 /* ImportSpecifier */: - case 229 /* ImportEqualsDeclaration */: - case 231 /* ImportClause */: - case 232 /* NamespaceImport */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); - } - return undefined; - function createItem(node, name, scriptElementKind) { - return getNavigationBarItem(name, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)]); - } + return a.length - b.length; + }; + /** + * This differs from getItemName because this is just used for sorting. + * We only sort nodes by name that have a more-or-less "direct" name, as opposed to `new()` and the like. + * So `new()` can still come before an `aardvark` method. + */ + function tryGetName(node) { + if (node.kind === 225 /* ModuleDeclaration */) { + return getModuleName(node); } - function isEmpty(text) { - return !text || text.trim() === ""; + var decl = node; + if (decl.name) { + return ts.getPropertyNameForPropertyNameNode(decl.name); } - function getNavigationBarItem(text, kind, kindModifiers, spans, childItems, indent) { - if (childItems === void 0) { childItems = []; } - if (indent === void 0) { indent = 0; } - if (isEmpty(text)) { + switch (node.kind) { + case 179 /* FunctionExpression */: + case 180 /* ArrowFunction */: + case 192 /* ClassExpression */: + return getFunctionOrClassName(node); + case 279 /* JSDocTypedefTag */: + return getJSDocTypedefTagName(node); + default: return undefined; + } + } + function getItemName(node) { + if (node.kind === 225 /* ModuleDeclaration */) { + return getModuleName(node); + } + var name = node.name; + if (name) { + var text = nodeText(name); + if (text.length > 0) { + return text; } + } + switch (node.kind) { + case 256 /* SourceFile */: + var sourceFile = node; + return ts.isExternalModule(sourceFile) + ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" + : ""; + case 180 /* ArrowFunction */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + if (node.flags & 512 /* Default */) { + return "default"; + } + return getFunctionOrClassName(node); + case 148 /* Constructor */: + return "constructor"; + case 152 /* ConstructSignature */: + return "new()"; + case 151 /* CallSignature */: + return "()"; + case 153 /* IndexSignature */: + return "[]"; + case 279 /* JSDocTypedefTag */: + return getJSDocTypedefTagName(node); + default: + ts.Debug.fail(); + return ""; + } + } + function getJSDocTypedefTagName(node) { + if (node.name) { + return node.name.text; + } + else { + var parentNode = node.parent && node.parent.parent; + if (parentNode && parentNode.kind === 200 /* VariableStatement */) { + if (parentNode.declarationList.declarations.length > 0) { + var nameIdentifier = parentNode.declarationList.declarations[0].name; + if (nameIdentifier.kind === 69 /* Identifier */) { + return nameIdentifier.text; + } + } + } + return ""; + } + } + /** Flattens the NavNode tree to a list, keeping only the top-level items. */ + function topLevelItems(root) { + var topLevel = []; + function recur(item) { + if (isTopLevel(item)) { + topLevel.push(item); + if (item.children) { + for (var _i = 0, _a = item.children; _i < _a.length; _i++) { + var child = _a[_i]; + recur(child); + } + } + } + } + recur(root); + return topLevel; + function isTopLevel(item) { + switch (navigationBarNodeKind(item)) { + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + case 224 /* EnumDeclaration */: + case 222 /* InterfaceDeclaration */: + case 225 /* ModuleDeclaration */: + case 256 /* SourceFile */: + case 223 /* TypeAliasDeclaration */: + case 279 /* JSDocTypedefTag */: + return true; + case 148 /* Constructor */: + case 147 /* MethodDeclaration */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + return hasSomeImportantChild(item); + case 180 /* ArrowFunction */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + return isTopLevelFunctionDeclaration(item); + default: + return false; + } + function isTopLevelFunctionDeclaration(item) { + if (!item.node.body) { + return false; + } + switch (navigationBarNodeKind(item.parent)) { + case 226 /* ModuleBlock */: + case 256 /* SourceFile */: + case 147 /* MethodDeclaration */: + case 148 /* Constructor */: + return true; + default: + return hasSomeImportantChild(item); + } + } + function hasSomeImportantChild(item) { + return ts.forEach(item.children, function (child) { + var childKind = navigationBarNodeKind(child); + return childKind !== 218 /* VariableDeclaration */ && childKind !== 169 /* BindingElement */; + }); + } + } + } + // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance. + var emptyChildItemArray = []; + function convertToTopLevelItem(n) { + return { + text: getItemName(n.node), + kind: nodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, + indent: n.indent, + bolded: false, + grayed: false + }; + function convertToChildItem(n) { return { - text: text, - kind: kind, - kindModifiers: kindModifiers, - spans: spans, - childItems: childItems, - indent: indent, + text: getItemName(n.node), + kind: nodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: emptyChildItemArray, + indent: 0, bolded: false, grayed: false }; } - function createTopLevelItem(node) { - switch (node.kind) { - case 256 /* SourceFile */: - return createSourceFileItem(node); - case 221 /* ClassDeclaration */: - return createClassItem(node); - case 147 /* MethodDeclaration */: - case 148 /* Constructor */: - return createMemberFunctionLikeItem(node); - case 224 /* EnumDeclaration */: - return createEnumItem(node); - case 222 /* InterfaceDeclaration */: - return createInterfaceItem(node); - case 225 /* ModuleDeclaration */: - return createModuleItem(node); - case 220 /* FunctionDeclaration */: - return createFunctionItem(node); - case 223 /* TypeAliasDeclaration */: - return createTypeAliasItem(node); - } - return undefined; - function createModuleItem(node) { - var moduleName = getModuleName(node); - var childItems = getItemsWorker(getChildNodes(getInnermostModule(node).body.statements), createChildItem); - return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createFunctionItem(node) { - if (node.body && node.body.kind === 199 /* Block */) { - var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); - return getNavigationBarItem(!node.name ? "default" : node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); } - return undefined; } - function createTypeAliasItem(node) { - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.typeElement, ts.getNodeModifiers(node), [getNodeSpan(node)], [], getIndent(node)); - } - function createMemberFunctionLikeItem(node) { - if (node.body && node.body.kind === 199 /* Block */) { - var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); - var scriptElementKind = void 0; - var memberFunctionName = void 0; - if (node.kind === 147 /* MethodDeclaration */) { - memberFunctionName = ts.getPropertyNameForPropertyNameNode(node.name); - scriptElementKind = ts.ScriptElementKind.memberFunctionElement; - } - else { - memberFunctionName = "constructor"; - scriptElementKind = ts.ScriptElementKind.constructorImplementationElement; - } - return getNavigationBarItem(memberFunctionName, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - return undefined; - } - function createSourceFileItem(node) { - var childItems = getItemsWorker(getChildNodes(node.statements), createChildItem); - var rootName = ts.isExternalModule(node) - ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(node.fileName)))) + "\"" - : ""; - return getNavigationBarItem(rootName, ts.ScriptElementKind.moduleElement, ts.ScriptElementKindModifier.none, [getNodeSpan(node)], childItems); - } - function createClassItem(node) { - var childItems; - if (node.members) { - var constructor = ts.forEach(node.members, function (member) { - return member.kind === 148 /* Constructor */ && member; - }); - // Add the constructor parameters in as children of the class (for property parameters). - // Note that *all non-binding pattern named* parameters will be added to the nodes array, but parameters that - // are not properties will be filtered out later by createChildItem. - var nodes = removeDynamicallyNamedProperties(node); - if (constructor) { - ts.addRange(nodes, ts.filter(constructor.parameters, function (p) { return !ts.isBindingPattern(p.name); })); - } - childItems = getItemsWorker(sortNodes(nodes), createChildItem); - } - var nodeName = !node.name ? "default" : node.name.text; - return getNavigationBarItem(nodeName, ts.ScriptElementKind.classElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createEnumItem(node) { - var childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem); - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.enumElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createInterfaceItem(node) { - var childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem); - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.interfaceElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - } - function getModuleName(moduleDeclaration) { - // We want to maintain quotation marks. - if (ts.isAmbientModule(moduleDeclaration)) { - return getTextOfNode(moduleDeclaration.name); - } - // Otherwise, we need to aggregate each identifier to build up the qualified name. - var result = []; - result.push(moduleDeclaration.name.text); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { - moduleDeclaration = moduleDeclaration.body; - result.push(moduleDeclaration.name.text); - } - return result.join("."); - } - function removeComputedProperties(node) { - return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 140 /* ComputedPropertyName */; }); - } - /** - * Like removeComputedProperties, but retains the properties with well known symbol names - */ - function removeDynamicallyNamedProperties(node) { - return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); - } - function getInnermostModule(node) { - while (node.body.kind === 225 /* ModuleDeclaration */) { - node = node.body; - } - return node; - } - function getNodeSpan(node) { - return node.kind === 256 /* SourceFile */ - ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); - } - function getTextOfNode(node) { - return ts.getTextOfNodeFromSourceText(sourceFile.text, node); + return spans; } } - NavigationBar.getNavigationBarItems = getNavigationBarItems; - function getJsNavigationBarItems(sourceFile, compilerOptions) { - var anonFnText = ""; - var anonClassText = ""; - var indent = 0; - var rootName = ts.isExternalModule(sourceFile) ? - "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" - : ""; - var sourceFileItem = getNavBarItem(rootName, ts.ScriptElementKind.moduleElement, [getNodeSpan(sourceFile)]); - var topItem = sourceFileItem; - // Walk the whole file, because we want to also find function expressions - which may be in variable initializer, - // call arguments, expressions, etc... - ts.forEachChild(sourceFile, visitNode); - function visitNode(node) { - var newItem = createNavBarItem(node); - if (newItem) { - topItem.childItems.push(newItem); - } - if (node.jsDocComments && node.jsDocComments.length > 0) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - visitNode(jsDocComment); - } - } - // Add a level if traversing into a container - if (newItem && (ts.isFunctionLike(node) || ts.isClassLike(node))) { - var lastTop = topItem; - indent++; - topItem = newItem; - ts.forEachChild(node, visitNode); - topItem = lastTop; - indent--; - // If the last item added was an anonymous function expression, and it had no children, discard it. - if (newItem && newItem.text === anonFnText && newItem.childItems.length === 0) { - topItem.childItems.pop(); - } - } - else { - ts.forEachChild(node, visitNode); - } - } - function createNavBarItem(node) { - switch (node.kind) { - case 218 /* VariableDeclaration */: - // Only add to the navbar if at the top-level of the file - // Note: "const" and "let" are also SyntaxKind.VariableDeclarations - if (node.parent /*VariableDeclarationList*/.parent /*VariableStatement*/ - .parent /*SourceFile*/.kind !== 256 /* SourceFile */) { - return undefined; + // TODO: GH#9145: We should just use getNodeKind. No reason why navigationBar and navigateTo should have different behaviors. + function nodeKind(node) { + switch (node.kind) { + case 256 /* SourceFile */: + return ts.ScriptElementKind.moduleElement; + case 255 /* EnumMember */: + return ts.ScriptElementKind.memberVariableElement; + case 218 /* VariableDeclaration */: + case 169 /* BindingElement */: + var variableDeclarationNode = void 0; + var name_38; + if (node.kind === 169 /* BindingElement */) { + name_38 = node.name; + variableDeclarationNode = node; + // binding elements are added only for variable declarations + // bubble up to the containing variable declaration + while (variableDeclarationNode && variableDeclarationNode.kind !== 218 /* VariableDeclaration */) { + variableDeclarationNode = variableDeclarationNode.parent; } - // If it is initialized with a function expression, handle it when we reach the function expression node - var varDecl = node; - if (varDecl.initializer && (varDecl.initializer.kind === 179 /* FunctionExpression */ || - varDecl.initializer.kind === 180 /* ArrowFunction */ || - varDecl.initializer.kind === 192 /* ClassExpression */)) { - return undefined; - } - // Fall through - case 220 /* FunctionDeclaration */: - case 221 /* ClassDeclaration */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - // "export default function().." looks just like a regular function/class declaration, except with the 'default' flag - var name_37 = node.flags && (node.flags & 512 /* Default */) && !node.name ? "default" : - node.kind === 148 /* Constructor */ ? "constructor" : - ts.declarationNameToString(node.name); - return getNavBarItem(name_37, getScriptKindForElementKind(node.kind), [getNodeSpan(node)]); - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 192 /* ClassExpression */: - return getDefineModuleItem(node) || getFunctionOrClassExpressionItem(node); - case 147 /* MethodDeclaration */: - var methodDecl = node; - return getNavBarItem(ts.declarationNameToString(methodDecl.name), ts.ScriptElementKind.memberFunctionElement, [getNodeSpan(node)]); - case 235 /* ExportAssignment */: - // e.g. "export default " - return getNavBarItem("default", ts.ScriptElementKind.variableElement, [getNodeSpan(node)]); - case 231 /* ImportClause */: - if (!node.name) { - // No default import (this node is still a parent of named & namespace imports, which are handled below) - return undefined; - } - // fall through - case 234 /* ImportSpecifier */: // e.g. 'id' in: import {id} from 'mod' (in NamedImports, in ImportClause) - case 232 /* NamespaceImport */: // e.g. '* as ns' in: import * as ns from 'mod' (in ImportClause) - case 238 /* ExportSpecifier */: - // Export specifiers are only interesting if they are reexports from another module, or renamed, else they are already globals - if (node.kind === 238 /* ExportSpecifier */) { - if (!node.parent.parent.moduleSpecifier && !node.propertyName) { - return undefined; - } - } - var decl = node; - if (!decl.name) { - return undefined; - } - var declName = ts.declarationNameToString(decl.name); - return getNavBarItem(declName, ts.ScriptElementKind.constElement, [getNodeSpan(node)]); - case 279 /* JSDocTypedefTag */: - if (node.name) { - return getNavBarItem(node.name.text, ts.ScriptElementKind.typeElement, [getNodeSpan(node)]); - } - else { - var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 200 /* VariableStatement */) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 69 /* Identifier */) { - return getNavBarItem(nameIdentifier.text, ts.ScriptElementKind.typeElement, [getNodeSpan(node)]); - } - } - } - } - default: - return undefined; - } - } - function getNavBarItem(text, kind, spans, kindModifiers) { - if (kindModifiers === void 0) { kindModifiers = ts.ScriptElementKindModifier.none; } - return { - text: text, kind: kind, kindModifiers: kindModifiers, spans: spans, childItems: [], indent: indent, bolded: false, grayed: false - }; - } - function getDefineModuleItem(node) { - if (node.kind !== 179 /* FunctionExpression */ && node.kind !== 180 /* ArrowFunction */) { - return undefined; - } - // No match if this is not a call expression to an identifier named 'define' - if (node.parent.kind !== 174 /* CallExpression */) { - return undefined; - } - var callExpr = node.parent; - if (callExpr.expression.kind !== 69 /* Identifier */ || callExpr.expression.getText() !== "define") { - return undefined; - } - // Return a module of either the given text in the first argument, or of the source file path - var defaultName = node.getSourceFile().fileName; - if (callExpr.arguments[0].kind === 9 /* StringLiteral */) { - defaultName = (callExpr.arguments[0]).text; - } - return getNavBarItem(defaultName, ts.ScriptElementKind.moduleElement, [getNodeSpan(node.parent)]); - } - function getFunctionOrClassExpressionItem(node) { - if (node.kind !== 179 /* FunctionExpression */ && - node.kind !== 180 /* ArrowFunction */ && - node.kind !== 192 /* ClassExpression */) { - return undefined; - } - var fnExpr = node; - var fnName; - if (fnExpr.name && ts.getFullWidth(fnExpr.name) > 0) { - // The expression has an identifier, so use that as the name - fnName = ts.declarationNameToString(fnExpr.name); - } - else { - // See if it is a var initializer. If so, use the var name. - if (fnExpr.parent.kind === 218 /* VariableDeclaration */) { - fnName = ts.declarationNameToString(fnExpr.parent.name); - } - else if (fnExpr.parent.kind === 187 /* BinaryExpression */ && - fnExpr.parent.operatorToken.kind === 56 /* EqualsToken */) { - fnName = fnExpr.parent.left.getText(); - } - else if (fnExpr.parent.kind === 253 /* PropertyAssignment */ && - fnExpr.parent.name) { - fnName = fnExpr.parent.name.getText(); + ts.Debug.assert(!!variableDeclarationNode); } else { - fnName = node.kind === 192 /* ClassExpression */ ? anonClassText : anonFnText; + ts.Debug.assert(!ts.isBindingPattern(node.name)); + variableDeclarationNode = node; + name_38 = node.name; } - } - var scriptKind = node.kind === 192 /* ClassExpression */ ? ts.ScriptElementKind.classElement : ts.ScriptElementKind.functionElement; - return getNavBarItem(fnName, scriptKind, [getNodeSpan(node)]); - } - function getNodeSpan(node) { - return node.kind === 256 /* SourceFile */ - ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); - } - function getScriptKindForElementKind(kind) { - switch (kind) { - case 218 /* VariableDeclaration */: + if (ts.isConst(variableDeclarationNode)) { + return ts.ScriptElementKind.constElement; + } + else if (ts.isLet(variableDeclarationNode)) { + return ts.ScriptElementKind.letElement; + } + else { return ts.ScriptElementKind.variableElement; - case 220 /* FunctionDeclaration */: - return ts.ScriptElementKind.functionElement; - case 221 /* ClassDeclaration */: - return ts.ScriptElementKind.classElement; - case 148 /* Constructor */: - return ts.ScriptElementKind.constructorImplementationElement; - case 149 /* GetAccessor */: - return ts.ScriptElementKind.memberGetAccessorElement; - case 150 /* SetAccessor */: - return ts.ScriptElementKind.memberSetAccessorElement; - default: - return "unknown"; - } + } + case 180 /* ArrowFunction */: + return ts.ScriptElementKind.functionElement; + case 279 /* JSDocTypedefTag */: + return ts.ScriptElementKind.typeElement; + default: + return ts.getNodeKind(node); } - return sourceFileItem.childItems; } - NavigationBar.getJsNavigationBarItems = getJsNavigationBarItems; + function getModuleName(moduleDeclaration) { + // We want to maintain quotation marks. + if (ts.isAmbientModule(moduleDeclaration)) { + return ts.getTextOfNode(moduleDeclaration.name); + } + // Otherwise, we need to aggregate each identifier to build up the qualified name. + var result = []; + result.push(moduleDeclaration.name.text); + while (moduleDeclaration.body && moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { + moduleDeclaration = moduleDeclaration.body; + result.push(moduleDeclaration.name.text); + } + return result.join("."); + } + /** + * For 'module A.B.C', we want to get the node for 'C'. + * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. + */ + function getInteriorModule(decl) { + return decl.body.kind === 225 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; + } + function isComputedProperty(member) { + return !member.name || member.name.kind === 140 /* ComputedPropertyName */; + } + function getNodeSpan(node) { + return node.kind === 256 /* SourceFile */ + ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) + : ts.createTextSpanFromBounds(node.getStart(curSourceFile), node.getEnd()); + } + function getFunctionOrClassName(node) { + if (node.name && ts.getFullWidth(node.name) > 0) { + return ts.declarationNameToString(node.name); + } + else if (node.parent.kind === 218 /* VariableDeclaration */) { + return ts.declarationNameToString(node.parent.name); + } + else if (node.parent.kind === 187 /* BinaryExpression */ && + node.parent.operatorToken.kind === 56 /* EqualsToken */) { + return nodeText(node.parent.left); + } + else if (node.parent.kind === 253 /* PropertyAssignment */ && node.parent.name) { + return nodeText(node.parent.name); + } + else if (node.flags & 512 /* Default */) { + return "default"; + } + else { + return ts.isClassLike(node) ? "" : ""; + } + } + function isFunctionOrClassExpression(node) { + return node.kind === 179 /* FunctionExpression */ || node.kind === 180 /* ArrowFunction */ || node.kind === 192 /* ClassExpression */; + } })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); /* @internal */ @@ -47848,9 +48643,9 @@ var ts; } getTypingNamesFromSourceFileNames(fileNames); // Add the cached typing locations for inferred typings that are already installed - for (var name_38 in packageNameToTypingLocation) { - if (ts.hasProperty(inferredTypings, name_38) && !inferredTypings[name_38]) { - inferredTypings[name_38] = packageNameToTypingLocation[name_38]; + for (var name_39 in packageNameToTypingLocation) { + if (ts.hasProperty(inferredTypings, name_39) && !inferredTypings[name_39]) { + inferredTypings[name_39] = packageNameToTypingLocation[name_39]; } } // Remove typings that the user has added to the exclude list @@ -47936,9 +48731,9 @@ var ts; return; } var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, "*.json", /*exclude*/ undefined, /*depth*/ 2); - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; + var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); if (ts.getBaseFileName(normalizedFileName) !== "package.json") { continue; @@ -48679,9 +49474,9 @@ var ts; } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_39 in o) { - if (o[name_39] === rule) { - return name_39; + for (var name_40 in o) { + if (o[name_40] === rule) { + return name_40; } } throw new Error("Unknown rule"); @@ -50686,6 +51481,7 @@ var ts; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); /// +/// /// /// /// @@ -50825,8 +51621,8 @@ var ts; var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, 0, this); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { - var node = nodes_7[_i]; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; if (pos < node.pos) { pos = this.addSyntheticNodes(list._children, pos, node.pos); } @@ -50961,7 +51757,7 @@ var ts; addCommentParts(declaration.parent, sourceFileOfDeclaration, getCleanedParamJsDocComment); } // If this is left side of dotted module declaration, there is no doc comments associated with this node - if (declaration.kind === 225 /* ModuleDeclaration */ && declaration.body.kind === 225 /* ModuleDeclaration */) { + if (declaration.kind === 225 /* ModuleDeclaration */ && declaration.body && declaration.body.kind === 225 /* ModuleDeclaration */) { return; } if ((declaration.kind === 179 /* FunctionExpression */ || declaration.kind === 180 /* ArrowFunction */) && @@ -51797,11 +52593,11 @@ var ts; sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - var commandLineOptions_stringToEnum; + var commandLineOptionsStringToEnum; /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */ function fixupCompilerOptions(options, diagnostics) { // Lazily create this value to fix module loading errors. - commandLineOptions_stringToEnum = commandLineOptions_stringToEnum || ts.filter(ts.optionDeclarations, function (o) { + commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachValue(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); @@ -51822,8 +52618,8 @@ var ts; } } }; - for (var _i = 0, commandLineOptions_stringToEnum_1 = commandLineOptions_stringToEnum; _i < commandLineOptions_stringToEnum_1.length; _i++) { - var opt = commandLineOptions_stringToEnum_1[_i]; + for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { + var opt = commandLineOptionsStringToEnum_1[_i]; _loop_2(opt); } return options; @@ -51848,6 +52644,17 @@ var ts; // We are not returning a sourceFile for lib file when asked by the program, // so pass --noLib to avoid reporting a file not found error. options.noLib = true; + // Clear out other settings that would not be used in transpiling this module + options.lib = undefined; + options.types = undefined; + options.noEmit = undefined; + options.noEmitOnError = undefined; + options.paths = undefined; + options.rootDirs = undefined; + options.declaration = undefined; + options.declarationDir = undefined; + options.out = undefined; + options.outFile = undefined; // We are not doing a full typecheck, we are not resolving the whole context, // so pass --noResolve to avoid reporting missing file errors. options.noResolve = true; @@ -51882,7 +52689,8 @@ var ts; getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, readFile: function (fileName) { return ""; }, - directoryExists: function (directoryExists) { return true; } + directoryExists: function (directoryExists) { return true; }, + getDirectories: function (path) { return []; } }; var program = ts.createProgram([inputFileName], options, compilerHost); if (transpileOptions.reportDiagnostics) { @@ -51970,7 +52778,7 @@ var ts; var buckets = {}; var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyForCompilationSettings(settings) { - return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + settings.typesRoot + "|" + settings.typesSearchPaths + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); + return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = ts.lookUp(buckets, key); @@ -52716,7 +53524,8 @@ var ts; oldSettings.moduleResolution !== newSettings.moduleResolution || oldSettings.noResolve !== newSettings.noResolve || oldSettings.jsx !== newSettings.jsx || - oldSettings.allowJs !== newSettings.allowJs); + oldSettings.allowJs !== newSettings.allowJs || + oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit); // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -52739,8 +53548,10 @@ var ts; return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); }, directoryExists: function (directoryName) { - ts.Debug.assert(!host.resolveModuleNames || !host.resolveTypeReferenceDirectives); return ts.directoryProbablyExists(directoryName, host); + }, + getDirectories: function (path) { + return host.getDirectories ? host.getDirectories(path) : []; } }; if (host.trace) { @@ -53588,8 +54399,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_40 = element.propertyName || element.name; - existingImportsOrExports[name_40.text] = true; + var name_41 = element.propertyName || element.name; + existingImportsOrExports[name_41.text] = true; } if (ts.isEmpty(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); @@ -53709,14 +54520,14 @@ var ts; var entries = []; var target = program.getCompilerOptions().target; var nameTable = getNameTable(sourceFile); - for (var name_41 in nameTable) { + for (var name_42 in nameTable) { // Skip identifiers produced only from the current location - if (nameTable[name_41] === position) { + if (nameTable[name_42] === position) { continue; } - if (!uniqueNames[name_41]) { - uniqueNames[name_41] = name_41; - var displayName = getCompletionEntryDisplayName(name_41, target, /*performCharacterChecks*/ true); + if (!uniqueNames[name_42]) { + uniqueNames[name_42] = name_42; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_42), target, /*performCharacterChecks*/ true); if (displayName) { var entry = { name: displayName, @@ -53833,10 +54644,10 @@ var ts; var typeChecker = program.getTypeChecker(); var type = typeChecker.getContextualType(node); if (type) { - var entries_1 = []; - addStringLiteralCompletionsFromType(type, entries_1); - if (entries_1.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_1 }; + var entries_2 = []; + addStringLiteralCompletionsFromType(type, entries_2); + if (entries_2.length) { + return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -55136,7 +55947,8 @@ var ts; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference + isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference, + isDefinition: false }); } } @@ -55486,7 +56298,8 @@ var ts; references: [{ fileName: sourceFile.fileName, textSpan: ts.createTextSpan(position, searchText.length), - isWriteAccess: false + isWriteAccess: false, + isDefinition: false }] }); } @@ -55964,7 +56777,8 @@ var ts; return { fileName: node.getSourceFile().fileName, textSpan: ts.createTextSpanFromBounds(start, end), - isWriteAccess: isWriteAccess(node) + isWriteAccess: isWriteAccess(node), + isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node) }; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ @@ -56206,7 +57020,7 @@ var ts; } function getNavigationBarItems(fileName) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile, host.getCompilationSettings()); + return ts.NavigationBar.getNavigationBarItems(sourceFile); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); @@ -56639,7 +57453,8 @@ var ts; return; case 142 /* Parameter */: if (token.parent.name === token) { - return 17 /* parameterName */; + var isThis = token.kind === 69 /* Identifier */ && token.originalKeywordKind === 97 /* ThisKeyword */; + return isThis ? 3 /* keyword */ : 17 /* parameterName */; } return; } @@ -58437,6 +59252,7 @@ var ts; function CoreServicesShimHostAdapter(shimHost) { var _this = this; this.shimHost = shimHost; + this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; if ("directoryExists" in this.shimHost) { this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; } @@ -58444,17 +59260,26 @@ var ts; this.realpath = function (path) { return _this.shimHost.realpath(path); }; } } - CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extension, exclude, depth) { + CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { // Wrap the API changes for 2.0 release. This try/catch // should be removed once TypeScript 2.0 has shipped. - var encoded; try { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude), depth); + var pattern = ts.getFileMatcherPatterns(rootDir, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); } catch (e) { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); + var results = []; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + for (var _a = 0, _b = this.readDirectoryFallback(rootDir, extension, exclude); _a < _b.length; _a++) { + var file = _b[_a]; + if (!ts.contains(results, file)) { + results.push(file); + } + } + } + return results; } - return JSON.parse(encoded); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { return this.shimHost.fileExists(fileName); @@ -58462,6 +59287,9 @@ var ts; CoreServicesShimHostAdapter.prototype.readFile = function (fileName) { return this.shimHost.readFile(fileName); }; + CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { + return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); + }; return CoreServicesShimHostAdapter; }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; @@ -58987,4 +59815,4 @@ var TypeScript; // TODO: it should be moved into a namespace though. /* @internal */ var toolsVersion = "1.9"; -/* tslint:enable:no-unused-variable */ +/* tslint:enable:no-unused-variable */ diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index a9930066fc1..76690ff9d0f 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -713,7 +713,6 @@ declare namespace ts { } interface PropertyAccessExpression extends MemberExpression, Declaration { expression: LeftHandSideExpression; - dotToken: Node; name: Identifier; } type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression; @@ -844,6 +843,7 @@ declare namespace ts { interface SwitchStatement extends Statement { expression: Expression; caseBlock: CaseBlock; + possiblyExhaustive?: boolean; } interface CaseBlock extends Node { clauses: NodeArray; @@ -919,7 +919,7 @@ declare namespace ts { type ModuleBody = ModuleBlock | ModuleDeclaration; interface ModuleDeclaration extends DeclarationStatement { name: Identifier | LiteralExpression; - body: ModuleBlock | ModuleDeclaration; + body?: ModuleBlock | ModuleDeclaration; } interface ModuleBlock extends Node, Statement { statements: NodeArray; @@ -1075,8 +1075,9 @@ declare namespace ts { Assignment = 16, TrueCondition = 32, FalseCondition = 64, - Referenced = 128, - Shared = 256, + SwitchClause = 128, + Referenced = 256, + Shared = 512, Label = 12, Condition = 96, } @@ -1098,6 +1099,12 @@ declare namespace ts { expression: Expression; antecedent: FlowNode; } + interface FlowSwitchClause extends FlowNode { + switchStatement: SwitchStatement; + clauseStart: number; + clauseEnd: number; + antecedent: FlowNode; + } interface AmdDependency { path: string; name: string; @@ -1132,7 +1139,13 @@ declare namespace ts { getCurrentDirectory(): string; } interface ParseConfigHost { - readDirectory(rootDir: string, extension: string, exclude: string[]): string[]; + useCaseSensitiveFileNames: boolean; + readDirectory(rootDir: string, extensions: string[], excludes: string[], includes: string[]): string[]; + /** + * Gets a value indicating whether the specified path exists and is a file. + * @param path The path to test. + */ + fileExists(path: string): boolean; } interface WriteFileCallback { (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void; @@ -1412,7 +1425,6 @@ declare namespace ts { ThisType = 33554432, ObjectLiteralPatternWithComputedProperties = 67108864, Never = 134217728, - Falsy = 126, StringLike = 258, NumberLike = 132, ObjectType = 80896, @@ -1574,7 +1586,10 @@ declare namespace ts { suppressImplicitAnyIndexErrors?: boolean; target?: ScriptTarget; traceResolution?: boolean; + disableSizeLimit?: boolean; types?: string[]; + /** Paths used to used to compute primary types search locations */ + typeRoots?: string[]; typesSearchPaths?: string[]; [option: string]: CompilerOptionsValue | undefined; } @@ -1638,6 +1653,15 @@ declare namespace ts { fileNames: string[]; raw?: any; errors: Diagnostic[]; + wildcardDirectories?: Map; + } + enum WatchDirectoryFlags { + None = 0, + Recursive = 1, + } + interface ExpandResult { + fileNames: string[]; + wildcardDirectories: Map; } interface ModuleResolutionHost { fileExists(fileName: string): boolean; @@ -1672,6 +1696,7 @@ declare namespace ts { getDefaultTypeDirectiveNames?(rootPath: string): string[]; writeFile: WriteFileCallback; getCurrentDirectory(): string; + getDirectories(path: string): string[]; getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; @@ -1707,6 +1732,7 @@ declare namespace ts { useCaseSensitiveFileNames: boolean; write(s: string): void; readFile(path: string, encoding?: string): string; + getFileSize?(path: string): number; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; watchFile?(path: string, callback: FileWatcherCallback): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; @@ -1717,7 +1743,7 @@ declare namespace ts { getExecutingFilePath(): string; getCurrentDirectory(): string; getDirectories(path: string): string[]; - readDirectory(path: string, extension?: string, exclude?: string[]): string[]; + readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; getModifiedTime?(path: string): Date; createHash?(data: string): string; getMemoryUsage?(): number; @@ -1821,6 +1847,7 @@ declare namespace ts { function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { + /** The version of the TypeScript compiler release */ const version: string; function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string; function resolveTripleslashReference(moduleName: string, containingFile: string): string; @@ -1836,7 +1863,15 @@ declare namespace ts { function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; - function getDefaultTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; + /** + * Given a set of options and a set of root files, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options: CompilerOptions, rootFiles: string[], host: CompilerHost): string[]; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { @@ -1978,6 +2013,7 @@ declare namespace ts { resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists?(directoryName: string): boolean; + getDirectories?(directoryName: string): string[]; } interface LanguageService { cleanupSemanticCache(): void; @@ -2068,6 +2104,7 @@ declare namespace ts { textSpan: TextSpan; fileName: string; isWriteAccess: boolean; + isDefinition: boolean; } interface DocumentHighlights { fileName: string; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 9e41f640305..30d49888df1 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -439,8 +439,9 @@ var ts; FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment"; FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition"; FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition"; - FlowFlags[FlowFlags["Referenced"] = 128] = "Referenced"; - FlowFlags[FlowFlags["Shared"] = 256] = "Shared"; + FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; + FlowFlags[FlowFlags["Referenced"] = 256] = "Referenced"; + FlowFlags[FlowFlags["Shared"] = 512] = "Shared"; FlowFlags[FlowFlags["Label"] = 12] = "Label"; FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; })(ts.FlowFlags || (ts.FlowFlags = {})); @@ -654,7 +655,8 @@ var ts; TypeFlags[TypeFlags["Never"] = 134217728] = "Never"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 96] = "Nullable"; - TypeFlags[TypeFlags["Falsy"] = 126] = "Falsy"; + /* @internal */ + TypeFlags[TypeFlags["Falsy"] = 112] = "Falsy"; /* @internal */ TypeFlags[TypeFlags["Intrinsic"] = 150995071] = "Intrinsic"; /* @internal */ @@ -755,6 +757,11 @@ var ts; DiagnosticStyle[DiagnosticStyle["Pretty"] = 1] = "Pretty"; })(ts.DiagnosticStyle || (ts.DiagnosticStyle = {})); var DiagnosticStyle = ts.DiagnosticStyle; + (function (WatchDirectoryFlags) { + WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None"; + WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive"; + })(ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {})); + var WatchDirectoryFlags = ts.WatchDirectoryFlags; /* @internal */ (function (CharacterCodes) { CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; @@ -994,6 +1001,15 @@ var ts; return -1; } ts.indexOf = indexOf; + function indexOfAnyCharCode(text, charCodes, start) { + for (var i = start || 0, len = text.length; i < len; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; + } + ts.indexOfAnyCharCode = indexOfAnyCharCode; function countWhere(array, predicate) { var count = 0; if (array) { @@ -1021,12 +1037,24 @@ var ts; return result; } ts.filter = filter; + function filterMutate(array, f) { + var outIndex = 0; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + if (f(item)) { + array[outIndex] = item; + outIndex++; + } + } + array.length = outIndex; + } + ts.filterMutate = filterMutate; function map(array, f) { var result; if (array) { result = []; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var v = array_4[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; result.push(f(v)); } } @@ -1045,8 +1073,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var item = array_5[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var item = array_6[_i]; if (!contains(result, item, areEqual)) { result.push(item); } @@ -1057,8 +1085,8 @@ var ts; ts.deduplicate = deduplicate; function sum(array, prop) { var result = 0; - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var v = array_6[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var v = array_7[_i]; result += v[prop]; } return result; @@ -1383,6 +1411,30 @@ var ts; return a < b ? -1 /* LessThan */ : 1 /* GreaterThan */; } ts.compareValues = compareValues; + function compareStrings(a, b, ignoreCase) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + if (ignoreCase) { + if (String.prototype.localeCompare) { + var result = a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" }); + return result < 0 ? -1 /* LessThan */ : result > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + a = a.toUpperCase(); + b = b.toUpperCase(); + if (a === b) + return 0 /* EqualTo */; + } + return a < b ? -1 /* LessThan */ : 1 /* GreaterThan */; + } + ts.compareStrings = compareStrings; + function compareStringsCaseInsensitive(a, b) { + return compareStrings(a, b, /*ignoreCase*/ true); + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; function getDiagnosticFileName(diagnostic) { return diagnostic.file ? diagnostic.file.fileName : undefined; } @@ -1637,12 +1689,242 @@ var ts; return path1 + ts.directorySeparator + path2; } ts.combinePaths = combinePaths; + /** + * Removes a trailing directory separator from a path. + * @param path The path. + */ + function removeTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) === ts.directorySeparator) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + /** + * Adds a trailing directory separator to a path, if it does not already have one. + * @param path The path. + */ + function ensureTrailingDirectorySeparator(path) { + if (path.charAt(path.length - 1) !== ts.directorySeparator) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + a = removeTrailingDirectorySeparator(a); + b = removeTrailingDirectorySeparator(b); + var aComponents = getNormalizedPathComponents(a, currentDirectory); + var bComponents = getNormalizedPathComponents(b, currentDirectory); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 0; i < sharedLength; i++) { + var result = compareStrings(aComponents[i], bComponents[i], ignoreCase); + if (result !== 0 /* EqualTo */) { + return result; + } + } + return compareValues(aComponents.length, bComponents.length); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + parent = removeTrailingDirectorySeparator(parent); + child = removeTrailingDirectorySeparator(child); + if (parent === child) + return true; + var parentComponents = getNormalizedPathComponents(parent, currentDirectory); + var childComponents = getNormalizedPathComponents(child, currentDirectory); + if (childComponents.length < parentComponents.length) { + return false; + } + for (var i = 0; i < parentComponents.length; i++) { + var result = compareStrings(parentComponents[i], childComponents[i], ignoreCase); + if (result !== 0 /* EqualTo */) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; function fileExtensionIs(path, extension) { var pathLen = path.length; var extLen = extension.length; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsAny(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsAny = fileExtensionIsAny; + // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. + // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future + // proof. + var reservedCharacterPattern = /[^\w\s\/]/g; + var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; + function getRegularExpressionForWildcard(specs, basePath, usage) { + if (specs === undefined || specs.length === 0) { + return undefined; + } + var pattern = ""; + var hasWrittenSubpattern = false; + spec: for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { + var spec = specs_1[_i]; + if (!spec) { + continue; + } + var subpattern = ""; + var hasRecursiveDirectoryWildcard = false; + var hasWrittenComponent = false; + var components = getNormalizedPathComponents(spec, basePath); + if (usage !== "exclude" && components[components.length - 1] === "**") { + continue spec; + } + // getNormalizedPathComponents includes the separator for the root component. + // We need to remove to create our regex correctly. + components[0] = removeTrailingDirectorySeparator(components[0]); + var optionalCount = 0; + for (var _a = 0, components_1 = components; _a < components_1.length; _a++) { + var component = components_1[_a]; + if (component === "**") { + if (hasRecursiveDirectoryWildcard) { + continue spec; + } + subpattern += "(/.+?)?"; + hasRecursiveDirectoryWildcard = true; + hasWrittenComponent = true; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + subpattern += ts.directorySeparator; + } + subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter); + hasWrittenComponent = true; + } + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + if (hasWrittenSubpattern) { + pattern += "|"; + } + pattern += "(" + subpattern + ")"; + hasWrittenSubpattern = true; + } + if (!pattern) { + return undefined; + } + return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$"); + } + ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function replaceWildcardCharacter(match) { + return match === "*" ? "[^/]*" : match === "?" ? "[^/]" : "\\" + match; + } + function getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + }; + } + ts.getFileMatcherPatterns = getFileMatcherPatterns; + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, getFileSystemEntries) { + path = normalizePath(path); + currentDirectory = normalizePath(currentDirectory); + var patterns = getFileMatcherPatterns(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + var regexFlag = useCaseSensitiveFileNames ? "" : "i"; + var includeFileRegex = patterns.includeFilePattern && new RegExp(patterns.includeFilePattern, regexFlag); + var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); + var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); + var result = []; + for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { + var basePath = _a[_i]; + visitDirectory(basePath, combinePaths(currentDirectory, basePath)); + } + return result; + function visitDirectory(path, absolutePath) { + var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var current = files_1[_i]; + var name_1 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!extensions || fileExtensionIsAny(name_1, extensions)) && + (!includeFileRegex || includeFileRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + result.push(name_1); + } + } + for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { + var current = directories_1[_b]; + var name_2 = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name_2, absoluteName); + } + } + } + } + ts.matchFiles = matchFiles; + /** + * Computes the unique non-wildcard base paths amongst the provided include patterns. + */ + function getBasePaths(path, includes, useCaseSensitiveFileNames) { + // Storage for our results in the form of literal paths (e.g. the paths as written by the user). + var basePaths = [path]; + if (includes) { + // Storage for literal base paths amongst the include patterns. + var includeBasePaths = []; + for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { + var include = includes_1[_i]; + if (isRootedDiskPath(include)) { + var wildcardOffset = indexOfAnyCharCode(include, wildcardCharCodes); + var includeBasePath = wildcardOffset < 0 + ? removeTrailingDirectorySeparator(getDirectoryPath(include)) + : include.substring(0, include.lastIndexOf(ts.directorySeparator, wildcardOffset)); + // Append the literal and canonical candidate base paths. + includeBasePaths.push(includeBasePath); + } + } + // Sort the offsets array using either the literal or canonical path representations. + includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive); + // Iterate over each include base path and include unique base paths that are not a + // subpath of an existing base path + include: for (var i = 0; i < includeBasePaths.length; i++) { + var includeBasePath = includeBasePaths[i]; + for (var j = 0; j < basePaths.length; j++) { + if (containsPath(basePaths[j], includeBasePath, path, !useCaseSensitiveFileNames)) { + continue include; + } + } + basePaths.push(includeBasePath); + } + } + return basePaths; + } function ensureScriptKind(fileName, scriptKind) { // Using scriptKind as a condition handles both: // - 'scriptKind' is unspecified and thus it is `undefined` @@ -1692,6 +1974,57 @@ var ts; return false; } ts.isSupportedSourceFileName = isSupportedSourceFileName; + /** + * Extension boundaries by priority. Lower numbers indicate higher priorities, and are + * aligned to the offset of the highest priority extension in the + * allSupportedExtensions array. + */ + (function (ExtensionPriority) { + ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; + ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; + ExtensionPriority[ExtensionPriority["Limit"] = 5] = "Limit"; + ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; + ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; + })(ts.ExtensionPriority || (ts.ExtensionPriority = {})); + var ExtensionPriority = ts.ExtensionPriority; + function getExtensionPriority(path, supportedExtensions) { + for (var i = supportedExtensions.length - 1; i >= 0; i--) { + if (fileExtensionIs(path, supportedExtensions[i])) { + return adjustExtensionPriority(i); + } + } + // If its not in the list of supported extensions, this is likely a + // TypeScript file with a non-ts extension + return 0 /* Highest */; + } + ts.getExtensionPriority = getExtensionPriority; + /** + * Adjusts an extension priority to be the highest priority within the same range. + */ + function adjustExtensionPriority(extensionPriority) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 0 /* TypeScriptFiles */; + } + else if (extensionPriority < 5 /* Limit */) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return 5 /* Limit */; + } + } + ts.adjustExtensionPriority = adjustExtensionPriority; + /** + * Gets the next lowest extension priority for a given priority. + */ + function getNextLowestExtensionPriority(extensionPriority) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return 5 /* Limit */; + } + } + ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { @@ -1712,6 +2045,10 @@ var ts; return ext === ".jsx" || ext === ".tsx"; } ts.isJsxOrTsxExtension = isJsxOrTsxExtension; + function changeExtension(path, newExtension) { + return (removeFileExtension(path) + newExtension); + } + ts.changeExtension = changeExtension; function Symbol(flags, name) { this.flags = flags; this.name = name; @@ -1790,6 +2127,7 @@ var ts; ts.sys = (function () { function getWScriptSystem() { var fso = new ActiveXObject("Scripting.FileSystemObject"); + var shell = new ActiveXObject("WScript.Shell"); var fileStream = new ActiveXObject("ADODB.Stream"); fileStream.Type = 2 /*text*/; var binaryStream = new ActiveXObject("ADODB.Stream"); @@ -1851,9 +2189,6 @@ var ts; fileStream.Close(); } } - function getCanonicalPath(path) { - return path.toLowerCase(); - } function getNames(collection) { var result = []; for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { @@ -1865,30 +2200,19 @@ var ts; var folder = fso.GetFolder(path); return getNames(folder.subfolders); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { + function getAccessibleFileSystemEntries(path) { + try { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var current = files_1[_i]; - var name_1 = ts.combinePaths(path, current); - if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { - result.push(name_1); - } - } - var subfolders = getNames(folder.subfolders); - for (var _a = 0, subfolders_1 = subfolders; _a < subfolders_1.length; _a++) { - var current = subfolders_1[_a]; - var name_2 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_2))) { - visitDirectory(name_2); - } - } + var directories = getNames(folder.subfolders); + return { files: files, directories: directories }; } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, /*useCaseSensitiveFileNames*/ false, shell.CurrentDirectory, getAccessibleFileSystemEntries); } return { args: args, @@ -1917,7 +2241,7 @@ var ts; return WScript.ScriptFullName; }, getCurrentDirectory: function () { - return new ActiveXObject("WScript.Shell").CurrentDirectory; + return shell.CurrentDirectory; }, getDirectories: getDirectories, readDirectory: readDirectory, @@ -2056,8 +2380,41 @@ var ts; } } } - function getCanonicalPath(path) { - return useCaseSensitiveFileNames ? path : path.toLowerCase(); + function getAccessibleFileSystemEntries(path) { + try { + var entries = _fs.readdirSync(path || ".").sort(); + var files = []; + var directories = []; + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var entry = entries_1[_i]; + // This is necessary because on some file system node fails to exclude + // "." and "..". See https://github.com/nodejs/node/issues/4002 + if (entry === "." || entry === "..") { + continue; + } + var name_3 = ts.combinePaths(path, entry); + var stat = void 0; + try { + stat = _fs.statSync(name_3); + } + catch (e) { + continue; + } + if (stat.isFile()) { + files.push(entry); + } + else if (stat.isDirectory()) { + directories.push(entry); + } + } + return { files: files, directories: directories }; + } + catch (e) { + return { files: [], directories: [] }; + } + } + function readDirectory(path, extensions, excludes, includes) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); } var FileSystemEntryKind; (function (FileSystemEntryKind) { @@ -2085,40 +2442,6 @@ var ts; function getDirectories(path) { return ts.filter(_fs.readdirSync(path), function (p) { return fileSystemEntryExists(ts.combinePaths(path, p), 1 /* Directory */); }); } - function readDirectory(path, extension, exclude) { - var result = []; - exclude = ts.map(exclude, function (s) { return getCanonicalPath(ts.combinePaths(path, s)); }); - visitDirectory(path); - return result; - function visitDirectory(path) { - var files = _fs.readdirSync(path || ".").sort(); - var directories = []; - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var current = files_2[_i]; - // This is necessary because on some file system node fails to exclude - // "." and "..". See https://github.com/nodejs/node/issues/4002 - if (current === "." || current === "..") { - continue; - } - var name_3 = ts.combinePaths(path, current); - if (!ts.contains(exclude, getCanonicalPath(name_3))) { - var stat = _fs.statSync(name_3); - if (stat.isFile()) { - if (!extension || ts.fileExtensionIs(name_3, extension)) { - result.push(name_3); - } - } - else if (stat.isDirectory()) { - directories.push(name_3); - } - } - } - for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { - var current = directories_1[_a]; - visitDirectory(current); - } - } - } return { args: process.argv.slice(2), newLine: _os.EOL, @@ -2206,6 +2529,16 @@ var ts; } return process.memoryUsage().heapUsed; }, + getFileSize: function (path) { + try { + var stat = _fs.statSync(path); + if (stat.isFile()) { + return stat.size; + } + } + catch (e) { } + return 0; + }, exit: function (exitCode) { process.exit(exitCode); }, @@ -2239,7 +2572,10 @@ var ts; getExecutingFilePath: function () { return ChakraHost.executingFile; }, getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, - readDirectory: ChakraHost.readDirectory, + readDirectory: function (path, extensions, excludes, includes) { + var pattern = ts.getFileMatcherPatterns(path, extensions, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); + return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); + }, exit: ChakraHost.quit, realpath: realpath }; @@ -2409,7 +2745,7 @@ var ts; Modifiers_cannot_appear_here: { code: 1184, category: ts.DiagnosticCategory.Error, key: "Modifiers_cannot_appear_here_1184", message: "Modifiers cannot appear here." }, Merge_conflict_marker_encountered: { code: 1185, category: ts.DiagnosticCategory.Error, key: "Merge_conflict_marker_encountered_1185", message: "Merge conflict marker encountered." }, A_rest_element_cannot_have_an_initializer: { code: 1186, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_have_an_initializer_1186", message: "A rest element cannot have an initializer." }, - A_parameter_property_may_not_be_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_a_binding_pattern_1187", message: "A parameter property may not be a binding pattern." }, + A_parameter_property_may_not_be_declared_using_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", message: "A parameter property may not be declared using a binding pattern." }, Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: { code: 1188, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", message: "Only a single variable declaration is allowed in a 'for...of' statement." }, The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: { code: 1189, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", message: "The variable declaration of a 'for...in' statement cannot have an initializer." }, The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: { code: 1190, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", message: "The variable declaration of a 'for...of' statement cannot have an initializer." }, @@ -2425,7 +2761,6 @@ var ts; Line_terminator_not_permitted_before_arrow: { code: 1200, category: ts.DiagnosticCategory.Error, key: "Line_terminator_not_permitted_before_arrow_1200", message: "Line terminator not permitted before arrow." }, Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead: { code: 1202, category: ts.DiagnosticCategory.Error, key: "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", message: "Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead." }, Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead: { code: 1203, category: ts.DiagnosticCategory.Error, key: "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", message: "Export assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'export default' or another module format instead." }, - Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower: { code: 1204, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower_1204", message: "Cannot compile modules into 'es2015' when targeting 'ES5' or lower." }, Decorators_are_not_valid_here: { code: 1206, category: ts.DiagnosticCategory.Error, key: "Decorators_are_not_valid_here_1206", message: "Decorators are not valid here." }, Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: { code: 1207, category: ts.DiagnosticCategory.Error, key: "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", message: "Decorators cannot be applied to multiple get/set accessors of the same name." }, Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: { code: 1208, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", message: "Cannot compile namespaces when the '--isolatedModules' flag is provided." }, @@ -2480,6 +2815,7 @@ var ts; Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, Global_module_exports_may_only_appear_in_declaration_files: { code: 1315, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_declaration_files_1315", message: "Global module exports may only appear in declaration files." }, Global_module_exports_may_only_appear_at_top_level: { code: 1316, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_at_top_level_1316", message: "Global module exports may only appear at top level." }, + A_parameter_property_cannot_be_declared_using_a_rest_parameter: { code: 1317, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", message: "A parameter property cannot be declared using a rest parameter." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, @@ -2750,6 +3086,8 @@ var ts; The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, + Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, + Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -2823,6 +3161,8 @@ var ts; Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_t_4090", message: "Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict." }, The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, + File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { code: 5011, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", message: "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'." }, Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot_read_file_0_Colon_1_5012", message: "Cannot read file '{0}': {1}" }, Unsupported_file_encoding: { code: 5013, category: ts.DiagnosticCategory.Error, key: "Unsupported_file_encoding_5013", message: "Unsupported file encoding." }, Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed_to_parse_file_0_Colon_1_5014", message: "Failed to parse file '{0}': {1}." }, @@ -2996,7 +3336,6 @@ var ts; types_can_only_be_used_in_a_ts_file: { code: 8010, category: ts.DiagnosticCategory.Error, key: "types_can_only_be_used_in_a_ts_file_8010", message: "'types' can only be used in a .ts file." }, type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: ts.DiagnosticCategory.Error, key: "type_arguments_can_only_be_used_in_a_ts_file_8011", message: "'type arguments' can only be used in a .ts file." }, parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: ts.DiagnosticCategory.Error, key: "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", message: "'parameter modifiers' can only be used in a .ts file." }, - property_declarations_can_only_be_used_in_a_ts_file: { code: 8014, category: ts.DiagnosticCategory.Error, key: "property_declarations_can_only_be_used_in_a_ts_file_8014", message: "'property declarations' can only be used in a .ts file." }, enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "enum_declarations_can_only_be_used_in_a_ts_file_8015", message: "'enum declarations' can only be used in a .ts file." }, type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." }, @@ -4985,6 +5324,11 @@ var ts; (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isShorthandAmbientModule(node) { + // The only kind of module that can be missing a body is a shorthand ambient module. + return node.kind === 225 /* ModuleDeclaration */ && (!node.body); + } + ts.isShorthandAmbientModule = isShorthandAmbientModule; function isBlockScopedContainerTopLevel(node) { return node.kind === 256 /* SourceFile */ || node.kind === 225 /* ModuleDeclaration */ || @@ -5417,6 +5761,7 @@ var ts; case 157 /* ConstructorType */: return true; } + return false; } ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { @@ -5839,6 +6184,18 @@ var ts; return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; } ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + /** + * Returns true if the node is a variable declaration whose initializer is a function expression. + * This function does not test if the node is in a JavaScript file or not. + */ + function isDeclarationOfFunctionExpression(s) { + if (s.valueDeclaration && s.valueDeclaration.kind === 218 /* VariableDeclaration */) { + var declaration = s.valueDeclaration; + return declaration.initializer && declaration.initializer.kind === 179 /* FunctionExpression */; + } + return false; + } + ts.isDeclarationOfFunctionExpression = isDeclarationOfFunctionExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder function getSpecialPropertyAssignmentKind(expression) { @@ -6815,7 +7172,9 @@ var ts; ts.forEachExpectedEmitFile = forEachExpectedEmitFile; function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); + var commonSourceDirectory = host.getCommonSourceDirectory(); + var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; return ts.combinePaths(newDirPath, sourceFilePath); } ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; @@ -7175,6 +7534,10 @@ var ts; return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences * representing the UTF-8 encoding of the character, and return the expanded char code list. @@ -7679,7 +8042,6 @@ var ts; return visitNodes(cbNodes, node.properties); case 172 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.dotToken) || visitNode(cbNode, node.name); case 173 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || @@ -8602,6 +8964,7 @@ var ts; return token === 19 /* OpenBracketToken */ || token === 15 /* OpenBraceToken */ || token === 37 /* AsteriskToken */ + || token === 22 /* DotDotDotToken */ || isLiteralPropertyName(); } function nextTokenIsClassOrFunction() { @@ -10703,7 +11066,7 @@ var ts; // If it wasn't then just try to parse out a '.' and report an error. var node = createNode(172 /* PropertyAccessExpression */, expression.pos); node.expression = expression; - node.dotToken = parseExpectedToken(21 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken(21 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } @@ -10905,7 +11268,6 @@ var ts; if (dotToken) { var propertyAccess = createNode(172 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; - propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); continue; @@ -12250,7 +12612,12 @@ var ts; else { node.name = parseLiteralNode(/*internName*/ true); } - node.body = parseModuleBlock(); + if (token === 15 /* OpenBraceToken */) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } return finishNode(node); } function parseModuleDeclaration(fullStart, decorators, modifiers) { @@ -13341,8 +13708,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var node = array_7[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } } @@ -13479,8 +13846,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { - var node = array_8[_i]; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; visitNode(node); } return; @@ -13752,7 +14119,8 @@ var ts; return state_1; } else if (node.kind === 225 /* ModuleDeclaration */) { - return getModuleInstanceState(node.body); + var body = node.body; + return body ? getModuleInstanceState(body) : 1 /* Instantiated */; } else { return 1 /* Instantiated */; @@ -14232,11 +14600,6 @@ var ts; break; } } - function isNarrowableReference(expr) { - return expr.kind === 69 /* Identifier */ || - expr.kind === 97 /* ThisKeyword */ || - expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); - } function isNarrowingExpression(expr) { switch (expr.kind) { case 69 /* Identifier */: @@ -14244,7 +14607,7 @@ var ts; case 172 /* PropertyAccessExpression */: return isNarrowableReference(expr); case 174 /* CallExpression */: - return true; + return hasNarrowableArgument(expr); case 178 /* ParenthesizedExpression */: return isNarrowingExpression(expr.expression); case 187 /* BinaryExpression */: @@ -14254,6 +14617,35 @@ var ts; } return false; } + function isNarrowableReference(expr) { + return expr.kind === 69 /* Identifier */ || + expr.kind === 97 /* ThisKeyword */ || + expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 172 /* PropertyAccessExpression */ && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingNullCheckOperands(expr1, expr2) { + return (expr1.kind === 93 /* NullKeyword */ || expr1.kind === 69 /* Identifier */ && expr1.text === "undefined") && isNarrowableOperand(expr2); + } + function isNarrowingTypeofOperands(expr1, expr2) { + return expr1.kind === 182 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; + } + function isNarrowingDiscriminant(expr) { + return expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 56 /* EqualsToken */: @@ -14262,20 +14654,34 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: - if (isNarrowingExpression(expr.left) && (expr.right.kind === 93 /* NullKeyword */ || expr.right.kind === 69 /* Identifier */)) { - return true; - } - if (expr.left.kind === 182 /* TypeOfExpression */ && isNarrowingExpression(expr.left.expression) && expr.right.kind === 9 /* StringLiteral */) { - return true; - } - return false; + return isNarrowingNullCheckOperands(expr.right, expr.left) || isNarrowingNullCheckOperands(expr.left, expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right) || + isNarrowingDiscriminant(expr.left) || isNarrowingDiscriminant(expr.right); case 91 /* InstanceOfKeyword */: - return isNarrowingExpression(expr.left); + return isNarrowableOperand(expr.left); case 24 /* CommaToken */: return isNarrowingExpression(expr.right); } return false; } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 178 /* ParenthesizedExpression */: + return isNarrowableOperand(expr.expression); + case 187 /* BinaryExpression */: + switch (expr.operatorToken.kind) { + case 56 /* EqualsToken */: + return isNarrowableOperand(expr.left); + case 24 /* CommaToken */: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function isNarrowingSwitchStatement(switchStatement) { + var expr = switchStatement.expression; + return expr.kind === 172 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } function createBranchLabel() { return { flags: 4 /* BranchLabel */, @@ -14290,7 +14696,7 @@ var ts; } function setFlowNodeReferenced(flow) { // On first reference we set the Referenced flag, thereafter we set the Shared flag - flow.flags |= flow.flags & 128 /* Referenced */ ? 256 /* Shared */ : 128 /* Referenced */; + flow.flags |= flow.flags & 256 /* Referenced */ ? 512 /* Shared */ : 256 /* Referenced */; } function addAntecedent(label, antecedent) { if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { @@ -14315,8 +14721,21 @@ var ts; setFlowNodeReferenced(antecedent); return { flags: flags, - antecedent: antecedent, - expression: expression + expression: expression, + antecedent: antecedent + }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingSwitchStatement(switchStatement)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: 128 /* SwitchClause */, + switchStatement: switchStatement, + clauseStart: clauseStart, + clauseEnd: clauseEnd, + antecedent: antecedent }; } function createFlowAssignment(antecedent, node) { @@ -14527,9 +14946,12 @@ var ts; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); - var hasNonEmptyDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250 /* DefaultClause */ && c.statements.length; }); - if (!hasNonEmptyDefault) { - addAntecedent(postSwitchLabel, preSwitchCaseFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 250 /* DefaultClause */; }); + // We mark a switch statement as possibly exhaustive if it has no default clause and if all + // case clauses have unreachable end points (e.g. they all return). + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); } currentBreakTarget = saveBreakTarget; preSwitchCaseFlow = savePreSwitchCaseFlow; @@ -14537,25 +14959,22 @@ var ts; } function bindCaseBlock(node) { var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; for (var i = 0; i < clauses.length; i++) { - var clause = clauses[i]; - if (clause.statements.length) { - if (currentFlow.flags & 1 /* Unreachable */) { - currentFlow = preSwitchCaseFlow; - } - else { - var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, preSwitchCaseFlow); - addAntecedent(preCaseLabel, currentFlow); - currentFlow = finishFlowLabel(preCaseLabel); - } - bind(clause); - if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; } - else { - bind(clause); + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); } } } @@ -14855,7 +15274,7 @@ var ts; } function hasExportDeclarations(node) { var body = node.kind === 256 /* SourceFile */ ? node : node.body; - if (body.kind === 256 /* SourceFile */ || body.kind === 226 /* ModuleBlock */) { + if (body && (body.kind === 256 /* SourceFile */ || body.kind === 226 /* ModuleBlock */)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; if (stat.kind === 236 /* ExportDeclaration */ || stat.kind === 235 /* ExportAssignment */) { @@ -15471,7 +15890,7 @@ var ts; constructorFunction.parent = classPrototype; classPrototype.parent = leftSideOfAssignment; var funcSymbol = container.locals[constructorFunction.text]; - if (!funcSymbol || !(funcSymbol.flags & 16 /* Function */)) { + if (!funcSymbol || !(funcSymbol.flags & 16 /* Function */ || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return; } // Set up the members collection if it doesn't exist already @@ -16193,7 +16612,8 @@ var ts; var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { - if (modulekind || (!compilerOptions.outFile && !compilerOptions.out)) { + if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out)) { // nodes are in different files and order cannot be determines return true; } @@ -16458,7 +16878,8 @@ var ts; } if (!result) { if (nameNotFoundMessage) { - if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg)) { + if (!checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation)) { error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); } } @@ -16532,6 +16953,29 @@ var ts; } return false; } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var parentClassExpression = errorLocation; + while (parentClassExpression) { + var kind = parentClassExpression.kind; + if (kind === 69 /* Identifier */ || kind === 172 /* PropertyAccessExpression */) { + parentClassExpression = parentClassExpression.parent; + continue; + } + if (kind === 194 /* ExpressionWithTypeArguments */) { + break; + } + return false; + } + if (!parentClassExpression) { + return false; + } + var expression = parentClassExpression.expression; + if (resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; + } + return false; + } function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert((result.flags & 2 /* BlockScopedVariable */) !== 0); // Block-scoped variables cannot be used before their definition @@ -16579,9 +17023,11 @@ var ts; function getTargetOfImportClause(node) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { - var exportDefaultSymbol = moduleSymbol.exports["export="] ? - getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : - resolveSymbol(moduleSymbol.exports["default"]); + var exportDefaultSymbol = ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration) ? + moduleSymbol : + moduleSymbol.exports["export="] ? + getPropertyOfType(getTypeOfSymbol(moduleSymbol.exports["export="]), "default") : + resolveSymbol(moduleSymbol.exports["default"]); if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } @@ -16650,6 +17096,9 @@ var ts; if (targetSymbol) { var name_10 = specifier.propertyName || specifier.name; if (name_10.text) { + if (ts.isShorthandAmbientModule(moduleSymbol.valueDeclaration)) { + return moduleSymbol; + } var symbolFromVariable = void 0; // First check if module was specified with "export=". If so, get the member from the resolved type if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { @@ -18171,6 +18620,9 @@ var ts; function isTypeAny(type) { return type && (type.flags & 1 /* Any */) !== 0; } + function isTypeNever(type) { + return type && (type.flags & 134217728 /* Never */) !== 0; + } // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been // assigned by contextual typing. function getTypeForBindingElementParent(node) { @@ -18491,23 +18943,26 @@ var ts; if (declaration.kind === 235 /* ExportAssignment */) { return links.type = checkExpression(declaration.expression); } - // Handle module.exports = expr - if (declaration.kind === 187 /* BinaryExpression */) { - return links.type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); - } - if (declaration.kind === 172 /* PropertyAccessExpression */) { - // Declarations only exist for property access expressions for certain - // special assignment kinds - if (declaration.parent.kind === 187 /* BinaryExpression */) { - // Handle exports.p = expr or this.p = expr or className.prototype.method = expr - return links.type = checkExpressionCached(declaration.parent.right); - } - } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { return unknownType; } - var type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); + var type = undefined; + // Handle module.exports = expr or this.p = expr + if (declaration.kind === 187 /* BinaryExpression */) { + type = getUnionType(ts.map(symbol.declarations, function (decl) { return checkExpressionCached(decl.right); })); + } + else if (declaration.kind === 172 /* PropertyAccessExpression */) { + // Declarations only exist for property access expressions for certain + // special assignment kinds + if (declaration.parent.kind === 187 /* BinaryExpression */) { + // Handle exports.p = expr or className.prototype.method = expr + type = checkExpressionCached(declaration.parent.right); + } + } + if (type === undefined) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); + } if (!popTypeResolution()) { if (symbol.valueDeclaration.type) { // Variable has type annotation that circularly references the variable itself @@ -18600,9 +19055,14 @@ var ts; function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var type = createObjectType(65536 /* Anonymous */, symbol); - links.type = strictNullChecks && symbol.flags & 536870912 /* Optional */ ? - addTypeKind(type, 32 /* Undefined */) : type; + if (symbol.valueDeclaration.kind === 225 /* ModuleDeclaration */ && ts.isShorthandAmbientModule(symbol.valueDeclaration)) { + links.type = anyType; + } + else { + var type = createObjectType(65536 /* Anonymous */, symbol); + links.type = strictNullChecks && symbol.flags & 536870912 /* Optional */ ? + addTypeKind(type, 32 /* Undefined */) : type; + } } return links.type; } @@ -19660,7 +20120,7 @@ var ts; } return result; } - function isOptionalParameter(node) { + function isJSDocOptionalParameter(node) { if (node.flags & 134217728 /* JavaScriptFile */) { if (node.type && node.type.kind === 268 /* JSDocOptionalType */) { return true; @@ -19675,7 +20135,9 @@ var ts; } } } - if (ts.hasQuestionToken(node)) { + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { return true; } if (node.initializer) { @@ -19734,7 +20196,7 @@ var ts; if (param.type && param.type.kind === 166 /* StringLiteralType */) { hasStringLiterals = true; } - if (param.initializer || param.questionToken || param.dotDotDotToken) { + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { minArgumentCount = i - (hasThisParameter ? 1 : 0); } @@ -20818,6 +21280,9 @@ var ts; function isTypeComparableTo(source, target) { return checkTypeComparableTo(source, target, /*errorNode*/ undefined); } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); } @@ -21897,8 +22362,10 @@ var ts; function isTupleLikeType(type) { return !!getPropertyOfType(type, "0"); } - function isStringLiteralType(type) { - return type.flags & 256 /* StringLiteral */; + function isStringLiteralUnionType(type) { + return type.flags & 256 /* StringLiteral */ ? true : + type.flags & 16384 /* Union */ ? ts.forEach(type.types, isStringLiteralUnionType) : + false; } /** * Check if a Type was written as a tuple type literal. @@ -22709,6 +23176,31 @@ var ts; } return node; } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 249 /* CaseClause */) { + var expr = clause.expression; + return expr.kind === 9 /* StringLiteral */ ? getStringLiteralTypeForText(expr.text) : checkExpression(expr); + } + return undefined; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + // If all case clauses specify expressions that have unit types, we return an array + // of those unit types. Otherwise we return an empty array. + var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); + links.switchTypes = ts.forEach(types, function (t) { return !t || t.flags & 256 /* StringLiteral */; }) ? types : emptyArray; + } + return links.switchTypes; + } + function eachTypeContainedIn(source, types) { + return source.flags & 16384 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function filterType(type, f) { + return type.flags & 16384 /* Union */ ? + getUnionType(ts.filter(type.types, f)) : + f(type) ? type : neverType; + } function getFlowTypeOfReference(reference, declaredType, assumeInitialized, includeOuterFunctions) { var key; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 16908175 /* Narrowable */)) { @@ -22724,7 +23216,7 @@ var ts; return result; function getTypeAtFlowNode(flow) { while (true) { - if (flow.flags & 256 /* Shared */) { + if (flow.flags & 512 /* Shared */) { // We cache results of flow type resolution for shared nodes that were previously visited in // the same getFlowTypeOfReference invocation. A node is considered shared when it is the // antecedent of more than one node. @@ -22745,6 +23237,9 @@ var ts; else if (flow.flags & 96 /* Condition */) { type = getTypeAtFlowCondition(flow); } + else if (flow.flags & 128 /* SwitchClause */) { + type = getTypeAtSwitchClause(flow); + } else if (flow.flags & 12 /* Label */) { if (flow.antecedents.length === 1) { flow = flow.antecedents[0]; @@ -22769,7 +23264,7 @@ var ts; // simply return the declared type to reduce follow-on errors. type = declaredType; } - if (flow.flags & 256 /* Shared */) { + if (flow.flags & 512 /* Shared */) { // Record visited node and the associated type in the cache. visitedFlowNodes[visitedFlowCount] = flow; visitedFlowTypes[visitedFlowCount] = type; @@ -22825,6 +23320,10 @@ var ts; } return type; } + function getTypeAtSwitchClause(flow) { + var type = getTypeAtFlowNode(flow.antecedent); + return narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } function getTypeAtFlowBranchLabel(flow) { var antecedentTypes = []; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { @@ -22903,11 +23402,26 @@ var ts; case 31 /* ExclamationEqualsToken */: case 32 /* EqualsEqualsEqualsToken */: case 33 /* ExclamationEqualsEqualsToken */: - if (isNullOrUndefinedLiteral(expr.right)) { - return narrowTypeByNullCheck(type, expr, assumeTrue); + var left = expr.left; + var operator = expr.operatorToken.kind; + var right = expr.right; + if (isNullOrUndefinedLiteral(right)) { + return narrowTypeByNullCheck(type, left, operator, right, assumeTrue); } - if (expr.left.kind === 182 /* TypeOfExpression */ && expr.right.kind === 9 /* StringLiteral */) { - return narrowTypeByTypeof(type, expr, assumeTrue); + if (isNullOrUndefinedLiteral(left)) { + return narrowTypeByNullCheck(type, right, operator, left, assumeTrue); + } + if (left.kind === 182 /* TypeOfExpression */ && right.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); + } + if (right.kind === 182 /* TypeOfExpression */ && left.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); + } + if (left.kind === 172 /* PropertyAccessExpression */) { + return narrowTypeByDiscriminant(type, left, operator, right, assumeTrue); + } + if (right.kind === 172 /* PropertyAccessExpression */) { + return narrowTypeByDiscriminant(type, right, operator, left, assumeTrue); } break; case 91 /* InstanceOfKeyword */: @@ -22917,54 +23431,100 @@ var ts; } return type; } - function narrowTypeByNullCheck(type, expr, assumeTrue) { - // We have '==', '!=', '===', or '!==' operator with 'null' or 'undefined' on the right - var operator = expr.operatorToken.kind; + function narrowTypeByNullCheck(type, target, operator, literal, assumeTrue) { + // We have '==', '!=', '===', or '!==' operator with 'null' or 'undefined' as value if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(expr.left))) { + if (!strictNullChecks || !isMatchingReference(reference, getReferenceFromExpression(target))) { return type; } var doubleEquals = operator === 30 /* EqualsEqualsToken */ || operator === 31 /* ExclamationEqualsToken */; var facts = doubleEquals ? assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - expr.right.kind === 93 /* NullKeyword */ ? + literal.kind === 93 /* NullKeyword */ ? assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; return getTypeWithFacts(type, facts); } - function narrowTypeByTypeof(type, expr, assumeTrue) { - // We have '==', '!=', '====', or !==' operator with 'typeof xxx' on the left - // and string literal on the right - var left = getReferenceFromExpression(expr.left.expression); - var right = expr.right; - if (!isMatchingReference(reference, left)) { + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands + var target = getReferenceFromExpression(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, left)) { + if (containsMatchingReference(reference, target)) { return declaredType; } return type; } - if (expr.operatorToken.kind === 31 /* ExclamationEqualsToken */ || - expr.operatorToken.kind === 33 /* ExclamationEqualsEqualsToken */) { + if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } if (assumeTrue && !(type.flags & 16384 /* Union */)) { // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primtive type. For example, type 'any' can be narrowed // to one of the primitive types. - var targetType = ts.getProperty(typeofTypesByName, right.text); + var targetType = ts.getProperty(typeofTypesByName, literal.text); if (targetType && isTypeSubtypeOf(targetType, type)) { return targetType; } } var facts = assumeTrue ? - ts.getProperty(typeofEQFacts, right.text) || 64 /* TypeofEQHostObject */ : - ts.getProperty(typeofNEFacts, right.text) || 8192 /* TypeofNEHostObject */; + ts.getProperty(typeofEQFacts, literal.text) || 64 /* TypeofEQHostObject */ : + ts.getProperty(typeofNEFacts, literal.text) || 8192 /* TypeofNEHostObject */; return getTypeWithFacts(type, facts); } + function narrowTypeByDiscriminant(type, propAccess, operator, value, assumeTrue) { + // We have '==', '!=', '===', or '!==' operator with property access as target + if (!isMatchingReference(reference, propAccess.expression)) { + return type; + } + var propName = propAccess.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var discriminantType = value.kind === 9 /* StringLiteral */ ? getStringLiteralTypeForText(value.text) : checkExpression(value); + if (!isStringLiteralUnionType(discriminantType)) { + return type; + } + if (operator === 31 /* ExclamationEqualsToken */ || operator === 33 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + if (assumeTrue) { + return filterType(type, function (t) { return areTypesComparable(getTypeOfPropertyOfType(t, propName), discriminantType); }); + } + if (discriminantType.flags & 256 /* StringLiteral */) { + return filterType(type, function (t) { return getTypeOfPropertyOfType(t, propName) !== discriminantType; }); + } + return type; + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + // We have switch statement with property access expression + if (!isMatchingReference(reference, switchStatement.expression.expression)) { + return type; + } + var propName = switchStatement.expression.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return type; + } + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, undefined); + var caseTypes = hasDefaultClause ? ts.filter(clauseTypes, function (t) { return !!t; }) : clauseTypes; + var discriminantType = caseTypes.length ? getUnionType(caseTypes) : undefined; + var caseType = discriminantType && filterType(type, function (t) { return isTypeComparableTo(discriminantType, getTypeOfPropertyOfType(t, propName)); }); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !eachTypeContainedIn(getTypeOfPropertyOfType(t, propName), switchTypes); }); + return caseType ? getUnionType([caseType, defaultType]) : defaultType; + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceFromExpression(expr.left); if (!isMatchingReference(reference, left)) { @@ -23836,9 +24396,6 @@ var ts; function getIndexTypeOfContextualType(type, kind) { return applyToContextualType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); } - function contextualTypeIsStringLiteralType(type) { - return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isStringLiteralType) : isStringLiteralType(type)); - } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); @@ -24839,7 +25396,7 @@ var ts; } var prop = getPropertyOfType(apparentType, right.text); if (!prop) { - if (right.text) { + if (right.text && !checkAndReportErrorForExtendingInterface(node)) { error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(right), typeToString(type.flags & 33554432 /* ThisType */ ? apparentType : type)); } return unknownType; @@ -26126,8 +26683,12 @@ var ts; // When resolved signature is a call signature (and not a construct signature) the result type is any, unless // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations // in a JS file - var funcSymbol = checkExpression(node.expression).symbol; - if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 /* Function */)) { + // Note:JS inferred classes might come from a variable declaration instead of a function declaration. + // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. + var funcSymbol = node.expression.kind === 69 /* Identifier */ ? + getResolvedSymbol(node.expression) : + checkExpression(node.expression).symbol; + if (funcSymbol && funcSymbol.members && (funcSymbol.flags & 16 /* Function */ || ts.isDeclarationOfFunctionExpression(funcSymbol))) { return getInferredClassType(funcSymbol); } else if (compilerOptions.noImplicitAny) { @@ -26147,6 +26708,7 @@ var ts; } function checkAssertion(node) { var exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + checkSourceElement(node.type); var targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { var widenedType = getWidenedType(exprType); @@ -26264,6 +26826,14 @@ var ts; } return emptyObjectType; } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return unknownType; + } + return promiseType; + } function getReturnTypeFromBody(func, contextualMapper) { var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { @@ -26297,19 +26867,12 @@ var ts; else { types = checkAndAggregateReturnExpressionTypes(func, contextualMapper); if (!types) { - return neverType; + // For an async function, the return type will not be never, but rather a Promise for never. + return isAsync ? createPromiseReturnType(func, neverType) : neverType; } if (types.length === 0) { - if (isAsync) { - // For an async function, the return type will not be void, but rather a Promise for void. - var promiseType = createPromiseType(voidType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - return voidType; + // For an async function, the return type will not be void, but rather a Promise for void. + return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } // When yield/return statements are contextually typed we allow the return type to be a union type. @@ -26323,7 +26886,7 @@ var ts; else { error(func, ts.Diagnostics.No_best_common_type_exists_among_return_expressions); // Defer to unioning the return types so we get a) downstream errors earlier and b) better Salsa experience - return getUnionType(types); + return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); } } if (funcIsGenerator) { @@ -26334,20 +26897,10 @@ var ts; reportErrorsFromWidening(func, type); } var widenedType = getWidenedType(type); - if (isAsync) { - // From within an async function you can return either a non-promise value or a promise. Any - // Promise/A+ compatible implementation will always assimilate any foreign promise, so the - // return type of the body is awaited type of the body, wrapped in a native Promise type. - var promiseType = createPromiseType(widenedType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - else { - return widenedType; - } + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body is awaited type of the body, wrapped in a native Promise type. + return isAsync ? createPromiseReturnType(func, widenedType) : widenedType; } function checkAndAggregateYieldOperandTypes(func, contextualMapper) { var aggregatedTypes = []; @@ -26366,10 +26919,40 @@ var ts; }); return aggregatedTypes; } + function isExhaustiveSwitchStatement(node) { + var expr = node.expression; + if (!node.possiblyExhaustive || expr.kind !== 172 /* PropertyAccessExpression */) { + return false; + } + var type = checkExpression(expr.expression); + if (!(type.flags & 16384 /* Union */)) { + return false; + } + var propName = expr.name.text; + var propType = getTypeOfPropertyOfType(type, propName); + if (!propType || !isStringLiteralUnionType(propType)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length) { + return false; + } + return eachTypeContainedIn(propType, switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 32768 /* HasImplicitReturn */)) { + return false; + } + var lastStatement = ts.lastOrUndefined(func.body.statements); + if (lastStatement && lastStatement.kind === 213 /* SwitchStatement */ && isExhaustiveSwitchStatement(lastStatement)) { + return false; + } + return true; + } function checkAndAggregateReturnExpressionTypes(func, contextualMapper) { var isAsync = ts.isAsyncFunctionLike(func); var aggregatedTypes = []; - var hasReturnWithNoExpression = !!(func.flags & 32768 /* HasImplicitReturn */); + var hasReturnWithNoExpression = functionHasImplicitReturn(func); var hasReturnOfTypeNever = false; ts.forEachReturnStatement(func.body, function (returnStatement) { var expr = returnStatement.expression; @@ -26423,7 +27006,7 @@ var ts; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 /* Block */ || !(func.flags & 32768 /* HasImplicitReturn */)) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 199 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 65536 /* HasExplicitReturn */; @@ -27016,7 +27599,7 @@ var ts; case 90 /* InKeyword */: return checkInExpression(left, right, leftType, rightType); case 51 /* AmpersandAmpersandToken */: - return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 126 /* Falsy */) : rightType; + return strictNullChecks ? addTypeKind(rightType, getCombinedTypeFlags(leftType) & 112 /* Falsy */) : rightType; case 52 /* BarBarToken */: return getUnionType([getNonNullableType(leftType), rightType]); case 56 /* EqualsToken */: @@ -27132,7 +27715,7 @@ var ts; } function checkStringLiteralExpression(node) { var contextualType = getContextualType(node); - if (contextualType && contextualTypeIsStringLiteralType(contextualType)) { + if (contextualType && isStringLiteralUnionType(contextualType)) { return getStringLiteralTypeForText(node.text); } return stringType; @@ -27979,9 +28562,6 @@ var ts; } } } - // when checking exported function declarations across modules check only duplicate implementations - // names and consistency of modifiers are verified when we check local symbol - var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & 1536 /* Module */; var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { @@ -28013,7 +28593,7 @@ var ts; duplicateFunctionDeclaration = true; } } - else if (!isExportSymbolInsideModule && previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { reportImplementationExpectedError(previousDeclaration); } if (ts.nodeIsPresent(node.body)) { @@ -28041,7 +28621,7 @@ var ts; }); } // Abstract methods can't have an implementation -- in particular, they don't need one. - if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && !(lastSeenNonAmbientDeclaration.flags & 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } @@ -28142,7 +28722,7 @@ var ts; } function checkNonThenableType(type, location, message) { type = getWidenedType(type); - if (!isTypeAny(type) && isTypeAssignableTo(type, getGlobalThenableType())) { + if (!isTypeAny(type) && !isTypeNever(type) && isTypeAssignableTo(type, getGlobalThenableType())) { if (location) { if (!message) { message = ts.Diagnostics.Operand_for_await_does_not_have_a_valid_callable_then_member; @@ -28168,37 +28748,39 @@ var ts; // ): any; // } // - if (promise.flags & 1 /* Any */) { + if (isTypeAny(promise)) { return undefined; } - if ((promise.flags & 4096 /* Reference */) && promise.target === tryGetGlobalPromiseType()) { - return promise.typeArguments[0]; + if (promise.flags & 4096 /* Reference */) { + if (promise.target === tryGetGlobalPromiseType() + || promise.target === getGlobalPromiseLikeType()) { + return promise.typeArguments[0]; + } } var globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType(); if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) { return undefined; } var thenFunction = getTypeOfPropertyOfType(promise, "then"); - if (thenFunction && (thenFunction.flags & 1 /* Any */)) { + if (!thenFunction || isTypeAny(thenFunction)) { return undefined; } - var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : emptyArray; + var thenSignatures = getSignaturesOfType(thenFunction, 0 /* Call */); if (thenSignatures.length === 0) { return undefined; } var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 131072 /* NEUndefined */); - if (onfulfilledParameterType.flags & 1 /* Any */) { + if (isTypeAny(onfulfilledParameterType)) { return undefined; } var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */); if (onfulfilledParameterSignatures.length === 0) { return undefined; } - var valueParameterType = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); - return valueParameterType; + return getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); } function getTypeOfFirstParameterOfSignature(signature) { - return getTypeAtPosition(signature, 0); + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; } /** * Gets the "awaited type" of a type. @@ -30189,7 +30771,7 @@ var ts; // - augmentation for a global scope is always applied // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Merged */); - if (checkBody) { + if (checkBody && node.body) { // body of ambient external module is always a module block for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { var statement = _a[_i]; @@ -30217,7 +30799,13 @@ var ts; } } } - checkSourceElement(node.body); + if (compilerOptions.noImplicitAny && !node.body) { + // Ambient shorthand module is an implicit any + reportImplicitAnyError(node, anyType); + } + if (node.body) { + checkSourceElement(node.body); + } } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { @@ -31982,7 +32570,10 @@ var ts; return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } else if (node.kind === 142 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 142 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { return checkGrammarAsyncModifier(node, lastAsync); @@ -33812,21 +34403,26 @@ var ts; writeTextOfNode(currentText, node.name); } } - while (node.body.kind !== 226 /* ModuleBlock */) { + while (node.body && node.body.kind !== 226 /* ModuleBlock */) { node = node.body; write("."); writeTextOfNode(currentText, node.name); } var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; + if (node.body) { + enclosingDeclaration = node; + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.body.statements); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + else { + write(";"); + } } function writeTypeAliasDeclaration(node) { var prevEnclosingDeclaration = enclosingDeclaration; @@ -36393,7 +36989,6 @@ var ts; function createPropertyAccessExpression(expression, name) { var result = ts.createSynthesizedNode(172 /* PropertyAccessExpression */); result.expression = parenthesizeForAccess(expression); - result.dotToken = ts.createSynthesizedNode(21 /* DotToken */); result.name = name; return result; } @@ -36457,9 +37052,9 @@ var ts; emit(node.initializer); } // Return true if identifier resolves to an exported member of a namespace - function isNamespaceExportReference(node) { + function isExportReference(node) { var container = resolver.getReferencedExportContainer(node); - return container && container.kind !== 256 /* SourceFile */; + return !!container; } // Return true if identifier resolves to an imported identifier function isImportedReference(node) { @@ -36490,10 +37085,10 @@ var ts; // const foo_1 = require('./foo'); // exports.baz = { foo: foo_1.foo }; // - if (languageVersion < 2 /* ES6 */ || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isNamespaceExportReference(node.name)) { + if (languageVersion < 2 /* ES6 */ || (modulekind !== ts.ModuleKind.ES6 && isImportedReference(node.name)) || isExportReference(node.name)) { // Emit identifier as an identifier write(": "); - emit(node.name); + emitExpressionIdentifier(node.name); } if (languageVersion >= 2 /* ES6 */ && node.objectAssignmentInitializer) { write(" = "); @@ -36552,7 +37147,10 @@ var ts; return; } emit(node.expression); - var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); + var dotRangeStart = ts.nodeIsSynthesized(node.expression) ? -1 : node.expression.end; + var dotRangeEnd = ts.nodeIsSynthesized(node.expression) ? -1 : ts.skipTrivia(currentText, node.expression.end) + 1; + var dotToken = { pos: dotRangeStart, end: dotRangeEnd }; + var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, dotToken); // 1 .toString is a valid property access, emit a space after the literal // Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal var shouldEmitSpace = false; @@ -36575,7 +37173,7 @@ var ts; else { write("."); } - var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); + var indentedAfterDot = indentIfOnDifferentLines(node, dotToken, node.name); emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); } @@ -37014,7 +37612,6 @@ var ts; synthesizedLHS = ts.createSynthesizedNode(172 /* PropertyAccessExpression */, /*startsOnNewLine*/ false); var identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefineTempVariablesInPlace*/ false, /*shouldEmitCommaBeforeAssignment*/ false); synthesizedLHS.expression = identifier; - synthesizedLHS.dotToken = leftHandSideExpression.dotToken; synthesizedLHS.name = leftHandSideExpression.name; write(", "); } @@ -39556,7 +40153,11 @@ var ts; } } function emitClassLikeDeclarationBelowES6(node) { + var isES6ExportedClass = isES6ExportedDeclaration(node); if (node.kind === 221 /* ClassDeclaration */) { + if (isES6ExportedClass && !(node.flags & 512 /* Default */)) { + write("export "); + } // source file level classes in system modules are hoisted so 'var's for them are already defined if (!shouldHoistDeclarationInSystemJsModule(node)) { write("var "); @@ -39621,9 +40222,15 @@ var ts; write(";"); } emitEnd(node); - if (node.kind === 221 /* ClassDeclaration */) { + if (node.kind === 221 /* ClassDeclaration */ && !isES6ExportedClass) { emitExportMemberAssignment(node); } + else if (isES6ExportedClass && (node.flags & 512 /* Default */)) { + writeLine(); + write("export default "); + emitDeclarationName(node); + write(";"); + } } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); @@ -40000,10 +40607,10 @@ var ts; } if (parameters[i].dotDotDotToken) { var parameterType = parameters[i].type; - if (parameterType.kind === 160 /* ArrayType */) { + if (parameterType && parameterType.kind === 160 /* ArrayType */) { parameterType = parameterType.elementType; } - else if (parameterType.kind === 155 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { + else if (parameterType && parameterType.kind === 155 /* TypeReference */ && parameterType.typeArguments && parameterType.typeArguments.length === 1) { parameterType = parameterType.typeArguments[0]; } else { @@ -40021,9 +40628,15 @@ var ts; } /** Serializes the return type of function. Used by the __metadata decorator for a method. */ function emitSerializedReturnTypeOfNode(node) { - if (node && ts.isFunctionLike(node) && node.type) { - emitSerializedTypeNode(node.type); - return; + if (node && ts.isFunctionLike(node)) { + if (node.type) { + emitSerializedTypeNode(node.type); + return; + } + else if (ts.isAsyncFunctionLike(node)) { + write("Promise"); + return; + } } write("void 0"); } @@ -40162,7 +40775,7 @@ var ts; } } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { + if (moduleDeclaration.body && moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -40204,6 +40817,7 @@ var ts; write(getGeneratedNameForNode(node)); emitEnd(node.name); write(") "); + ts.Debug.assert(node.body !== undefined); // node.body must exist, as this is a non-ambient module if (node.body.kind === 226 /* ModuleBlock */) { var saveConvertedLoopState = convertedLoopState; var saveTempFlags = tempFlags; @@ -41998,13 +42612,9 @@ var ts; /* @internal */ ts.ioReadTime = 0; /* @internal */ ts.ioWriteTime = 0; /** The version of the TypeScript compiler release */ - var emptyArray = []; - var defaultLibrarySearchPaths = [ - "types/", - "node_modules/", - "node_modules/@types/", - ]; ts.version = "1.9.0"; + var emptyArray = []; + var defaultTypeRoots = ["node_modules/@types"]; function findConfigFile(searchPath, fileExists) { while (true) { var fileName = ts.combinePaths(searchPath, "tsconfig.json"); @@ -42144,6 +42754,10 @@ var ts; return undefined; } var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + return options.typeRoots || + ts.map(defaultTypeRoots, function (d) { return ts.combinePaths(options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(), d); }); + } /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups @@ -42157,37 +42771,35 @@ var ts; skipTsx: true, traceEnabled: traceEnabled }; - // use typesRoot and fallback to directory that contains tsconfig or current directory if typesRoot is not set - var rootDir = options.typesRoot || (options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : (host.getCurrentDirectory && host.getCurrentDirectory())); + var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); } } else { - if (rootDir === undefined) { + if (typeRoots === undefined) { trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); } else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, rootDir); + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); } } } var failedLookupLocations = []; // Check primary library paths - if (rootDir !== undefined) { - var effectivePrimarySearchPaths = options.typesSearchPaths || defaultLibrarySearchPaths; - for (var _i = 0, effectivePrimarySearchPaths_1 = effectivePrimarySearchPaths; _i < effectivePrimarySearchPaths_1.length; _i++) { - var searchPath = effectivePrimarySearchPaths_1[_i]; - var primaryPath = ts.combinePaths(rootDir, searchPath); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, primaryPath); - } - var candidate = ts.combinePaths(primaryPath, typeReferenceDirectiveName); + if (typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); var candidateDirectory = ts.getDirectoryPath(candidate); var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); if (resolvedFile_1) { @@ -42211,9 +42823,6 @@ var ts; if (containingFile) { initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); } - else { - initialLocationForSecondaryLookup = rootDir; - } if (initialLocationForSecondaryLookup !== undefined) { // check secondary locations if (traceEnabled) { @@ -42808,25 +43417,12 @@ var ts; } } } - function getDefaultTypeDirectiveNames(rootPath) { - var localTypes = ts.combinePaths(rootPath, "types"); - var npmTypes = ts.combinePaths(rootPath, "node_modules/@types"); - var result = []; - if (ts.sys.directoryExists(localTypes)) { - result = result.concat(ts.sys.getDirectories(localTypes)); - } - if (ts.sys.directoryExists(npmTypes)) { - result = result.concat(ts.sys.getDirectories(npmTypes)); - } - return result; - } function getDefaultLibLocation() { return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); } var newLine = ts.getNewLineCharacter(options); var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); return { - getDefaultTypeDirectiveNames: getDefaultTypeDirectiveNames, getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -42839,6 +43435,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, + getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; } @@ -42894,21 +43491,36 @@ var ts; } return resolutions; } - function getDefaultTypeDirectiveNames(options, rootFiles, host) { + function getInferredTypesRoot(options, rootFiles, host) { + return computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + /** + * Given a set of options and a set of root files, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options, rootFiles, host) { // Use explicit type list from tsconfig.json if (options.types) { return options.types; } - // or load all types from the automatic type import fields - if (host && host.getDefaultTypeDirectiveNames) { - var commonRoot = computeCommonSourceDirectoryOfFilenames(rootFiles, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); - if (commonRoot) { - return host.getDefaultTypeDirectiveNames(commonRoot); + // Walk the primary type lookup locations + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + result = result.concat(host.getDirectories(root)); + } } } - return undefined; + return result; } - ts.getDefaultTypeDirectiveNames = getDefaultTypeDirectiveNames; + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -42948,10 +43560,12 @@ var ts; var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); - // load type declarations specified via 'types' argument - var typeReferences = getDefaultTypeDirectiveNames(options, rootNames, host); + // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders + var typeReferences = getAutomaticTypeDirectiveNames(options, rootNames, host); if (typeReferences) { - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, /*containingFile*/ undefined); + var inferredRoot = getInferredTypesRoot(options, rootNames, host); + var containingFilename = ts.combinePaths(inferredRoot, "__inferred type names__.ts"); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); } @@ -43026,8 +43640,8 @@ var ts; // Initialize a checker so that all our files are bound. getTypeChecker(); classifiableNames = {}; - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var sourceFile = files_3[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } @@ -43048,10 +43662,9 @@ var ts; (oldOptions.jsx !== options.jsx) || (oldOptions.allowJs !== options.allowJs) || (oldOptions.rootDir !== options.rootDir) || - (oldOptions.typesSearchPaths !== options.typesSearchPaths) || (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || - (oldOptions.typesRoot !== options.typesRoot) || + !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.mapIsEqualTo(oldOptions.paths, options.paths)) { return false; @@ -43383,8 +43996,20 @@ var ts; } break; case 145 /* PropertyDeclaration */: - diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.property_declarations_can_only_be_used_in_a_ts_file)); - return true; + var propertyDeclaration = node; + if (propertyDeclaration.modifiers) { + for (var _i = 0, _a = propertyDeclaration.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 113 /* StaticKeyword */) { + diagnostics.push(ts.createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + return true; + } + } + } + if (checkTypeAnnotation(node.type)) { + return true; + } + break; case 224 /* EnumDeclaration */: diagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return true; @@ -43530,10 +44155,13 @@ var ts; // This type of declaration is permitted only in the global module. // The StringLiteral must specify a top - level external module name. // Relative external module names are not permitted - // NOTE: body of ambient module is always a module block - for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - collectModuleReferences(statement, /*inAmbientModule*/ true); + // NOTE: body of ambient module is always a module block, if it exists + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, /*inAmbientModule*/ true); + } } } } @@ -43696,7 +44324,7 @@ var ts; } } else { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_name_0, typeReferenceDirective)); + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); } if (saveResolution) { resolvedTypeReferenceDirectives[typeReferenceDirective] = resolvedTypeReferenceDirective; @@ -43868,10 +44496,6 @@ var ts; var span = ts.getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(ts.createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); } - // Cannot specify module gen target of es6 when below es6 - if (options.module === ts.ModuleKind.ES6 && languageVersion < 2 /* ES6 */) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower)); - } // Cannot specify module gen that isn't amd or system with --out if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { @@ -44278,8 +44902,13 @@ var ts; } }, { - name: "typesRoot", - type: "string" + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + } }, { name: "types", @@ -44348,6 +44977,10 @@ var ts; }, description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon }, + { + name: "disableProjectSizeLimit", + type: "boolean" + }, { name: "strictNullChecks", type: "boolean", @@ -44418,7 +45051,15 @@ var ts; ts.parseCustomTypeOption = parseCustomTypeOption; /* @internal */ function parseListTypeOption(opt, value, errors) { - var values = trimString((value || "")).split(","); + if (value === void 0) { value = ""; } + value = trimString(value); + if (ts.startsWith(value, "-")) { + return undefined; + } + if (value === "") { + return []; + } + var values = value.split(","); switch (opt.element.type) { case "number": return ts.map(values, parseInt); @@ -44478,8 +45119,11 @@ var ts; i++; break; case "list": - options[opt.name] = parseListTypeOption(opt, args[i], errors); - i++; + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } break; // If not a primitive, the possible types are specified in what is effectively a map of options. default: @@ -44590,7 +45234,7 @@ var ts; } // Skip over any minified JavaScript files (ending in ".min.js") // Skip over dotted files and folders as well - var IgnoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; + var ignoreFileNamePattern = /(\.min\.js$)|([\\/]\.[\w.])/; /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -44605,72 +45249,59 @@ var ts; var options = ts.extend(existingOptions, compilerOptions); var typingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName); options.configFilePath = configFileName; - var fileNames = getFileNames(errors); + var _a = getFileNames(errors), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, - errors: errors + errors: errors, + wildcardDirectories: wildcardDirectories }; function getFileNames(errors) { - var fileNames = []; + var fileNames; if (ts.hasProperty(json, "files")) { if (ts.isArray(json["files"])) { - fileNames = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); + fileNames = json["files"]; } else { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); } } - else { - var filesSeen = {}; - var exclude = []; - if (ts.isArray(json["exclude"])) { - exclude = json["exclude"]; + var includeSpecs; + if (ts.hasProperty(json, "include")) { + if (ts.isArray(json["include"])) { + includeSpecs = json["include"]; } else { - // by default exclude node_modules, and any specificied output directory - exclude = ["node_modules", "bower_components", "jspm_packages"]; - } - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; - if (outDir) { - exclude.push(outDir); - } - exclude = ts.map(exclude, function (e) { return ts.getNormalizedAbsolutePath(e, basePath); }); - var supportedExtensions = ts.getSupportedExtensions(options); - ts.Debug.assert(ts.indexOf(supportedExtensions, ".ts") < ts.indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick"); - // Get files of supported extensions in their order of resolution - for (var _i = 0, supportedExtensions_1 = supportedExtensions; _i < supportedExtensions_1.length; _i++) { - var extension = supportedExtensions_1[_i]; - var filesInDirWithExtension = host.readDirectory(basePath, extension, exclude); - for (var _a = 0, filesInDirWithExtension_1 = filesInDirWithExtension; _a < filesInDirWithExtension_1.length; _a++) { - var fileName = filesInDirWithExtension_1[_a]; - // .ts extension would read the .d.ts extension files too but since .d.ts is lower priority extension, - // lets pick them when its turn comes up - if (extension === ".ts" && ts.fileExtensionIs(fileName, ".d.ts")) { - continue; - } - if (IgnoreFileNamePattern.test(fileName)) { - continue; - } - // If this is one of the output extension (which would be .d.ts and .js if we are allowing compilation of js files) - // do not include this file if we included .ts or .tsx file with same base name as it could be output of the earlier compilation - if (extension === ".d.ts" || (options.allowJs && ts.contains(ts.supportedJavascriptExtensions, extension))) { - var baseName = fileName.substr(0, fileName.length - extension.length); - if (ts.hasProperty(filesSeen, baseName + ".ts") || ts.hasProperty(filesSeen, baseName + ".tsx")) { - continue; - } - } - filesSeen[fileName] = true; - fileNames.push(fileName); - } + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array")); } } - if (ts.hasProperty(json, "excludes") && !ts.hasProperty(json, "exclude")) { + var excludeSpecs; + if (ts.hasProperty(json, "exclude")) { + if (ts.isArray(json["exclude"])) { + excludeSpecs = json["exclude"]; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); + } + } + else if (ts.hasProperty(json, "excludes")) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); } - return fileNames; + else { + // By default, exclude common package folders + excludeSpecs = ["node_modules", "bower_components", "jspm_packages"]; + } + // Always exclude the output directory unless explicitly included + var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + if (outDir) { + excludeSpecs.push(outDir); + } + if (fileNames === undefined && includeSpecs === undefined) { + includeSpecs = ["**/*"]; + } + return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors); } } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; @@ -44752,6 +45383,273 @@ var ts; function trimString(s) { return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); } + /** + * Tests for a path that ends in a recursive directory wildcard. + * Matches **, \**, **\, and \**\, but not a**b. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\* # matches the recursive directory wildcard "**". + * \/?$ # matches an optional trailing directory separator at the end of the string. + */ + var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + /** + * Tests for a path with multiple recursive directory wildcards. + * Matches **\** and **\a\**, but not **\a**b. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. + * (.*\/)? # optionally matches any number of characters followed by a directory separator. + * \*\* # matches a recursive directory wildcard "**" + * ($|\/) # matches either the end of the string or a directory separator. + */ + var invalidMultipleRecursionPatterns = /(^|\/)\*\*\/(.*\/)?\*\*($|\/)/; + /** + * Tests for a path containing a wildcard character in a directory component of the path. + * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * \/ # matches a directory separator. + * [^/]*? # matches any number of characters excluding directory separators (non-greedy). + * [*?] # matches either a wildcard character (* or ?) + * [^/]* # matches any number of characters excluding directory separators (greedy). + * \/ # matches a directory separator. + */ + var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + /** + * Matches the portion of a wildcard path that does not contain wildcards. + * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * ^ # matches the beginning of the string + * [^*?]* # matches any number of non-wildcard characters + * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by + * # a path component that contains at least one wildcard character (* or ?). + */ + var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; + /** + * Expands an array of file specifications. + * + * @param fileNames The literal file names to include. + * @param include The wildcard file specifications to include. + * @param exclude The wildcard file specifications to exclude. + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param errors An array for diagnostic reporting. + */ + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors) { + basePath = ts.normalizePath(basePath); + // The exclude spec list is converted into a regular expression, which allows us to quickly + // test whether a file or directory should be excluded before recursively traversing the + // file system. + var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; + // Literal file names (provided via the "files" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map later when when including + // wildcard paths. + var literalFileMap = {}; + // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard, and to handle extension priority. + var wildcardFileMap = {}; + if (include) { + include = validateSpecs(include, errors, /*allowTrailingRecursion*/ false); + } + if (exclude) { + exclude = validateSpecs(exclude, errors, /*allowTrailingRecursion*/ true); + } + // Wildcard directories (provided as part of a wildcard path) are stored in a + // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), + // or a recursive directory. This information is used by filesystem watchers to monitor for + // new entries in these paths. + var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); + // Rather than requery this for each file and filespec, we query the supported extensions + // once and store it on the expansion context. + var supportedExtensions = ts.getSupportedExtensions(options); + // Literal files are always included verbatim. An "include" or "exclude" specification cannot + // remove a literal file. + if (fileNames) { + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; + var file = ts.combinePaths(basePath, fileName); + literalFileMap[keyMapper(file)] = file; + } + } + if (include && include.length > 0) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include); _a < _b.length; _a++) { + var file = _b[_a]; + // If we have already included a literal or wildcard path with a + // higher priority extension, we should skip this file. + // + // This handles cases where we may encounter both .ts and + // .d.ts (or .js if "allowJs" is enabled) in the same + // directory when they are compilation outputs. + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + continue; + } + if (ignoreFileNamePattern.test(file)) { + continue; + } + // We may have included a wildcard path with a lower priority + // extension due to the user-defined order of entries in the + // "include" array. If there is a lower priority extension in the + // same directory, we should remove it. + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file); + if (!ts.hasProperty(literalFileMap, key) && !ts.hasProperty(wildcardFileMap, key)) { + wildcardFileMap[key] = file; + } + } + } + var literalFiles = ts.reduceProperties(literalFileMap, addFileToOutput, []); + var wildcardFiles = ts.reduceProperties(wildcardFileMap, addFileToOutput, []); + wildcardFiles.sort(host.useCaseSensitiveFileNames ? ts.compareStrings : ts.compareStringsCaseInsensitive); + return { + fileNames: literalFiles.concat(wildcardFiles), + wildcardDirectories: wildcardDirectories + }; + } + function validateSpecs(specs, errors, allowTrailingRecursion) { + var validSpecs = []; + for (var _i = 0, specs_2 = specs; _i < specs_2.length; _i++) { + var spec = specs_2[_i]; + if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + } + else if (invalidMultipleRecursionPatterns.test(spec)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); + } + else { + validSpecs.push(spec); + } + } + return validSpecs; + } + /** + * Gets directories in a set of include patterns that should be watched for changes. + */ + function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + // We watch a directory recursively if it contains a wildcard anywhere in a directory segment + // of the pattern: + // + // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively + // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added + // + // We watch a directory without recursion if it contains a wildcard in the file segment of + // the pattern: + // + // /a/b/* - Watch /a/b directly to catch any new file + // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z + var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); + var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + var wildcardDirectories = {}; + if (include !== undefined) { + var recursiveKeys = []; + for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { + var file = include_1[_i]; + var name_35 = ts.combinePaths(path, file); + if (excludeRegex && excludeRegex.test(name_35)) { + continue; + } + var match = wildcardDirectoryPattern.exec(name_35); + if (match) { + var key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(); + var flags = watchRecursivePattern.test(name_35) ? 1 /* Recursive */ : 0 /* None */; + var existingFlags = ts.getProperty(wildcardDirectories, key); + if (existingFlags === undefined || existingFlags < flags) { + wildcardDirectories[key] = flags; + if (flags === 1 /* Recursive */) { + recursiveKeys.push(key); + } + } + } + } + // Remove any subpaths under an existing recursively watched directory. + for (var key in wildcardDirectories) { + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } + } + } + } + } + return wildcardDirectories; + } + /** + * Determines whether a literal or wildcard file has already been included that has a higher + * extension priority. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); + for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { + var higherPriorityExtension = extensions[i]; + var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); + if (ts.hasProperty(literalFiles, higherPriorityPath) || ts.hasProperty(wildcardFiles, higherPriorityPath)) { + return true; + } + } + return false; + } + /** + * Removes files included via wildcard expansion with a lower extension priority that have + * already been included. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority); + for (var i = nextExtensionPriority; i < extensions.length; i++) { + var lowerPriorityExtension = extensions[i]; + var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); + delete wildcardFiles[lowerPriorityPath]; + } + } + /** + * Adds a file to an array of files. + * + * @param output The output array. + * @param file The file path. + */ + function addFileToOutput(output, file) { + output.push(file); + return output; + } + /** + * Gets a case sensitive key. + * + * @param key The original key. + */ + function caseSensitiveKeyMapper(key) { + return key; + } + /** + * Gets a case insensitive key. + * + * @param key The original key. + */ + function caseInsensitiveKeyMapper(key) { + return key.toLowerCase(); + } })(ts || (ts = {})); /* @internal */ var ts; @@ -44929,12 +45827,12 @@ var ts; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); - for (var name_35 in nameToDeclarations) { - var declarations = ts.getProperty(nameToDeclarations, name_35); + for (var name_36 in nameToDeclarations) { + var declarations = ts.getProperty(nameToDeclarations, name_36); if (declarations) { // First do a quick check to see if the name of the declaration matches the // last portion of the (possibly) dotted name they're searching for. - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_35); + var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name_36); if (!matches) { continue; } @@ -44947,14 +45845,14 @@ var ts; if (!containers) { return undefined; } - matches = patternMatcher.getMatches(containers, name_35); + matches = patternMatcher.getMatches(containers, name_36); if (!matches) { continue; } } var fileName = sourceFile.fileName; var matchKind = bestMatchKind(matches); - rawItems.push({ name: name_35, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); + rawItems.push({ name: name_36, fileName: fileName, matchKind: matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration: declaration }); } } } @@ -45100,689 +45998,586 @@ var ts; (function (ts) { var NavigationBar; (function (NavigationBar) { - function getNavigationBarItems(sourceFile, compilerOptions) { - // TODO: Handle JS files differently in 'navbar' calls for now, but ideally we should unify - // the 'navbar' and 'navto' logic for TypeScript and JavaScript. - if (ts.isSourceFileJavaScript(sourceFile)) { - return getJsNavigationBarItems(sourceFile, compilerOptions); + function getNavigationBarItems(sourceFile) { + curSourceFile = sourceFile; + var result = ts.map(topLevelItems(rootNavigationBarNode(sourceFile)), convertToTopLevelItem); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationBarItems = getNavigationBarItems; + // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. + var curSourceFile; + function nodeText(node) { + return node.getText(curSourceFile); + } + function navigationBarNodeKind(n) { + return n.node.kind; + } + function pushChild(parent, child) { + if (parent.children) { + parent.children.push(child); } - return getItemsWorker(getTopLevelNodes(sourceFile), createTopLevelItem); - function getIndent(node) { - var indent = 1; // Global node is the only one with indent 0. - var current = node.parent; - while (current) { - switch (current.kind) { - case 225 /* ModuleDeclaration */: - // If we have a module declared as A.B.C, it is more "intuitive" - // to say it only has a single layer of depth - do { - current = current.parent; - } while (current.kind === 225 /* ModuleDeclaration */); - // fall through - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - case 222 /* InterfaceDeclaration */: - case 220 /* FunctionDeclaration */: - indent++; + else { + parent.children = [child]; + } + } + /* + For performance, we keep navigation bar parents on a stack rather than passing them through each recursion. + `parent` is the current parent and is *not* stored in parentsStack. + `startNode` sets a new parent and `endNode` returns to the previous parent. + */ + var parentsStack = []; + var parent; + function rootNavigationBarNode(sourceFile) { + ts.Debug.assert(!parentsStack.length); + var root = { node: sourceFile, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 }; + parent = root; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + addChildrenRecursively(statement); + } + endNode(); + ts.Debug.assert(!parent && !parentsStack.length); + return root; + } + function addLeafNode(node) { + pushChild(parent, emptyNavigationBarNode(node)); + } + function emptyNavigationBarNode(node) { + return { + node: node, + additionalNodes: undefined, + parent: parent, + children: undefined, + indent: parent.indent + 1 + }; + } + /** + * Add a new level of NavigationBarNodes. + * This pushes to the stack, so you must call `endNode` when you are done adding to this node. + */ + function startNode(node) { + var navNode = emptyNavigationBarNode(node); + pushChild(parent, navNode); + // Save the old parent + parentsStack.push(parent); + parent = navNode; + } + /** Call after calling `startNode` and adding children to it. */ + function endNode() { + if (parent.children) { + mergeChildren(parent.children); + sortChildren(parent.children); + } + parent = parentsStack.pop(); + } + function addNodeWithRecursiveChild(node, child) { + startNode(node); + addChildrenRecursively(child); + endNode(); + } + /** Look for navigation bar items in node's subtree, adding them to the current `parent`. */ + function addChildrenRecursively(node) { + if (!node || ts.isToken(node)) { + return; + } + switch (node.kind) { + case 148 /* Constructor */: + // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. + var ctr = node; + addNodeWithRecursiveChild(ctr, ctr.body); + // Parameter properties are children of the class, not the constructor. + for (var _i = 0, _a = ctr.parameters; _i < _a.length; _i++) { + var param = _a[_i]; + if (ts.isParameterPropertyDeclaration(param)) { + addLeafNode(param); + } } - current = current.parent; - } - return indent; - } - function getChildNodes(nodes) { - var childNodes = []; - function visit(node) { - switch (node.kind) { - case 200 /* VariableStatement */: - ts.forEach(node.declarationList.declarations, visit); - break; - case 167 /* ObjectBindingPattern */: - case 168 /* ArrayBindingPattern */: - ts.forEach(node.elements, visit); - break; - case 236 /* ExportDeclaration */: - // Handle named exports case e.g.: - // export {a, b as B} from "mod"; - if (node.exportClause) { - ts.forEach(node.exportClause.elements, visit); + break; + case 147 /* MethodDeclaration */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + case 146 /* MethodSignature */: + if (!ts.hasDynamicName(node)) { + addNodeWithRecursiveChild(node, node.body); + } + break; + case 145 /* PropertyDeclaration */: + case 144 /* PropertySignature */: + if (!ts.hasDynamicName(node)) { + addLeafNode(node); + } + break; + case 231 /* ImportClause */: + var importClause = node; + // Handle default import case e.g.: + // import d from "mod"; + if (importClause.name) { + addLeafNode(importClause); + } + // Handle named bindings in imports e.g.: + // import * as NS from "mod"; + // import {a, b as B} from "mod"; + var namedBindings = importClause.namedBindings; + if (namedBindings) { + if (namedBindings.kind === 232 /* NamespaceImport */) { + addLeafNode(namedBindings); + } + else { + for (var _b = 0, _c = namedBindings.elements; _b < _c.length; _b++) { + var element = _c[_b]; + addLeafNode(element); } - break; - case 230 /* ImportDeclaration */: - var importClause = node.importClause; - if (importClause) { - // Handle default import case e.g.: - // import d from "mod"; - if (importClause.name) { - childNodes.push(importClause); - } - // Handle named bindings in imports e.g.: - // import * as NS from "mod"; - // import {a, b as B} from "mod"; - if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 232 /* NamespaceImport */) { - childNodes.push(importClause.namedBindings); - } - else { - ts.forEach(importClause.namedBindings.elements, visit); - } - } - } - break; - case 169 /* BindingElement */: - case 218 /* VariableDeclaration */: - if (ts.isBindingPattern(node.name)) { - visit(node.name); - break; - } - // Fall through - case 221 /* ClassDeclaration */: - case 224 /* EnumDeclaration */: - case 222 /* InterfaceDeclaration */: - case 225 /* ModuleDeclaration */: - case 220 /* FunctionDeclaration */: - case 229 /* ImportEqualsDeclaration */: - case 234 /* ImportSpecifier */: - case 238 /* ExportSpecifier */: - case 223 /* TypeAliasDeclaration */: - childNodes.push(node); - break; + } } - } - // for (let i = 0, n = nodes.length; i < n; i++) { - // let node = nodes[i]; - // if (node.kind === SyntaxKind.ClassDeclaration || - // node.kind === SyntaxKind.EnumDeclaration || - // node.kind === SyntaxKind.InterfaceDeclaration || - // node.kind === SyntaxKind.ModuleDeclaration || - // node.kind === SyntaxKind.FunctionDeclaration) { - // childNodes.push(node); - // } - // else if (node.kind === SyntaxKind.VariableStatement) { - // childNodes.push.apply(childNodes, (node).declarations); - // } - // } - ts.forEach(nodes, visit); - return sortNodes(childNodes); - } - function getTopLevelNodes(node) { - var topLevelNodes = []; - topLevelNodes.push(node); - addTopLevelNodes(node.statements, topLevelNodes); - return topLevelNodes; - } - function sortNodes(nodes) { - return nodes.slice(0).sort(function (n1, n2) { - if (n1.name && n2.name) { - return localeCompareFix(ts.getPropertyNameForPropertyNameNode(n1.name), ts.getPropertyNameForPropertyNameNode(n2.name)); + break; + case 169 /* BindingElement */: + case 218 /* VariableDeclaration */: + var decl = node; + var name_37 = decl.name; + if (ts.isBindingPattern(name_37)) { + addChildrenRecursively(name_37); } - else if (n1.name) { - return 1; - } - else if (n2.name) { - return -1; + else if (decl.initializer && isFunctionOrClassExpression(decl.initializer)) { + // For `const x = function() {}`, just use the function node, not the const. + addChildrenRecursively(decl.initializer); } else { - return n1.kind - n2.kind; + addNodeWithRecursiveChild(decl, decl.initializer); } - }); - // node 0.10 treats "a" as greater than "B". - // For consistency, sort alphabetically, falling back to which is lower-case. - function localeCompareFix(a, b) { - var cmp = a.toLowerCase().localeCompare(b.toLowerCase()); - if (cmp !== 0) - return cmp; - // Return the *opposite* of the `<` operator, which works the same in node 0.10 and 6.0. - return a < b ? 1 : a > b ? -1 : 0; - } - } - function addTopLevelNodes(nodes, topLevelNodes) { - nodes = sortNodes(nodes); - for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { - var node = nodes_4[_i]; - switch (node.kind) { - case 221 /* ClassDeclaration */: - topLevelNodes.push(node); - for (var _a = 0, _b = node.members; _a < _b.length; _a++) { - var member = _b[_a]; - if (member.kind === 147 /* MethodDeclaration */ || member.kind === 148 /* Constructor */) { - if (member.body) { - // We do not include methods that does not have child functions in it, because of duplications. - if (hasNamedFunctionDeclarations(member.body.statements)) { - topLevelNodes.push(member); - } - addTopLevelNodes(member.body.statements, topLevelNodes); - } + break; + case 180 /* ArrowFunction */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + addNodeWithRecursiveChild(node, node.body); + break; + case 224 /* EnumDeclaration */: + startNode(node); + for (var _d = 0, _e = node.members; _d < _e.length; _d++) { + var member = _e[_d]; + if (!isComputedProperty(member)) { + addLeafNode(member); + } + } + endNode(); + break; + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + case 222 /* InterfaceDeclaration */: + startNode(node); + for (var _f = 0, _g = node.members; _f < _g.length; _f++) { + var member = _g[_f]; + addChildrenRecursively(member); + } + endNode(); + break; + case 225 /* ModuleDeclaration */: + addNodeWithRecursiveChild(node, getInteriorModule(node).body); + break; + case 238 /* ExportSpecifier */: + case 229 /* ImportEqualsDeclaration */: + case 153 /* IndexSignature */: + case 151 /* CallSignature */: + case 152 /* ConstructSignature */: + case 223 /* TypeAliasDeclaration */: + addLeafNode(node); + break; + default: + if (node.jsDocComments) { + for (var _h = 0, _j = node.jsDocComments; _h < _j.length; _h++) { + var jsDocComment = _j[_h]; + for (var _k = 0, _l = jsDocComment.tags; _k < _l.length; _k++) { + var tag = _l[_k]; + if (tag.kind === 279 /* JSDocTypedefTag */) { + addLeafNode(tag); } } - break; - case 224 /* EnumDeclaration */: - case 222 /* InterfaceDeclaration */: - case 223 /* TypeAliasDeclaration */: - topLevelNodes.push(node); - break; - case 225 /* ModuleDeclaration */: - var moduleDeclaration = node; - topLevelNodes.push(node); - addTopLevelNodes(getInnermostModule(moduleDeclaration).body.statements, topLevelNodes); - break; - case 220 /* FunctionDeclaration */: - var functionDeclaration = node; - if (isTopLevelFunctionDeclaration(functionDeclaration)) { - topLevelNodes.push(node); - addTopLevelNodes(functionDeclaration.body.statements, topLevelNodes); - } - break; + } } - } + ts.forEachChild(node, addChildrenRecursively); } - function hasNamedFunctionDeclarations(nodes) { - for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { - var s = nodes_5[_i]; - if (s.kind === 220 /* FunctionDeclaration */ && !isEmpty(s.name.text)) { + } + /** Merge declarations of the same kind. */ + function mergeChildren(children) { + var nameToItems = {}; + ts.filterMutate(children, function (child) { + var decl = child.node; + var name = decl.name && nodeText(decl.name); + if (!name) { + // Anonymous items are never merged. + return true; + } + var itemsWithSameName = ts.getProperty(nameToItems, name); + if (!itemsWithSameName) { + nameToItems[name] = child; + return true; + } + if (itemsWithSameName instanceof Array) { + for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { + var itemWithSameName = itemsWithSameName_1[_i]; + if (tryMerge(itemWithSameName, child)) { + return false; + } + } + itemsWithSameName.push(child); + return true; + } + else { + var itemWithSameName = itemsWithSameName; + if (tryMerge(itemWithSameName, child)) { + return false; + } + nameToItems[name] = [itemWithSameName, child]; + return true; + } + function tryMerge(a, b) { + if (shouldReallyMerge(a.node, b.node)) { + merge(a, b); return true; } + return false; } - return false; - } - function isTopLevelFunctionDeclaration(functionDeclaration) { - if (functionDeclaration.kind === 220 /* FunctionDeclaration */) { - // A function declaration is 'top level' if it contains any function declarations - // within it. - if (functionDeclaration.body && functionDeclaration.body.kind === 199 /* Block */) { - // Proper function declarations can only have identifier names - if (hasNamedFunctionDeclarations(functionDeclaration.body.statements)) { - return true; - } - // Or if it is not parented by another function. I.e all functions at module scope are 'top level'. - if (!ts.isFunctionBlock(functionDeclaration.parent)) { - return true; - } - else { - // We have made sure that a grand parent node exists with 'isFunctionBlock()' above. - var grandParentKind = functionDeclaration.parent.parent.kind; - if (grandParentKind === 147 /* MethodDeclaration */ || - grandParentKind === 148 /* Constructor */) { - return true; - } - } + }); + /** a and b have the same name, but they may not be mergeable. */ + function shouldReallyMerge(a, b) { + return a.kind === b.kind && (a.kind !== 225 /* ModuleDeclaration */ || areSameModule(a, b)); + // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. + // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! + function areSameModule(a, b) { + if (a.body.kind !== b.body.kind) { + return false; } - } - return false; - } - function getItemsWorker(nodes, createItem) { - var items = []; - var keyToItem = {}; - for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { - var child = nodes_6[_i]; - var item = createItem(child); - if (item !== undefined) { - if (item.text.length > 0) { - var key = item.text + "-" + item.kind + "-" + item.indent; - var itemWithSameName = keyToItem[key]; - if (itemWithSameName) { - // We had an item with the same name. Merge these items together. - merge(itemWithSameName, item); - } - else { - keyToItem[key] = item; - items.push(item); - } - } + if (a.body.kind !== 225 /* ModuleDeclaration */) { + return true; } + return areSameModule(a.body, b.body); } - return items; } + /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { - // First, add any spans in the source to the target. - ts.addRange(target.spans, source.spans); - if (source.childItems) { - if (!target.childItems) { - target.childItems = []; - } - // Next, recursively merge or add any children in the source as appropriate. - outer: for (var _i = 0, _a = source.childItems; _i < _a.length; _i++) { - var sourceChild = _a[_i]; - for (var _b = 0, _c = target.childItems; _b < _c.length; _b++) { - var targetChild = _c[_b]; - if (targetChild.text === sourceChild.text && targetChild.kind === sourceChild.kind) { - // Found a match. merge them. - merge(targetChild, sourceChild); - continue outer; - } - } - // Didn't find a match, just add this child to the list. - target.childItems.push(sourceChild); - } + target.additionalNodes = target.additionalNodes || []; + target.additionalNodes.push(source.node); + if (source.additionalNodes) { + (_a = target.additionalNodes).push.apply(_a, source.additionalNodes); + } + target.children = ts.concatenate(target.children, source.children); + if (target.children) { + mergeChildren(target.children); + sortChildren(target.children); + } + var _a; + } + } + /** Recursively ensure that each NavNode's children are in sorted order. */ + function sortChildren(children) { + children.sort(compareChildren); + } + function compareChildren(child1, child2) { + var name1 = tryGetName(child1.node), name2 = tryGetName(child2.node); + if (name1 && name2) { + var cmp = localeCompareFix(name1, name2); + return cmp !== 0 ? cmp : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + } + else { + return name1 ? 1 : name2 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); + } + } + // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. + var collator = typeof Intl === "undefined" ? undefined : new Intl.Collator(); + // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B". + var localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; + var localeCompareFix = localeCompareIsCorrect ? collator.compare : function (a, b) { + // This isn't perfect, but it passes all of our tests. + for (var i = 0; i < Math.min(a.length, b.length); i++) { + var chA = a.charAt(i), chB = b.charAt(i); + if (chA === "\"" && chB === "'") { + return 1; + } + if (chA === "'" && chB === "\"") { + return -1; + } + var cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + if (cmp !== 0) { + return cmp; } } - function createChildItem(node) { - switch (node.kind) { - case 142 /* Parameter */: - if (ts.isBindingPattern(node.name)) { - break; - } - if ((node.flags & 1023 /* Modifier */) === 0) { - return undefined; - } - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 147 /* MethodDeclaration */: - case 146 /* MethodSignature */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberFunctionElement); - case 149 /* GetAccessor */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberGetAccessorElement); - case 150 /* SetAccessor */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberSetAccessorElement); - case 153 /* IndexSignature */: - return createItem(node, "[]", ts.ScriptElementKind.indexSignatureElement); - case 224 /* EnumDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.enumElement); - case 255 /* EnumMember */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 225 /* ModuleDeclaration */: - return createItem(node, getModuleName(node), ts.ScriptElementKind.moduleElement); - case 222 /* InterfaceDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.interfaceElement); - case 223 /* TypeAliasDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.typeElement); - case 151 /* CallSignature */: - return createItem(node, "()", ts.ScriptElementKind.callSignatureElement); - case 152 /* ConstructSignature */: - return createItem(node, "new()", ts.ScriptElementKind.constructSignatureElement); - case 145 /* PropertyDeclaration */: - case 144 /* PropertySignature */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); - case 221 /* ClassDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.classElement); - case 220 /* FunctionDeclaration */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); - case 218 /* VariableDeclaration */: - case 169 /* BindingElement */: - var variableDeclarationNode = void 0; - var name_36; - if (node.kind === 169 /* BindingElement */) { - name_36 = node.name; - variableDeclarationNode = node; - // binding elements are added only for variable declarations - // bubble up to the containing variable declaration - while (variableDeclarationNode && variableDeclarationNode.kind !== 218 /* VariableDeclaration */) { - variableDeclarationNode = variableDeclarationNode.parent; - } - ts.Debug.assert(variableDeclarationNode !== undefined); - } - else { - ts.Debug.assert(!ts.isBindingPattern(node.name)); - variableDeclarationNode = node; - name_36 = node.name; - } - if (ts.isConst(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.constElement); - } - else if (ts.isLet(variableDeclarationNode)) { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.letElement); - } - else { - return createItem(node, getTextOfNode(name_36), ts.ScriptElementKind.variableElement); - } - case 148 /* Constructor */: - return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); - case 238 /* ExportSpecifier */: - case 234 /* ImportSpecifier */: - case 229 /* ImportEqualsDeclaration */: - case 231 /* ImportClause */: - case 232 /* NamespaceImport */: - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.alias); - } - return undefined; - function createItem(node, name, scriptElementKind) { - return getNavigationBarItem(name, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)]); - } + return a.length - b.length; + }; + /** + * This differs from getItemName because this is just used for sorting. + * We only sort nodes by name that have a more-or-less "direct" name, as opposed to `new()` and the like. + * So `new()` can still come before an `aardvark` method. + */ + function tryGetName(node) { + if (node.kind === 225 /* ModuleDeclaration */) { + return getModuleName(node); } - function isEmpty(text) { - return !text || text.trim() === ""; + var decl = node; + if (decl.name) { + return ts.getPropertyNameForPropertyNameNode(decl.name); } - function getNavigationBarItem(text, kind, kindModifiers, spans, childItems, indent) { - if (childItems === void 0) { childItems = []; } - if (indent === void 0) { indent = 0; } - if (isEmpty(text)) { + switch (node.kind) { + case 179 /* FunctionExpression */: + case 180 /* ArrowFunction */: + case 192 /* ClassExpression */: + return getFunctionOrClassName(node); + case 279 /* JSDocTypedefTag */: + return getJSDocTypedefTagName(node); + default: return undefined; + } + } + function getItemName(node) { + if (node.kind === 225 /* ModuleDeclaration */) { + return getModuleName(node); + } + var name = node.name; + if (name) { + var text = nodeText(name); + if (text.length > 0) { + return text; } + } + switch (node.kind) { + case 256 /* SourceFile */: + var sourceFile = node; + return ts.isExternalModule(sourceFile) + ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" + : ""; + case 180 /* ArrowFunction */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + if (node.flags & 512 /* Default */) { + return "default"; + } + return getFunctionOrClassName(node); + case 148 /* Constructor */: + return "constructor"; + case 152 /* ConstructSignature */: + return "new()"; + case 151 /* CallSignature */: + return "()"; + case 153 /* IndexSignature */: + return "[]"; + case 279 /* JSDocTypedefTag */: + return getJSDocTypedefTagName(node); + default: + ts.Debug.fail(); + return ""; + } + } + function getJSDocTypedefTagName(node) { + if (node.name) { + return node.name.text; + } + else { + var parentNode = node.parent && node.parent.parent; + if (parentNode && parentNode.kind === 200 /* VariableStatement */) { + if (parentNode.declarationList.declarations.length > 0) { + var nameIdentifier = parentNode.declarationList.declarations[0].name; + if (nameIdentifier.kind === 69 /* Identifier */) { + return nameIdentifier.text; + } + } + } + return ""; + } + } + /** Flattens the NavNode tree to a list, keeping only the top-level items. */ + function topLevelItems(root) { + var topLevel = []; + function recur(item) { + if (isTopLevel(item)) { + topLevel.push(item); + if (item.children) { + for (var _i = 0, _a = item.children; _i < _a.length; _i++) { + var child = _a[_i]; + recur(child); + } + } + } + } + recur(root); + return topLevel; + function isTopLevel(item) { + switch (navigationBarNodeKind(item)) { + case 221 /* ClassDeclaration */: + case 192 /* ClassExpression */: + case 224 /* EnumDeclaration */: + case 222 /* InterfaceDeclaration */: + case 225 /* ModuleDeclaration */: + case 256 /* SourceFile */: + case 223 /* TypeAliasDeclaration */: + case 279 /* JSDocTypedefTag */: + return true; + case 148 /* Constructor */: + case 147 /* MethodDeclaration */: + case 149 /* GetAccessor */: + case 150 /* SetAccessor */: + return hasSomeImportantChild(item); + case 180 /* ArrowFunction */: + case 220 /* FunctionDeclaration */: + case 179 /* FunctionExpression */: + return isTopLevelFunctionDeclaration(item); + default: + return false; + } + function isTopLevelFunctionDeclaration(item) { + if (!item.node.body) { + return false; + } + switch (navigationBarNodeKind(item.parent)) { + case 226 /* ModuleBlock */: + case 256 /* SourceFile */: + case 147 /* MethodDeclaration */: + case 148 /* Constructor */: + return true; + default: + return hasSomeImportantChild(item); + } + } + function hasSomeImportantChild(item) { + return ts.forEach(item.children, function (child) { + var childKind = navigationBarNodeKind(child); + return childKind !== 218 /* VariableDeclaration */ && childKind !== 169 /* BindingElement */; + }); + } + } + } + // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance. + var emptyChildItemArray = []; + function convertToTopLevelItem(n) { + return { + text: getItemName(n.node), + kind: nodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToChildItem) || emptyChildItemArray, + indent: n.indent, + bolded: false, + grayed: false + }; + function convertToChildItem(n) { return { - text: text, - kind: kind, - kindModifiers: kindModifiers, - spans: spans, - childItems: childItems, - indent: indent, + text: getItemName(n.node), + kind: nodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: emptyChildItemArray, + indent: 0, bolded: false, grayed: false }; } - function createTopLevelItem(node) { - switch (node.kind) { - case 256 /* SourceFile */: - return createSourceFileItem(node); - case 221 /* ClassDeclaration */: - return createClassItem(node); - case 147 /* MethodDeclaration */: - case 148 /* Constructor */: - return createMemberFunctionLikeItem(node); - case 224 /* EnumDeclaration */: - return createEnumItem(node); - case 222 /* InterfaceDeclaration */: - return createInterfaceItem(node); - case 225 /* ModuleDeclaration */: - return createModuleItem(node); - case 220 /* FunctionDeclaration */: - return createFunctionItem(node); - case 223 /* TypeAliasDeclaration */: - return createTypeAliasItem(node); - } - return undefined; - function createModuleItem(node) { - var moduleName = getModuleName(node); - var childItems = getItemsWorker(getChildNodes(getInnermostModule(node).body.statements), createChildItem); - return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createFunctionItem(node) { - if (node.body && node.body.kind === 199 /* Block */) { - var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); - return getNavigationBarItem(!node.name ? "default" : node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); } - return undefined; } - function createTypeAliasItem(node) { - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.typeElement, ts.getNodeModifiers(node), [getNodeSpan(node)], [], getIndent(node)); - } - function createMemberFunctionLikeItem(node) { - if (node.body && node.body.kind === 199 /* Block */) { - var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); - var scriptElementKind = void 0; - var memberFunctionName = void 0; - if (node.kind === 147 /* MethodDeclaration */) { - memberFunctionName = ts.getPropertyNameForPropertyNameNode(node.name); - scriptElementKind = ts.ScriptElementKind.memberFunctionElement; - } - else { - memberFunctionName = "constructor"; - scriptElementKind = ts.ScriptElementKind.constructorImplementationElement; - } - return getNavigationBarItem(memberFunctionName, scriptElementKind, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - return undefined; - } - function createSourceFileItem(node) { - var childItems = getItemsWorker(getChildNodes(node.statements), createChildItem); - var rootName = ts.isExternalModule(node) - ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(node.fileName)))) + "\"" - : ""; - return getNavigationBarItem(rootName, ts.ScriptElementKind.moduleElement, ts.ScriptElementKindModifier.none, [getNodeSpan(node)], childItems); - } - function createClassItem(node) { - var childItems; - if (node.members) { - var constructor = ts.forEach(node.members, function (member) { - return member.kind === 148 /* Constructor */ && member; - }); - // Add the constructor parameters in as children of the class (for property parameters). - // Note that *all non-binding pattern named* parameters will be added to the nodes array, but parameters that - // are not properties will be filtered out later by createChildItem. - var nodes = removeDynamicallyNamedProperties(node); - if (constructor) { - ts.addRange(nodes, ts.filter(constructor.parameters, function (p) { return !ts.isBindingPattern(p.name); })); - } - childItems = getItemsWorker(sortNodes(nodes), createChildItem); - } - var nodeName = !node.name ? "default" : node.name.text; - return getNavigationBarItem(nodeName, ts.ScriptElementKind.classElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createEnumItem(node) { - var childItems = getItemsWorker(sortNodes(removeComputedProperties(node)), createChildItem); - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.enumElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - function createInterfaceItem(node) { - var childItems = getItemsWorker(sortNodes(removeDynamicallyNamedProperties(node)), createChildItem); - return getNavigationBarItem(node.name.text, ts.ScriptElementKind.interfaceElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); - } - } - function getModuleName(moduleDeclaration) { - // We want to maintain quotation marks. - if (ts.isAmbientModule(moduleDeclaration)) { - return getTextOfNode(moduleDeclaration.name); - } - // Otherwise, we need to aggregate each identifier to build up the qualified name. - var result = []; - result.push(moduleDeclaration.name.text); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { - moduleDeclaration = moduleDeclaration.body; - result.push(moduleDeclaration.name.text); - } - return result.join("."); - } - function removeComputedProperties(node) { - return ts.filter(node.members, function (member) { return member.name === undefined || member.name.kind !== 140 /* ComputedPropertyName */; }); - } - /** - * Like removeComputedProperties, but retains the properties with well known symbol names - */ - function removeDynamicallyNamedProperties(node) { - return ts.filter(node.members, function (member) { return !ts.hasDynamicName(member); }); - } - function getInnermostModule(node) { - while (node.body.kind === 225 /* ModuleDeclaration */) { - node = node.body; - } - return node; - } - function getNodeSpan(node) { - return node.kind === 256 /* SourceFile */ - ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); - } - function getTextOfNode(node) { - return ts.getTextOfNodeFromSourceText(sourceFile.text, node); + return spans; } } - NavigationBar.getNavigationBarItems = getNavigationBarItems; - function getJsNavigationBarItems(sourceFile, compilerOptions) { - var anonFnText = ""; - var anonClassText = ""; - var indent = 0; - var rootName = ts.isExternalModule(sourceFile) ? - "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" - : ""; - var sourceFileItem = getNavBarItem(rootName, ts.ScriptElementKind.moduleElement, [getNodeSpan(sourceFile)]); - var topItem = sourceFileItem; - // Walk the whole file, because we want to also find function expressions - which may be in variable initializer, - // call arguments, expressions, etc... - ts.forEachChild(sourceFile, visitNode); - function visitNode(node) { - var newItem = createNavBarItem(node); - if (newItem) { - topItem.childItems.push(newItem); - } - if (node.jsDocComments && node.jsDocComments.length > 0) { - for (var _i = 0, _a = node.jsDocComments; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - visitNode(jsDocComment); - } - } - // Add a level if traversing into a container - if (newItem && (ts.isFunctionLike(node) || ts.isClassLike(node))) { - var lastTop = topItem; - indent++; - topItem = newItem; - ts.forEachChild(node, visitNode); - topItem = lastTop; - indent--; - // If the last item added was an anonymous function expression, and it had no children, discard it. - if (newItem && newItem.text === anonFnText && newItem.childItems.length === 0) { - topItem.childItems.pop(); - } - } - else { - ts.forEachChild(node, visitNode); - } - } - function createNavBarItem(node) { - switch (node.kind) { - case 218 /* VariableDeclaration */: - // Only add to the navbar if at the top-level of the file - // Note: "const" and "let" are also SyntaxKind.VariableDeclarations - if (node.parent /*VariableDeclarationList*/.parent /*VariableStatement*/ - .parent /*SourceFile*/.kind !== 256 /* SourceFile */) { - return undefined; + // TODO: GH#9145: We should just use getNodeKind. No reason why navigationBar and navigateTo should have different behaviors. + function nodeKind(node) { + switch (node.kind) { + case 256 /* SourceFile */: + return ts.ScriptElementKind.moduleElement; + case 255 /* EnumMember */: + return ts.ScriptElementKind.memberVariableElement; + case 218 /* VariableDeclaration */: + case 169 /* BindingElement */: + var variableDeclarationNode = void 0; + var name_38; + if (node.kind === 169 /* BindingElement */) { + name_38 = node.name; + variableDeclarationNode = node; + // binding elements are added only for variable declarations + // bubble up to the containing variable declaration + while (variableDeclarationNode && variableDeclarationNode.kind !== 218 /* VariableDeclaration */) { + variableDeclarationNode = variableDeclarationNode.parent; } - // If it is initialized with a function expression, handle it when we reach the function expression node - var varDecl = node; - if (varDecl.initializer && (varDecl.initializer.kind === 179 /* FunctionExpression */ || - varDecl.initializer.kind === 180 /* ArrowFunction */ || - varDecl.initializer.kind === 192 /* ClassExpression */)) { - return undefined; - } - // Fall through - case 220 /* FunctionDeclaration */: - case 221 /* ClassDeclaration */: - case 148 /* Constructor */: - case 149 /* GetAccessor */: - case 150 /* SetAccessor */: - // "export default function().." looks just like a regular function/class declaration, except with the 'default' flag - var name_37 = node.flags && (node.flags & 512 /* Default */) && !node.name ? "default" : - node.kind === 148 /* Constructor */ ? "constructor" : - ts.declarationNameToString(node.name); - return getNavBarItem(name_37, getScriptKindForElementKind(node.kind), [getNodeSpan(node)]); - case 179 /* FunctionExpression */: - case 180 /* ArrowFunction */: - case 192 /* ClassExpression */: - return getDefineModuleItem(node) || getFunctionOrClassExpressionItem(node); - case 147 /* MethodDeclaration */: - var methodDecl = node; - return getNavBarItem(ts.declarationNameToString(methodDecl.name), ts.ScriptElementKind.memberFunctionElement, [getNodeSpan(node)]); - case 235 /* ExportAssignment */: - // e.g. "export default " - return getNavBarItem("default", ts.ScriptElementKind.variableElement, [getNodeSpan(node)]); - case 231 /* ImportClause */: - if (!node.name) { - // No default import (this node is still a parent of named & namespace imports, which are handled below) - return undefined; - } - // fall through - case 234 /* ImportSpecifier */: // e.g. 'id' in: import {id} from 'mod' (in NamedImports, in ImportClause) - case 232 /* NamespaceImport */: // e.g. '* as ns' in: import * as ns from 'mod' (in ImportClause) - case 238 /* ExportSpecifier */: - // Export specifiers are only interesting if they are reexports from another module, or renamed, else they are already globals - if (node.kind === 238 /* ExportSpecifier */) { - if (!node.parent.parent.moduleSpecifier && !node.propertyName) { - return undefined; - } - } - var decl = node; - if (!decl.name) { - return undefined; - } - var declName = ts.declarationNameToString(decl.name); - return getNavBarItem(declName, ts.ScriptElementKind.constElement, [getNodeSpan(node)]); - case 279 /* JSDocTypedefTag */: - if (node.name) { - return getNavBarItem(node.name.text, ts.ScriptElementKind.typeElement, [getNodeSpan(node)]); - } - else { - var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 200 /* VariableStatement */) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 69 /* Identifier */) { - return getNavBarItem(nameIdentifier.text, ts.ScriptElementKind.typeElement, [getNodeSpan(node)]); - } - } - } - } - default: - return undefined; - } - } - function getNavBarItem(text, kind, spans, kindModifiers) { - if (kindModifiers === void 0) { kindModifiers = ts.ScriptElementKindModifier.none; } - return { - text: text, kind: kind, kindModifiers: kindModifiers, spans: spans, childItems: [], indent: indent, bolded: false, grayed: false - }; - } - function getDefineModuleItem(node) { - if (node.kind !== 179 /* FunctionExpression */ && node.kind !== 180 /* ArrowFunction */) { - return undefined; - } - // No match if this is not a call expression to an identifier named 'define' - if (node.parent.kind !== 174 /* CallExpression */) { - return undefined; - } - var callExpr = node.parent; - if (callExpr.expression.kind !== 69 /* Identifier */ || callExpr.expression.getText() !== "define") { - return undefined; - } - // Return a module of either the given text in the first argument, or of the source file path - var defaultName = node.getSourceFile().fileName; - if (callExpr.arguments[0].kind === 9 /* StringLiteral */) { - defaultName = (callExpr.arguments[0]).text; - } - return getNavBarItem(defaultName, ts.ScriptElementKind.moduleElement, [getNodeSpan(node.parent)]); - } - function getFunctionOrClassExpressionItem(node) { - if (node.kind !== 179 /* FunctionExpression */ && - node.kind !== 180 /* ArrowFunction */ && - node.kind !== 192 /* ClassExpression */) { - return undefined; - } - var fnExpr = node; - var fnName; - if (fnExpr.name && ts.getFullWidth(fnExpr.name) > 0) { - // The expression has an identifier, so use that as the name - fnName = ts.declarationNameToString(fnExpr.name); - } - else { - // See if it is a var initializer. If so, use the var name. - if (fnExpr.parent.kind === 218 /* VariableDeclaration */) { - fnName = ts.declarationNameToString(fnExpr.parent.name); - } - else if (fnExpr.parent.kind === 187 /* BinaryExpression */ && - fnExpr.parent.operatorToken.kind === 56 /* EqualsToken */) { - fnName = fnExpr.parent.left.getText(); - } - else if (fnExpr.parent.kind === 253 /* PropertyAssignment */ && - fnExpr.parent.name) { - fnName = fnExpr.parent.name.getText(); + ts.Debug.assert(!!variableDeclarationNode); } else { - fnName = node.kind === 192 /* ClassExpression */ ? anonClassText : anonFnText; + ts.Debug.assert(!ts.isBindingPattern(node.name)); + variableDeclarationNode = node; + name_38 = node.name; } - } - var scriptKind = node.kind === 192 /* ClassExpression */ ? ts.ScriptElementKind.classElement : ts.ScriptElementKind.functionElement; - return getNavBarItem(fnName, scriptKind, [getNodeSpan(node)]); - } - function getNodeSpan(node) { - return node.kind === 256 /* SourceFile */ - ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) - : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); - } - function getScriptKindForElementKind(kind) { - switch (kind) { - case 218 /* VariableDeclaration */: + if (ts.isConst(variableDeclarationNode)) { + return ts.ScriptElementKind.constElement; + } + else if (ts.isLet(variableDeclarationNode)) { + return ts.ScriptElementKind.letElement; + } + else { return ts.ScriptElementKind.variableElement; - case 220 /* FunctionDeclaration */: - return ts.ScriptElementKind.functionElement; - case 221 /* ClassDeclaration */: - return ts.ScriptElementKind.classElement; - case 148 /* Constructor */: - return ts.ScriptElementKind.constructorImplementationElement; - case 149 /* GetAccessor */: - return ts.ScriptElementKind.memberGetAccessorElement; - case 150 /* SetAccessor */: - return ts.ScriptElementKind.memberSetAccessorElement; - default: - return "unknown"; - } + } + case 180 /* ArrowFunction */: + return ts.ScriptElementKind.functionElement; + case 279 /* JSDocTypedefTag */: + return ts.ScriptElementKind.typeElement; + default: + return ts.getNodeKind(node); } - return sourceFileItem.childItems; } - NavigationBar.getJsNavigationBarItems = getJsNavigationBarItems; + function getModuleName(moduleDeclaration) { + // We want to maintain quotation marks. + if (ts.isAmbientModule(moduleDeclaration)) { + return ts.getTextOfNode(moduleDeclaration.name); + } + // Otherwise, we need to aggregate each identifier to build up the qualified name. + var result = []; + result.push(moduleDeclaration.name.text); + while (moduleDeclaration.body && moduleDeclaration.body.kind === 225 /* ModuleDeclaration */) { + moduleDeclaration = moduleDeclaration.body; + result.push(moduleDeclaration.name.text); + } + return result.join("."); + } + /** + * For 'module A.B.C', we want to get the node for 'C'. + * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. + */ + function getInteriorModule(decl) { + return decl.body.kind === 225 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; + } + function isComputedProperty(member) { + return !member.name || member.name.kind === 140 /* ComputedPropertyName */; + } + function getNodeSpan(node) { + return node.kind === 256 /* SourceFile */ + ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) + : ts.createTextSpanFromBounds(node.getStart(curSourceFile), node.getEnd()); + } + function getFunctionOrClassName(node) { + if (node.name && ts.getFullWidth(node.name) > 0) { + return ts.declarationNameToString(node.name); + } + else if (node.parent.kind === 218 /* VariableDeclaration */) { + return ts.declarationNameToString(node.parent.name); + } + else if (node.parent.kind === 187 /* BinaryExpression */ && + node.parent.operatorToken.kind === 56 /* EqualsToken */) { + return nodeText(node.parent.left); + } + else if (node.parent.kind === 253 /* PropertyAssignment */ && node.parent.name) { + return nodeText(node.parent.name); + } + else if (node.flags & 512 /* Default */) { + return "default"; + } + else { + return ts.isClassLike(node) ? "" : ""; + } + } + function isFunctionOrClassExpression(node) { + return node.kind === 179 /* FunctionExpression */ || node.kind === 180 /* ArrowFunction */ || node.kind === 192 /* ClassExpression */; + } })(NavigationBar = ts.NavigationBar || (ts.NavigationBar = {})); })(ts || (ts = {})); /* @internal */ @@ -47848,9 +48643,9 @@ var ts; } getTypingNamesFromSourceFileNames(fileNames); // Add the cached typing locations for inferred typings that are already installed - for (var name_38 in packageNameToTypingLocation) { - if (ts.hasProperty(inferredTypings, name_38) && !inferredTypings[name_38]) { - inferredTypings[name_38] = packageNameToTypingLocation[name_38]; + for (var name_39 in packageNameToTypingLocation) { + if (ts.hasProperty(inferredTypings, name_39) && !inferredTypings[name_39]) { + inferredTypings[name_39] = packageNameToTypingLocation[name_39]; } } // Remove typings that the user has added to the exclude list @@ -47936,9 +48731,9 @@ var ts; return; } var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, "*.json", /*exclude*/ undefined, /*depth*/ 2); - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; + var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); if (ts.getBaseFileName(normalizedFileName) !== "package.json") { continue; @@ -48679,9 +49474,9 @@ var ts; } Rules.prototype.getRuleName = function (rule) { var o = this; - for (var name_39 in o) { - if (o[name_39] === rule) { - return name_39; + for (var name_40 in o) { + if (o[name_40] === rule) { + return name_40; } } throw new Error("Unknown rule"); @@ -50686,6 +51481,7 @@ var ts; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); /// +/// /// /// /// @@ -50825,8 +51621,8 @@ var ts; var list = createNode(282 /* SyntaxList */, nodes.pos, nodes.end, 0, this); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { - var node = nodes_7[_i]; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; if (pos < node.pos) { pos = this.addSyntheticNodes(list._children, pos, node.pos); } @@ -50961,7 +51757,7 @@ var ts; addCommentParts(declaration.parent, sourceFileOfDeclaration, getCleanedParamJsDocComment); } // If this is left side of dotted module declaration, there is no doc comments associated with this node - if (declaration.kind === 225 /* ModuleDeclaration */ && declaration.body.kind === 225 /* ModuleDeclaration */) { + if (declaration.kind === 225 /* ModuleDeclaration */ && declaration.body && declaration.body.kind === 225 /* ModuleDeclaration */) { return; } if ((declaration.kind === 179 /* FunctionExpression */ || declaration.kind === 180 /* ArrowFunction */) && @@ -51797,11 +52593,11 @@ var ts; sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - var commandLineOptions_stringToEnum; + var commandLineOptionsStringToEnum; /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */ function fixupCompilerOptions(options, diagnostics) { // Lazily create this value to fix module loading errors. - commandLineOptions_stringToEnum = commandLineOptions_stringToEnum || ts.filter(ts.optionDeclarations, function (o) { + commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachValue(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); @@ -51822,8 +52618,8 @@ var ts; } } }; - for (var _i = 0, commandLineOptions_stringToEnum_1 = commandLineOptions_stringToEnum; _i < commandLineOptions_stringToEnum_1.length; _i++) { - var opt = commandLineOptions_stringToEnum_1[_i]; + for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { + var opt = commandLineOptionsStringToEnum_1[_i]; _loop_2(opt); } return options; @@ -51848,6 +52644,17 @@ var ts; // We are not returning a sourceFile for lib file when asked by the program, // so pass --noLib to avoid reporting a file not found error. options.noLib = true; + // Clear out other settings that would not be used in transpiling this module + options.lib = undefined; + options.types = undefined; + options.noEmit = undefined; + options.noEmitOnError = undefined; + options.paths = undefined; + options.rootDirs = undefined; + options.declaration = undefined; + options.declarationDir = undefined; + options.out = undefined; + options.outFile = undefined; // We are not doing a full typecheck, we are not resolving the whole context, // so pass --noResolve to avoid reporting missing file errors. options.noResolve = true; @@ -51882,7 +52689,8 @@ var ts; getNewLine: function () { return newLine; }, fileExists: function (fileName) { return fileName === inputFileName; }, readFile: function (fileName) { return ""; }, - directoryExists: function (directoryExists) { return true; } + directoryExists: function (directoryExists) { return true; }, + getDirectories: function (path) { return []; } }; var program = ts.createProgram([inputFileName], options, compilerHost); if (transpileOptions.reportDiagnostics) { @@ -51970,7 +52778,7 @@ var ts; var buckets = {}; var getCanonicalFileName = ts.createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyForCompilationSettings(settings) { - return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + settings.typesRoot + "|" + settings.typesSearchPaths + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); + return ("_" + settings.target + "|" + settings.module + "|" + settings.noResolve + "|" + settings.jsx + "|" + settings.allowJs + "|" + settings.baseUrl + "|" + JSON.stringify(settings.typeRoots) + "|" + JSON.stringify(settings.rootDirs) + "|" + JSON.stringify(settings.paths)); } function getBucketForCompilationSettings(key, createIfMissing) { var bucket = ts.lookUp(buckets, key); @@ -52716,7 +53524,8 @@ var ts; oldSettings.moduleResolution !== newSettings.moduleResolution || oldSettings.noResolve !== newSettings.noResolve || oldSettings.jsx !== newSettings.jsx || - oldSettings.allowJs !== newSettings.allowJs); + oldSettings.allowJs !== newSettings.allowJs || + oldSettings.disableSizeLimit !== oldSettings.disableSizeLimit); // Now create a new compiler var compilerHost = { getSourceFile: getOrCreateSourceFile, @@ -52739,8 +53548,10 @@ var ts; return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); }, directoryExists: function (directoryName) { - ts.Debug.assert(!host.resolveModuleNames || !host.resolveTypeReferenceDirectives); return ts.directoryProbablyExists(directoryName, host); + }, + getDirectories: function (path) { + return host.getDirectories ? host.getDirectories(path) : []; } }; if (host.trace) { @@ -53588,8 +54399,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_40 = element.propertyName || element.name; - existingImportsOrExports[name_40.text] = true; + var name_41 = element.propertyName || element.name; + existingImportsOrExports[name_41.text] = true; } if (ts.isEmpty(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); @@ -53709,14 +54520,14 @@ var ts; var entries = []; var target = program.getCompilerOptions().target; var nameTable = getNameTable(sourceFile); - for (var name_41 in nameTable) { + for (var name_42 in nameTable) { // Skip identifiers produced only from the current location - if (nameTable[name_41] === position) { + if (nameTable[name_42] === position) { continue; } - if (!uniqueNames[name_41]) { - uniqueNames[name_41] = name_41; - var displayName = getCompletionEntryDisplayName(name_41, target, /*performCharacterChecks*/ true); + if (!uniqueNames[name_42]) { + uniqueNames[name_42] = name_42; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_42), target, /*performCharacterChecks*/ true); if (displayName) { var entry = { name: displayName, @@ -53833,10 +54644,10 @@ var ts; var typeChecker = program.getTypeChecker(); var type = typeChecker.getContextualType(node); if (type) { - var entries_1 = []; - addStringLiteralCompletionsFromType(type, entries_1); - if (entries_1.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_1 }; + var entries_2 = []; + addStringLiteralCompletionsFromType(type, entries_2); + if (entries_2.length) { + return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -55136,7 +55947,8 @@ var ts; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference + isWriteAccess: highlightSpan.kind === HighlightSpanKind.writtenReference, + isDefinition: false }); } } @@ -55486,7 +56298,8 @@ var ts; references: [{ fileName: sourceFile.fileName, textSpan: ts.createTextSpan(position, searchText.length), - isWriteAccess: false + isWriteAccess: false, + isDefinition: false }] }); } @@ -55964,7 +56777,8 @@ var ts; return { fileName: node.getSourceFile().fileName, textSpan: ts.createTextSpanFromBounds(start, end), - isWriteAccess: isWriteAccess(node) + isWriteAccess: isWriteAccess(node), + isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node) }; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ @@ -56206,7 +57020,7 @@ var ts; } function getNavigationBarItems(fileName) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile, host.getCompilationSettings()); + return ts.NavigationBar.getNavigationBarItems(sourceFile); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); @@ -56639,7 +57453,8 @@ var ts; return; case 142 /* Parameter */: if (token.parent.name === token) { - return 17 /* parameterName */; + var isThis = token.kind === 69 /* Identifier */ && token.originalKeywordKind === 97 /* ThisKeyword */; + return isThis ? 3 /* keyword */ : 17 /* parameterName */; } return; } @@ -58437,6 +59252,7 @@ var ts; function CoreServicesShimHostAdapter(shimHost) { var _this = this; this.shimHost = shimHost; + this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; if ("directoryExists" in this.shimHost) { this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; } @@ -58444,17 +59260,26 @@ var ts; this.realpath = function (path) { return _this.shimHost.realpath(path); }; } } - CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extension, exclude, depth) { + CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { // Wrap the API changes for 2.0 release. This try/catch // should be removed once TypeScript 2.0 has shipped. - var encoded; try { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude), depth); + var pattern = ts.getFileMatcherPatterns(rootDir, extensions, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); } catch (e) { - encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude)); + var results = []; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + for (var _a = 0, _b = this.readDirectoryFallback(rootDir, extension, exclude); _a < _b.length; _a++) { + var file = _b[_a]; + if (!ts.contains(results, file)) { + results.push(file); + } + } + } + return results; } - return JSON.parse(encoded); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { return this.shimHost.fileExists(fileName); @@ -58462,6 +59287,9 @@ var ts; CoreServicesShimHostAdapter.prototype.readFile = function (fileName) { return this.shimHost.readFile(fileName); }; + CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { + return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); + }; return CoreServicesShimHostAdapter; }()); ts.CoreServicesShimHostAdapter = CoreServicesShimHostAdapter; @@ -58987,4 +59815,4 @@ var TypeScript; // TODO: it should be moved into a namespace though. /* @internal */ var toolsVersion = "1.9"; -/* tslint:enable:no-unused-variable */ +/* tslint:enable:no-unused-variable */ diff --git a/package.json b/package.json index bb476070286..ee6ed62964c 100644 --- a/package.json +++ b/package.json @@ -29,15 +29,48 @@ "node": ">=0.8.0" }, "devDependencies": { - "jake": "latest", - "mocha": "latest", - "chai": "latest", + "@types/browserify": "latest", + "@types/del": "latest", + "@types/glob": "latest", + "@types/gulp": "latest", + "@types/gulp-concat": "latest", + "@types/gulp-help": "latest", + "@types/gulp-newer": "latest", + "@types/gulp-sourcemaps": "latest", + "@types/gulp-typescript": "latest", + "@types/merge2": "latest", + "@types/minimatch": "latest", + "@types/minimist": "latest", + "@types/mkdirp": "latest", + "@types/node": "latest", + "@types/q": "latest", + "@types/run-sequence": "latest", + "@types/through2": "latest", "browserify": "latest", + "chai": "latest", + "del": "latest", + "gulp": "latest", + "gulp-clone": "latest", + "gulp-concat": "latest", + "gulp-help": "latest", + "gulp-insert": "latest", + "gulp-newer": "latest", + "gulp-sourcemaps": "latest", + "gulp-typescript": "latest", + "into-stream": "latest", "istanbul": "latest", + "jake": "latest", + "merge2": "latest", + "minimist": "latest", + "mkdirp": "latest", + "mocha": "latest", "mocha-fivemat-progress-reporter": "latest", + "run-sequence": "latest", + "through2": "latest", + "ts-node": "latest", + "tsd": "latest", "tslint": "next", - "typescript": "next", - "tsd": "latest" + "typescript": "next" }, "scripts": { "pretest": "jake tests", @@ -47,6 +80,7 @@ "build:tests": "jake tests", "start": "node lib/tsc", "clean": "jake clean", + "gulp": "gulp", "jake": "jake", "lint": "jake lint", "setup-hooks": "node scripts/link-hooks.js" diff --git a/scripts/mocha-parallel.js b/scripts/mocha-parallel.js index bf33f68f204..ce40c832b21 100644 --- a/scripts/mocha-parallel.js +++ b/scripts/mocha-parallel.js @@ -245,6 +245,13 @@ function runTests(taskConfigsFolder, run, options, cb) { } } +var nodeModulesPathPrefix = path.resolve("./node_modules/.bin/") + path.delimiter; +if (process.env.path !== undefined) { + process.env.path = nodeModulesPathPrefix + process.env.path; +} else if (process.env.PATH !== undefined) { + process.env.PATH = nodeModulesPathPrefix + process.env.PATH; +} + function spawnProcess(cmd, options) { var shell = process.platform === "win32" ? "cmd" : "/bin/sh"; var prefix = process.platform === "win32" ? "/c" : "-c"; diff --git a/scripts/tslint/objectLiteralSurroundingSpaceRule.ts b/scripts/tslint/objectLiteralSurroundingSpaceRule.ts new file mode 100644 index 00000000000..b527746bf51 --- /dev/null +++ b/scripts/tslint/objectLiteralSurroundingSpaceRule.ts @@ -0,0 +1,42 @@ +import * as Lint from "tslint/lib/lint"; +import * as ts from "typescript"; + + +export class Rule extends Lint.Rules.AbstractRule { + public static LEADING_FAILURE_STRING = "No leading whitespace found on single-line object literal."; + public static TRAILING_FAILURE_STRING = "No trailing whitespace found on single-line object literal."; + public static LEADING_EXCESS_FAILURE_STRING = "Excess leading whitespace found on single-line object literal."; + public static TRAILING_EXCESS_FAILURE_STRING = "Excess trailing whitespace found on single-line object literal."; + + public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { + return this.applyWithWalker(new ObjectLiteralSpaceWalker(sourceFile, this.getOptions())); + } +} + +class ObjectLiteralSpaceWalker extends Lint.RuleWalker { + public visitNode(node: ts.Node) { + if (node.kind === ts.SyntaxKind.ObjectLiteralExpression) { + const literal = node as ts.ObjectLiteralExpression; + const text = literal.getText(); + if (text.match(/^{[^\n]+}$/g)) { + if (text.charAt(1) !== " ") { + const failure = this.createFailure(node.pos, node.getWidth(), Rule.LEADING_FAILURE_STRING); + this.addFailure(failure); + } + if (text.charAt(2) === " ") { + const failure = this.createFailure(node.pos + 2, 1, Rule.LEADING_EXCESS_FAILURE_STRING); + this.addFailure(failure); + } + if (text.charAt(text.length - 2) !== " ") { + const failure = this.createFailure(node.pos, node.getWidth(), Rule.TRAILING_FAILURE_STRING); + this.addFailure(failure); + } + if (text.charAt(text.length - 3) === " ") { + const failure = this.createFailure(node.pos + node.getWidth() - 3, 1, Rule.TRAILING_EXCESS_FAILURE_STRING); + this.addFailure(failure); + } + } + } + super.visitNode(node); + } +} diff --git a/scripts/types/ambient.d.ts b/scripts/types/ambient.d.ts new file mode 100644 index 00000000000..8a86a290bee --- /dev/null +++ b/scripts/types/ambient.d.ts @@ -0,0 +1,22 @@ +declare module "gulp-clone" { + function Clone(): NodeJS.ReadWriteStream; + namespace Clone { + export function sink() : NodeJS.ReadWriteStream & {tap: () => NodeJS.ReadWriteStream}; + } + export = Clone; +} + +declare module "gulp-insert" { + export function append(text: string | Buffer): NodeJS.ReadWriteStream; + export function prepend(text: string | Buffer): NodeJS.ReadWriteStream; + export function wrap(text: string | Buffer, tail: string | Buffer): NodeJS.ReadWriteStream; + export function transform(cb: (contents: string, file: {path: string}) => string): NodeJS.ReadWriteStream; // file is a vinyl file +} + +declare module "into-stream" { + function IntoStream(content: string | Buffer | (string | Buffer)[]): NodeJS.ReadableStream; + namespace IntoStream { + export function obj(content: any): NodeJS.ReadableStream + } + export = IntoStream; +} \ No newline at end of file diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ac8a47a9913..06591a7ab3d 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1125,7 +1125,7 @@ namespace ts { return getExternalModuleMember(node.parent.parent.parent, node); } - function getTargetOfGlobalModuleExportDeclaration(node: NamespaceExportDeclaration): Symbol { + function getTargetOfNamespaceExportDeclaration(node: NamespaceExportDeclaration): Symbol { return resolveExternalModuleSymbol(node.parent.symbol); } @@ -1154,7 +1154,7 @@ namespace ts { case SyntaxKind.ExportAssignment: return getTargetOfExportAssignment(node); case SyntaxKind.NamespaceExportDeclaration: - return getTargetOfGlobalModuleExportDeclaration(node); + return getTargetOfNamespaceExportDeclaration(node); } } @@ -1265,9 +1265,13 @@ namespace ts { const right = name.kind === SyntaxKind.QualifiedName ? (name).right : (name).name; const namespace = resolveEntityName(left, SymbolFlags.Namespace, ignoreErrors); - if (!namespace || namespace === unknownSymbol || nodeIsMissing(right)) { + if (!namespace || nodeIsMissing(right)) { return undefined; } + else if (namespace === unknownSymbol) { + return namespace; + } + symbol = getSymbol(getExportsOfSymbol(namespace), right.text, meaning); if (!symbol) { if (!ignoreErrors) { @@ -2473,16 +2477,13 @@ namespace ts { } } - function buildDisplayForParametersAndDelimiters(thisType: Type, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { + function buildDisplayForParametersAndDelimiters(thisParameter: Symbol | undefined, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { writePunctuation(writer, SyntaxKind.OpenParenToken); - if (thisType) { - writeKeyword(writer, SyntaxKind.ThisKeyword); - writePunctuation(writer, SyntaxKind.ColonToken); - writeSpace(writer); - buildTypeDisplay(thisType, writer, enclosingDeclaration, flags, symbolStack); + if (thisParameter) { + buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); } for (let i = 0; i < parameters.length; i++) { - if (i > 0 || thisType) { + if (i > 0 || thisParameter) { writePunctuation(writer, SyntaxKind.CommaToken); writeSpace(writer); } @@ -2538,7 +2539,7 @@ namespace ts { buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); } - buildDisplayForParametersAndDelimiters(signature.thisType, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); + buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); } @@ -2794,6 +2795,10 @@ namespace ts { return type && (type.flags & TypeFlags.Any) !== 0; } + function isTypeNever(type: Type) { + return type && (type.flags & TypeFlags.Never) !== 0; + } + // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been // assigned by contextual typing. function getTypeForBindingElementParent(node: VariableLikeDeclaration) { @@ -2977,12 +2982,14 @@ namespace ts { if (func.kind === SyntaxKind.SetAccessor && !hasDynamicName(func)) { const getter = getDeclarationOfKind(declaration.parent.symbol, SyntaxKind.GetAccessor); if (getter) { - const signature = getSignatureFromDeclaration(getter); + const getterSignature = getSignatureFromDeclaration(getter); const thisParameter = getAccessorThisParameter(func as AccessorDeclaration); if (thisParameter && declaration === thisParameter) { - return signature.thisType; + // Use the type from the *getter* + Debug.assert(!thisParameter.type); + return getTypeOfSymbol(getterSignature.thisParameter); } - return getReturnTypeOfSignature(signature); + return getReturnTypeOfSignature(getterSignature); } } // Use contextual parameter type if one is available @@ -3147,23 +3154,29 @@ namespace ts { if (declaration.kind === SyntaxKind.ExportAssignment) { return links.type = checkExpression((declaration).expression); } - // Handle module.exports = expr - if (declaration.kind === SyntaxKind.BinaryExpression) { - return links.type = getUnionType(map(symbol.declarations, (decl: BinaryExpression) => checkExpressionCached(decl.right))); - } - if (declaration.kind === SyntaxKind.PropertyAccessExpression) { - // Declarations only exist for property access expressions for certain - // special assignment kinds - if (declaration.parent.kind === SyntaxKind.BinaryExpression) { - // Handle exports.p = expr or this.p = expr or className.prototype.method = expr - return links.type = checkExpressionCached((declaration.parent).right); - } - } // Handle variable, parameter or property if (!pushTypeResolution(symbol, TypeSystemPropertyName.Type)) { return unknownType; } - let type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); + + let type: Type = undefined; + // Handle module.exports = expr or this.p = expr + if (declaration.kind === SyntaxKind.BinaryExpression) { + type = getUnionType(map(symbol.declarations, (decl: BinaryExpression) => checkExpressionCached(decl.right))); + } + else if (declaration.kind === SyntaxKind.PropertyAccessExpression) { + // Declarations only exist for property access expressions for certain + // special assignment kinds + if (declaration.parent.kind === SyntaxKind.BinaryExpression) { + // Handle exports.p = expr or className.prototype.method = expr + type = checkExpressionCached((declaration.parent).right); + } + } + + if (type === undefined) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); + } + if (!popTypeResolution()) { if ((symbol.valueDeclaration).type) { // Variable has type annotation that circularly references the variable itself @@ -3198,14 +3211,13 @@ namespace ts { return undefined; } - function getAnnotatedAccessorThisType(accessor: AccessorDeclaration): Type { - if (accessor) { - const parameter = getAccessorThisParameter(accessor); - if (parameter && parameter.type) { - return getTypeFromTypeNode(accessor.parameters[0].type); - } - } - return undefined; + function getAnnotatedAccessorThisParameter(accessor: AccessorDeclaration): Symbol | undefined { + const parameter = getAccessorThisParameter(accessor); + return parameter && parameter.symbol; + } + + function getThisTypeOfDeclaration(declaration: SignatureDeclaration): Type | undefined { + return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); } function getTypeOfAccessors(symbol: Symbol): Type { @@ -3888,13 +3900,13 @@ namespace ts { resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } - function createSignature(declaration: SignatureDeclaration, typeParameters: TypeParameter[], thisType: Type, parameters: Symbol[], + function createSignature(declaration: SignatureDeclaration, typeParameters: TypeParameter[], thisParameter: Symbol | undefined, parameters: Symbol[], resolvedReturnType: Type, typePredicate: TypePredicate, minArgumentCount: number, hasRestParameter: boolean, hasStringLiterals: boolean): Signature { const sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; - sig.thisType = thisType; + sig.thisParameter = thisParameter; sig.resolvedReturnType = resolvedReturnType; sig.typePredicate = typePredicate; sig.minArgumentCount = minArgumentCount; @@ -3904,7 +3916,7 @@ namespace ts { } function cloneSignature(sig: Signature): Signature { - return createSignature(sig.declaration, sig.typeParameters, sig.thisType, sig.parameters, sig.resolvedReturnType, + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasStringLiterals); } @@ -4002,8 +4014,9 @@ namespace ts { // Union the result types when more than one signature matches if (unionSignatures.length > 1) { s = cloneSignature(signature); - if (forEach(unionSignatures, sig => sig.thisType)) { - s.thisType = getUnionType(map(unionSignatures, sig => sig.thisType || anyType)); + if (forEach(unionSignatures, sig => sig.thisParameter)) { + const thisType = getUnionType(map(unionSignatures, sig => getTypeOfSymbol(sig.thisParameter) || anyType)); + s.thisParameter = createTransientSymbol(signature.thisParameter, thisType); } // Clear resolved return type we possibly got from cloneSignature s.resolvedReturnType = undefined; @@ -4224,6 +4237,7 @@ namespace ts { let props: Symbol[]; // Flags we want to propagate to the result if they exist in all source symbols let commonFlags = (containingType.flags & TypeFlags.Intersection) ? SymbolFlags.Optional : SymbolFlags.None; + let isReadonly = false; for (const current of types) { const type = getApparentType(current); if (type !== unknownType) { @@ -4236,6 +4250,9 @@ namespace ts { else if (!contains(props, prop)) { props.push(prop); } + if (isReadonlySymbol(prop)) { + isReadonly = true; + } } else if (containingType.flags & TypeFlags.Union) { // A union type requires the property to be present in all constituent types @@ -4265,6 +4282,7 @@ namespace ts { name); result.containingType = containingType; result.declarations = declarations; + result.isReadonly = isReadonly; result.type = containingType.flags & TypeFlags.Union ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } @@ -4397,7 +4415,7 @@ namespace ts { return result; } - function isOptionalParameter(node: ParameterDeclaration) { + function isJSDocOptionalParameter(node: ParameterDeclaration) { if (node.flags & NodeFlags.JavaScriptFile) { if (node.type && node.type.kind === SyntaxKind.JSDocOptionalType) { return true; @@ -4414,8 +4432,10 @@ namespace ts { } } } + } - if (hasQuestionToken(node)) { + function isOptionalParameter(node: ParameterDeclaration) { + if (hasQuestionToken(node) || isJSDocOptionalParameter(node)) { return true; } @@ -4454,7 +4474,7 @@ namespace ts { const parameters: Symbol[] = []; let hasStringLiterals = false; let minArgumentCount = -1; - let thisType: Type = undefined; + let thisParameter: Symbol = undefined; let hasThisParameter: boolean; const isJSConstructSignature = isJSDocConstructSignature(declaration); @@ -4472,7 +4492,7 @@ namespace ts { } if (i === 0 && paramSymbol.name === "this") { hasThisParameter = true; - thisType = param.type ? getTypeFromTypeNode(param.type) : unknownType; + thisParameter = param.symbol; } else { parameters.push(paramSymbol); @@ -4482,7 +4502,7 @@ namespace ts { hasStringLiterals = true; } - if (param.initializer || param.questionToken || param.dotDotDotToken) { + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { if (minArgumentCount < 0) { minArgumentCount = i - (hasThisParameter ? 1 : 0); } @@ -4496,10 +4516,12 @@ namespace ts { // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation if ((declaration.kind === SyntaxKind.GetAccessor || declaration.kind === SyntaxKind.SetAccessor) && !hasDynamicName(declaration) && - (!hasThisParameter || thisType === unknownType)) { + (!hasThisParameter || !thisParameter)) { const otherKind = declaration.kind === SyntaxKind.GetAccessor ? SyntaxKind.SetAccessor : SyntaxKind.GetAccessor; - const setter = getDeclarationOfKind(declaration.symbol, otherKind); - thisType = getAnnotatedAccessorThisType(setter); + const other = getDeclarationOfKind(declaration.symbol, otherKind); + if (other) { + thisParameter = getAnnotatedAccessorThisParameter(other); + } } if (minArgumentCount < 0) { @@ -4520,7 +4542,7 @@ namespace ts { createTypePredicateFromTypePredicateNode(declaration.type as TypePredicateNode) : undefined; - links.resolvedSignature = createSignature(declaration, typeParameters, thisType, parameters, returnType, typePredicate, minArgumentCount, hasRestParameter(declaration), hasStringLiterals); + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, hasRestParameter(declaration), hasStringLiterals); } return links.resolvedSignature; } @@ -4602,6 +4624,12 @@ namespace ts { return anyType; } + function getThisTypeOfSignature(signature: Signature): Type | undefined { + if (signature.thisParameter) { + return getTypeOfSymbol(signature.thisParameter); + } + } + function getReturnTypeOfSignature(signature: Signature): Type { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, TypeSystemPropertyName.ResolvedReturnType)) { @@ -5453,7 +5481,7 @@ namespace ts { freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); } const result = createSignature(signature.declaration, freshTypeParameters, - signature.thisType && instantiateType(signature.thisType, mapper), + signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, @@ -5725,17 +5753,22 @@ namespace ts { target = getErasedSignature(target); let result = Ternary.True; - if (source.thisType && target.thisType && source.thisType !== voidType) { - // void sources are assignable to anything. - const related = compareTypes(source.thisType, target.thisType, /*reportErrors*/ false) - || compareTypes(target.thisType, source.thisType, reportErrors); - if (!related) { - if (reportErrors) { - errorReporter(Diagnostics.The_this_types_of_each_signature_are_incompatible); + + const sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType && sourceThisType !== voidType) { + const targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + // void sources are assignable to anything. + const related = compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false) + || compareTypes(targetThisType, sourceThisType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(Diagnostics.The_this_types_of_each_signature_are_incompatible); + } + return Ternary.False; } - return Ternary.False; + result &= related; } - result &= related; } const sourceMax = getNumNonRestParameters(source); @@ -6750,13 +6783,21 @@ namespace ts { source = getErasedSignature(source); target = getErasedSignature(target); let result = Ternary.True; - if (!ignoreThisTypes && source.thisType && target.thisType) { - const related = compareTypes(source.thisType, target.thisType); - if (!related) { - return Ternary.False; + + if (!ignoreThisTypes) { + const sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + const targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + const related = compareTypes(sourceThisType, targetThisType); + if (!related) { + return Ternary.False; + } + result &= related; + } } - result &= related; } + const targetLen = target.parameters.length; for (let i = 0; i < targetLen; i++) { const s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfParameter(source.parameters[i]); @@ -8278,8 +8319,21 @@ namespace ts { return container === declarationContainer; } + function updateReferencesForInterfaceHeritiageClauseTargets(node: InterfaceDeclaration): void { + const extendedTypeNode = getClassExtendsHeritageClauseElement(node); + if (extendedTypeNode) { + const t = getTypeFromTypeNode(extendedTypeNode); + if (t !== unknownType && t.symbol && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters) && !isInAmbientContext(node)) { + t.symbol.hasReference = true; + } + } + } + function checkIdentifier(node: Identifier): Type { const symbol = getResolvedSymbol(node); + if (symbol && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters) && !isInAmbientContext(node)) { + symbol.hasReference = true; + } // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. // Although in down-level emit of arrow function, we emit it using function expression which means that @@ -8582,9 +8636,10 @@ namespace ts { if (type) { return type; } - const signature = getSignatureFromDeclaration(container); - if (signature.thisType) { - return signature.thisType; + + const thisType = getThisTypeOfDeclaration(container); + if (thisType) { + return thisType; } } if (isClassLike(container.parent)) { @@ -8825,7 +8880,7 @@ namespace ts { if (isContextSensitiveFunctionOrObjectLiteralMethod(func) && func.kind !== SyntaxKind.ArrowFunction) { const contextualSignature = getContextualSignature(func); if (contextualSignature) { - return contextualSignature.thisType; + return getThisTypeOfSignature(contextualSignature); } } @@ -9624,8 +9679,9 @@ namespace ts { /** * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name */ - function isJsxIntrinsicIdentifier(tagName: Identifier | QualifiedName) { - if (tagName.kind === SyntaxKind.QualifiedName) { + function isJsxIntrinsicIdentifier(tagName: JsxTagNameExpression) { + // TODO (yuisu): comment + if (tagName.kind === SyntaxKind.PropertyAccessExpression || tagName.kind === SyntaxKind.ThisKeyword) { return false; } else { @@ -9821,6 +9877,29 @@ namespace ts { })); } + // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type + if (elemType.flags & TypeFlags.String) { + return anyType; + } + else if (elemType.flags & TypeFlags.StringLiteral) { + // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type + const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + if (intrinsicElementsType !== unknownType) { + const stringLiteralTypeName = (elemType).text; + const intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + const indexSignatureType = getIndexTypeOfType(intrinsicElementsType, IndexKind.String); + if (indexSignatureType) { + return indexSignatureType; + } + error(node, Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); + } + // If we need to report an error, we already done so here. So just return any to prevent any more error downstream + return anyType; + } + // Get the element instance type (the result of newing or invoking this tag) const elemInstanceType = getJsxElementInstanceType(node, elemType); @@ -10169,6 +10248,10 @@ namespace ts { return unknownType; } + if ((compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters) && !isInAmbientContext(node)) { + prop.hasReference = true; + } + getNodeLinks(node).resolvedSymbol = prop; if (prop.parent && prop.parent.flags & SymbolFlags.Class) { @@ -10625,10 +10708,11 @@ namespace ts { context.failedTypeParameterIndex = undefined; } - if (signature.thisType) { + const thisType = getThisTypeOfSignature(signature); + if (thisType) { const thisArgumentNode = getThisArgumentOfCall(node); const thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypes(context, thisArgumentType, signature.thisType); + inferTypes(context, thisArgumentType, thisType); } // We perform two passes over the arguments. In the first pass we infer from all arguments, but use @@ -10704,8 +10788,8 @@ namespace ts { } function checkApplicableSignature(node: CallLikeExpression, args: Expression[], signature: Signature, relation: Map, excludeArgument: boolean[], reportErrors: boolean) { - - if (signature.thisType && signature.thisType !== voidType && node.kind !== SyntaxKind.NewExpression) { + const thisType = getThisTypeOfSignature(signature); + if (thisType && thisType !== voidType && node.kind !== SyntaxKind.NewExpression) { // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. @@ -10713,7 +10797,7 @@ namespace ts { const thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; const errorNode = reportErrors ? (thisArgumentNode || node) : undefined; const headMessage = Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; - if (!checkTypeRelatedTo(thisArgumentType, signature.thisType, relation, errorNode, headMessage)) { + if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage)) { return false; } } @@ -11432,7 +11516,7 @@ namespace ts { if (getReturnTypeOfSignature(signature) !== voidType) { error(node, Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); } - if (signature.thisType === voidType) { + if (getThisTypeOfSignature(signature) === voidType) { error(node, Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); } return signature; @@ -11779,6 +11863,16 @@ namespace ts { return emptyObjectType; } + function createPromiseReturnType(func: FunctionLikeDeclaration, promisedType: Type) { + const promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); + return unknownType; + } + + return promiseType; + } + function getReturnTypeFromBody(func: FunctionLikeDeclaration, contextualMapper?: TypeMapper): Type { const contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { @@ -11814,19 +11908,12 @@ namespace ts { else { types = checkAndAggregateReturnExpressionTypes(func, contextualMapper); if (!types) { - return neverType; + // For an async function, the return type will not be never, but rather a Promise for never. + return isAsync ? createPromiseReturnType(func, neverType) : neverType; } if (types.length === 0) { - if (isAsync) { - // For an async function, the return type will not be void, but rather a Promise for void. - const promiseType = createPromiseType(voidType); - if (promiseType === emptyObjectType) { - error(func, Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - return promiseType; - } - return voidType; + // For an async function, the return type will not be void, but rather a Promise for void. + return isAsync ? createPromiseReturnType(func, voidType) : voidType; } } // When yield/return statements are contextually typed we allow the return type to be a union type. @@ -11840,7 +11927,7 @@ namespace ts { else { error(func, Diagnostics.No_best_common_type_exists_among_return_expressions); // Defer to unioning the return types so we get a) downstream errors earlier and b) better Salsa experience - return getUnionType(types); + return isAsync ? createPromiseReturnType(func, getUnionType(types)) : getUnionType(types); } } @@ -11853,21 +11940,10 @@ namespace ts { } const widenedType = getWidenedType(type); - if (isAsync) { - // From within an async function you can return either a non-promise value or a promise. Any - // Promise/A+ compatible implementation will always assimilate any foreign promise, so the - // return type of the body is awaited type of the body, wrapped in a native Promise type. - const promiseType = createPromiseType(widenedType); - if (promiseType === emptyObjectType) { - error(func, Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); - return unknownType; - } - - return promiseType; - } - else { - return widenedType; - } + // From within an async function you can return either a non-promise value or a promise. Any + // Promise/A+ compatible implementation will always assimilate any foreign promise, so the + // return type of the body is awaited type of the body, wrapped in a native Promise type. + return isAsync ? createPromiseReturnType(func, widenedType) : widenedType; } function checkAndAggregateYieldOperandTypes(func: FunctionLikeDeclaration, contextualMapper: TypeMapper): Type[] { @@ -12118,6 +12194,8 @@ namespace ts { } } } + checkUnusedIdentifiers(node); + checkUnusedTypeParameters(node); } } @@ -12135,7 +12213,9 @@ namespace ts { // Variables declared with 'const' // Get accessors without matching set accessors // Enum members - return symbol.flags & SymbolFlags.Property && (getDeclarationFlagsFromSymbol(symbol) & NodeFlags.Readonly) !== 0 || + // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) + return symbol.isReadonly || + symbol.flags & SymbolFlags.Property && (getDeclarationFlagsFromSymbol(symbol) & NodeFlags.Readonly) !== 0 || symbol.flags & SymbolFlags.Variable && (getDeclarationFlagsFromSymbol(symbol) & NodeFlags.Const) !== 0 || symbol.flags & SymbolFlags.Accessor && !(symbol.flags & SymbolFlags.SetAccessor) || (symbol.flags & SymbolFlags.EnumMember) !== 0; @@ -13188,6 +13268,9 @@ namespace ts { checkAsyncFunctionReturnType(node); } } + if (!(node).body) { + checkUnusedTypeParameters(node); + } } } @@ -13340,6 +13423,8 @@ namespace ts { checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); checkSourceElement(node.body); + checkUnusedIdentifiers(node); + checkUnusedTypeParameters(node); const symbol = getSymbolOfNode(node); const firstDeclaration = getDeclarationOfKind(symbol, node.kind); @@ -13478,7 +13563,7 @@ namespace ts { // TypeScript 1.0 spec (April 2014): 4.5 // If both accessors include type annotations, the specified types must be identical. checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, Diagnostics.get_and_set_accessor_must_have_the_same_type); - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorThisType, Diagnostics.get_and_set_accessor_must_have_the_same_this_type); + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, Diagnostics.get_and_set_accessor_must_have_the_same_this_type); } } getTypeOfAccessors(getSymbolOfNode(node)); @@ -13532,13 +13617,18 @@ namespace ts { function checkTypeReferenceNode(node: TypeReferenceNode | ExpressionWithTypeArguments) { checkGrammarTypeArguments(node, node.typeArguments); const type = getTypeFromTypeReference(node); - if (type !== unknownType && node.typeArguments) { - // Do type argument local checks only if referenced type is successfully resolved - forEach(node.typeArguments, checkSourceElement); - if (produceDiagnostics) { - const symbol = getNodeLinks(node).resolvedSymbol; - const typeParameters = symbol.flags & SymbolFlags.TypeAlias ? getSymbolLinks(symbol).typeParameters : (type).target.localTypeParameters; - checkTypeArgumentConstraints(typeParameters, node.typeArguments); + if (type !== unknownType) { + if (type.symbol && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters) && !isInAmbientContext(node)) { + type.symbol.hasReference = true; + } + if (node.typeArguments) { + // Do type argument local checks only if referenced type is successfully resolved + forEach(node.typeArguments, checkSourceElement); + if (produceDiagnostics) { + const symbol = getNodeLinks(node).resolvedSymbol; + const typeParameters = symbol.flags & SymbolFlags.TypeAlias ? getSymbolLinks(symbol).typeParameters : (type).target.localTypeParameters; + checkTypeArgumentConstraints(typeParameters, node.typeArguments); + } } } } @@ -13896,7 +13986,7 @@ namespace ts { function checkNonThenableType(type: Type, location?: Node, message?: DiagnosticMessage) { type = getWidenedType(type); - if (!isTypeAny(type) && isTypeAssignableTo(type, getGlobalThenableType())) { + if (!isTypeAny(type) && !isTypeNever(type) && isTypeAssignableTo(type, getGlobalThenableType())) { if (location) { if (!message) { message = Diagnostics.Operand_for_await_does_not_have_a_valid_callable_then_member; @@ -13927,12 +14017,15 @@ namespace ts { // } // - if (promise.flags & TypeFlags.Any) { + if (isTypeAny(promise)) { return undefined; } - if ((promise.flags & TypeFlags.Reference) && (promise).target === tryGetGlobalPromiseType()) { - return (promise).typeArguments[0]; + if (promise.flags & TypeFlags.Reference) { + if ((promise).target === tryGetGlobalPromiseType() + || (promise).target === getGlobalPromiseLikeType()) { + return (promise).typeArguments[0]; + } } const globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType(); @@ -13941,17 +14034,17 @@ namespace ts { } const thenFunction = getTypeOfPropertyOfType(promise, "then"); - if (thenFunction && (thenFunction.flags & TypeFlags.Any)) { + if (!thenFunction || isTypeAny(thenFunction)) { return undefined; } - const thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, SignatureKind.Call) : emptyArray; + const thenSignatures = getSignaturesOfType(thenFunction, SignatureKind.Call); if (thenSignatures.length === 0) { return undefined; } const onfulfilledParameterType = getTypeWithFacts(getUnionType(map(thenSignatures, getTypeOfFirstParameterOfSignature)), TypeFacts.NEUndefined); - if (onfulfilledParameterType.flags & TypeFlags.Any) { + if (isTypeAny(onfulfilledParameterType)) { return undefined; } @@ -13960,12 +14053,11 @@ namespace ts { return undefined; } - const valueParameterType = getUnionType(map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); - return valueParameterType; + return getUnionType(map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); } function getTypeOfFirstParameterOfSignature(signature: Signature) { - return getTypeAtPosition(signature, 0); + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; } /** @@ -14379,6 +14471,8 @@ namespace ts { } checkSourceElement(node.body); + checkUnusedIdentifiers(node); + checkUnusedTypeParameters(node); if (!node.asteriskToken) { const returnOrPromisedType = node.type && (isAsync ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); @@ -14400,12 +14494,83 @@ namespace ts { } } + function checkUnusedIdentifiers(node: FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction | ForInStatement | Block | CatchClause): void { + if (node.parent.kind !== SyntaxKind.InterfaceDeclaration && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters) && !isInAmbientContext(node)) { + for (const key in node.locals) { + if (hasProperty(node.locals, key)) { + const local = node.locals[key]; + if (!local.hasReference && local.valueDeclaration) { + if (local.valueDeclaration.kind !== SyntaxKind.Parameter && compilerOptions.noUnusedLocals) { + error(local.valueDeclaration.name, Diagnostics._0_is_declared_but_never_used, local.name); + } + else if (local.valueDeclaration.kind === SyntaxKind.Parameter && compilerOptions.noUnusedParameters) { + if (local.valueDeclaration.flags === 0) { + error(local.valueDeclaration.name, Diagnostics._0_is_declared_but_never_used, local.name); + } + } + } + } + } + } + } + + function checkUnusedClassLocals(node: ClassDeclaration): void { + if (compilerOptions.noUnusedLocals && !isInAmbientContext(node)) { + if (node.members) { + for (const member of node.members) { + if (member.kind === SyntaxKind.MethodDeclaration || member.kind === SyntaxKind.PropertyDeclaration) { + if (isPrivateNode(member) && !member.symbol.hasReference) { + error(member.name, Diagnostics._0_is_declared_but_never_used, member.symbol.name); + } + } + else if (member.kind === SyntaxKind.Constructor) { + for (const parameter of (member).parameters) { + if (isPrivateNode(parameter) && !parameter.symbol.hasReference) { + error(parameter.name, Diagnostics._0_is_declared_but_never_used, parameter.symbol.name); + } + } + } + } + } + } + } + + function checkUnusedTypeParameters(node: ClassDeclaration | FunctionDeclaration | MethodDeclaration | FunctionExpression | ArrowFunction | ConstructorDeclaration | SignatureDeclaration | InterfaceDeclaration) { + if (compilerOptions.noUnusedLocals && !isInAmbientContext(node)) { + if (node.typeParameters) { + for (const typeParameter of node.typeParameters) { + if (!typeParameter.symbol.hasReference) { + error(typeParameter.name, Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name); + } + } + } + } + } + + function isPrivateNode(node: Node): boolean { + return (node.flags & NodeFlags.Private) !== 0; + } + + function checkUnusedModuleLocals(node: ModuleDeclaration | SourceFile): void { + if (compilerOptions.noUnusedLocals && !isInAmbientContext(node)) { + for (const key in node.locals) { + if (hasProperty(node.locals, key)) { + const local = node.locals[key]; + if (!local.hasReference && !local.exportSymbol) { + forEach(local.declarations, d => error(d.name, Diagnostics._0_is_declared_but_never_used, local.name)); + } + } + } + } + } + function checkBlock(node: Block) { // Grammar checking for SyntaxKind.Block if (node.kind === SyntaxKind.Block) { checkGrammarStatementInAmbientContext(node); } forEach(node.statements, checkSourceElement); + checkUnusedIdentifiers(node); } function checkCollisionWithArgumentsInGeneratedCode(node: SignatureDeclaration) { @@ -14910,6 +15075,7 @@ namespace ts { } checkSourceElement(node.statement); + checkUnusedIdentifiers(node); } function checkForInStatement(node: ForInStatement) { @@ -14957,6 +15123,7 @@ namespace ts { } checkSourceElement(node.statement); + checkUnusedIdentifiers(node); } function checkForInOrForOfVariableDeclaration(iterationStatement: ForInStatement | ForOfStatement): void { @@ -15396,6 +15563,7 @@ namespace ts { } checkBlock(catchClause.block); + checkUnusedIdentifiers(catchClause); } if (node.finallyBlock) { @@ -15557,6 +15725,8 @@ namespace ts { } checkClassLikeDeclaration(node); forEach(node.members, checkSourceElement); + checkUnusedClassLocals(node); + checkUnusedTypeParameters(node); } function checkClassLikeDeclaration(node: ClassLikeDeclaration) { @@ -15866,6 +16036,8 @@ namespace ts { if (produceDiagnostics) { checkTypeForDuplicateIndexSignatures(node); + updateReferencesForInterfaceHeritiageClauseTargets(node); + checkUnusedTypeParameters(node); } } @@ -16262,6 +16434,7 @@ namespace ts { if (node.body) { checkSourceElement(node.body); + checkUnusedModuleLocals(node); } } @@ -16442,6 +16615,9 @@ namespace ts { if (target.flags & SymbolFlags.Type) { checkTypeNameIsReserved(node.name, Diagnostics.Import_name_cannot_be_0); } + if ((compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters) && !isInAmbientContext(node)) { + target.hasReference = true; + } } } else { @@ -16784,6 +16960,9 @@ namespace ts { deferredNodes = []; forEach(node.statements, checkSourceElement); + if (isExternalModule(node)) { + checkUnusedModuleLocals(node); + } checkDeferredNodes(); deferredNodes = undefined; @@ -17156,6 +17335,15 @@ namespace ts { return getSymbolOfEntityNameOrPropertyAccessExpression(node); case SyntaxKind.ThisKeyword: + const container = getThisContainer(node, /*includeArrowFunctions*/ false); + if (isFunctionLike(container)) { + const sig = getSignatureFromDeclaration(container); + if (sig.thisParameter) { + return sig.thisParameter; + } + } + // fallthrough + case SyntaxKind.SuperKeyword: const type = isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; @@ -17426,7 +17614,10 @@ namespace ts { const parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { if (parentSymbol.flags & SymbolFlags.ValueModule && parentSymbol.valueDeclaration.kind === SyntaxKind.SourceFile) { - return parentSymbol.valueDeclaration; + // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. + if (parentSymbol.valueDeclaration === getSourceFileOfNode(node)) { + return parentSymbol.valueDeclaration; + } } for (let n = node.parent; n; n = n.parent) { if ((n.kind === SyntaxKind.ModuleDeclaration || n.kind === SyntaxKind.EnumDeclaration) && getSymbolOfNode(n) === parentSymbol) { @@ -18204,7 +18395,10 @@ namespace ts { return grammarErrorOnNode(lastDeclare, Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } else if (node.kind === SyntaxKind.Parameter && (flags & NodeFlags.ParameterPropertyModifier) && isBindingPattern((node).name)) { - return grammarErrorOnNode(node, Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); + return grammarErrorOnNode(node, Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === SyntaxKind.Parameter && (flags & NodeFlags.ParameterPropertyModifier) && (node).dotDotDotToken) { + return grammarErrorOnNode(node, Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & NodeFlags.Async) { return checkGrammarAsyncModifier(node, lastAsync); @@ -18685,7 +18879,7 @@ namespace ts { return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === SyntaxKind.GetAccessor ? 0 : 1); } - function getAccessorThisParameter(accessor: AccessorDeclaration) { + function getAccessorThisParameter(accessor: AccessorDeclaration): ParameterDeclaration { if (accessor.parameters.length === (accessor.kind === SyntaxKind.GetAccessor ? 1 : 2) && accessor.parameters[0].name.kind === SyntaxKind.Identifier && (accessor.parameters[0].name).originalKeywordKind === SyntaxKind.ThisKeyword) { diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 2e0bfa8290a..1c1b51f2a29 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -132,6 +132,16 @@ namespace ts { type: "boolean", description: Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, }, + { + name: "noUnusedLocals", + type: "boolean", + description: Diagnostics.Report_Errors_on_Unused_Locals, + }, + { + name: "noUnusedParameters", + type: "boolean", + description: Diagnostics.Report_Errors_on_Unused_Parameters + }, { name: "noLib", type: "boolean", diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index d3ecb1715a9..e2ad55f95ef 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -571,7 +571,7 @@ "category": "Error", "code": 1186 }, - "A parameter property may not be a binding pattern.": { + "A parameter property may not be declared using a binding pattern.": { "category": "Error", "code": 1187 }, @@ -851,6 +851,10 @@ "category": "Error", "code": 1316 }, + "A parameter property cannot be declared using a rest parameter.": { + "category": "Error", + "code": 1317 + }, "Duplicate identifier '{0}'.": { "category": "Error", "code": 2300 @@ -2788,6 +2792,18 @@ "category": "Message", "code": 6132 }, + "'{0}' is declared but never used.": { + "category": "Error", + "code": 6133 + }, + "Report Errors on Unused Locals.": { + "category": "Message", + "code": 6134 + }, + "Report Errors on Unused Parameters.": { + "category": "Message", + "code": 6135 + }, "Variable '{0}' implicitly has an '{1}' type.": { "category": "Error", diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 101778e7322..0879a3a9ee4 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -753,6 +753,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge return generateNameForExportDefault(); case SyntaxKind.ClassExpression: return generateNameForClassExpression(); + default: + Debug.fail(); } } @@ -1217,7 +1219,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge function jsxEmitReact(node: JsxElement | JsxSelfClosingElement) { /// Emit a tag name, which is either '"div"' for lower-cased names, or /// 'Div' for upper-cased or dotted names - function emitTagName(name: Identifier | QualifiedName) { + function emitTagName(name: LeftHandSideExpression) { if (name.kind === SyntaxKind.Identifier && isIntrinsicJsxName((name).text)) { write('"'); emit(name); @@ -1671,6 +1673,21 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge return false; } + function getClassExpressionInPropertyAccessInStaticPropertyDeclaration(node: Identifier) { + if (languageVersion >= ScriptTarget.ES6) { + let parent = node.parent; + if (parent.kind === SyntaxKind.PropertyAccessExpression && (parent).expression === node) { + parent = parent.parent; + while (parent && parent.kind !== SyntaxKind.PropertyDeclaration) { + parent = parent.parent; + } + return parent && parent.kind === SyntaxKind.PropertyDeclaration && (parent.flags & NodeFlags.Static) !== 0 && + parent.parent.kind === SyntaxKind.ClassExpression ? parent.parent : undefined; + } + } + return undefined; + } + function emitIdentifier(node: Identifier) { if (convertedLoopState) { if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { @@ -1685,6 +1702,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge write(node.text); } else if (isExpressionIdentifier(node)) { + const classExpression = getClassExpressionInPropertyAccessInStaticPropertyDeclaration(node); + if (classExpression) { + const declaration = resolver.getReferencedValueDeclaration(node); + if (declaration === classExpression) { + write(getGeneratedNameForNode(declaration.name)); + return; + } + } emitExpressionIdentifier(node); } else if (isNameOfNestedBlockScopedRedeclarationOrCapturedBinding(node)) { @@ -5084,13 +5109,13 @@ const _super = (function (geti, seti) { } } - function emitPropertyDeclaration(node: ClassLikeDeclaration, property: PropertyDeclaration, receiver?: Identifier, isExpression?: boolean) { + function emitPropertyDeclaration(node: ClassLikeDeclaration, property: PropertyDeclaration, receiver?: string, isExpression?: boolean) { writeLine(); emitLeadingComments(property); emitStart(property); emitStart(property.name); if (receiver) { - emit(receiver); + write(receiver); } else { if (property.flags & NodeFlags.Static) { @@ -5509,13 +5534,16 @@ const _super = (function (geti, seti) { // of it have been initialized by the time it is used. const staticProperties = getInitializedProperties(node, /*isStatic*/ true); const isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === SyntaxKind.ClassExpression; - let tempVariable: Identifier; + let generatedName: string; if (isClassExpressionWithStaticProperties) { - tempVariable = createAndRecordTempVariable(TempFlags.Auto); + generatedName = getGeneratedNameForNode(node.name); + const synthesizedNode = createSynthesizedNode(SyntaxKind.Identifier); + synthesizedNode.text = generatedName; + recordTempDeclaration(synthesizedNode); write("("); increaseIndent(); - emit(tempVariable); + emit(synthesizedNode); write(" = "); } @@ -5569,11 +5597,11 @@ const _super = (function (geti, seti) { for (const property of staticProperties) { write(","); writeLine(); - emitPropertyDeclaration(node, property, /*receiver*/ tempVariable, /*isExpression*/ true); + emitPropertyDeclaration(node, property, /*receiver*/ generatedName, /*isExpression*/ true); } write(","); writeLine(); - emit(tempVariable); + write(generatedName); decreaseIndent(); write(")"); } diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index f5155858b04..149f11e155d 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -1179,6 +1179,7 @@ namespace ts { return token === SyntaxKind.OpenBracketToken || token === SyntaxKind.OpenBraceToken || token === SyntaxKind.AsteriskToken + || token === SyntaxKind.DotDotDotToken || isLiteralPropertyName(); } @@ -3576,7 +3577,7 @@ namespace ts { return finishNode(node); } - function tagNamesAreEquivalent(lhs: EntityName, rhs: EntityName): boolean { + function tagNamesAreEquivalent(lhs: JsxTagNameExpression, rhs: JsxTagNameExpression): boolean { if (lhs.kind !== rhs.kind) { return false; } @@ -3585,8 +3586,15 @@ namespace ts { return (lhs).text === (rhs).text; } - return (lhs).right.text === (rhs).right.text && - tagNamesAreEquivalent((lhs).left, (rhs).left); + if (lhs.kind === SyntaxKind.ThisKeyword) { + return true; + } + + // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only + // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression + // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element + return (lhs).name.text === (rhs).name.text && + tagNamesAreEquivalent((lhs).expression as JsxTagNameExpression, (rhs).expression as JsxTagNameExpression); } @@ -3654,7 +3662,7 @@ namespace ts { Debug.fail("Unknown JSX child kind " + token); } - function parseJsxChildren(openingTagName: EntityName): NodeArray { + function parseJsxChildren(openingTagName: LeftHandSideExpression): NodeArray { const result = >[]; result.pos = scanner.getStartPos(); const saveParsingContext = parsingContext; @@ -3717,17 +3725,22 @@ namespace ts { return finishNode(node); } - function parseJsxElementName(): EntityName { + function parseJsxElementName(): JsxTagNameExpression { scanJsxIdentifier(); - let elementName: EntityName = parseIdentifierName(); + // JsxElement can have name in the form of + // propertyAccessExpression + // primaryExpression in the form of an identifier and "this" keyword + // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword + // We only want to consider "this" as a primaryExpression + let expression: JsxTagNameExpression = token === SyntaxKind.ThisKeyword ? + parseTokenNode() : parseIdentifierName(); while (parseOptional(SyntaxKind.DotToken)) { - scanJsxIdentifier(); - const node: QualifiedName = createNode(SyntaxKind.QualifiedName, elementName.pos); // !!! - node.left = elementName; - node.right = parseIdentifierName(); - elementName = finishNode(node); + const propertyAccess: PropertyAccessExpression = createNode(SyntaxKind.PropertyAccessExpression, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + expression = finishNode(propertyAccess); } - return elementName; + return expression; } function parseJsxExpression(inExpressionContext: boolean): JsxExpression { @@ -4699,7 +4712,7 @@ namespace ts { case SyntaxKind.EqualsToken: return parseExportAssignment(fullStart, decorators, modifiers); case SyntaxKind.AsKeyword: - return parseGlobalModuleExportDeclaration(fullStart, decorators, modifiers); + return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); default: return parseExportDeclaration(fullStart, decorators, modifiers); } @@ -5378,7 +5391,7 @@ namespace ts { return nextToken() === SyntaxKind.SlashToken; } - function parseGlobalModuleExportDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): NamespaceExportDeclaration { + function parseNamespaceExportDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): NamespaceExportDeclaration { const exportDeclaration = createNode(SyntaxKind.NamespaceExportDeclaration, fullStart); exportDeclaration.decorators = decorators; exportDeclaration.modifiers = modifiers; diff --git a/src/compiler/tsconfig.json b/src/compiler/tsconfig.json index 5460f162935..76308c2cba4 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -3,22 +3,26 @@ "noImplicitAny": true, "removeComments": true, "preserveConstEnums": true, - "out": "../../built/local/tsc.js", - "sourceMap": true + "outFile": "../../built/local/tsc.js", + "sourceMap": true, + "declaration": true, + "stripInternal": true }, "files": [ - "types.ts", "core.ts", "sys.ts", - "diagnosticInformationMap.generated.ts", + "types.ts", "scanner.ts", "parser.ts", "utilities.ts", "binder.ts", "checker.ts", + "sourcemap.ts", + "declarationEmitter.ts", "emitter.ts", "program.ts", "commandLineParser.ts", - "tsc.ts" + "tsc.ts", + "diagnosticInformationMap.generated.ts" ] } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index ad572ceb00b..050c3970f17 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -1042,11 +1042,13 @@ namespace ts { closingElement: JsxClosingElement; } + export type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression; + /// The opening element of a ... JsxElement // @kind(SyntaxKind.JsxOpeningElement) export interface JsxOpeningElement extends Expression { _openingElementBrand?: any; - tagName: EntityName; + tagName: JsxTagNameExpression; attributes: NodeArray; } @@ -1073,7 +1075,7 @@ namespace ts { // @kind(SyntaxKind.JsxClosingElement) export interface JsxClosingElement extends Node { - tagName: EntityName; + tagName: JsxTagNameExpression; } // @kind(SyntaxKind.JsxExpression) @@ -1875,7 +1877,7 @@ namespace ts { buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildDisplayForParametersAndDelimiters(thisType: Type, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; } @@ -2121,11 +2123,13 @@ namespace ts { members?: SymbolTable; // Class, interface or literal instance members exports?: SymbolTable; // Module exports globalExports?: SymbolTable; // Conditional global UMD exports + /* @internal */ isReadonly?: boolean; // readonly? (set only for intersections and unions) /* @internal */ id?: number; // Unique id (used to look up SymbolLinks) /* @internal */ mergeId?: number; // Merge id (used to look up merged symbol) /* @internal */ parent?: Symbol; // Parent symbol /* @internal */ exportSymbol?: Symbol; // Exported symbol associated with this symbol /* @internal */ constEnumOnlyModule?: boolean; // True if module contains only const enums or other modules with only const enums + /* @internal */ hasReference?: boolean; // True if the symbol is referenced elsewhere } /* @internal */ @@ -2395,7 +2399,8 @@ namespace ts { declaration: SignatureDeclaration; // Originating declaration typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic) parameters: Symbol[]; // Parameters - thisType?: Type; // type of this-type + /* @internal */ + thisParameter?: Symbol; // symbol of this-type parameter /* @internal */ resolvedReturnType: Type; // Resolved return type /* @internal */ @@ -2555,6 +2560,8 @@ namespace ts { noImplicitAny?: boolean; noImplicitReturns?: boolean; noImplicitThis?: boolean; + noUnusedLocals?: boolean; + noUnusedParameters?: boolean; noImplicitUseStrict?: boolean; noLib?: boolean; noResolve?: boolean; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index b4ef62c6c3e..99e158e6ab7 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1702,7 +1702,7 @@ namespace ts { node.kind === SyntaxKind.ExportAssignment && (node).expression.kind === SyntaxKind.Identifier; } - export function getClassExtendsHeritageClauseElement(node: ClassLikeDeclaration) { + export function getClassExtendsHeritageClauseElement(node: ClassLikeDeclaration | InterfaceDeclaration) { const heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ExtendsKeyword); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index a3aec8b0f44..2111e836376 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -310,6 +310,7 @@ namespace FourSlash { } this.formatCodeSettings = { + baseIndentSize: 0, indentSize: 4, tabSize: 4, newLineCharacter: Harness.IO.newLine(), @@ -730,29 +731,6 @@ namespace FourSlash { } } - public verifyReferencesCountIs(count: number, localFilesOnly = true) { - const references = this.getReferencesAtCaret(); - let referencesCount = 0; - - if (localFilesOnly) { - const localFiles = this.testData.files.map(file => file.fileName); - // Count only the references in local files. Filter the ones in lib and other files. - ts.forEach(references, entry => { - if (localFiles.some((fileName) => fileName === entry.fileName)) { - referencesCount++; - } - }); - } - else { - referencesCount = references && references.length || 0; - } - - if (referencesCount !== count) { - const condition = localFilesOnly ? "excluding libs" : "including libs"; - this.raiseError("Expected references count (" + condition + ") to be " + count + ", but is actually " + referencesCount); - } - } - public verifyReferencesAre(expectedReferences: Range[]) { const actualReferences = this.getReferencesAtCaret() || []; @@ -760,7 +738,7 @@ namespace FourSlash { // Find the unaccounted-for reference. for (const actual of actualReferences) { if (!ts.forEach(expectedReferences, r => r.start === actual.textSpan.start)) { - this.raiseError(`A reference ${actual} is unaccounted for.`); + this.raiseError(`A reference ${stringify(actual)} is unaccounted for.`); } } // Probably will never reach here. @@ -769,7 +747,7 @@ namespace FourSlash { for (const reference of expectedReferences) { const {fileName, start, end} = reference; - if (reference.marker) { + if (reference.marker && reference.marker.data) { const {isWriteAccess, isDefinition} = reference.marker.data; this.verifyReferencesWorker(actualReferences, fileName, start, end, isWriteAccess, isDefinition); } @@ -793,12 +771,8 @@ namespace FourSlash { } } - public verifyReferencesAtPositionListContains(fileName: string, start: number, end: number, isWriteAccess?: boolean, isDefinition?: boolean) { - const references = this.getReferencesAtCaret(); - if (!references || references.length === 0) { - this.raiseError("verifyReferencesAtPositionListContains failed - found 0 references, expected at least one."); - } - this.verifyReferencesWorker(references, fileName, start, end, isWriteAccess, isDefinition); + public verifyRangesWithSameTextReferenceEachOther() { + ts.forEachValue(this.rangesByText(), ranges => this.verifyRangesReferenceEachOther(ranges)); } private verifyReferencesWorker(references: ts.ReferenceEntry[], fileName: string, start: number, end: number, isWriteAccess?: boolean, isDefinition?: boolean) { @@ -817,7 +791,6 @@ namespace FourSlash { const missingItem = { fileName, start, end, isWriteAccess, isDefinition }; this.raiseError(`verifyReferencesAtPositionListContains failed - could not find the item: ${stringify(missingItem)} in the returned list: (${stringify(references)})`); - } private getMemberListAtCaret() { @@ -907,13 +880,13 @@ namespace FourSlash { assert.equal(getDisplayPartsJson(actualQuickInfo.documentation), getDisplayPartsJson(documentation), this.messageAtLastKnownMarker("QuickInfo documentation")); } - public verifyRenameLocations(findInStrings: boolean, findInComments: boolean) { + public verifyRenameLocations(findInStrings: boolean, findInComments: boolean, ranges?: Range[]) { const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); if (renameInfo.canRename) { let references = this.languageService.findRenameLocations( this.activeFile.fileName, this.currentCaretPosition, findInStrings, findInComments); - let ranges = this.getRanges(); + ranges = ranges || this.getRanges(); if (!references) { if (ranges.length !== 0) { @@ -1541,19 +1514,32 @@ namespace FourSlash { } private updateMarkersForEdit(fileName: string, minChar: number, limChar: number, text: string) { - for (let i = 0; i < this.testData.markers.length; i++) { - const marker = this.testData.markers[i]; + for (const marker of this.testData.markers) { if (marker.fileName === fileName) { - if (marker.position > minChar) { - if (marker.position < limChar) { - // Marker is inside the edit - mark it as invalidated (?) - marker.position = -1; - } - else { - // Move marker back/forward by the appropriate amount - marker.position += (minChar - limChar) + text.length; - } + marker.position = updatePosition(marker.position); + } + } + + for (const range of this.testData.ranges) { + if (range.fileName === fileName) { + range.start = updatePosition(range.start); + range.end = updatePosition(range.end); + } + } + + function updatePosition(position: number) { + if (position > minChar) { + if (position < limChar) { + // Inside the edit - mark it as invalidated (?) + return -1; } + else { + // Move marker back/forward by the appropriate amount + return position + (minChar - limChar) + text.length; + } + } + else { + return position; } } } @@ -1648,8 +1634,20 @@ namespace FourSlash { } public getRanges(): Range[] { - // Return a copy of the list - return this.testData.ranges.slice(0); + return this.testData.ranges; + } + + public rangesByText(): ts.Map { + const result: ts.Map = {}; + for (const range of this.getRanges()) { + const text = this.rangeText(range); + (ts.getProperty(result, text) || (result[text] = [])).push(range); + } + return result; + } + + private rangeText({fileName, start, end}: Range, more = false): string { + return this.getFileContent(fileName).slice(start, end); } public verifyCaretAtMarker(markerName = "") { @@ -1662,24 +1660,23 @@ namespace FourSlash { } } - private getIndentation(fileName: string, position: number, indentStyle: ts.IndentStyle): number { - + private getIndentation(fileName: string, position: number, indentStyle: ts.IndentStyle, baseIndentSize: number): number { const formatOptions = ts.clone(this.formatCodeSettings); formatOptions.indentStyle = indentStyle; - + formatOptions.baseIndentSize = baseIndentSize; return this.languageService.getIndentationAtPosition(fileName, position, formatOptions); } - public verifyIndentationAtCurrentPosition(numberOfSpaces: number, indentStyle: ts.IndentStyle = ts.IndentStyle.Smart) { - const actual = this.getIndentation(this.activeFile.fileName, this.currentCaretPosition, indentStyle); + public verifyIndentationAtCurrentPosition(numberOfSpaces: number, indentStyle: ts.IndentStyle = ts.IndentStyle.Smart, baseIndentSize = 0) { + const actual = this.getIndentation(this.activeFile.fileName, this.currentCaretPosition, indentStyle, baseIndentSize); const lineCol = this.getLineColStringAtPosition(this.currentCaretPosition); if (actual !== numberOfSpaces) { this.raiseError(`verifyIndentationAtCurrentPosition failed at ${lineCol} - expected: ${numberOfSpaces}, actual: ${actual}`); } } - public verifyIndentationAtPosition(fileName: string, position: number, numberOfSpaces: number, indentStyle: ts.IndentStyle = ts.IndentStyle.Smart) { - const actual = this.getIndentation(fileName, position, indentStyle); + public verifyIndentationAtPosition(fileName: string, position: number, numberOfSpaces: number, indentStyle: ts.IndentStyle = ts.IndentStyle.Smart, baseIndentSize = 0) { + const actual = this.getIndentation(fileName, position, indentStyle, baseIndentSize); const lineCol = this.getLineColStringAtPosition(position); if (actual !== numberOfSpaces) { this.raiseError(`verifyIndentationAtPosition failed at ${lineCol} - expected: ${numberOfSpaces}, actual: ${actual}`); @@ -1895,7 +1892,7 @@ namespace FourSlash { }); } - public verifyBraceCompletionAtPostion(negative: boolean, openingBrace: string) { + public verifyBraceCompletionAtPosition(negative: boolean, openingBrace: string) { const openBraceMap: ts.Map = { "(": ts.CharacterCodes.openParen, @@ -1915,7 +1912,7 @@ namespace FourSlash { const position = this.currentCaretPosition; - const validBraceCompletion = this.languageService.isValidBraceCompletionAtPostion(this.activeFile.fileName, position, charCode); + const validBraceCompletion = this.languageService.isValidBraceCompletionAtPosition(this.activeFile.fileName, position, charCode); if (!negative && !validBraceCompletion) { this.raiseError(`${position} is not a valid brace completion position for ${openingBrace}`); @@ -2772,6 +2769,10 @@ namespace FourSlashInterface { return this.state.getRanges(); } + public rangesByText(): ts.Map { + return this.state.rangesByText(); + } + public markerByName(s: string): FourSlash.Marker { return this.state.getMarkerByName(s); } @@ -2919,8 +2920,8 @@ namespace FourSlashInterface { this.state.verifyDefinitionsName(this.negative, name, containerName); } - public isValidBraceCompletionAtPostion(openingBrace: string) { - this.state.verifyBraceCompletionAtPostion(this.negative, openingBrace); + public isValidBraceCompletionAtPosition(openingBrace: string) { + this.state.verifyBraceCompletionAtPosition(this.negative, openingBrace); } } @@ -2937,8 +2938,8 @@ namespace FourSlashInterface { this.state.verifyIndentationAtCurrentPosition(numberOfSpaces); } - public indentationAtPositionIs(fileName: string, position: number, numberOfSpaces: number, indentStyle = ts.IndentStyle.Smart) { - this.state.verifyIndentationAtPosition(fileName, position, numberOfSpaces, indentStyle); + public indentationAtPositionIs(fileName: string, position: number, numberOfSpaces: number, indentStyle = ts.IndentStyle.Smart, baseIndentSize = 0) { + this.state.verifyIndentationAtPosition(fileName, position, numberOfSpaces, indentStyle, baseIndentSize); } public textAtCaretIs(text: string) { @@ -2970,10 +2971,6 @@ namespace FourSlashInterface { this.state.verifyGetEmitOutputContentsForCurrentFile(expected); } - public referencesCountIs(count: number) { - this.state.verifyReferencesCountIs(count, /*localFilesOnly*/ false); - } - public referencesAre(ranges: FourSlash.Range[]) { this.state.verifyReferencesAre(ranges); } @@ -2986,6 +2983,10 @@ namespace FourSlashInterface { this.state.verifyRangesReferenceEachOther(ranges); } + public rangesWithSameTextReferenceEachOther() { + this.state.verifyRangesWithSameTextReferenceEachOther(); + } + public currentParameterHelpArgumentNameIs(name: string) { this.state.verifyCurrentParameterHelpName(name); } @@ -3128,8 +3129,8 @@ namespace FourSlashInterface { this.state.verifyRenameInfoFailed(message); } - public renameLocations(findInStrings: boolean, findInComments: boolean) { - this.state.verifyRenameLocations(findInStrings, findInComments); + public renameLocations(findInStrings: boolean, findInComments: boolean, ranges?: FourSlash.Range[]) { + this.state.verifyRenameLocations(findInStrings, findInComments, ranges); } public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: { start: number; length: number; }, diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index 5864ee77bb2..7a7d0f6dcd8 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -450,8 +450,8 @@ namespace Harness.LanguageService { getDocCommentTemplateAtPosition(fileName: string, position: number): ts.TextInsertion { return unwrapJSONCallResult(this.shim.getDocCommentTemplateAtPosition(fileName, position)); } - isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): boolean { - return unwrapJSONCallResult(this.shim.isValidBraceCompletionAtPostion(fileName, position, openingBrace)); + isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean { + return unwrapJSONCallResult(this.shim.isValidBraceCompletionAtPosition(fileName, position, openingBrace)); } getEmitOutput(fileName: string): ts.EmitOutput { return unwrapJSONCallResult(this.shim.getEmitOutput(fileName)); diff --git a/src/harness/loggedIO.ts b/src/harness/loggedIO.ts index a60c7341206..81b5e4a672d 100644 --- a/src/harness/loggedIO.ts +++ b/src/harness/loggedIO.ts @@ -224,12 +224,7 @@ namespace Playback { recordLog.directoriesRead.push(logEntry); return result; }, - (path, extension, exclude) => findResultByPath(wrapper, - replayLog.directoriesRead.filter( - d => { - return d.extension === extension; - } - ), path)); + (path, extension, exclude) => findResultByPath(wrapper, replayLog.directoriesRead, path)); wrapper.writeFile = recordReplay(wrapper.writeFile, underlying)( (path: string, contents: string) => callAndRecord(underlying.writeFile(path, contents), recordLog.filesWritten, { path, contents, bom: false }), diff --git a/src/lib/es2015.promise.d.ts b/src/lib/es2015.promise.d.ts index 6ade205dc42..c5af984f7e0 100644 --- a/src/lib/es2015.promise.d.ts +++ b/src/lib/es2015.promise.d.ts @@ -3,59 +3,149 @@ */ interface Promise { /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike): Promise; + + /** + * Creates a new Promise with the same internal state of this Promise. + * @returns A Promise. + */ + then(): Promise; /** * Attaches a callback for only the rejection of the Promise. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of the callback. */ - catch(onrejected?: (reason: any) => T | PromiseLike): Promise; - catch(onrejected?: (reason: any) => void): Promise; + catch(onrejected: (reason: any) => TResult | PromiseLike): Promise; + + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected: (reason: any) => T | PromiseLike): Promise; } interface PromiseConstructor { - /** - * A reference to the prototype. + /** + * A reference to the prototype. */ readonly prototype: Promise; /** * Creates a new Promise. - * @param executor A callback used to initialize the promise. This callback is passed two arguments: - * a resolve callback used resolve the promise with a value or the result of another promise, + * @param executor A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used resolve the promise with a value or the result of another promise, * and a reject callback used to reject the promise with a provided reason or error. */ new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises + * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values An array of Promises. + * @returns A new Promise. + */ + all(values: (T | PromiseLike)[]): Promise; + /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ - reject(reason: any): Promise; + reject(reason: any): Promise; /** * Creates a new rejected promise for the provided reason. diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index 8447b31fc89..4f657d4b52b 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -1255,13 +1255,33 @@ declare type PromiseConstructorLike = new (executor: (resolve: (value?: T | P interface PromiseLike { /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; - then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): PromiseLike; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): PromiseLike; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled: (value: T) => TResult | PromiseLike): PromiseLike; + + /** + * Creates a new Promise with the same internal state of this Promise. + * @returns A Promise. + */ + then(): PromiseLike; } interface ArrayLike { @@ -1524,7 +1544,7 @@ interface Int8Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -1797,7 +1817,7 @@ interface Uint8Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2071,7 +2091,7 @@ interface Uint8ClampedArray { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2344,7 +2364,7 @@ interface Int16Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2618,7 +2638,7 @@ interface Uint16Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -2891,7 +2911,7 @@ interface Int32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3164,7 +3184,7 @@ interface Uint32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3437,7 +3457,7 @@ interface Float32Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. @@ -3711,7 +3731,7 @@ interface Float64Array { * Returns the index of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, + * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. diff --git a/src/server/client.ts b/src/server/client.ts index 09cfa2ac739..f04dbd8dc02 100644 --- a/src/server/client.ts +++ b/src/server/client.ts @@ -588,7 +588,7 @@ namespace ts.server { throw new Error("Not Implemented Yet."); } - isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): boolean { + isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean { throw new Error("Not Implemented Yet."); } diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index adc038d1882..f5a7aba2917 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -544,6 +544,7 @@ namespace ts.server { if (!this.logger.isVerbose()) { return; } + this.logger.startGroup(); let counter = 0; diff --git a/src/server/protocol.d.ts b/src/server/protocol.d.ts index a4e9062717a..54ce4acea41 100644 --- a/src/server/protocol.d.ts +++ b/src/server/protocol.d.ts @@ -543,6 +543,9 @@ declare namespace ts.server.protocol { /** Number of spaces to indent during formatting. Default value is 4. */ indentSize?: number; + /** Number of additional spaces to indent during formatting to preserve base indentation (ex. script block indentation). Default value is 0. */ + baseIndentSize?: number; + /** The new line character to be used. Default value is the OS line delimiter. */ newLineCharacter?: string; @@ -1051,7 +1054,6 @@ declare namespace ts.server.protocol { * Arguments of a signature help request. */ export interface SignatureHelpRequestArgs extends FileLocationRequestArgs { - } /** @@ -1070,6 +1072,43 @@ declare namespace ts.server.protocol { body?: SignatureHelpItems; } + /** + * Synchronous request for semantic diagnostics of one file. + */ + export interface SemanticDiagnosticsSyncRequest extends FileRequest { + arguments: SemanticDiagnosticsSyncRequestArgs; + } + + export interface SemanticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + + + /** + * Response object for synchronous sematic diagnostics request. + */ + export interface SemanticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + + /** + * Synchronous request for syntactic diagnostics of one file. + */ + export interface SyntacticDiagnosticsSyncRequest extends FileRequest { + arguments: SyntacticDiagnosticsSyncRequestArgs; + } + + export interface SyntacticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + + /** + * Response object for synchronous syntactic diagnostics request. + */ + export interface SyntacticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + /** * Arguments for GeterrForProject request. */ diff --git a/src/server/session.ts b/src/server/session.ts index 10cf03e96da..d300cd13990 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -21,16 +21,16 @@ namespace ts.server { return spaceCache[n]; } - export function generateIndentString(n: number, editorOptions: EditorOptions): string { - if (editorOptions.ConvertTabsToSpaces) { + export function generateIndentString(n: number, editorOptions: EditorSettings): string { + if (editorOptions.convertTabsToSpaces) { return generateSpaces(n); } else { let result = ""; - for (let i = 0; i < Math.floor(n / editorOptions.TabSize); i++) { + for (let i = 0; i < Math.floor(n / editorOptions.tabSize); i++) { result += "\t"; } - for (let i = 0; i < n % editorOptions.TabSize; i++) { + for (let i = 0; i < n % editorOptions.tabSize; i++) { result += " "; } return result; @@ -119,7 +119,8 @@ namespace ts.server { export const FormatRangeFull = "formatRange-full"; export const Geterr = "geterr"; export const GeterrForProject = "geterrForProject"; - export const SemanticDiagnosticsFull = "semanticDiagnostics-full"; + export const SemanticDiagnosticsSync = "semanticDiagnosticsSync"; + export const SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; export const NavBar = "navbar"; export const NavBarFull = "navbar-full"; export const Navto = "navto"; @@ -154,7 +155,6 @@ namespace ts.server { export const TodoComments = "todoComments"; export const Indentation = "indentation"; export const DocCommentTemplate = "docCommentTemplate"; - export const SyntacticDiagnosticsFull = "syntacticDiagnostics-full"; export const CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; export const NameOrDottedNameSpan = "nameOrDottedNameSpan"; export const BreakpointStatement = "breakpointStatement"; @@ -162,6 +162,7 @@ namespace ts.server { namespace Errors { export const NoProject = new Error("No Project."); + export const ProjectLanguageServiceDisabled = new Error("The project's language service is disabled."); } export interface ServerHost extends ts.System { @@ -380,10 +381,10 @@ namespace ts.server { private getCompilerOptionsDiagnostics(args: protocol.ProjectRequestArgs) { const project = this.getProject(args.projectFileName); - return this.convertDiagnostics(project.languageService.getCompilerOptionsDiagnostics(), /*scriptInfo*/ undefined); + return this.convertToDiagnosticsWithLinePosition(project.languageService.getCompilerOptionsDiagnostics(), /*scriptInfo*/ undefined); } - private convertDiagnostics(diagnostics: Diagnostic[], scriptInfo: ScriptInfo) { + private convertToDiagnosticsWithLinePosition(diagnostics: Diagnostic[], scriptInfo: ScriptInfo) { return diagnostics.map(d => { message: flattenDiagnosticMessageText(d.messageText, this.host.newLine), start: d.start, @@ -395,19 +396,13 @@ namespace ts.server { }); } - private getDiagnosticsWorker(args: protocol.FileRequestArgs, selector: (project: Project, file: string) => Diagnostic[]) { + private getDiagnosticsWorker(args: protocol.FileRequestArgs, selector: (project: Project, file: string) => Diagnostic[], includeLinePosition: boolean) { const { project, file } = this.getFileAndProject(args); const scriptInfo = project.getScriptInfoForNormalizedPath(file); const diagnostics = selector(project, file); - return this.convertDiagnostics(diagnostics, scriptInfo); - } - - private getSyntacticDiagnostics(args: protocol.FileRequestArgs): protocol.DiagnosticWithLinePosition[] { - return this.getDiagnosticsWorker(args, (project, file) => project.languageService.getSyntacticDiagnostics(file)); - } - - private getSemanticDiagnostics(args: protocol.FileRequestArgs): protocol.DiagnosticWithLinePosition[] { - return this.getDiagnosticsWorker(args, (project, file) => project.languageService.getSemanticDiagnostics(file)); + return includeLinePosition + ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) + : diagnostics.map(d => formatDiag(file, project, d)); } private getDefinition(args: protocol.FileLocationRequestArgs, simplifiedResult: boolean): protocol.FileSpan[] | DefinitionInfo[] { @@ -480,11 +475,18 @@ namespace ts.server { }); } + private getSyntacticDiagnosticsSync(args: protocol.SyntacticDiagnosticsSyncRequestArgs): protocol.Diagnostic[] | protocol.DiagnosticWithLinePosition[] { + return this.getDiagnosticsWorker(args, (project, file) => project.languageService.getSyntacticDiagnostics(file), args.includeLinePosition); + } + + private getSemanticDiagnosticsSync(args: protocol.SemanticDiagnosticsSyncRequestArgs): protocol.Diagnostic[] | protocol.DiagnosticWithLinePosition[] { + return this.getDiagnosticsWorker(args, (project, file) => project.languageService.getSemanticDiagnostics(file), args.includeLinePosition); + } + private getDocumentHighlights(args: protocol.DocumentHighlightsRequestArgs, simplifiedResult: boolean): protocol.DocumentHighlightsItem[] | DocumentHighlights[] { const { file, project } = this.getFileAndProject(args); const scriptInfo = project.getScriptInfoForNormalizedPath(file); const position = this.getPosition(args, scriptInfo); - const documentHighlights = project.languageService.getDocumentHighlights(file, position, args.filesToSearch); if (!documentHighlights) { @@ -797,7 +799,7 @@ namespace ts.server { private isValidBraceCompletion(args: protocol.BraceCompletionRequestArgs) { const { file, project } = this.getFileAndProject(args); const position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); - return project.languageService.isValidBraceCompletionAtPostion(file, position, args.openingBrace.charCodeAt(0)); + return project.languageService.isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0)); } private getQuickInfoWorker(args: protocol.FileLocationRequestArgs, simplifiedResult: boolean): protocol.QuickInfoResponseBody | QuickInfo { @@ -881,15 +883,7 @@ namespace ts.server { if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { const lineText = lineInfo.leaf.text; if (lineText.search("\\S") < 0) { - // TODO: get these options from host - const editorOptions: ts.EditorOptions = { - IndentSize: formatOptions.indentSize, - TabSize: formatOptions.tabSize, - NewLineCharacter: formatOptions.newLineCharacter, - ConvertTabsToSpaces: formatOptions.convertTabsToSpaces, - IndentStyle: ts.IndentStyle.Smart, - }; - const preferredIndent = project.languageService.getIndentationAtPosition(file, position, editorOptions); + const preferredIndent = project.languageService.getIndentationAtPosition(file, position, formatOptions); let hasIndent = 0; let i: number, len: number; for (i = 0, len = lineText.length; i < len; i++) { @@ -897,7 +891,7 @@ namespace ts.server { hasIndent++; } else if (lineText.charAt(i) == "\t") { - hasIndent += editorOptions.TabSize; + hasIndent += formatOptions.tabSize; } else { break; @@ -908,7 +902,7 @@ namespace ts.server { const firstNoWhiteSpacePosition = lineInfo.offset + i; edits.push({ span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), - newText: generateIndentString(preferredIndent, editorOptions) + newText: generateIndentString(preferredIndent, formatOptions) }); } } @@ -1376,12 +1370,6 @@ namespace ts.server { [CommandNames.SignatureHelpFull]: (request: protocol.SignatureHelpRequest) => { return this.requiredResponse(this.getSignatureHelpItems(request.arguments, /*simplifiedResult*/ false)); }, - [CommandNames.SemanticDiagnosticsFull]: (request: protocol.FileRequest) => { - return this.requiredResponse(this.getSemanticDiagnostics(request.arguments)); - }, - [CommandNames.SyntacticDiagnosticsFull]: (request: protocol.FileRequest) => { - return this.requiredResponse(this.getSyntacticDiagnostics(request.arguments)); - }, [CommandNames.CompilerOptionsDiagnosticsFull]: (request: protocol.ProjectRequest) => { return this.requiredResponse(this.getCompilerOptionsDiagnostics(request.arguments)); }, @@ -1392,6 +1380,12 @@ namespace ts.server { this.cleanup(); return this.requiredResponse(true); }, + [CommandNames.SemanticDiagnosticsSync]: (request: protocol.FileRequest) => { + return this.requiredResponse(this.getSemanticDiagnosticsSync(request.arguments)); + }, + [CommandNames.SyntacticDiagnosticsSync]: (request: protocol.FileRequest) => { + return this.requiredResponse(this.getSyntacticDiagnosticsSync(request.arguments)); + }, [CommandNames.Geterr]: (request: protocol.Request) => { const geterrArgs = request.arguments; return { response: this.getDiagnostics(geterrArgs.delay, geterrArgs.files), responseRequired: false }; diff --git a/src/server/tsconfig.json b/src/server/tsconfig.json index 0772210cb15..0a8cfb89ab3 100644 --- a/src/server/tsconfig.json +++ b/src/server/tsconfig.json @@ -4,13 +4,16 @@ "removeComments": true, "preserveConstEnums": true, "out": "../../built/local/tsserver.js", - "sourceMap": true + "sourceMap": true, + "stripInternal": true }, "files": [ + "../services/shims.ts", + "../services/utilities.ts", "node.d.ts", "editorServices.ts", "protocol.d.ts", - "server.ts", - "session.ts" + "session.ts", + "server.ts" ] } diff --git a/src/server/utilities.ts b/src/server/utilities.ts index 18970f578b3..a5cb4fc6afe 100644 --- a/src/server/utilities.ts +++ b/src/server/utilities.ts @@ -133,7 +133,7 @@ namespace ts.server { getFormattingEditsForDocument: (): any => throwLanguageServiceIsDisabledError(), getFormattingEditsAfterKeystroke: (): any => throwLanguageServiceIsDisabledError(), getDocCommentTemplateAtPosition: (): any => throwLanguageServiceIsDisabledError(), - isValidBraceCompletionAtPostion: (): any => throwLanguageServiceIsDisabledError(), + isValidBraceCompletionAtPosition: (): any => throwLanguageServiceIsDisabledError(), getEmitOutput: (): any => throwLanguageServiceIsDisabledError(), getProgram: (): any => throwLanguageServiceIsDisabledError(), getNonBoundSourceFile: (): any => throwLanguageServiceIsDisabledError(), diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index fccb9fb0b1c..a5e8a489244 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -394,7 +394,10 @@ namespace ts.formatting { const startLinePosition = getLineStartPositionForPosition(startPos, sourceFile); const column = SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options); if (startLine !== parentStartLine || startPos === column) { - return column; + // Use the base indent size if it is greater than + // the indentation of the inherited predecessor. + const baseIndentSize = SmartIndenter.getBaseIndentation(options); + return baseIndentSize > column ? baseIndentSize : column; } } diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index 9c9d9eb9149..cc4c40af88c 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -10,7 +10,7 @@ namespace ts.formatting { export function getIndentation(position: number, sourceFile: SourceFile, options: EditorSettings): number { if (position > sourceFile.text.length) { - return 0; // past EOF + return getBaseIndentation(options); // past EOF } // no indentation when the indent style is set to none, @@ -21,7 +21,7 @@ namespace ts.formatting { const precedingToken = findPrecedingToken(position, sourceFile); if (!precedingToken) { - return 0; + return getBaseIndentation(options); } // no indentation in string \regex\template literals @@ -96,8 +96,8 @@ namespace ts.formatting { } if (!current) { - // no parent was found - return 0 to be indented on the level of SourceFile - return 0; + // no parent was found - return the base indentation of the SourceFile + return getBaseIndentation(options); } return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, options); @@ -108,6 +108,10 @@ namespace ts.formatting { return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, options); } + export function getBaseIndentation(options: EditorSettings) { + return options.baseIndentSize || 0; + } + function getIndentationForNodeWorker( current: Node, currentStart: LineAndCharacter, @@ -162,7 +166,7 @@ namespace ts.formatting { parent = current.parent; } - return indentationDelta; + return indentationDelta + getBaseIndentation(options); } diff --git a/src/services/services.ts b/src/services/services.ts index 5728adb5b9d..2886771a33a 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -795,7 +795,7 @@ namespace ts { declaration: SignatureDeclaration; typeParameters: TypeParameter[]; parameters: Symbol[]; - thisType: Type; + thisParameter: Symbol; resolvedReturnType: Type; minArgumentCount: number; hasRestParameter: boolean; @@ -1163,7 +1163,7 @@ namespace ts { getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; - isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): boolean; + isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; getEmitOutput(fileName: string): EmitOutput; @@ -1261,6 +1261,7 @@ namespace ts { /* @deprecated - consider using EditorSettings instead */ export interface EditorOptions { + BaseIndentSize?: number; IndentSize: number; TabSize: number; NewLineCharacter: string; @@ -1269,6 +1270,7 @@ namespace ts { } export interface EditorSettings { + baseIndentSize?: number; indentSize: number; tabSize: number; newLineCharacter: string; @@ -5904,17 +5906,32 @@ namespace ts { return undefined; } - if (node.kind !== SyntaxKind.Identifier && - // TODO (drosen): This should be enabled in a later release - currently breaks rename. - // node.kind !== SyntaxKind.ThisKeyword && - // node.kind !== SyntaxKind.SuperKeyword && - node.kind !== SyntaxKind.StringLiteral && - !isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { - return undefined; + switch (node.kind) { + case SyntaxKind.NumericLiteral: + if (!isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { + break; + } + // Fallthrough + case SyntaxKind.Identifier: + case SyntaxKind.ThisKeyword: + // case SyntaxKind.SuperKeyword: TODO:GH#9268 + case SyntaxKind.StringLiteral: + return getReferencedSymbolsForNode(node, program.getSourceFiles(), findInStrings, findInComments); } + return undefined; + } - Debug.assert(node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.NumericLiteral || node.kind === SyntaxKind.StringLiteral); - return getReferencedSymbolsForNode(node, program.getSourceFiles(), findInStrings, findInComments); + function isThis(node: Node): boolean { + switch (node.kind) { + case SyntaxKind.ThisKeyword: + // case SyntaxKind.ThisType: TODO: GH#9267 + return true; + case SyntaxKind.Identifier: + // 'this' as a parameter + return (node as Identifier).originalKeywordKind === SyntaxKind.ThisKeyword && node.parent.kind === SyntaxKind.Parameter; + default: + return false; + } } function getReferencedSymbolsForNode(node: Node, sourceFiles: SourceFile[], findInStrings: boolean, findInComments: boolean): ReferencedSymbol[] { @@ -5934,7 +5951,7 @@ namespace ts { } } - if (node.kind === SyntaxKind.ThisKeyword || node.kind === SyntaxKind.ThisType) { + if (isThis(node)) { return getReferencesForThisKeyword(node, sourceFiles); } @@ -6469,7 +6486,7 @@ namespace ts { cancellationToken.throwIfCancellationRequested(); const node = getTouchingWord(sourceFile, position); - if (!node || (node.kind !== SyntaxKind.ThisKeyword && node.kind !== SyntaxKind.ThisType)) { + if (!node || !isThis(node)) { return; } @@ -7858,7 +7875,7 @@ namespace ts { return { newText: result, caretOffset: preamble.length }; } - function isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): boolean { + function isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean { // '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too // expensive to do during typing scenarios @@ -8101,11 +8118,11 @@ namespace ts { const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); - // Can only rename an identifier. if (node) { if (node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.StringLiteral || - isLiteralNameOfPropertyDeclarationOrIndexAccess(node)) { + isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || + isThis(node)) { const symbol = typeChecker.getSymbolAtLocation(node); // Only allow a symbol to be renamed if it actually has at least one declaration. @@ -8226,7 +8243,7 @@ namespace ts { getFormattingEditsForDocument, getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition, - isValidBraceCompletionAtPostion, + isValidBraceCompletionAtPosition, getEmitOutput, getNonBoundSourceFile, getProgram diff --git a/src/services/shims.ts b/src/services/shims.ts index e2645d5e8be..0de4f5d4c7a 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -228,7 +228,7 @@ namespace ts { * at the current position. * E.g. we don't want brace completion inside string-literals, comments, etc. */ - isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): string; + isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): string; getEmitOutput(fileName: string): string; } @@ -758,10 +758,10 @@ namespace ts { ); } - public isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): string { + public isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): string { return this.forwardJSONCall( - `isValidBraceCompletionAtPostion('${fileName}', ${position}, ${openingBrace})`, - () => this.languageService.isValidBraceCompletionAtPostion(fileName, position, openingBrace) + `isValidBraceCompletionAtPosition('${fileName}', ${position}, ${openingBrace})`, + () => this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace) ); } diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index b5df2b5af20..50378aa64b1 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -357,8 +357,8 @@ namespace ts.SignatureHelp { } function getArgumentIndex(argumentsList: Node, node: Node) { - // The list we got back can include commas. In the presence of errors it may - // also just have nodes without commas. For example "Foo(a b c)" will have 3 + // The list we got back can include commas. In the presence of errors it may + // also just have nodes without commas. For example "Foo(a b c)" will have 3 // args without commas. We want to find what index we're at. So we count // forward until we hit ourselves, only incrementing the index if it isn't a // comma. @@ -390,8 +390,8 @@ namespace ts.SignatureHelp { // 'a' ''. So, in the case where the last child is a comma, we increase the // arg count by one to compensate. // - // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then - // we'll have: 'a' '' '' + // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then + // we'll have: 'a' '' '' // That will give us 2 non-commas. We then add one for the last comma, givin us an // arg count of 3. const listChildren = argumentsList.getChildren(); @@ -563,7 +563,7 @@ namespace ts.SignatureHelp { signatureHelpParameters = typeParameters && typeParameters.length > 0 ? map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray; suffixDisplayParts.push(punctuationPart(SyntaxKind.GreaterThanToken)); const parameterParts = mapToDisplayParts(writer => - typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisType, candidateSignature.parameters, writer, invocation)); + typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation)); addRange(suffixDisplayParts, parameterParts); } else { diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index 6aa7e61391b..4bf6e87d7a6 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -1,10 +1,13 @@ { "compilerOptions": { "noImplicitAny": true, - "removeComments": true, + "removeComments": false, "preserveConstEnums": true, - "out": "../../built/local/typescriptServices.js", - "sourceMap": true + "outFile": "../../built/local/typescriptServices.js", + "sourceMap": true, + "stripInternal": true, + "noResolve": false, + "declaration": true }, "files": [ "../compiler/core.ts", @@ -15,11 +18,12 @@ "../compiler/utilities.ts", "../compiler/binder.ts", "../compiler/checker.ts", + "../compiler/sourcemap.ts", + "../compiler/declarationEmitter.ts", "../compiler/emitter.ts", "../compiler/program.ts", - "../compiler/declarationEmitter.ts", - "../compiler/diagnosticInformationMap.generated.ts", "../compiler/commandLineParser.ts", + "../compiler/diagnosticInformationMap.generated.ts", "breakpoints.ts", "navigateTo.ts", "navigationBar.ts", diff --git a/tests/baselines/reference/classExpressionWithStaticPropertiesES61.js b/tests/baselines/reference/classExpressionWithStaticPropertiesES61.js index 43f5e7415c4..7ddacb70405 100644 --- a/tests/baselines/reference/classExpressionWithStaticPropertiesES61.js +++ b/tests/baselines/reference/classExpressionWithStaticPropertiesES61.js @@ -1,10 +1,15 @@ //// [classExpressionWithStaticPropertiesES61.ts] -var v = class C { static a = 1; static b = 2 }; +var v = class C { + static a = 1; + static b = 2; + static c = C.a + 3; +}; //// [classExpressionWithStaticPropertiesES61.js] -var v = (_a = class C { +var v = (C_1 = class C { }, - _a.a = 1, - _a.b = 2, - _a); -var _a; + C_1.a = 1, + C_1.b = 2, + C_1.c = C_1.a + 3, + C_1); +var C_1; diff --git a/tests/baselines/reference/classExpressionWithStaticPropertiesES61.symbols b/tests/baselines/reference/classExpressionWithStaticPropertiesES61.symbols index c5f53e19bff..1101c0bab2f 100644 --- a/tests/baselines/reference/classExpressionWithStaticPropertiesES61.symbols +++ b/tests/baselines/reference/classExpressionWithStaticPropertiesES61.symbols @@ -1,7 +1,18 @@ === tests/cases/compiler/classExpressionWithStaticPropertiesES61.ts === -var v = class C { static a = 1; static b = 2 }; +var v = class C { >v : Symbol(v, Decl(classExpressionWithStaticPropertiesES61.ts, 0, 3)) >C : Symbol(C, Decl(classExpressionWithStaticPropertiesES61.ts, 0, 7)) ->a : Symbol(C.a, Decl(classExpressionWithStaticPropertiesES61.ts, 0, 17)) ->b : Symbol(C.b, Decl(classExpressionWithStaticPropertiesES61.ts, 0, 31)) + static a = 1; +>a : Symbol(C.a, Decl(classExpressionWithStaticPropertiesES61.ts, 0, 17)) + + static b = 2; +>b : Symbol(C.b, Decl(classExpressionWithStaticPropertiesES61.ts, 1, 17)) + + static c = C.a + 3; +>c : Symbol(C.c, Decl(classExpressionWithStaticPropertiesES61.ts, 2, 17)) +>C.a : Symbol(C.a, Decl(classExpressionWithStaticPropertiesES61.ts, 0, 17)) +>C : Symbol(C, Decl(classExpressionWithStaticPropertiesES61.ts, 0, 7)) +>a : Symbol(C.a, Decl(classExpressionWithStaticPropertiesES61.ts, 0, 17)) + +}; diff --git a/tests/baselines/reference/classExpressionWithStaticPropertiesES61.types b/tests/baselines/reference/classExpressionWithStaticPropertiesES61.types index 02c385b7525..0ba6ada4131 100644 --- a/tests/baselines/reference/classExpressionWithStaticPropertiesES61.types +++ b/tests/baselines/reference/classExpressionWithStaticPropertiesES61.types @@ -1,10 +1,23 @@ === tests/cases/compiler/classExpressionWithStaticPropertiesES61.ts === -var v = class C { static a = 1; static b = 2 }; +var v = class C { >v : typeof C ->class C { static a = 1; static b = 2 } : typeof C +>class C { static a = 1; static b = 2; static c = C.a + 3;} : typeof C >C : typeof C + + static a = 1; >a : number >1 : number + + static b = 2; >b : number >2 : number + static c = C.a + 3; +>c : number +>C.a + 3 : number +>C.a : number +>C : typeof C +>a : number +>3 : number + +}; diff --git a/tests/baselines/reference/classExpressionWithStaticPropertiesES62.js b/tests/baselines/reference/classExpressionWithStaticPropertiesES62.js index 1efa56ecaa2..0a4b7645ecc 100644 --- a/tests/baselines/reference/classExpressionWithStaticPropertiesES62.js +++ b/tests/baselines/reference/classExpressionWithStaticPropertiesES62.js @@ -1,9 +1,20 @@ //// [classExpressionWithStaticPropertiesES62.ts] -var v = class C { static a = 1; static b }; +var v = class C { + static a = 1; + static b + static c = { + x: "hi" + } + static d = C.c.x + " world"; + }; //// [classExpressionWithStaticPropertiesES62.js] -var v = (_a = class C { +var v = (C_1 = class C { }, - _a.a = 1, - _a); -var _a; + C_1.a = 1, + C_1.c = { + x: "hi" + }, + C_1.d = C_1.c.x + " world", + C_1); +var C_1; diff --git a/tests/baselines/reference/classExpressionWithStaticPropertiesES62.symbols b/tests/baselines/reference/classExpressionWithStaticPropertiesES62.symbols index be57a289f53..697be499595 100644 --- a/tests/baselines/reference/classExpressionWithStaticPropertiesES62.symbols +++ b/tests/baselines/reference/classExpressionWithStaticPropertiesES62.symbols @@ -1,7 +1,26 @@ === tests/cases/compiler/classExpressionWithStaticPropertiesES62.ts === -var v = class C { static a = 1; static b }; +var v = class C { >v : Symbol(v, Decl(classExpressionWithStaticPropertiesES62.ts, 0, 3)) >C : Symbol(C, Decl(classExpressionWithStaticPropertiesES62.ts, 0, 7)) ->a : Symbol(C.a, Decl(classExpressionWithStaticPropertiesES62.ts, 0, 17)) ->b : Symbol(C.b, Decl(classExpressionWithStaticPropertiesES62.ts, 0, 31)) + static a = 1; +>a : Symbol(C.a, Decl(classExpressionWithStaticPropertiesES62.ts, 0, 17)) + + static b +>b : Symbol(C.b, Decl(classExpressionWithStaticPropertiesES62.ts, 1, 17)) + + static c = { +>c : Symbol(C.c, Decl(classExpressionWithStaticPropertiesES62.ts, 2, 12)) + + x: "hi" +>x : Symbol(x, Decl(classExpressionWithStaticPropertiesES62.ts, 3, 16)) + } + static d = C.c.x + " world"; +>d : Symbol(C.d, Decl(classExpressionWithStaticPropertiesES62.ts, 5, 5)) +>C.c.x : Symbol(x, Decl(classExpressionWithStaticPropertiesES62.ts, 3, 16)) +>C.c : Symbol(C.c, Decl(classExpressionWithStaticPropertiesES62.ts, 2, 12)) +>C : Symbol(C, Decl(classExpressionWithStaticPropertiesES62.ts, 0, 7)) +>c : Symbol(C.c, Decl(classExpressionWithStaticPropertiesES62.ts, 2, 12)) +>x : Symbol(x, Decl(classExpressionWithStaticPropertiesES62.ts, 3, 16)) + + }; diff --git a/tests/baselines/reference/classExpressionWithStaticPropertiesES62.types b/tests/baselines/reference/classExpressionWithStaticPropertiesES62.types index e8ded1422f1..97d6940a3fc 100644 --- a/tests/baselines/reference/classExpressionWithStaticPropertiesES62.types +++ b/tests/baselines/reference/classExpressionWithStaticPropertiesES62.types @@ -1,9 +1,32 @@ === tests/cases/compiler/classExpressionWithStaticPropertiesES62.ts === -var v = class C { static a = 1; static b }; +var v = class C { >v : typeof C ->class C { static a = 1; static b } : typeof C +>class C { static a = 1; static b static c = { x: "hi" } static d = C.c.x + " world"; } : typeof C >C : typeof C + + static a = 1; >a : number >1 : number + + static b >b : any + static c = { +>c : { x: string; } +>{ x: "hi" } : { x: string; } + + x: "hi" +>x : string +>"hi" : string + } + static d = C.c.x + " world"; +>d : string +>C.c.x + " world" : string +>C.c.x : string +>C.c : { x: string; } +>C : typeof C +>c : { x: string; } +>x : string +>" world" : string + + }; diff --git a/tests/baselines/reference/classExpressionWithStaticPropertiesES63.js b/tests/baselines/reference/classExpressionWithStaticPropertiesES63.js new file mode 100644 index 00000000000..53955735762 --- /dev/null +++ b/tests/baselines/reference/classExpressionWithStaticPropertiesES63.js @@ -0,0 +1,23 @@ +//// [classExpressionWithStaticPropertiesES63.ts] + +declare var console: any; +const arr: {y(): number}[] = []; +for (let i = 0; i < 3; i++) { + arr.push(class C { + static x = i; + static y = () => C.x * 2; + }); +} +arr.forEach(C => console.log(C.y())); + +//// [classExpressionWithStaticPropertiesES63.js] +const arr = []; +for (let i = 0; i < 3; i++) { + arr.push((C_1 = class C { + }, + C_1.x = i, + C_1.y = () => C_1.x * 2, + C_1)); +} +arr.forEach(C => console.log(C.y())); +var C_1; diff --git a/tests/baselines/reference/classExpressionWithStaticPropertiesES63.symbols b/tests/baselines/reference/classExpressionWithStaticPropertiesES63.symbols new file mode 100644 index 00000000000..f1a7fa807f5 --- /dev/null +++ b/tests/baselines/reference/classExpressionWithStaticPropertiesES63.symbols @@ -0,0 +1,42 @@ +=== tests/cases/compiler/classExpressionWithStaticPropertiesES63.ts === + +declare var console: any; +>console : Symbol(console, Decl(classExpressionWithStaticPropertiesES63.ts, 1, 11)) + +const arr: {y(): number}[] = []; +>arr : Symbol(arr, Decl(classExpressionWithStaticPropertiesES63.ts, 2, 5)) +>y : Symbol(y, Decl(classExpressionWithStaticPropertiesES63.ts, 2, 12)) + +for (let i = 0; i < 3; i++) { +>i : Symbol(i, Decl(classExpressionWithStaticPropertiesES63.ts, 3, 8)) +>i : Symbol(i, Decl(classExpressionWithStaticPropertiesES63.ts, 3, 8)) +>i : Symbol(i, Decl(classExpressionWithStaticPropertiesES63.ts, 3, 8)) + + arr.push(class C { +>arr.push : Symbol(Array.push, Decl(lib.es5.d.ts, --, --)) +>arr : Symbol(arr, Decl(classExpressionWithStaticPropertiesES63.ts, 2, 5)) +>push : Symbol(Array.push, Decl(lib.es5.d.ts, --, --)) +>C : Symbol(C, Decl(classExpressionWithStaticPropertiesES63.ts, 4, 13)) + + static x = i; +>x : Symbol(C.x, Decl(classExpressionWithStaticPropertiesES63.ts, 4, 22)) +>i : Symbol(i, Decl(classExpressionWithStaticPropertiesES63.ts, 3, 8)) + + static y = () => C.x * 2; +>y : Symbol(C.y, Decl(classExpressionWithStaticPropertiesES63.ts, 5, 21)) +>C.x : Symbol(C.x, Decl(classExpressionWithStaticPropertiesES63.ts, 4, 22)) +>C : Symbol(C, Decl(classExpressionWithStaticPropertiesES63.ts, 4, 13)) +>x : Symbol(C.x, Decl(classExpressionWithStaticPropertiesES63.ts, 4, 22)) + + }); +} +arr.forEach(C => console.log(C.y())); +>arr.forEach : Symbol(Array.forEach, Decl(lib.es5.d.ts, --, --)) +>arr : Symbol(arr, Decl(classExpressionWithStaticPropertiesES63.ts, 2, 5)) +>forEach : Symbol(Array.forEach, Decl(lib.es5.d.ts, --, --)) +>C : Symbol(C, Decl(classExpressionWithStaticPropertiesES63.ts, 9, 12)) +>console : Symbol(console, Decl(classExpressionWithStaticPropertiesES63.ts, 1, 11)) +>C.y : Symbol(y, Decl(classExpressionWithStaticPropertiesES63.ts, 2, 12)) +>C : Symbol(C, Decl(classExpressionWithStaticPropertiesES63.ts, 9, 12)) +>y : Symbol(y, Decl(classExpressionWithStaticPropertiesES63.ts, 2, 12)) + diff --git a/tests/baselines/reference/classExpressionWithStaticPropertiesES63.types b/tests/baselines/reference/classExpressionWithStaticPropertiesES63.types new file mode 100644 index 00000000000..92f14f3f65f --- /dev/null +++ b/tests/baselines/reference/classExpressionWithStaticPropertiesES63.types @@ -0,0 +1,58 @@ +=== tests/cases/compiler/classExpressionWithStaticPropertiesES63.ts === + +declare var console: any; +>console : any + +const arr: {y(): number}[] = []; +>arr : { y(): number; }[] +>y : () => number +>[] : undefined[] + +for (let i = 0; i < 3; i++) { +>i : number +>0 : number +>i < 3 : boolean +>i : number +>3 : number +>i++ : number +>i : number + + arr.push(class C { +>arr.push(class C { static x = i; static y = () => C.x * 2; }) : number +>arr.push : (...items: { y(): number; }[]) => number +>arr : { y(): number; }[] +>push : (...items: { y(): number; }[]) => number +>class C { static x = i; static y = () => C.x * 2; } : typeof C +>C : typeof C + + static x = i; +>x : number +>i : number + + static y = () => C.x * 2; +>y : () => number +>() => C.x * 2 : () => number +>C.x * 2 : number +>C.x : number +>C : typeof C +>x : number +>2 : number + + }); +} +arr.forEach(C => console.log(C.y())); +>arr.forEach(C => console.log(C.y())) : void +>arr.forEach : (callbackfn: (value: { y(): number; }, index: number, array: { y(): number; }[]) => void, thisArg?: any) => void +>arr : { y(): number; }[] +>forEach : (callbackfn: (value: { y(): number; }, index: number, array: { y(): number; }[]) => void, thisArg?: any) => void +>C => console.log(C.y()) : (C: { y(): number; }) => any +>C : { y(): number; } +>console.log(C.y()) : any +>console.log : any +>console : any +>log : any +>C.y() : number +>C.y : () => number +>C : { y(): number; } +>y : () => number + diff --git a/tests/baselines/reference/constDeclarations-useBeforeDefinition2.symbols b/tests/baselines/reference/constDeclarations-useBeforeDefinition2.symbols deleted file mode 100644 index 281ce427733..00000000000 --- a/tests/baselines/reference/constDeclarations-useBeforeDefinition2.symbols +++ /dev/null @@ -1,9 +0,0 @@ -=== tests/cases/compiler/file1.ts === - -c; ->c : Symbol(c, Decl(file2.ts, 0, 5)) - -=== tests/cases/compiler/file2.ts === -const c = 0; ->c : Symbol(c, Decl(file2.ts, 0, 5)) - diff --git a/tests/baselines/reference/constDeclarations-useBeforeDefinition2.types b/tests/baselines/reference/constDeclarations-useBeforeDefinition2.types deleted file mode 100644 index ae60fdfa477..00000000000 --- a/tests/baselines/reference/constDeclarations-useBeforeDefinition2.types +++ /dev/null @@ -1,10 +0,0 @@ -=== tests/cases/compiler/file1.ts === - -c; ->c : number - -=== tests/cases/compiler/file2.ts === -const c = 0; ->c : number ->0 : number - diff --git a/tests/baselines/reference/declarationEmitDestructuringParameterProperties.errors.txt b/tests/baselines/reference/declarationEmitDestructuringParameterProperties.errors.txt index 83785e86f65..aab9d18d629 100644 --- a/tests/baselines/reference/declarationEmitDestructuringParameterProperties.errors.txt +++ b/tests/baselines/reference/declarationEmitDestructuringParameterProperties.errors.txt @@ -1,13 +1,13 @@ -tests/cases/compiler/declarationEmitDestructuringParameterProperties.ts(2,17): error TS1187: A parameter property may not be a binding pattern. -tests/cases/compiler/declarationEmitDestructuringParameterProperties.ts(8,17): error TS1187: A parameter property may not be a binding pattern. -tests/cases/compiler/declarationEmitDestructuringParameterProperties.ts(14,17): error TS1187: A parameter property may not be a binding pattern. +tests/cases/compiler/declarationEmitDestructuringParameterProperties.ts(2,17): error TS1187: A parameter property may not be declared using a binding pattern. +tests/cases/compiler/declarationEmitDestructuringParameterProperties.ts(8,17): error TS1187: A parameter property may not be declared using a binding pattern. +tests/cases/compiler/declarationEmitDestructuringParameterProperties.ts(14,17): error TS1187: A parameter property may not be declared using a binding pattern. ==== tests/cases/compiler/declarationEmitDestructuringParameterProperties.ts (3 errors) ==== class C1 { constructor(public [x, y, z]: string[]) { ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS1187: A parameter property may not be a binding pattern. +!!! error TS1187: A parameter property may not be declared using a binding pattern. } } @@ -15,7 +15,7 @@ tests/cases/compiler/declarationEmitDestructuringParameterProperties.ts(14,17): class C2 { constructor(public [x, y, z]: TupleType1) { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS1187: A parameter property may not be a binding pattern. +!!! error TS1187: A parameter property may not be declared using a binding pattern. } } @@ -23,6 +23,6 @@ tests/cases/compiler/declarationEmitDestructuringParameterProperties.ts(14,17): class C3 { constructor(public { x, y, z }: ObjType1) { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS1187: A parameter property may not be a binding pattern. +!!! error TS1187: A parameter property may not be declared using a binding pattern. } } \ No newline at end of file diff --git a/tests/baselines/reference/decoratorMetadataWithImportDeclarationNameCollision4.js b/tests/baselines/reference/decoratorMetadataWithImportDeclarationNameCollision4.js index 4af0beeddcb..a057b496b25 100644 --- a/tests/baselines/reference/decoratorMetadataWithImportDeclarationNameCollision4.js +++ b/tests/baselines/reference/decoratorMetadataWithImportDeclarationNameCollision4.js @@ -46,8 +46,9 @@ var MyClass = (function () { } MyClass = __decorate([ someDecorator, - __metadata('design:paramtypes', [Object]) + __metadata('design:paramtypes', [(typeof (_a = typeof db_1.default !== 'undefined' && db_1.default.db) === 'function' && _a) || Object]) ], MyClass); return MyClass; + var _a; }()); exports.MyClass = MyClass; diff --git a/tests/baselines/reference/destructuringParameterDeclaration4.errors.txt b/tests/baselines/reference/destructuringParameterDeclaration4.errors.txt index aa5a8e8daea..89c771139ce 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration4.errors.txt +++ b/tests/baselines/reference/destructuringParameterDeclaration4.errors.txt @@ -1,5 +1,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(11,13): error TS2370: A rest parameter must be of an array type. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(13,13): error TS2370: A rest parameter must be of an array type. +tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(14,17): error TS1047: A rest parameter cannot be optional. +tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(15,16): error TS1048: A rest parameter cannot have an initializer. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(20,19): error TS2345: Argument of type 'boolean' is not assignable to parameter of type 'number | string'. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(21,7): error TS2304: Cannot find name 'array2'. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(22,4): error TS2345: Argument of type '[number, number, string, boolean, boolean]' is not assignable to parameter of type '[any, any, [[any]]]'. @@ -10,12 +12,12 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts( tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(24,4): error TS2345: Argument of type '(number | string)[]' is not assignable to parameter of type 'number[]'. Type 'number | string' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'. -tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(29,24): error TS1005: ',' expected. +tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(29,17): error TS1317: A parameter property cannot be declared using a rest parameter. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(34,22): error TS2304: Cannot find name 'E1'. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts(34,28): error TS2304: Cannot find name 'E'. -==== tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts (10 errors) ==== +==== tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts (12 errors) ==== // If the parameter is a rest parameter, the parameter type is any[] // A type annotation for a rest parameter must denote an array type. @@ -34,7 +36,11 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts( ~~~~~~~~~~~~~~~ !!! error TS2370: A rest parameter must be of an array type. function a3(...b?) { } // Error, can't be optional + ~ +!!! error TS1047: A rest parameter cannot be optional. function a4(...b = [1,2,3]) { } // Error, can't have initializer + ~ +!!! error TS1048: A rest parameter cannot have an initializer. function a5([a, b, [[c]]]) { } function a6([a, b, c, ...x]: number[]) { } @@ -63,9 +69,9 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts( var temp = [1, 2, 3]; class C { - constructor(public ...temp) { } // Error, rest parameter can't have accessibilityModifier - ~~~ -!!! error TS1005: ',' expected. + constructor(public ...temp) { } // Error, rest parameter can't have properties + ~~~~~~~~~~~~~~ +!!! error TS1317: A parameter property cannot be declared using a rest parameter. } // Rest parameter with generic diff --git a/tests/baselines/reference/destructuringParameterDeclaration4.js b/tests/baselines/reference/destructuringParameterDeclaration4.js index 2f0f24ac123..44838d600d8 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration4.js +++ b/tests/baselines/reference/destructuringParameterDeclaration4.js @@ -27,7 +27,7 @@ a6([1, 2, "string"]); // Error, parameter type is number[] var temp = [1, 2, 3]; class C { - constructor(public ...temp) { } // Error, rest parameter can't have accessibilityModifier + constructor(public ...temp) { } // Error, rest parameter can't have properties } // Rest parameter with generic @@ -83,12 +83,13 @@ a5([1, 2]); // Error, parameter type is [any, any, [[any]]] a6([1, 2, "string"]); // Error, parameter type is number[] var temp = [1, 2, 3]; var C = (function () { - function C(public) { + function C() { var temp = []; - for (var _i = 1; _i < arguments.length; _i++) { - temp[_i - 1] = arguments[_i]; + for (var _i = 0; _i < arguments.length; _i++) { + temp[_i - 0] = arguments[_i]; } - } // Error, rest parameter can't have accessibilityModifier + this.temp = temp; + } // Error, rest parameter can't have properties return C; }()); // Rest parameter with generic diff --git a/tests/baselines/reference/destructuringParameterProperties1.errors.txt b/tests/baselines/reference/destructuringParameterProperties1.errors.txt index b8f3a22b4c5..09d44a64a62 100644 --- a/tests/baselines/reference/destructuringParameterProperties1.errors.txt +++ b/tests/baselines/reference/destructuringParameterProperties1.errors.txt @@ -1,6 +1,6 @@ -tests/cases/conformance/es6/destructuring/destructuringParameterProperties1.ts(2,17): error TS1187: A parameter property may not be a binding pattern. -tests/cases/conformance/es6/destructuring/destructuringParameterProperties1.ts(9,17): error TS1187: A parameter property may not be a binding pattern. -tests/cases/conformance/es6/destructuring/destructuringParameterProperties1.ts(16,17): error TS1187: A parameter property may not be a binding pattern. +tests/cases/conformance/es6/destructuring/destructuringParameterProperties1.ts(2,17): error TS1187: A parameter property may not be declared using a binding pattern. +tests/cases/conformance/es6/destructuring/destructuringParameterProperties1.ts(9,17): error TS1187: A parameter property may not be declared using a binding pattern. +tests/cases/conformance/es6/destructuring/destructuringParameterProperties1.ts(16,17): error TS1187: A parameter property may not be declared using a binding pattern. tests/cases/conformance/es6/destructuring/destructuringParameterProperties1.ts(22,26): error TS2339: Property 'x' does not exist on type 'C1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties1.ts(22,35): error TS2339: Property 'y' does not exist on type 'C1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties1.ts(22,43): error TS2339: Property 'y' does not exist on type 'C1'. @@ -17,7 +17,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterProperties1.ts(2 class C1 { constructor(public [x, y, z]: string[]) { ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS1187: A parameter property may not be a binding pattern. +!!! error TS1187: A parameter property may not be declared using a binding pattern. } } @@ -26,7 +26,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterProperties1.ts(2 class C2 { constructor(public [x, y, z]: TupleType1) { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS1187: A parameter property may not be a binding pattern. +!!! error TS1187: A parameter property may not be declared using a binding pattern. } } @@ -35,7 +35,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterProperties1.ts(2 class C3 { constructor(public { x, y, z }: ObjType1) { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS1187: A parameter property may not be a binding pattern. +!!! error TS1187: A parameter property may not be declared using a binding pattern. } } diff --git a/tests/baselines/reference/destructuringParameterProperties2.errors.txt b/tests/baselines/reference/destructuringParameterProperties2.errors.txt index bc7588a853d..ec0f400631f 100644 --- a/tests/baselines/reference/destructuringParameterProperties2.errors.txt +++ b/tests/baselines/reference/destructuringParameterProperties2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/destructuring/destructuringParameterProperties2.ts(2,36): error TS1187: A parameter property may not be a binding pattern. +tests/cases/conformance/es6/destructuring/destructuringParameterProperties2.ts(2,36): error TS1187: A parameter property may not be declared using a binding pattern. tests/cases/conformance/es6/destructuring/destructuringParameterProperties2.ts(3,59): error TS2339: Property 'b' does not exist on type 'C1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties2.ts(3,83): error TS2339: Property 'c' does not exist on type 'C1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties2.ts(4,18): error TS2339: Property 'a' does not exist on type 'C1'. @@ -14,7 +14,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterProperties2.ts(2 class C1 { constructor(private k: number, private [a, b, c]: [number, string, boolean]) { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS1187: A parameter property may not be a binding pattern. +!!! error TS1187: A parameter property may not be declared using a binding pattern. if ((b === undefined && c === undefined) || (this.b === undefined && this.c === undefined)) { ~ !!! error TS2339: Property 'b' does not exist on type 'C1'. diff --git a/tests/baselines/reference/destructuringParameterProperties3.errors.txt b/tests/baselines/reference/destructuringParameterProperties3.errors.txt index 73d7dab2a38..cbd2d089c71 100644 --- a/tests/baselines/reference/destructuringParameterProperties3.errors.txt +++ b/tests/baselines/reference/destructuringParameterProperties3.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/destructuring/destructuringParameterProperties3.ts(2,31): error TS1187: A parameter property may not be a binding pattern. +tests/cases/conformance/es6/destructuring/destructuringParameterProperties3.ts(2,31): error TS1187: A parameter property may not be declared using a binding pattern. tests/cases/conformance/es6/destructuring/destructuringParameterProperties3.ts(3,59): error TS2339: Property 'b' does not exist on type 'C1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties3.ts(3,83): error TS2339: Property 'c' does not exist on type 'C1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties3.ts(4,18): error TS2339: Property 'a' does not exist on type 'C1'. @@ -11,7 +11,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterProperties3.ts(1 class C1 { constructor(private k: T, private [a, b, c]: [T,U,V]) { ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS1187: A parameter property may not be a binding pattern. +!!! error TS1187: A parameter property may not be declared using a binding pattern. if ((b === undefined && c === undefined) || (this.b === undefined && this.c === undefined)) { ~ !!! error TS2339: Property 'b' does not exist on type 'C1'. diff --git a/tests/baselines/reference/destructuringParameterProperties4.errors.txt b/tests/baselines/reference/destructuringParameterProperties4.errors.txt index 04f6f82b5df..249cecbc74f 100644 --- a/tests/baselines/reference/destructuringParameterProperties4.errors.txt +++ b/tests/baselines/reference/destructuringParameterProperties4.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/destructuring/destructuringParameterProperties4.ts(3,31): error TS1187: A parameter property may not be a binding pattern. +tests/cases/conformance/es6/destructuring/destructuringParameterProperties4.ts(3,31): error TS1187: A parameter property may not be declared using a binding pattern. tests/cases/conformance/es6/destructuring/destructuringParameterProperties4.ts(4,59): error TS2339: Property 'b' does not exist on type 'C1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties4.ts(4,83): error TS2339: Property 'c' does not exist on type 'C1'. tests/cases/conformance/es6/destructuring/destructuringParameterProperties4.ts(5,18): error TS2339: Property 'a' does not exist on type 'C1'. @@ -15,7 +15,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterProperties4.ts(2 class C1 { constructor(private k: T, protected [a, b, c]: [T,U,V]) { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS1187: A parameter property may not be a binding pattern. +!!! error TS1187: A parameter property may not be declared using a binding pattern. if ((b === undefined && c === undefined) || (this.b === undefined && this.c === undefined)) { ~ !!! error TS2339: Property 'b' does not exist on type 'C1'. diff --git a/tests/baselines/reference/destructuringParameterProperties5.errors.txt b/tests/baselines/reference/destructuringParameterProperties5.errors.txt index cfb38fde90b..6f5801b7898 100644 --- a/tests/baselines/reference/destructuringParameterProperties5.errors.txt +++ b/tests/baselines/reference/destructuringParameterProperties5.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,17): error TS1187: A parameter property may not be a binding pattern. +tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,17): error TS1187: A parameter property may not be declared using a binding pattern. tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,27): error TS2459: Type '{ x: number; y: string; z: boolean; }' has no property 'x1' and no string index signature. tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,31): error TS2459: Type '{ x: number; y: string; z: boolean; }' has no property 'x2' and no string index signature. tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(5,35): error TS2459: Type '{ x: number; y: string; z: boolean; }' has no property 'x3' and no string index signature. @@ -20,7 +20,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterProperties5.ts(1 class C1 { constructor(public [{ x1, x2, x3 }, y, z]: TupleType1) { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS1187: A parameter property may not be a binding pattern. +!!! error TS1187: A parameter property may not be declared using a binding pattern. ~~ !!! error TS2459: Type '{ x: number; y: string; z: boolean; }' has no property 'x1' and no string index signature. ~~ diff --git a/tests/baselines/reference/inferParameterWithMethodCallInitializer.symbols b/tests/baselines/reference/inferParameterWithMethodCallInitializer.symbols index e0734a4b39b..ce098f6e243 100644 --- a/tests/baselines/reference/inferParameterWithMethodCallInitializer.symbols +++ b/tests/baselines/reference/inferParameterWithMethodCallInitializer.symbols @@ -30,7 +30,7 @@ function weird(this: Example, a = this.getNumber()) { >Example : Symbol(Example, Decl(inferParameterWithMethodCallInitializer.ts, 2, 1)) >a : Symbol(a, Decl(inferParameterWithMethodCallInitializer.ts, 11, 29)) >this.getNumber : Symbol(Example.getNumber, Decl(inferParameterWithMethodCallInitializer.ts, 3, 15)) ->this : Symbol(Example, Decl(inferParameterWithMethodCallInitializer.ts, 2, 1)) +>this : Symbol(this, Decl(inferParameterWithMethodCallInitializer.ts, 11, 15)) >getNumber : Symbol(Example.getNumber, Decl(inferParameterWithMethodCallInitializer.ts, 3, 15)) return a; @@ -45,7 +45,7 @@ class Weird { >Example : Symbol(Example, Decl(inferParameterWithMethodCallInitializer.ts, 2, 1)) >a : Symbol(a, Decl(inferParameterWithMethodCallInitializer.ts, 15, 30)) >this.getNumber : Symbol(Example.getNumber, Decl(inferParameterWithMethodCallInitializer.ts, 3, 15)) ->this : Symbol(Example, Decl(inferParameterWithMethodCallInitializer.ts, 2, 1)) +>this : Symbol(this, Decl(inferParameterWithMethodCallInitializer.ts, 15, 16)) >getNumber : Symbol(Example.getNumber, Decl(inferParameterWithMethodCallInitializer.ts, 3, 15)) return a; diff --git a/tests/baselines/reference/inferenceLimit.symbols b/tests/baselines/reference/inferenceLimit.symbols index bedea9ce1f0..4601de27b51 100644 --- a/tests/baselines/reference/inferenceLimit.symbols +++ b/tests/baselines/reference/inferenceLimit.symbols @@ -37,14 +37,14 @@ export class BrokenClass { >reject : Symbol(reject, Decl(file1.ts, 13, 34)) this.doStuff(order.id) ->this.doStuff(order.id) .then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>this.doStuff(order.id) .then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) >this.doStuff : Symbol(BrokenClass.doStuff, Decl(file1.ts, 27, 3)) >this : Symbol(BrokenClass, Decl(file1.ts, 1, 39)) >doStuff : Symbol(BrokenClass.doStuff, Decl(file1.ts, 27, 3)) >order : Symbol(order, Decl(file1.ts, 12, 25)) .then((items) => { ->then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) >items : Symbol(items, Decl(file1.ts, 15, 17)) order.items = items; @@ -60,17 +60,17 @@ export class BrokenClass { }; return Promise.all(result.map(populateItems)) ->Promise.all(result.map(populateItems)) .then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) ->Promise.all : Symbol(PromiseConstructor.all, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>Promise.all(result.map(populateItems)) .then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>Promise.all : Symbol(PromiseConstructor.all, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) >Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) ->all : Symbol(PromiseConstructor.all, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>all : Symbol(PromiseConstructor.all, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) >result.map : Symbol(Array.map, Decl(lib.es5.d.ts, --, --)) >result : Symbol(result, Decl(file1.ts, 10, 7)) >map : Symbol(Array.map, Decl(lib.es5.d.ts, --, --)) >populateItems : Symbol(populateItems, Decl(file1.ts, 12, 7)) .then((orders: Array) => { ->then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) >orders : Symbol(orders, Decl(file1.ts, 23, 13)) >Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --)) >MyModule : Symbol(MyModule, Decl(file1.ts, 1, 6)) diff --git a/tests/baselines/reference/inferenceLimit.types b/tests/baselines/reference/inferenceLimit.types index 58f9b1e4ae0..37b51e49644 100644 --- a/tests/baselines/reference/inferenceLimit.types +++ b/tests/baselines/reference/inferenceLimit.types @@ -46,7 +46,7 @@ export class BrokenClass { this.doStuff(order.id) >this.doStuff(order.id) .then((items) => { order.items = items; resolve(order); }) : Promise ->this.doStuff(order.id) .then : { (onfulfilled?: (value: void) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled?: (value: void) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; } +>this.doStuff(order.id) .then : { (onfulfilled: (value: void) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: void) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: void) => TResult | PromiseLike): Promise; (): Promise; } >this.doStuff(order.id) : Promise >this.doStuff : (id: number) => Promise >this : this @@ -56,7 +56,7 @@ export class BrokenClass { >id : any .then((items) => { ->then : { (onfulfilled?: (value: void) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled?: (value: void) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; } +>then : { (onfulfilled: (value: void) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: void) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: void) => TResult | PromiseLike): Promise; (): Promise; } >(items) => { order.items = items; resolve(order); } : (items: void) => void >items : void @@ -78,11 +78,11 @@ export class BrokenClass { return Promise.all(result.map(populateItems)) >Promise.all(result.map(populateItems)) .then((orders: Array) => { resolve(orders); }) : Promise ->Promise.all(result.map(populateItems)) .then : { (onfulfilled?: (value: {}[]) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled?: (value: {}[]) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; } +>Promise.all(result.map(populateItems)) .then : { (onfulfilled: (value: {}[]) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: {}[]) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: {}[]) => TResult | PromiseLike): Promise; (): Promise<{}[]>; } >Promise.all(result.map(populateItems)) : Promise<{}[]> ->Promise.all : { (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise<[T1, T2, T3, T4]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; (values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; (values: Iterable>): Promise; } +>Promise.all : { (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise<[T1, T2, T3, T4]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; (values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; (values: (T | PromiseLike)[]): Promise; (values: Iterable>): Promise; } >Promise : PromiseConstructor ->all : { (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise<[T1, T2, T3, T4]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; (values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; (values: Iterable>): Promise; } +>all : { (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise<[T1, T2, T3, T4]>; (values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; (values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; (values: (T | PromiseLike)[]): Promise; (values: Iterable>): Promise; } >result.map(populateItems) : Promise<{}>[] >result.map : (callbackfn: (value: MyModule.MyModel, index: number, array: MyModule.MyModel[]) => U, thisArg?: any) => U[] >result : MyModule.MyModel[] @@ -90,7 +90,7 @@ export class BrokenClass { >populateItems : (order: any) => Promise<{}> .then((orders: Array) => { ->then : { (onfulfilled?: (value: {}[]) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled?: (value: {}[]) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; } +>then : { (onfulfilled: (value: {}[]) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: {}[]) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: {}[]) => TResult | PromiseLike): Promise; (): Promise<{}[]>; } >(orders: Array) => { resolve(orders); } : (orders: MyModule.MyModel[]) => void >orders : MyModule.MyModel[] >Array : T[] diff --git a/tests/baselines/reference/intersectionTypeReadonly.errors.txt b/tests/baselines/reference/intersectionTypeReadonly.errors.txt new file mode 100644 index 00000000000..d9e22fd2223 --- /dev/null +++ b/tests/baselines/reference/intersectionTypeReadonly.errors.txt @@ -0,0 +1,44 @@ +tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts(17,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts(19,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts(21,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts(23,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts(25,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + + +==== tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts (5 errors) ==== + interface Base { + readonly value: number; + } + interface Identical { + readonly value: number; + } + interface Mutable { + value: number; + } + interface DifferentType { + readonly value: string; + } + interface DifferentName { + readonly other: number; + } + let base: Base; + base.value = 12 // error, lhs can't be a readonly property + ~~~~~~~~~~ +!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + let identical: Base & Identical; + identical.value = 12; // error, lhs can't be a readonly property + ~~~~~~~~~~~~~~~ +!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + let mutable: Base & Mutable; + mutable.value = 12; // error, lhs can't be a readonly property + ~~~~~~~~~~~~~ +!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + let differentType: Base & DifferentType; + differentType.value = 12; // error, lhs can't be a readonly property + ~~~~~~~~~~~~~~~~~~~ +!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + let differentName: Base & DifferentName; + differentName.value = 12; // error, property 'value' doesn't exist + ~~~~~~~~~~~~~~~~~~~ +!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + \ No newline at end of file diff --git a/tests/baselines/reference/intersectionTypeReadonly.js b/tests/baselines/reference/intersectionTypeReadonly.js new file mode 100644 index 00000000000..7399125bbb1 --- /dev/null +++ b/tests/baselines/reference/intersectionTypeReadonly.js @@ -0,0 +1,39 @@ +//// [intersectionTypeReadonly.ts] +interface Base { + readonly value: number; +} +interface Identical { + readonly value: number; +} +interface Mutable { + value: number; +} +interface DifferentType { + readonly value: string; +} +interface DifferentName { + readonly other: number; +} +let base: Base; +base.value = 12 // error, lhs can't be a readonly property +let identical: Base & Identical; +identical.value = 12; // error, lhs can't be a readonly property +let mutable: Base & Mutable; +mutable.value = 12; // error, lhs can't be a readonly property +let differentType: Base & DifferentType; +differentType.value = 12; // error, lhs can't be a readonly property +let differentName: Base & DifferentName; +differentName.value = 12; // error, property 'value' doesn't exist + + +//// [intersectionTypeReadonly.js] +var base; +base.value = 12; // error, lhs can't be a readonly property +var identical; +identical.value = 12; // error, lhs can't be a readonly property +var mutable; +mutable.value = 12; // error, lhs can't be a readonly property +var differentType; +differentType.value = 12; // error, lhs can't be a readonly property +var differentName; +differentName.value = 12; // error, property 'value' doesn't exist diff --git a/tests/baselines/reference/jsFileClassSelfReferencedProperty.symbols b/tests/baselines/reference/jsFileClassSelfReferencedProperty.symbols new file mode 100644 index 00000000000..2d9626897bf --- /dev/null +++ b/tests/baselines/reference/jsFileClassSelfReferencedProperty.symbols @@ -0,0 +1,17 @@ +=== tests/cases/compiler/foo.js === + +export class StackOverflowTest { +>StackOverflowTest : Symbol(StackOverflowTest, Decl(foo.js, 0, 0)) + + constructor () { + this.testStackOverflow = this.testStackOverflow.bind(this) +>this.testStackOverflow : Symbol(StackOverflowTest.testStackOverflow, Decl(foo.js, 2, 18)) +>this : Symbol(StackOverflowTest, Decl(foo.js, 0, 0)) +>testStackOverflow : Symbol(StackOverflowTest.testStackOverflow, Decl(foo.js, 2, 18)) +>this.testStackOverflow : Symbol(StackOverflowTest.testStackOverflow, Decl(foo.js, 2, 18)) +>this : Symbol(StackOverflowTest, Decl(foo.js, 0, 0)) +>testStackOverflow : Symbol(StackOverflowTest.testStackOverflow, Decl(foo.js, 2, 18)) +>this : Symbol(StackOverflowTest, Decl(foo.js, 0, 0)) + } +} + diff --git a/tests/baselines/reference/jsFileClassSelfReferencedProperty.types b/tests/baselines/reference/jsFileClassSelfReferencedProperty.types new file mode 100644 index 00000000000..44344ac1472 --- /dev/null +++ b/tests/baselines/reference/jsFileClassSelfReferencedProperty.types @@ -0,0 +1,21 @@ +=== tests/cases/compiler/foo.js === + +export class StackOverflowTest { +>StackOverflowTest : StackOverflowTest + + constructor () { + this.testStackOverflow = this.testStackOverflow.bind(this) +>this.testStackOverflow = this.testStackOverflow.bind(this) : any +>this.testStackOverflow : any +>this : this +>testStackOverflow : any +>this.testStackOverflow.bind(this) : any +>this.testStackOverflow.bind : any +>this.testStackOverflow : any +>this : this +>testStackOverflow : any +>bind : any +>this : this + } +} + diff --git a/tests/baselines/reference/letDeclarations-useBeforeDefinition2.symbols b/tests/baselines/reference/letDeclarations-useBeforeDefinition2.symbols deleted file mode 100644 index c5a067ede4d..00000000000 --- a/tests/baselines/reference/letDeclarations-useBeforeDefinition2.symbols +++ /dev/null @@ -1,9 +0,0 @@ -=== tests/cases/compiler/file1.ts === - -l; ->l : Symbol(l, Decl(file2.ts, 0, 5)) - -=== tests/cases/compiler/file2.ts === -const l = 0; ->l : Symbol(l, Decl(file2.ts, 0, 5)) - diff --git a/tests/baselines/reference/letDeclarations-useBeforeDefinition2.types b/tests/baselines/reference/letDeclarations-useBeforeDefinition2.types deleted file mode 100644 index 793a7a78ba7..00000000000 --- a/tests/baselines/reference/letDeclarations-useBeforeDefinition2.types +++ /dev/null @@ -1,10 +0,0 @@ -=== tests/cases/compiler/file1.ts === - -l; ->l : number - -=== tests/cases/compiler/file2.ts === -const l = 0; ->l : number ->0 : number - diff --git a/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions1.symbols b/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions1.symbols index 3bbe91bc9fa..d8520698e6c 100644 --- a/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions1.symbols +++ b/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions1.symbols @@ -121,9 +121,9 @@ declare var console: any; >console : Symbol(console, Decl(modularizeLibrary_NoErrorDuplicateLibOptions1.ts, 52, 11)) out().then(() => { ->out().then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>out().then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) >out : Symbol(out, Decl(modularizeLibrary_NoErrorDuplicateLibOptions1.ts, 45, 37)) ->then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) console.log("Yea!"); >console : Symbol(console, Decl(modularizeLibrary_NoErrorDuplicateLibOptions1.ts, 52, 11)) diff --git a/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions1.types b/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions1.types index 16051c14b7c..e0d0c492f4d 100644 --- a/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions1.types +++ b/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions1.types @@ -148,10 +148,10 @@ declare var console: any; out().then(() => { >out().then(() => { console.log("Yea!");}) : Promise ->out().then : { (onfulfilled?: (value: {}) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled?: (value: {}) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; } +>out().then : { (onfulfilled: (value: {}) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: {}) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: {}) => TResult | PromiseLike): Promise; (): Promise<{}>; } >out() : Promise<{}> >out : () => Promise<{}> ->then : { (onfulfilled?: (value: {}) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled?: (value: {}) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; } +>then : { (onfulfilled: (value: {}) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: {}) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: {}) => TResult | PromiseLike): Promise; (): Promise<{}>; } >() => { console.log("Yea!");} : () => void console.log("Yea!"); diff --git a/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions2.symbols b/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions2.symbols index 89cb8fe7179..ea1eb599c6f 100644 --- a/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions2.symbols +++ b/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions2.symbols @@ -121,9 +121,9 @@ declare var console: any; >console : Symbol(console, Decl(modularizeLibrary_NoErrorDuplicateLibOptions2.ts, 52, 11)) out().then(() => { ->out().then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>out().then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) >out : Symbol(out, Decl(modularizeLibrary_NoErrorDuplicateLibOptions2.ts, 45, 37)) ->then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) console.log("Yea!"); >console : Symbol(console, Decl(modularizeLibrary_NoErrorDuplicateLibOptions2.ts, 52, 11)) diff --git a/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions2.types b/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions2.types index a7d8e77e28c..21e658e29ce 100644 --- a/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions2.types +++ b/tests/baselines/reference/modularizeLibrary_NoErrorDuplicateLibOptions2.types @@ -148,10 +148,10 @@ declare var console: any; out().then(() => { >out().then(() => { console.log("Yea!");}) : Promise ->out().then : { (onfulfilled?: (value: {}) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled?: (value: {}) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; } +>out().then : { (onfulfilled: (value: {}) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: {}) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: {}) => TResult | PromiseLike): Promise; (): Promise<{}>; } >out() : Promise<{}> >out : () => Promise<{}> ->then : { (onfulfilled?: (value: {}) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled?: (value: {}) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; } +>then : { (onfulfilled: (value: {}) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: {}) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: {}) => TResult | PromiseLike): Promise; (): Promise<{}>; } >() => { console.log("Yea!");} : () => void console.log("Yea!"); diff --git a/tests/baselines/reference/modularizeLibrary_TargetES5UsingES6Lib.symbols b/tests/baselines/reference/modularizeLibrary_TargetES5UsingES6Lib.symbols index c8ccdd98653..ed1fb96ded3 100644 --- a/tests/baselines/reference/modularizeLibrary_TargetES5UsingES6Lib.symbols +++ b/tests/baselines/reference/modularizeLibrary_TargetES5UsingES6Lib.symbols @@ -121,9 +121,9 @@ declare var console: any; >console : Symbol(console, Decl(modularizeLibrary_TargetES5UsingES6Lib.ts, 52, 11)) out().then(() => { ->out().then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>out().then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) >out : Symbol(out, Decl(modularizeLibrary_TargetES5UsingES6Lib.ts, 45, 37)) ->then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) console.log("Yea!"); >console : Symbol(console, Decl(modularizeLibrary_TargetES5UsingES6Lib.ts, 52, 11)) diff --git a/tests/baselines/reference/modularizeLibrary_TargetES5UsingES6Lib.types b/tests/baselines/reference/modularizeLibrary_TargetES5UsingES6Lib.types index 8272465da5e..24ff905f166 100644 --- a/tests/baselines/reference/modularizeLibrary_TargetES5UsingES6Lib.types +++ b/tests/baselines/reference/modularizeLibrary_TargetES5UsingES6Lib.types @@ -148,10 +148,10 @@ declare var console: any; out().then(() => { >out().then(() => { console.log("Yea!");}) : Promise ->out().then : { (onfulfilled?: (value: {}) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled?: (value: {}) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; } +>out().then : { (onfulfilled: (value: {}) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: {}) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: {}) => TResult | PromiseLike): Promise; (): Promise<{}>; } >out() : Promise<{}> >out : () => Promise<{}> ->then : { (onfulfilled?: (value: {}) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled?: (value: {}) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; } +>then : { (onfulfilled: (value: {}) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: {}) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: {}) => TResult | PromiseLike): Promise; (): Promise<{}>; } >() => { console.log("Yea!");} : () => void console.log("Yea!"); diff --git a/tests/baselines/reference/parser509668.errors.txt b/tests/baselines/reference/parser509668.errors.txt index 5ea380592ef..f83c53db449 100644 --- a/tests/baselines/reference/parser509668.errors.txt +++ b/tests/baselines/reference/parser509668.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/parser/ecmascript5/RegressionTests/parser509668.ts(3,23): error TS1005: ',' expected. +tests/cases/conformance/parser/ecmascript5/RegressionTests/parser509668.ts(3,16): error TS1317: A parameter property cannot be declared using a rest parameter. ==== tests/cases/conformance/parser/ecmascript5/RegressionTests/parser509668.ts (1 errors) ==== class Foo3 { // Doesn't work, but should constructor (public ...args: string[]) { } - ~~~ -!!! error TS1005: ',' expected. + ~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS1317: A parameter property cannot be declared using a rest parameter. } \ No newline at end of file diff --git a/tests/baselines/reference/parser509668.js b/tests/baselines/reference/parser509668.js index 97a51d8a5e7..c767aea676a 100644 --- a/tests/baselines/reference/parser509668.js +++ b/tests/baselines/reference/parser509668.js @@ -7,11 +7,12 @@ class Foo3 { //// [parser509668.js] var Foo3 = (function () { // Doesn't work, but should - function Foo3(public) { + function Foo3() { var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; } + this.args = args; } return Foo3; }()); diff --git a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/amd/emitDecoratorMetadataCommonJSISolatedModules.errors.txt b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/amd/emitDecoratorMetadataCommonJSISolatedModules.errors.txt new file mode 100644 index 00000000000..d6d803104c9 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/amd/emitDecoratorMetadataCommonJSISolatedModules.errors.txt @@ -0,0 +1,14 @@ +main.ts(1,21): error TS2307: Cannot find module 'angular2/core'. + + +==== main.ts (1 errors) ==== + import * as ng from "angular2/core"; + ~~~~~~~~~~~~~~~ +!!! error TS2307: Cannot find module 'angular2/core'. + + declare function foo(...args: any[]); + + @foo + export class MyClass1 { + constructor(private _elementRef: ng.ElementRef){} + } \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/amd/emitDecoratorMetadataCommonJSISolatedModules.json b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/amd/emitDecoratorMetadataCommonJSISolatedModules.json new file mode 100644 index 00000000000..470c5bf1301 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/amd/emitDecoratorMetadataCommonJSISolatedModules.json @@ -0,0 +1,13 @@ +{ + "scenario": "Emit decorator metadata when commonJS and isolatedModules are on", + "projectRoot": "tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModule", + "baselineCheck": true, + "runTest": true, + "resolvedInputFiles": [ + "lib.d.ts", + "main.ts" + ], + "emittedFiles": [ + "main.js" + ] +} \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/amd/main.js b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/amd/main.js new file mode 100644 index 00000000000..41ab9194c4e --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/amd/main.js @@ -0,0 +1,24 @@ +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define(["require", "exports", "angular2/core"], function (require, exports, ng) { + "use strict"; + var MyClass1 = (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } + MyClass1 = __decorate([ + foo, + __metadata('design:paramtypes', [(typeof (_a = typeof ng !== 'undefined' && ng.ElementRef) === 'function' && _a) || Object]) + ], MyClass1); + return MyClass1; + var _a; + }()); + exports.MyClass1 = MyClass1; +}); diff --git a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/node/emitDecoratorMetadataCommonJSISolatedModules.errors.txt b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/node/emitDecoratorMetadataCommonJSISolatedModules.errors.txt new file mode 100644 index 00000000000..d6d803104c9 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/node/emitDecoratorMetadataCommonJSISolatedModules.errors.txt @@ -0,0 +1,14 @@ +main.ts(1,21): error TS2307: Cannot find module 'angular2/core'. + + +==== main.ts (1 errors) ==== + import * as ng from "angular2/core"; + ~~~~~~~~~~~~~~~ +!!! error TS2307: Cannot find module 'angular2/core'. + + declare function foo(...args: any[]); + + @foo + export class MyClass1 { + constructor(private _elementRef: ng.ElementRef){} + } \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/node/emitDecoratorMetadataCommonJSISolatedModules.json b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/node/emitDecoratorMetadataCommonJSISolatedModules.json new file mode 100644 index 00000000000..470c5bf1301 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/node/emitDecoratorMetadataCommonJSISolatedModules.json @@ -0,0 +1,13 @@ +{ + "scenario": "Emit decorator metadata when commonJS and isolatedModules are on", + "projectRoot": "tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModule", + "baselineCheck": true, + "runTest": true, + "resolvedInputFiles": [ + "lib.d.ts", + "main.ts" + ], + "emittedFiles": [ + "main.js" + ] +} \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/node/main.js b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/node/main.js new file mode 100644 index 00000000000..e8bd90fc475 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModules/node/main.js @@ -0,0 +1,23 @@ +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +var ng = require("angular2/core"); +var MyClass1 = (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } + MyClass1 = __decorate([ + foo, + __metadata('design:paramtypes', [(typeof (_a = typeof ng !== 'undefined' && ng.ElementRef) === 'function' && _a) || Object]) + ], MyClass1); + return MyClass1; + var _a; +}()); +exports.MyClass1 = MyClass1; diff --git a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/amd/emitDecoratorMetadataCommonJSISolatedModulesNoResolve.errors.txt b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/amd/emitDecoratorMetadataCommonJSISolatedModulesNoResolve.errors.txt new file mode 100644 index 00000000000..d6d803104c9 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/amd/emitDecoratorMetadataCommonJSISolatedModulesNoResolve.errors.txt @@ -0,0 +1,14 @@ +main.ts(1,21): error TS2307: Cannot find module 'angular2/core'. + + +==== main.ts (1 errors) ==== + import * as ng from "angular2/core"; + ~~~~~~~~~~~~~~~ +!!! error TS2307: Cannot find module 'angular2/core'. + + declare function foo(...args: any[]); + + @foo + export class MyClass1 { + constructor(private _elementRef: ng.ElementRef){} + } \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/amd/emitDecoratorMetadataCommonJSISolatedModulesNoResolve.json b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/amd/emitDecoratorMetadataCommonJSISolatedModulesNoResolve.json new file mode 100644 index 00000000000..91749c0e189 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/amd/emitDecoratorMetadataCommonJSISolatedModulesNoResolve.json @@ -0,0 +1,13 @@ +{ + "scenario": "Emit decorator metadata when commonJS and isolatedModules are on", + "projectRoot": "tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModuleNoResolve", + "baselineCheck": true, + "runTest": true, + "resolvedInputFiles": [ + "lib.d.ts", + "main.ts" + ], + "emittedFiles": [ + "main.js" + ] +} \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/amd/main.js b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/amd/main.js new file mode 100644 index 00000000000..41ab9194c4e --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/amd/main.js @@ -0,0 +1,24 @@ +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define(["require", "exports", "angular2/core"], function (require, exports, ng) { + "use strict"; + var MyClass1 = (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } + MyClass1 = __decorate([ + foo, + __metadata('design:paramtypes', [(typeof (_a = typeof ng !== 'undefined' && ng.ElementRef) === 'function' && _a) || Object]) + ], MyClass1); + return MyClass1; + var _a; + }()); + exports.MyClass1 = MyClass1; +}); diff --git a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/node/emitDecoratorMetadataCommonJSISolatedModulesNoResolve.errors.txt b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/node/emitDecoratorMetadataCommonJSISolatedModulesNoResolve.errors.txt new file mode 100644 index 00000000000..d6d803104c9 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/node/emitDecoratorMetadataCommonJSISolatedModulesNoResolve.errors.txt @@ -0,0 +1,14 @@ +main.ts(1,21): error TS2307: Cannot find module 'angular2/core'. + + +==== main.ts (1 errors) ==== + import * as ng from "angular2/core"; + ~~~~~~~~~~~~~~~ +!!! error TS2307: Cannot find module 'angular2/core'. + + declare function foo(...args: any[]); + + @foo + export class MyClass1 { + constructor(private _elementRef: ng.ElementRef){} + } \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/node/emitDecoratorMetadataCommonJSISolatedModulesNoResolve.json b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/node/emitDecoratorMetadataCommonJSISolatedModulesNoResolve.json new file mode 100644 index 00000000000..91749c0e189 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/node/emitDecoratorMetadataCommonJSISolatedModulesNoResolve.json @@ -0,0 +1,13 @@ +{ + "scenario": "Emit decorator metadata when commonJS and isolatedModules are on", + "projectRoot": "tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModuleNoResolve", + "baselineCheck": true, + "runTest": true, + "resolvedInputFiles": [ + "lib.d.ts", + "main.ts" + ], + "emittedFiles": [ + "main.js" + ] +} \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/node/main.js b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/node/main.js new file mode 100644 index 00000000000..e8bd90fc475 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve/node/main.js @@ -0,0 +1,23 @@ +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +var ng = require("angular2/core"); +var MyClass1 = (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } + MyClass1 = __decorate([ + foo, + __metadata('design:paramtypes', [(typeof (_a = typeof ng !== 'undefined' && ng.ElementRef) === 'function' && _a) || Object]) + ], MyClass1); + return MyClass1; + var _a; +}()); +exports.MyClass1 = MyClass1; diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/amd/emitDecoratorMetadataSystemJS.errors.txt b/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/amd/emitDecoratorMetadataSystemJS.errors.txt new file mode 100644 index 00000000000..d6d803104c9 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/amd/emitDecoratorMetadataSystemJS.errors.txt @@ -0,0 +1,14 @@ +main.ts(1,21): error TS2307: Cannot find module 'angular2/core'. + + +==== main.ts (1 errors) ==== + import * as ng from "angular2/core"; + ~~~~~~~~~~~~~~~ +!!! error TS2307: Cannot find module 'angular2/core'. + + declare function foo(...args: any[]); + + @foo + export class MyClass1 { + constructor(private _elementRef: ng.ElementRef){} + } \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/amd/emitDecoratorMetadataSystemJS.json b/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/amd/emitDecoratorMetadataSystemJS.json new file mode 100644 index 00000000000..5b48b8fe70c --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/amd/emitDecoratorMetadataSystemJS.json @@ -0,0 +1,13 @@ +{ + "scenario": "Emit decorator metadata when commonJS and isolatedModules are on", + "projectRoot": "tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJS", + "baselineCheck": true, + "runTest": true, + "resolvedInputFiles": [ + "lib.d.ts", + "main.ts" + ], + "emittedFiles": [ + "main.js" + ] +} \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/amd/main.js b/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/amd/main.js new file mode 100644 index 00000000000..41ab9194c4e --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/amd/main.js @@ -0,0 +1,24 @@ +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define(["require", "exports", "angular2/core"], function (require, exports, ng) { + "use strict"; + var MyClass1 = (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } + MyClass1 = __decorate([ + foo, + __metadata('design:paramtypes', [(typeof (_a = typeof ng !== 'undefined' && ng.ElementRef) === 'function' && _a) || Object]) + ], MyClass1); + return MyClass1; + var _a; + }()); + exports.MyClass1 = MyClass1; +}); diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/node/emitDecoratorMetadataSystemJS.errors.txt b/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/node/emitDecoratorMetadataSystemJS.errors.txt new file mode 100644 index 00000000000..d6d803104c9 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/node/emitDecoratorMetadataSystemJS.errors.txt @@ -0,0 +1,14 @@ +main.ts(1,21): error TS2307: Cannot find module 'angular2/core'. + + +==== main.ts (1 errors) ==== + import * as ng from "angular2/core"; + ~~~~~~~~~~~~~~~ +!!! error TS2307: Cannot find module 'angular2/core'. + + declare function foo(...args: any[]); + + @foo + export class MyClass1 { + constructor(private _elementRef: ng.ElementRef){} + } \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/node/emitDecoratorMetadataSystemJS.json b/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/node/emitDecoratorMetadataSystemJS.json new file mode 100644 index 00000000000..5b48b8fe70c --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/node/emitDecoratorMetadataSystemJS.json @@ -0,0 +1,13 @@ +{ + "scenario": "Emit decorator metadata when commonJS and isolatedModules are on", + "projectRoot": "tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJS", + "baselineCheck": true, + "runTest": true, + "resolvedInputFiles": [ + "lib.d.ts", + "main.ts" + ], + "emittedFiles": [ + "main.js" + ] +} \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/node/main.js b/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/node/main.js new file mode 100644 index 00000000000..e8bd90fc475 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJS/node/main.js @@ -0,0 +1,23 @@ +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +var ng = require("angular2/core"); +var MyClass1 = (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } + MyClass1 = __decorate([ + foo, + __metadata('design:paramtypes', [(typeof (_a = typeof ng !== 'undefined' && ng.ElementRef) === 'function' && _a) || Object]) + ], MyClass1); + return MyClass1; + var _a; +}()); +exports.MyClass1 = MyClass1; diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/amd/emitDecoratorMetadataSystemJSISolatedModules.errors.txt b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/amd/emitDecoratorMetadataSystemJSISolatedModules.errors.txt new file mode 100644 index 00000000000..d6d803104c9 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/amd/emitDecoratorMetadataSystemJSISolatedModules.errors.txt @@ -0,0 +1,14 @@ +main.ts(1,21): error TS2307: Cannot find module 'angular2/core'. + + +==== main.ts (1 errors) ==== + import * as ng from "angular2/core"; + ~~~~~~~~~~~~~~~ +!!! error TS2307: Cannot find module 'angular2/core'. + + declare function foo(...args: any[]); + + @foo + export class MyClass1 { + constructor(private _elementRef: ng.ElementRef){} + } \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/amd/emitDecoratorMetadataSystemJSISolatedModules.json b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/amd/emitDecoratorMetadataSystemJSISolatedModules.json new file mode 100644 index 00000000000..a01c921fdd1 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/amd/emitDecoratorMetadataSystemJSISolatedModules.json @@ -0,0 +1,13 @@ +{ + "scenario": "Emit decorator metadata when commonJS and isolatedModules are on", + "projectRoot": "tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJSIsolatedModule", + "baselineCheck": true, + "runTest": true, + "resolvedInputFiles": [ + "lib.d.ts", + "main.ts" + ], + "emittedFiles": [ + "main.js" + ] +} \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/amd/main.js b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/amd/main.js new file mode 100644 index 00000000000..41ab9194c4e --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/amd/main.js @@ -0,0 +1,24 @@ +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define(["require", "exports", "angular2/core"], function (require, exports, ng) { + "use strict"; + var MyClass1 = (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } + MyClass1 = __decorate([ + foo, + __metadata('design:paramtypes', [(typeof (_a = typeof ng !== 'undefined' && ng.ElementRef) === 'function' && _a) || Object]) + ], MyClass1); + return MyClass1; + var _a; + }()); + exports.MyClass1 = MyClass1; +}); diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/node/emitDecoratorMetadataSystemJSISolatedModules.errors.txt b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/node/emitDecoratorMetadataSystemJSISolatedModules.errors.txt new file mode 100644 index 00000000000..d6d803104c9 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/node/emitDecoratorMetadataSystemJSISolatedModules.errors.txt @@ -0,0 +1,14 @@ +main.ts(1,21): error TS2307: Cannot find module 'angular2/core'. + + +==== main.ts (1 errors) ==== + import * as ng from "angular2/core"; + ~~~~~~~~~~~~~~~ +!!! error TS2307: Cannot find module 'angular2/core'. + + declare function foo(...args: any[]); + + @foo + export class MyClass1 { + constructor(private _elementRef: ng.ElementRef){} + } \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/node/emitDecoratorMetadataSystemJSISolatedModules.json b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/node/emitDecoratorMetadataSystemJSISolatedModules.json new file mode 100644 index 00000000000..a01c921fdd1 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/node/emitDecoratorMetadataSystemJSISolatedModules.json @@ -0,0 +1,13 @@ +{ + "scenario": "Emit decorator metadata when commonJS and isolatedModules are on", + "projectRoot": "tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJSIsolatedModule", + "baselineCheck": true, + "runTest": true, + "resolvedInputFiles": [ + "lib.d.ts", + "main.ts" + ], + "emittedFiles": [ + "main.js" + ] +} \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/node/main.js b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/node/main.js new file mode 100644 index 00000000000..e8bd90fc475 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModules/node/main.js @@ -0,0 +1,23 @@ +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +var ng = require("angular2/core"); +var MyClass1 = (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } + MyClass1 = __decorate([ + foo, + __metadata('design:paramtypes', [(typeof (_a = typeof ng !== 'undefined' && ng.ElementRef) === 'function' && _a) || Object]) + ], MyClass1); + return MyClass1; + var _a; +}()); +exports.MyClass1 = MyClass1; diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/amd/emitDecoratorMetadataSystemJSISolatedModulesNoResolve.errors.txt b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/amd/emitDecoratorMetadataSystemJSISolatedModulesNoResolve.errors.txt new file mode 100644 index 00000000000..d6d803104c9 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/amd/emitDecoratorMetadataSystemJSISolatedModulesNoResolve.errors.txt @@ -0,0 +1,14 @@ +main.ts(1,21): error TS2307: Cannot find module 'angular2/core'. + + +==== main.ts (1 errors) ==== + import * as ng from "angular2/core"; + ~~~~~~~~~~~~~~~ +!!! error TS2307: Cannot find module 'angular2/core'. + + declare function foo(...args: any[]); + + @foo + export class MyClass1 { + constructor(private _elementRef: ng.ElementRef){} + } \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/amd/emitDecoratorMetadataSystemJSISolatedModulesNoResolve.json b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/amd/emitDecoratorMetadataSystemJSISolatedModulesNoResolve.json new file mode 100644 index 00000000000..14eafad1200 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/amd/emitDecoratorMetadataSystemJSISolatedModulesNoResolve.json @@ -0,0 +1,13 @@ +{ + "scenario": "Emit decorator metadata when commonJS and isolatedModules are on", + "projectRoot": "tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJSIsolatedModuleNoResolve", + "baselineCheck": true, + "runTest": true, + "resolvedInputFiles": [ + "lib.d.ts", + "main.ts" + ], + "emittedFiles": [ + "main.js" + ] +} \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/amd/main.js b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/amd/main.js new file mode 100644 index 00000000000..41ab9194c4e --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/amd/main.js @@ -0,0 +1,24 @@ +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +define(["require", "exports", "angular2/core"], function (require, exports, ng) { + "use strict"; + var MyClass1 = (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } + MyClass1 = __decorate([ + foo, + __metadata('design:paramtypes', [(typeof (_a = typeof ng !== 'undefined' && ng.ElementRef) === 'function' && _a) || Object]) + ], MyClass1); + return MyClass1; + var _a; + }()); + exports.MyClass1 = MyClass1; +}); diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/node/emitDecoratorMetadataSystemJSISolatedModulesNoResolve.errors.txt b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/node/emitDecoratorMetadataSystemJSISolatedModulesNoResolve.errors.txt new file mode 100644 index 00000000000..d6d803104c9 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/node/emitDecoratorMetadataSystemJSISolatedModulesNoResolve.errors.txt @@ -0,0 +1,14 @@ +main.ts(1,21): error TS2307: Cannot find module 'angular2/core'. + + +==== main.ts (1 errors) ==== + import * as ng from "angular2/core"; + ~~~~~~~~~~~~~~~ +!!! error TS2307: Cannot find module 'angular2/core'. + + declare function foo(...args: any[]); + + @foo + export class MyClass1 { + constructor(private _elementRef: ng.ElementRef){} + } \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/node/emitDecoratorMetadataSystemJSISolatedModulesNoResolve.json b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/node/emitDecoratorMetadataSystemJSISolatedModulesNoResolve.json new file mode 100644 index 00000000000..14eafad1200 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/node/emitDecoratorMetadataSystemJSISolatedModulesNoResolve.json @@ -0,0 +1,13 @@ +{ + "scenario": "Emit decorator metadata when commonJS and isolatedModules are on", + "projectRoot": "tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJSIsolatedModuleNoResolve", + "baselineCheck": true, + "runTest": true, + "resolvedInputFiles": [ + "lib.d.ts", + "main.ts" + ], + "emittedFiles": [ + "main.js" + ] +} \ No newline at end of file diff --git a/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/node/main.js b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/node/main.js new file mode 100644 index 00000000000..e8bd90fc475 --- /dev/null +++ b/tests/baselines/reference/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve/node/main.js @@ -0,0 +1,23 @@ +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +var ng = require("angular2/core"); +var MyClass1 = (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } + MyClass1 = __decorate([ + foo, + __metadata('design:paramtypes', [(typeof (_a = typeof ng !== 'undefined' && ng.ElementRef) === 'function' && _a) || Object]) + ], MyClass1); + return MyClass1; + var _a; +}()); +exports.MyClass1 = MyClass1; diff --git a/tests/baselines/reference/promiseType.js b/tests/baselines/reference/promiseType.js new file mode 100644 index 00000000000..6b8d292a2b0 --- /dev/null +++ b/tests/baselines/reference/promiseType.js @@ -0,0 +1,202 @@ +//// [promiseType.ts] +declare var p: Promise; + +const a = p.then(); +const b = p.then(b => 1); +const c = p.then(b => 1, e => 'error'); +const d = p.then(b => 1, e => { }); +const e = p.then(b => 1, e => { throw Error(); }); +const f = p.then(b => 1, e => Promise.reject(Error())); +const g = p.catch(e => 'error'); +const h = p.catch(e => { }); +const i = p.catch(e => { throw Error(); }); +const j = p.catch(e => Promise.reject(Error())); + +async function A() { + const a = await p; + return a; +} + +async function B() { + const a = await p; + return 1; +} + +// NOTE: This reports a "No best comment type exists among return expressions." error, and is +// ignored to get the types result for the test. +// async function C() { +// try { +// const a = await p; +// return 1; +// } +// catch (e) { +// return 'error'; +// } +// } + +async function D() { + try { + const a = await p; + return 1; + } + catch (e) { + } +} + +async function E() { + try { + const a = await p; + return 1; + } + catch (e) { + throw Error(); + } +} + +async function F() { + try { + const a = await p; + return 1; + } + catch (e) { + return Promise.reject(Error()); + } +} + +async function G() { + try { + const a = await p; + return a; + } + catch (e) { + return; + } +} + +async function H() { + try { + const a = await p; + return a; + } + catch (e) { + throw Error(); + } +} + +async function I() { + try { + const a = await p; + return a; + } + catch (e) { + return Promise.reject(Error()); + } +} + +//// [promiseType.js] +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments)).next()); + }); +}; +const a = p.then(); +const b = p.then(b => 1); +const c = p.then(b => 1, e => 'error'); +const d = p.then(b => 1, e => { }); +const e = p.then(b => 1, e => { throw Error(); }); +const f = p.then(b => 1, e => Promise.reject(Error())); +const g = p.catch(e => 'error'); +const h = p.catch(e => { }); +const i = p.catch(e => { throw Error(); }); +const j = p.catch(e => Promise.reject(Error())); +function A() { + return __awaiter(this, void 0, void 0, function* () { + const a = yield p; + return a; + }); +} +function B() { + return __awaiter(this, void 0, void 0, function* () { + const a = yield p; + return 1; + }); +} +// NOTE: This reports a "No best comment type exists among return expressions." error, and is +// ignored to get the types result for the test. +// async function C() { +// try { +// const a = await p; +// return 1; +// } +// catch (e) { +// return 'error'; +// } +// } +function D() { + return __awaiter(this, void 0, void 0, function* () { + try { + const a = yield p; + return 1; + } + catch (e) { + } + }); +} +function E() { + return __awaiter(this, void 0, void 0, function* () { + try { + const a = yield p; + return 1; + } + catch (e) { + throw Error(); + } + }); +} +function F() { + return __awaiter(this, void 0, void 0, function* () { + try { + const a = yield p; + return 1; + } + catch (e) { + return Promise.reject(Error()); + } + }); +} +function G() { + return __awaiter(this, void 0, void 0, function* () { + try { + const a = yield p; + return a; + } + catch (e) { + return; + } + }); +} +function H() { + return __awaiter(this, void 0, void 0, function* () { + try { + const a = yield p; + return a; + } + catch (e) { + throw Error(); + } + }); +} +function I() { + return __awaiter(this, void 0, void 0, function* () { + try { + const a = yield p; + return a; + } + catch (e) { + return Promise.reject(Error()); + } + }); +} diff --git a/tests/baselines/reference/promiseType.symbols b/tests/baselines/reference/promiseType.symbols new file mode 100644 index 00000000000..fde4cf4f6f2 --- /dev/null +++ b/tests/baselines/reference/promiseType.symbols @@ -0,0 +1,233 @@ +=== tests/cases/compiler/promiseType.ts === +declare var p: Promise; +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +const a = p.then(); +>a : Symbol(a, Decl(promiseType.ts, 2, 5)) +>p.then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) +>then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) + +const b = p.then(b => 1); +>b : Symbol(b, Decl(promiseType.ts, 3, 5)) +>p.then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) +>then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>b : Symbol(b, Decl(promiseType.ts, 3, 17)) + +const c = p.then(b => 1, e => 'error'); +>c : Symbol(c, Decl(promiseType.ts, 4, 5)) +>p.then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) +>then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>b : Symbol(b, Decl(promiseType.ts, 4, 17)) +>e : Symbol(e, Decl(promiseType.ts, 4, 24)) + +const d = p.then(b => 1, e => { }); +>d : Symbol(d, Decl(promiseType.ts, 5, 5)) +>p.then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) +>then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>b : Symbol(b, Decl(promiseType.ts, 5, 17)) +>e : Symbol(e, Decl(promiseType.ts, 5, 24)) + +const e = p.then(b => 1, e => { throw Error(); }); +>e : Symbol(e, Decl(promiseType.ts, 6, 5)) +>p.then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) +>then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>b : Symbol(b, Decl(promiseType.ts, 6, 17)) +>e : Symbol(e, Decl(promiseType.ts, 6, 24)) +>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +const f = p.then(b => 1, e => Promise.reject(Error())); +>f : Symbol(f, Decl(promiseType.ts, 7, 5)) +>p.then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) +>then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>b : Symbol(b, Decl(promiseType.ts, 7, 17)) +>e : Symbol(e, Decl(promiseType.ts, 7, 24)) +>Promise.reject : Symbol(PromiseConstructor.reject, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>reject : Symbol(PromiseConstructor.reject, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +const g = p.catch(e => 'error'); +>g : Symbol(g, Decl(promiseType.ts, 8, 5)) +>p.catch : Symbol(Promise.catch, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) +>catch : Symbol(Promise.catch, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>e : Symbol(e, Decl(promiseType.ts, 8, 18)) + +const h = p.catch(e => { }); +>h : Symbol(h, Decl(promiseType.ts, 9, 5)) +>p.catch : Symbol(Promise.catch, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) +>catch : Symbol(Promise.catch, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>e : Symbol(e, Decl(promiseType.ts, 9, 18)) + +const i = p.catch(e => { throw Error(); }); +>i : Symbol(i, Decl(promiseType.ts, 10, 5)) +>p.catch : Symbol(Promise.catch, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) +>catch : Symbol(Promise.catch, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>e : Symbol(e, Decl(promiseType.ts, 10, 18)) +>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +const j = p.catch(e => Promise.reject(Error())); +>j : Symbol(j, Decl(promiseType.ts, 11, 5)) +>p.catch : Symbol(Promise.catch, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) +>catch : Symbol(Promise.catch, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>e : Symbol(e, Decl(promiseType.ts, 11, 18)) +>Promise.reject : Symbol(PromiseConstructor.reject, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>reject : Symbol(PromiseConstructor.reject, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +async function A() { +>A : Symbol(A, Decl(promiseType.ts, 11, 48)) + + const a = await p; +>a : Symbol(a, Decl(promiseType.ts, 14, 9)) +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) + + return a; +>a : Symbol(a, Decl(promiseType.ts, 14, 9)) +} + +async function B() { +>B : Symbol(B, Decl(promiseType.ts, 16, 1)) + + const a = await p; +>a : Symbol(a, Decl(promiseType.ts, 19, 9)) +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) + + return 1; +} + +// NOTE: This reports a "No best comment type exists among return expressions." error, and is +// ignored to get the types result for the test. +// async function C() { +// try { +// const a = await p; +// return 1; +// } +// catch (e) { +// return 'error'; +// } +// } + +async function D() { +>D : Symbol(D, Decl(promiseType.ts, 21, 1)) + + try { + const a = await p; +>a : Symbol(a, Decl(promiseType.ts, 37, 13)) +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) + + return 1; + } + catch (e) { +>e : Symbol(e, Decl(promiseType.ts, 40, 11)) + } +} + +async function E() { +>E : Symbol(E, Decl(promiseType.ts, 42, 1)) + + try { + const a = await p; +>a : Symbol(a, Decl(promiseType.ts, 46, 13)) +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) + + return 1; + } + catch (e) { +>e : Symbol(e, Decl(promiseType.ts, 49, 11)) + + throw Error(); +>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + } +} + +async function F() { +>F : Symbol(F, Decl(promiseType.ts, 52, 1)) + + try { + const a = await p; +>a : Symbol(a, Decl(promiseType.ts, 56, 13)) +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) + + return 1; + } + catch (e) { +>e : Symbol(e, Decl(promiseType.ts, 59, 11)) + + return Promise.reject(Error()); +>Promise.reject : Symbol(PromiseConstructor.reject, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>reject : Symbol(PromiseConstructor.reject, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + } +} + +async function G() { +>G : Symbol(G, Decl(promiseType.ts, 62, 1)) + + try { + const a = await p; +>a : Symbol(a, Decl(promiseType.ts, 66, 13)) +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) + + return a; +>a : Symbol(a, Decl(promiseType.ts, 66, 13)) + } + catch (e) { +>e : Symbol(e, Decl(promiseType.ts, 69, 11)) + + return; + } +} + +async function H() { +>H : Symbol(H, Decl(promiseType.ts, 72, 1)) + + try { + const a = await p; +>a : Symbol(a, Decl(promiseType.ts, 76, 13)) +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) + + return a; +>a : Symbol(a, Decl(promiseType.ts, 76, 13)) + } + catch (e) { +>e : Symbol(e, Decl(promiseType.ts, 79, 11)) + + throw Error(); +>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + } +} + +async function I() { +>I : Symbol(I, Decl(promiseType.ts, 82, 1)) + + try { + const a = await p; +>a : Symbol(a, Decl(promiseType.ts, 86, 13)) +>p : Symbol(p, Decl(promiseType.ts, 0, 11)) + + return a; +>a : Symbol(a, Decl(promiseType.ts, 86, 13)) + } + catch (e) { +>e : Symbol(e, Decl(promiseType.ts, 89, 11)) + + return Promise.reject(Error()); +>Promise.reject : Symbol(PromiseConstructor.reject, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>reject : Symbol(PromiseConstructor.reject, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + } +} diff --git a/tests/baselines/reference/promiseType.types b/tests/baselines/reference/promiseType.types new file mode 100644 index 00000000000..42f885eff68 --- /dev/null +++ b/tests/baselines/reference/promiseType.types @@ -0,0 +1,287 @@ +=== tests/cases/compiler/promiseType.ts === +declare var p: Promise; +>p : Promise +>Promise : Promise + +const a = p.then(); +>a : Promise +>p.then() : Promise +>p.then : { (onfulfilled: (value: boolean) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike): Promise; (): Promise; } +>p : Promise +>then : { (onfulfilled: (value: boolean) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike): Promise; (): Promise; } + +const b = p.then(b => 1); +>b : Promise +>p.then(b => 1) : Promise +>p.then : { (onfulfilled: (value: boolean) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike): Promise; (): Promise; } +>p : Promise +>then : { (onfulfilled: (value: boolean) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike): Promise; (): Promise; } +>b => 1 : (b: boolean) => number +>b : boolean +>1 : number + +const c = p.then(b => 1, e => 'error'); +>c : Promise +>p.then(b => 1, e => 'error') : Promise +>p.then : { (onfulfilled: (value: boolean) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike): Promise; (): Promise; } +>p : Promise +>then : { (onfulfilled: (value: boolean) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike): Promise; (): Promise; } +>b => 1 : (b: boolean) => number +>b : boolean +>1 : number +>e => 'error' : (e: any) => string +>e : any +>'error' : string + +const d = p.then(b => 1, e => { }); +>d : Promise +>p.then(b => 1, e => { }) : Promise +>p.then : { (onfulfilled: (value: boolean) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike): Promise; (): Promise; } +>p : Promise +>then : { (onfulfilled: (value: boolean) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike): Promise; (): Promise; } +>b => 1 : (b: boolean) => number +>b : boolean +>1 : number +>e => { } : (e: any) => void +>e : any + +const e = p.then(b => 1, e => { throw Error(); }); +>e : Promise +>p.then(b => 1, e => { throw Error(); }) : Promise +>p.then : { (onfulfilled: (value: boolean) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike): Promise; (): Promise; } +>p : Promise +>then : { (onfulfilled: (value: boolean) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike): Promise; (): Promise; } +>b => 1 : (b: boolean) => number +>b : boolean +>1 : number +>e => { throw Error(); } : (e: any) => never +>e : any +>Error() : Error +>Error : ErrorConstructor + +const f = p.then(b => 1, e => Promise.reject(Error())); +>f : Promise +>p.then(b => 1, e => Promise.reject(Error())) : Promise +>p.then : { (onfulfilled: (value: boolean) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike): Promise; (): Promise; } +>p : Promise +>then : { (onfulfilled: (value: boolean) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: boolean) => TResult | PromiseLike): Promise; (): Promise; } +>b => 1 : (b: boolean) => number +>b : boolean +>1 : number +>e => Promise.reject(Error()) : (e: any) => Promise +>e : any +>Promise.reject(Error()) : Promise +>Promise.reject : { (reason: any): Promise; (reason: any): Promise; } +>Promise : PromiseConstructor +>reject : { (reason: any): Promise; (reason: any): Promise; } +>Error() : Error +>Error : ErrorConstructor + +const g = p.catch(e => 'error'); +>g : Promise +>p.catch(e => 'error') : Promise +>p.catch : { (onrejected: (reason: any) => TResult | PromiseLike): Promise; (onrejected: (reason: any) => boolean | PromiseLike): Promise; } +>p : Promise +>catch : { (onrejected: (reason: any) => TResult | PromiseLike): Promise; (onrejected: (reason: any) => boolean | PromiseLike): Promise; } +>e => 'error' : (e: any) => string +>e : any +>'error' : string + +const h = p.catch(e => { }); +>h : Promise +>p.catch(e => { }) : Promise +>p.catch : { (onrejected: (reason: any) => TResult | PromiseLike): Promise; (onrejected: (reason: any) => boolean | PromiseLike): Promise; } +>p : Promise +>catch : { (onrejected: (reason: any) => TResult | PromiseLike): Promise; (onrejected: (reason: any) => boolean | PromiseLike): Promise; } +>e => { } : (e: any) => void +>e : any + +const i = p.catch(e => { throw Error(); }); +>i : Promise +>p.catch(e => { throw Error(); }) : Promise +>p.catch : { (onrejected: (reason: any) => TResult | PromiseLike): Promise; (onrejected: (reason: any) => boolean | PromiseLike): Promise; } +>p : Promise +>catch : { (onrejected: (reason: any) => TResult | PromiseLike): Promise; (onrejected: (reason: any) => boolean | PromiseLike): Promise; } +>e => { throw Error(); } : (e: any) => never +>e : any +>Error() : Error +>Error : ErrorConstructor + +const j = p.catch(e => Promise.reject(Error())); +>j : Promise +>p.catch(e => Promise.reject(Error())) : Promise +>p.catch : { (onrejected: (reason: any) => TResult | PromiseLike): Promise; (onrejected: (reason: any) => boolean | PromiseLike): Promise; } +>p : Promise +>catch : { (onrejected: (reason: any) => TResult | PromiseLike): Promise; (onrejected: (reason: any) => boolean | PromiseLike): Promise; } +>e => Promise.reject(Error()) : (e: any) => Promise +>e : any +>Promise.reject(Error()) : Promise +>Promise.reject : { (reason: any): Promise; (reason: any): Promise; } +>Promise : PromiseConstructor +>reject : { (reason: any): Promise; (reason: any): Promise; } +>Error() : Error +>Error : ErrorConstructor + +async function A() { +>A : () => Promise + + const a = await p; +>a : boolean +>await p : boolean +>p : Promise + + return a; +>a : boolean +} + +async function B() { +>B : () => Promise + + const a = await p; +>a : boolean +>await p : boolean +>p : Promise + + return 1; +>1 : number +} + +// NOTE: This reports a "No best comment type exists among return expressions." error, and is +// ignored to get the types result for the test. +// async function C() { +// try { +// const a = await p; +// return 1; +// } +// catch (e) { +// return 'error'; +// } +// } + +async function D() { +>D : () => Promise + + try { + const a = await p; +>a : boolean +>await p : boolean +>p : Promise + + return 1; +>1 : number + } + catch (e) { +>e : any + } +} + +async function E() { +>E : () => Promise + + try { + const a = await p; +>a : boolean +>await p : boolean +>p : Promise + + return 1; +>1 : number + } + catch (e) { +>e : any + + throw Error(); +>Error() : Error +>Error : ErrorConstructor + } +} + +async function F() { +>F : () => Promise + + try { + const a = await p; +>a : boolean +>await p : boolean +>p : Promise + + return 1; +>1 : number + } + catch (e) { +>e : any + + return Promise.reject(Error()); +>Promise.reject(Error()) : Promise +>Promise.reject : { (reason: any): Promise; (reason: any): Promise; } +>Promise : PromiseConstructor +>reject : { (reason: any): Promise; (reason: any): Promise; } +>Error() : Error +>Error : ErrorConstructor + } +} + +async function G() { +>G : () => Promise + + try { + const a = await p; +>a : boolean +>await p : boolean +>p : Promise + + return a; +>a : boolean + } + catch (e) { +>e : any + + return; + } +} + +async function H() { +>H : () => Promise + + try { + const a = await p; +>a : boolean +>await p : boolean +>p : Promise + + return a; +>a : boolean + } + catch (e) { +>e : any + + throw Error(); +>Error() : Error +>Error : ErrorConstructor + } +} + +async function I() { +>I : () => Promise + + try { + const a = await p; +>a : boolean +>await p : boolean +>p : Promise + + return a; +>a : boolean + } + catch (e) { +>e : any + + return Promise.reject(Error()); +>Promise.reject(Error()) : Promise +>Promise.reject : { (reason: any): Promise; (reason: any): Promise; } +>Promise : PromiseConstructor +>reject : { (reason: any): Promise; (reason: any): Promise; } +>Error() : Error +>Error : ErrorConstructor + } +} diff --git a/tests/baselines/reference/promiseVoidErrorCallback.symbols b/tests/baselines/reference/promiseVoidErrorCallback.symbols index b2959f139ea..67747f5f150 100644 --- a/tests/baselines/reference/promiseVoidErrorCallback.symbols +++ b/tests/baselines/reference/promiseVoidErrorCallback.symbols @@ -47,12 +47,12 @@ function f2(x: T1): T2 { var x3 = f1() >x3 : Symbol(x3, Decl(promiseVoidErrorCallback.ts, 20, 3)) ->f1() .then(f2, (e: Error) => { throw e;}) .then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) ->f1() .then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>f1() .then(f2, (e: Error) => { throw e;}) .then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>f1() .then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) >f1 : Symbol(f1, Decl(promiseVoidErrorCallback.ts, 10, 1)) .then(f2, (e: Error) => { ->then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) >f2 : Symbol(f2, Decl(promiseVoidErrorCallback.ts, 14, 1)) >e : Symbol(e, Decl(promiseVoidErrorCallback.ts, 21, 15)) >Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) @@ -62,7 +62,7 @@ var x3 = f1() }) .then((x: T2) => { ->then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>then : Symbol(Promise.then, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) >x : Symbol(x, Decl(promiseVoidErrorCallback.ts, 24, 11)) >T2 : Symbol(T2, Decl(promiseVoidErrorCallback.ts, 2, 1)) diff --git a/tests/baselines/reference/promiseVoidErrorCallback.types b/tests/baselines/reference/promiseVoidErrorCallback.types index b536ab089bd..94773394ade 100644 --- a/tests/baselines/reference/promiseVoidErrorCallback.types +++ b/tests/baselines/reference/promiseVoidErrorCallback.types @@ -54,14 +54,14 @@ function f2(x: T1): T2 { var x3 = f1() >x3 : Promise<{ __t3: string; }> >f1() .then(f2, (e: Error) => { throw e;}) .then((x: T2) => { return { __t3: x.__t2 + "bar" };}) : Promise<{ __t3: string; }> ->f1() .then(f2, (e: Error) => { throw e;}) .then : { (onfulfilled?: (value: T2) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled?: (value: T2) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; } +>f1() .then(f2, (e: Error) => { throw e;}) .then : { (onfulfilled: (value: T2) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: T2) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: T2) => TResult | PromiseLike): Promise; (): Promise; } >f1() .then(f2, (e: Error) => { throw e;}) : Promise ->f1() .then : { (onfulfilled?: (value: T1) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled?: (value: T1) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; } +>f1() .then : { (onfulfilled: (value: T1) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: T1) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: T1) => TResult | PromiseLike): Promise; (): Promise; } >f1() : Promise >f1 : () => Promise .then(f2, (e: Error) => { ->then : { (onfulfilled?: (value: T1) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled?: (value: T1) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; } +>then : { (onfulfilled: (value: T1) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: T1) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: T1) => TResult | PromiseLike): Promise; (): Promise; } >f2 : (x: T1) => T2 >(e: Error) => { throw e;} : (e: Error) => never >e : Error @@ -72,7 +72,7 @@ var x3 = f1() }) .then((x: T2) => { ->then : { (onfulfilled?: (value: T2) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled?: (value: T2) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; } +>then : { (onfulfilled: (value: T2) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Promise; (onfulfilled: (value: T2) => TResult | PromiseLike, onrejected: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled: (value: T2) => TResult | PromiseLike): Promise; (): Promise; } >(x: T2) => { return { __t3: x.__t2 + "bar" };} : (x: T2) => { __t3: string; } >x : T2 >T2 : T2 diff --git a/tests/baselines/reference/restParamModifier2.errors.txt b/tests/baselines/reference/restParamModifier2.errors.txt index 773592fa9bf..032f657c107 100644 --- a/tests/baselines/reference/restParamModifier2.errors.txt +++ b/tests/baselines/reference/restParamModifier2.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/restParamModifier2.ts(2,24): error TS1005: ',' expected. +tests/cases/compiler/restParamModifier2.ts(2,17): error TS1317: A parameter property cannot be declared using a rest parameter. ==== tests/cases/compiler/restParamModifier2.ts (1 errors) ==== class C { constructor(public ...rest: string[]) {} - ~~~ -!!! error TS1005: ',' expected. + ~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS1317: A parameter property cannot be declared using a rest parameter. } \ No newline at end of file diff --git a/tests/baselines/reference/restParamModifier2.js b/tests/baselines/reference/restParamModifier2.js index ac8376319b3..a11b78a2376 100644 --- a/tests/baselines/reference/restParamModifier2.js +++ b/tests/baselines/reference/restParamModifier2.js @@ -5,11 +5,12 @@ class C { //// [restParamModifier2.js] var C = (function () { - function C(public) { + function C() { var rest = []; - for (var _i = 1; _i < arguments.length; _i++) { - rest[_i - 1] = arguments[_i]; + for (var _i = 0; _i < arguments.length; _i++) { + rest[_i - 0] = arguments[_i]; } + this.rest = rest; } return C; }()); diff --git a/tests/baselines/reference/signaturesUseJSDocForOptionalParameters.js b/tests/baselines/reference/signaturesUseJSDocForOptionalParameters.js new file mode 100644 index 00000000000..b3d61a9f590 --- /dev/null +++ b/tests/baselines/reference/signaturesUseJSDocForOptionalParameters.js @@ -0,0 +1,32 @@ +//// [jsDocOptionality.js] +function MyClass() { + this.prop = null; +} +/** + * @param {string} required + * @param {string} [notRequired] + * @returns {MyClass} + */ +MyClass.prototype.optionalParam = function(required, notRequired) { + return this; +}; +let pInst = new MyClass(); +let c1 = pInst.optionalParam('hello') +let c2 = pInst.optionalParam('hello', null) + + +//// [out_1.js] +function MyClass() { + this.prop = null; +} +/** + * @param {string} required + * @param {string} [notRequired] + * @returns {MyClass} + */ +MyClass.prototype.optionalParam = function (required, notRequired) { + return this; +}; +var pInst = new MyClass(); +var c1 = pInst.optionalParam('hello'); +var c2 = pInst.optionalParam('hello', null); diff --git a/tests/baselines/reference/signaturesUseJSDocForOptionalParameters.symbols b/tests/baselines/reference/signaturesUseJSDocForOptionalParameters.symbols new file mode 100644 index 00000000000..5ea2756598e --- /dev/null +++ b/tests/baselines/reference/signaturesUseJSDocForOptionalParameters.symbols @@ -0,0 +1,38 @@ +=== tests/cases/compiler/jsDocOptionality.js === +function MyClass() { +>MyClass : Symbol(MyClass, Decl(jsDocOptionality.js, 0, 0)) + + this.prop = null; +>prop : Symbol(MyClass.prop, Decl(jsDocOptionality.js, 0, 20)) +} +/** + * @param {string} required + * @param {string} [notRequired] + * @returns {MyClass} + */ +MyClass.prototype.optionalParam = function(required, notRequired) { +>MyClass.prototype : Symbol(MyClass.optionalParam, Decl(jsDocOptionality.js, 2, 1)) +>MyClass : Symbol(MyClass, Decl(jsDocOptionality.js, 0, 0)) +>prototype : Symbol(Function.prototype, Decl(lib.d.ts, --, --)) +>optionalParam : Symbol(MyClass.optionalParam, Decl(jsDocOptionality.js, 2, 1)) +>required : Symbol(required, Decl(jsDocOptionality.js, 8, 43)) +>notRequired : Symbol(notRequired, Decl(jsDocOptionality.js, 8, 52)) + + return this; +}; +let pInst = new MyClass(); +>pInst : Symbol(pInst, Decl(jsDocOptionality.js, 11, 3)) +>MyClass : Symbol(MyClass, Decl(jsDocOptionality.js, 0, 0)) + +let c1 = pInst.optionalParam('hello') +>c1 : Symbol(c1, Decl(jsDocOptionality.js, 12, 3)) +>pInst.optionalParam : Symbol(MyClass.optionalParam, Decl(jsDocOptionality.js, 2, 1)) +>pInst : Symbol(pInst, Decl(jsDocOptionality.js, 11, 3)) +>optionalParam : Symbol(MyClass.optionalParam, Decl(jsDocOptionality.js, 2, 1)) + +let c2 = pInst.optionalParam('hello', null) +>c2 : Symbol(c2, Decl(jsDocOptionality.js, 13, 3)) +>pInst.optionalParam : Symbol(MyClass.optionalParam, Decl(jsDocOptionality.js, 2, 1)) +>pInst : Symbol(pInst, Decl(jsDocOptionality.js, 11, 3)) +>optionalParam : Symbol(MyClass.optionalParam, Decl(jsDocOptionality.js, 2, 1)) + diff --git a/tests/baselines/reference/signaturesUseJSDocForOptionalParameters.types b/tests/baselines/reference/signaturesUseJSDocForOptionalParameters.types new file mode 100644 index 00000000000..2dcaa37b947 --- /dev/null +++ b/tests/baselines/reference/signaturesUseJSDocForOptionalParameters.types @@ -0,0 +1,53 @@ +=== tests/cases/compiler/jsDocOptionality.js === +function MyClass() { +>MyClass : () => void + + this.prop = null; +>this.prop = null : null +>this.prop : any +>this : any +>prop : any +>null : null +} +/** + * @param {string} required + * @param {string} [notRequired] + * @returns {MyClass} + */ +MyClass.prototype.optionalParam = function(required, notRequired) { +>MyClass.prototype.optionalParam = function(required, notRequired) { return this;} : (required: string, notRequired?: string) => { prop: null; optionalParam: any; } +>MyClass.prototype.optionalParam : any +>MyClass.prototype : any +>MyClass : () => void +>prototype : any +>optionalParam : any +>function(required, notRequired) { return this;} : (required: string, notRequired?: string) => { prop: null; optionalParam: any; } +>required : string +>notRequired : string + + return this; +>this : { prop: null; optionalParam: (required: string, notRequired?: string) => { prop: null; optionalParam: any; }; } + +}; +let pInst = new MyClass(); +>pInst : { prop: null; optionalParam: (required: string, notRequired?: string) => { prop: null; optionalParam: any; }; } +>new MyClass() : { prop: null; optionalParam: (required: string, notRequired?: string) => { prop: null; optionalParam: any; }; } +>MyClass : () => void + +let c1 = pInst.optionalParam('hello') +>c1 : { prop: null; optionalParam: (required: string, notRequired?: string) => { prop: null; optionalParam: any; }; } +>pInst.optionalParam('hello') : { prop: null; optionalParam: (required: string, notRequired?: string) => { prop: null; optionalParam: any; }; } +>pInst.optionalParam : (required: string, notRequired?: string) => { prop: null; optionalParam: any; } +>pInst : { prop: null; optionalParam: (required: string, notRequired?: string) => { prop: null; optionalParam: any; }; } +>optionalParam : (required: string, notRequired?: string) => { prop: null; optionalParam: any; } +>'hello' : string + +let c2 = pInst.optionalParam('hello', null) +>c2 : { prop: null; optionalParam: (required: string, notRequired?: string) => { prop: null; optionalParam: any; }; } +>pInst.optionalParam('hello', null) : { prop: null; optionalParam: (required: string, notRequired?: string) => { prop: null; optionalParam: any; }; } +>pInst.optionalParam : (required: string, notRequired?: string) => { prop: null; optionalParam: any; } +>pInst : { prop: null; optionalParam: (required: string, notRequired?: string) => { prop: null; optionalParam: any; }; } +>optionalParam : (required: string, notRequired?: string) => { prop: null; optionalParam: any; } +>'hello' : string +>null : null + diff --git a/tests/baselines/reference/thisTypeInAccessors.symbols b/tests/baselines/reference/thisTypeInAccessors.symbols index ef2201d3808..a68341dfc14 100644 --- a/tests/baselines/reference/thisTypeInAccessors.symbols +++ b/tests/baselines/reference/thisTypeInAccessors.symbols @@ -20,7 +20,7 @@ const explicit = { >this : Symbol(this, Decl(thisTypeInAccessors.ts, 7, 10)) >Foo : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 7, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) set x(this: Foo, n: number) { this.n = n; } @@ -29,7 +29,7 @@ const explicit = { >Foo : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 8, 20)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 8, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 8, 20)) } @@ -44,14 +44,14 @@ const copiedFromGetter = { >this : Symbol(this, Decl(thisTypeInAccessors.ts, 12, 10)) >Foo : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 12, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) set x(n) { this.n = n; } >x : Symbol(x, Decl(thisTypeInAccessors.ts, 11, 10), Decl(thisTypeInAccessors.ts, 12, 48)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 13, 10)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 12, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 13, 10)) } @@ -64,7 +64,7 @@ const copiedFromSetter = { get x() { return this.n }, >x : Symbol(x, Decl(thisTypeInAccessors.ts, 16, 10), Decl(thisTypeInAccessors.ts, 17, 30)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 18, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) set x(this: Foo, n: number) { this.n = n; } @@ -73,7 +73,7 @@ const copiedFromSetter = { >Foo : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 18, 20)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 18, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 18, 20)) } @@ -88,7 +88,7 @@ const copiedFromGetterUnannotated = { >this : Symbol(this, Decl(thisTypeInAccessors.ts, 22, 10)) >Foo : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 22, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) set x(this, n) { this.n = n; } @@ -96,7 +96,7 @@ const copiedFromGetterUnannotated = { >this : Symbol(this, Decl(thisTypeInAccessors.ts, 23, 10)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 23, 15)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 23, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 23, 15)) } @@ -112,7 +112,7 @@ class Explicit { >this : Symbol(this, Decl(thisTypeInAccessors.ts, 28, 10)) >Foo : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 28, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) set x(this: Foo, n: number) { this.n = n; } @@ -121,7 +121,7 @@ class Explicit { >Foo : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 29, 20)) >this.n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) ->this : Symbol(Foo, Decl(thisTypeInAccessors.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInAccessors.ts, 29, 10)) >n : Symbol(Foo.n, Decl(thisTypeInAccessors.ts, 0, 15)) >n : Symbol(n, Decl(thisTypeInAccessors.ts, 29, 20)) } diff --git a/tests/baselines/reference/thisTypeInFunctions.symbols b/tests/baselines/reference/thisTypeInFunctions.symbols index 3d4c3f6ecc7..8a0be7427ed 100644 --- a/tests/baselines/reference/thisTypeInFunctions.symbols +++ b/tests/baselines/reference/thisTypeInFunctions.symbols @@ -19,7 +19,7 @@ class C { return this.n + m; >this.n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) ->this : Symbol(C, Decl(thisTypeInFunctions.ts, 3, 1)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 6, 17)) >n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 6, 28)) } @@ -31,7 +31,7 @@ class C { return this.n + m; >this.n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) ->this : Symbol(C, Decl(thisTypeInFunctions.ts, 3, 1)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 9, 14)) >n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 9, 22)) } @@ -43,7 +43,7 @@ class C { return this.n + m; >this.n : Symbol(n, Decl(thisTypeInFunctions.ts, 12, 28)) ->this : Symbol(, Decl(thisTypeInFunctions.ts, 12, 26)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 12, 21)) >n : Symbol(n, Decl(thisTypeInFunctions.ts, 12, 28)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 12, 39)) } @@ -97,7 +97,7 @@ function explicitStructural(this: { y: number }, x: number): number { return x + this.y; >x : Symbol(x, Decl(thisTypeInFunctions.ts, 28, 48)) >this.y : Symbol(y, Decl(thisTypeInFunctions.ts, 28, 35)) ->this : Symbol(, Decl(thisTypeInFunctions.ts, 28, 33)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 28, 28)) >y : Symbol(y, Decl(thisTypeInFunctions.ts, 28, 35)) } function justThis(this: { y: number }): number { @@ -107,7 +107,7 @@ function justThis(this: { y: number }): number { return this.y; >this.y : Symbol(y, Decl(thisTypeInFunctions.ts, 31, 25)) ->this : Symbol(, Decl(thisTypeInFunctions.ts, 31, 23)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 31, 18)) >y : Symbol(y, Decl(thisTypeInFunctions.ts, 31, 25)) } function implicitThis(n: number): number { @@ -435,7 +435,7 @@ c.explicitC = function(this: C, m: number) { return this.n + m }; >C : Symbol(C, Decl(thisTypeInFunctions.ts, 3, 1)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 105, 31)) >this.n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) ->this : Symbol(C, Decl(thisTypeInFunctions.ts, 3, 1)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 105, 23)) >n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 105, 31)) @@ -453,7 +453,7 @@ c.explicitProperty = function(this: {n: number}, m: number) { return this.n + m >n : Symbol(n, Decl(thisTypeInFunctions.ts, 107, 37)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 107, 48)) >this.n : Symbol(n, Decl(thisTypeInFunctions.ts, 107, 37)) ->this : Symbol(, Decl(thisTypeInFunctions.ts, 107, 35)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 107, 30)) >n : Symbol(n, Decl(thisTypeInFunctions.ts, 107, 37)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 107, 48)) @@ -525,7 +525,7 @@ c.explicitThis = function(this: C, m: number) { return this.n + m }; >C : Symbol(C, Decl(thisTypeInFunctions.ts, 3, 1)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 123, 34)) >this.n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) ->this : Symbol(C, Decl(thisTypeInFunctions.ts, 3, 1)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 123, 26)) >n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 123, 34)) @@ -568,7 +568,7 @@ c.explicitThis = function(this, m) { return this.n + m }; >this : Symbol(this, Decl(thisTypeInFunctions.ts, 131, 26)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 131, 31)) >this.n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) ->this : Symbol(C, Decl(thisTypeInFunctions.ts, 3, 1)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 131, 26)) >n : Symbol(C.n, Decl(thisTypeInFunctions.ts, 4, 9)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 131, 31)) @@ -581,7 +581,7 @@ c.explicitC = function(this: B, m: number) { return this.n + m }; >B : Symbol(B, Decl(thisTypeInFunctions.ts, 0, 0)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 134, 31)) >this.n : Symbol(B.n, Decl(thisTypeInFunctions.ts, 1, 9)) ->this : Symbol(B, Decl(thisTypeInFunctions.ts, 0, 0)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 134, 23)) >n : Symbol(B.n, Decl(thisTypeInFunctions.ts, 1, 9)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 134, 31)) @@ -604,7 +604,7 @@ class Base1 { >polymorphic : Symbol(Base1.polymorphic, Decl(thisTypeInFunctions.ts, 141, 14)) >this : Symbol(this, Decl(thisTypeInFunctions.ts, 142, 23)) >this.x : Symbol(Base1.x, Decl(thisTypeInFunctions.ts, 140, 13)) ->this : Symbol(Base1, Decl(thisTypeInFunctions.ts, 137, 24)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 142, 23)) >x : Symbol(Base1.x, Decl(thisTypeInFunctions.ts, 140, 13)) explicit(this: Base1): number { return this.x; } @@ -612,7 +612,7 @@ class Base1 { >this : Symbol(this, Decl(thisTypeInFunctions.ts, 143, 13)) >Base1 : Symbol(Base1, Decl(thisTypeInFunctions.ts, 137, 24)) >this.x : Symbol(Base1.x, Decl(thisTypeInFunctions.ts, 140, 13)) ->this : Symbol(Base1, Decl(thisTypeInFunctions.ts, 137, 24)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 143, 13)) >x : Symbol(Base1.x, Decl(thisTypeInFunctions.ts, 140, 13)) static explicitStatic(this: typeof Base1): number { return this.y; } @@ -620,7 +620,7 @@ class Base1 { >this : Symbol(this, Decl(thisTypeInFunctions.ts, 144, 26)) >Base1 : Symbol(Base1, Decl(thisTypeInFunctions.ts, 137, 24)) >this.y : Symbol(Base1.y, Decl(thisTypeInFunctions.ts, 144, 72)) ->this : Symbol(Base1, Decl(thisTypeInFunctions.ts, 137, 24)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 144, 26)) >y : Symbol(Base1.y, Decl(thisTypeInFunctions.ts, 144, 72)) static y: number; @@ -643,7 +643,7 @@ class Base2 { >polymorphic : Symbol(Base2.polymorphic, Decl(thisTypeInFunctions.ts, 151, 13)) >this : Symbol(this, Decl(thisTypeInFunctions.ts, 152, 16)) >this.y : Symbol(Base2.y, Decl(thisTypeInFunctions.ts, 150, 13)) ->this : Symbol(Base2, Decl(thisTypeInFunctions.ts, 149, 1)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 152, 16)) >y : Symbol(Base2.y, Decl(thisTypeInFunctions.ts, 150, 13)) explicit(this: Base1): number { return this.x; } @@ -651,7 +651,7 @@ class Base2 { >this : Symbol(this, Decl(thisTypeInFunctions.ts, 153, 13)) >Base1 : Symbol(Base1, Decl(thisTypeInFunctions.ts, 137, 24)) >this.x : Symbol(Base1.x, Decl(thisTypeInFunctions.ts, 140, 13)) ->this : Symbol(Base1, Decl(thisTypeInFunctions.ts, 137, 24)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 153, 13)) >x : Symbol(Base1.x, Decl(thisTypeInFunctions.ts, 140, 13)) } class Derived2 extends Base2 { @@ -734,7 +734,7 @@ function InterfaceThis(this: I) { this.a = 12; >this.a : Symbol(I.a, Decl(thisTypeInFunctions.ts, 20, 13)) ->this : Symbol(I, Decl(thisTypeInFunctions.ts, 19, 21)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 172, 23)) >a : Symbol(I.a, Decl(thisTypeInFunctions.ts, 20, 13)) } function LiteralTypeThis(this: {x: string}) { @@ -744,7 +744,7 @@ function LiteralTypeThis(this: {x: string}) { this.x = "ok"; >this.x : Symbol(x, Decl(thisTypeInFunctions.ts, 175, 32)) ->this : Symbol(, Decl(thisTypeInFunctions.ts, 175, 30)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 175, 25)) >x : Symbol(x, Decl(thisTypeInFunctions.ts, 175, 32)) } function AnyThis(this: any) { @@ -752,6 +752,7 @@ function AnyThis(this: any) { >this : Symbol(this, Decl(thisTypeInFunctions.ts, 178, 17)) this.x = "ok"; +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 178, 17)) } let interfaceThis = new InterfaceThis(); >interfaceThis : Symbol(interfaceThis, Decl(thisTypeInFunctions.ts, 181, 3)) @@ -793,5 +794,6 @@ function missingTypeIsImplicitAny(this, a: number) { return this.anything + a; } >missingTypeIsImplicitAny : Symbol(missingTypeIsImplicitAny, Decl(thisTypeInFunctions.ts, 190, 27)) >this : Symbol(this, Decl(thisTypeInFunctions.ts, 192, 34)) >a : Symbol(a, Decl(thisTypeInFunctions.ts, 192, 39)) +>this : Symbol(this, Decl(thisTypeInFunctions.ts, 192, 34)) >a : Symbol(a, Decl(thisTypeInFunctions.ts, 192, 39)) diff --git a/tests/baselines/reference/thisTypeInFunctions.types b/tests/baselines/reference/thisTypeInFunctions.types index ddef8544a54..24c4fb87baf 100644 --- a/tests/baselines/reference/thisTypeInFunctions.types +++ b/tests/baselines/reference/thisTypeInFunctions.types @@ -692,11 +692,11 @@ c.explicitThis = function(m) { return this.n + m }; // this: contextual typing c.explicitThis = function(this, m) { return this.n + m }; ->c.explicitThis = function(this, m) { return this.n + m } : (this: any, m: number) => number +>c.explicitThis = function(this, m) { return this.n + m } : (this: C, m: number) => number >c.explicitThis : (this: C, m: number) => number >c : C >explicitThis : (this: C, m: number) => number ->function(this, m) { return this.n + m } : (this: any, m: number) => number +>function(this, m) { return this.n + m } : (this: C, m: number) => number >this : C >m : number >this.n + m : number diff --git a/tests/baselines/reference/transpile/Correctly serialize metadata when transpile with CommonJS option.js b/tests/baselines/reference/transpile/Correctly serialize metadata when transpile with CommonJS option.js new file mode 100644 index 00000000000..e5495f226d2 --- /dev/null +++ b/tests/baselines/reference/transpile/Correctly serialize metadata when transpile with CommonJS option.js @@ -0,0 +1,23 @@ +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +var ng = require("angular2/core"); +var MyClass1 = (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } + MyClass1 = __decorate([ + fooexport, + __metadata('design:paramtypes', [(typeof (_a = typeof ng !== 'undefined' && ng.ElementRef) === 'function' && _a) || Object]) + ], MyClass1); + return MyClass1; + var _a; +}()); +//# sourceMappingURL=file.js.map \ No newline at end of file diff --git a/tests/baselines/reference/transpile/Correctly serialize metadata when transpile with System option.js b/tests/baselines/reference/transpile/Correctly serialize metadata when transpile with System option.js new file mode 100644 index 00000000000..491481e6a40 --- /dev/null +++ b/tests/baselines/reference/transpile/Correctly serialize metadata when transpile with System option.js @@ -0,0 +1,35 @@ +System.register(["angular2/core"], function(exports_1, context_1) { + "use strict"; + var __moduleName = context_1 && context_1.id; + var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); + }; + var ng; + var MyClass1; + return { + setters:[ + function (ng_1) { + ng = ng_1; + }], + execute: function() { + MyClass1 = (function () { + function MyClass1(_elementRef) { + this._elementRef = _elementRef; + } + MyClass1 = __decorate([ + fooexport, + __metadata('design:paramtypes', [(typeof (_a = typeof ng !== 'undefined' && ng.ElementRef) === 'function' && _a) || Object]) + ], MyClass1); + return MyClass1; + var _a; + }()); + } + } +}); +//# sourceMappingURL=file.js.map \ No newline at end of file diff --git a/tests/baselines/reference/transpile/Report an error when compiler-options input is empty object.errors.txt b/tests/baselines/reference/transpile/Report an error when compiler-options input is empty object.errors.txt deleted file mode 100644 index d7d6eb69300..00000000000 --- a/tests/baselines/reference/transpile/Report an error when compiler-options input is empty object.errors.txt +++ /dev/null @@ -1,6 +0,0 @@ -error TS6046: Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015' - - -!!! error TS6046: Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015' -==== file.ts (0 errors) ==== - \ No newline at end of file diff --git a/tests/baselines/reference/transpile/Report an error when compiler-options input is empty object.js b/tests/baselines/reference/transpile/Report an error when compiler-options input is empty object.js deleted file mode 100644 index 1ceb1bcd146..00000000000 --- a/tests/baselines/reference/transpile/Report an error when compiler-options input is empty object.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -//# sourceMappingURL=file.js.map \ No newline at end of file diff --git a/tests/baselines/reference/transpile/Report an error when compiler-options input is empty string.errors.txt b/tests/baselines/reference/transpile/Report an error when compiler-options input is empty string.errors.txt deleted file mode 100644 index d7d6eb69300..00000000000 --- a/tests/baselines/reference/transpile/Report an error when compiler-options input is empty string.errors.txt +++ /dev/null @@ -1,6 +0,0 @@ -error TS6046: Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015' - - -!!! error TS6046: Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015' -==== file.ts (0 errors) ==== - \ No newline at end of file diff --git a/tests/baselines/reference/transpile/Report an error when compiler-options input is empty string.js b/tests/baselines/reference/transpile/Report an error when compiler-options input is empty string.js deleted file mode 100644 index 1ceb1bcd146..00000000000 --- a/tests/baselines/reference/transpile/Report an error when compiler-options input is empty string.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -//# sourceMappingURL=file.js.map \ No newline at end of file diff --git a/tests/baselines/reference/tsxDynamicTagName1.js b/tests/baselines/reference/tsxDynamicTagName1.js new file mode 100644 index 00000000000..e77d126dd83 --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName1.js @@ -0,0 +1,8 @@ +//// [tsxDynamicTagName1.tsx] + +var CustomTag = "h1"; + Hello World // No error + +//// [tsxDynamicTagName1.jsx] +var CustomTag = "h1"; + Hello World ; // No error diff --git a/tests/baselines/reference/tsxDynamicTagName1.symbols b/tests/baselines/reference/tsxDynamicTagName1.symbols new file mode 100644 index 00000000000..c3ba6440e48 --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName1.symbols @@ -0,0 +1,9 @@ +=== tests/cases/conformance/jsx/tsxDynamicTagName1.tsx === + +var CustomTag = "h1"; +>CustomTag : Symbol(CustomTag, Decl(tsxDynamicTagName1.tsx, 1, 3)) + + Hello World // No error +>CustomTag : Symbol(CustomTag, Decl(tsxDynamicTagName1.tsx, 1, 3)) +>CustomTag : Symbol(CustomTag, Decl(tsxDynamicTagName1.tsx, 1, 3)) + diff --git a/tests/baselines/reference/tsxDynamicTagName1.types b/tests/baselines/reference/tsxDynamicTagName1.types new file mode 100644 index 00000000000..005afcf6adb --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName1.types @@ -0,0 +1,11 @@ +=== tests/cases/conformance/jsx/tsxDynamicTagName1.tsx === + +var CustomTag = "h1"; +>CustomTag : string +>"h1" : string + + Hello World // No error +> Hello World : any +>CustomTag : string +>CustomTag : string + diff --git a/tests/baselines/reference/tsxDynamicTagName2.errors.txt b/tests/baselines/reference/tsxDynamicTagName2.errors.txt new file mode 100644 index 00000000000..008a013e379 --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName2.errors.txt @@ -0,0 +1,19 @@ +tests/cases/conformance/jsx/tsxDynamicTagName2.tsx(10,1): error TS2339: Property 'customTag' does not exist on type 'JSX.IntrinsicElements'. +tests/cases/conformance/jsx/tsxDynamicTagName2.tsx(10,25): error TS2339: Property 'customTag' does not exist on type 'JSX.IntrinsicElements'. + + +==== tests/cases/conformance/jsx/tsxDynamicTagName2.tsx (2 errors) ==== + + declare module JSX { + interface Element { } + interface IntrinsicElements { + div: any + } + } + + var customTag = "h1"; + Hello World // This should be an error. The lower-case is look up as an intrinsic element name + ~~~~~~~~~~~ +!!! error TS2339: Property 'customTag' does not exist on type 'JSX.IntrinsicElements'. + ~~~~~~~~~~~~ +!!! error TS2339: Property 'customTag' does not exist on type 'JSX.IntrinsicElements'. \ No newline at end of file diff --git a/tests/baselines/reference/tsxDynamicTagName2.js b/tests/baselines/reference/tsxDynamicTagName2.js new file mode 100644 index 00000000000..7fb7bb1a965 --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName2.js @@ -0,0 +1,15 @@ +//// [tsxDynamicTagName2.tsx] + +declare module JSX { + interface Element { } + interface IntrinsicElements { + div: any + } +} + +var customTag = "h1"; + Hello World // This should be an error. The lower-case is look up as an intrinsic element name + +//// [tsxDynamicTagName2.jsx] +var customTag = "h1"; + Hello World ; // This should be an error. The lower-case is look up as an intrinsic element name diff --git a/tests/baselines/reference/tsxDynamicTagName3.errors.txt b/tests/baselines/reference/tsxDynamicTagName3.errors.txt new file mode 100644 index 00000000000..40c10c63f53 --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName3.errors.txt @@ -0,0 +1,16 @@ +tests/cases/conformance/jsx/tsxDynamicTagName3.tsx(10,1): error TS2339: Property 'h1' does not exist on type 'JSX.IntrinsicElements'. + + +==== tests/cases/conformance/jsx/tsxDynamicTagName3.tsx (1 errors) ==== + + declare module JSX { + interface Element { } + interface IntrinsicElements { + div: any + } + } + + var CustomTag: "h1" = "h1"; + Hello World // This should be an error. we will try look up string literal type in JSX.IntrinsicElements + ~~~~~~~~~~~ +!!! error TS2339: Property 'h1' does not exist on type 'JSX.IntrinsicElements'. \ No newline at end of file diff --git a/tests/baselines/reference/tsxDynamicTagName3.js b/tests/baselines/reference/tsxDynamicTagName3.js new file mode 100644 index 00000000000..63c2a0a398b --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName3.js @@ -0,0 +1,15 @@ +//// [tsxDynamicTagName3.tsx] + +declare module JSX { + interface Element { } + interface IntrinsicElements { + div: any + } +} + +var CustomTag: "h1" = "h1"; + Hello World // This should be an error. we will try look up string literal type in JSX.IntrinsicElements + +//// [tsxDynamicTagName3.jsx] +var CustomTag = "h1"; + Hello World ; // This should be an error. we will try look up string literal type in JSX.IntrinsicElements diff --git a/tests/baselines/reference/tsxDynamicTagName4.js b/tests/baselines/reference/tsxDynamicTagName4.js new file mode 100644 index 00000000000..e708273237d --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName4.js @@ -0,0 +1,16 @@ +//// [tsxDynamicTagName4.tsx] + +declare module JSX { + interface Element { } + interface IntrinsicElements { + div: any + h1: any + } +} + +var CustomTag: "h1" = "h1"; + Hello World + +//// [tsxDynamicTagName4.jsx] +var CustomTag = "h1"; + Hello World ; diff --git a/tests/baselines/reference/tsxDynamicTagName4.symbols b/tests/baselines/reference/tsxDynamicTagName4.symbols new file mode 100644 index 00000000000..3f0fe57ce1f --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName4.symbols @@ -0,0 +1,26 @@ +=== tests/cases/conformance/jsx/tsxDynamicTagName4.tsx === + +declare module JSX { +>JSX : Symbol(JSX, Decl(tsxDynamicTagName4.tsx, 0, 0)) + + interface Element { } +>Element : Symbol(Element, Decl(tsxDynamicTagName4.tsx, 1, 20)) + + interface IntrinsicElements { +>IntrinsicElements : Symbol(IntrinsicElements, Decl(tsxDynamicTagName4.tsx, 2, 22)) + + div: any +>div : Symbol(IntrinsicElements.div, Decl(tsxDynamicTagName4.tsx, 3, 30)) + + h1: any +>h1 : Symbol(IntrinsicElements.h1, Decl(tsxDynamicTagName4.tsx, 4, 10)) + } +} + +var CustomTag: "h1" = "h1"; +>CustomTag : Symbol(CustomTag, Decl(tsxDynamicTagName4.tsx, 9, 3)) + + Hello World +>CustomTag : Symbol(CustomTag, Decl(tsxDynamicTagName4.tsx, 9, 3)) +>CustomTag : Symbol(CustomTag, Decl(tsxDynamicTagName4.tsx, 9, 3)) + diff --git a/tests/baselines/reference/tsxDynamicTagName4.types b/tests/baselines/reference/tsxDynamicTagName4.types new file mode 100644 index 00000000000..3a9a34f2898 --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName4.types @@ -0,0 +1,28 @@ +=== tests/cases/conformance/jsx/tsxDynamicTagName4.tsx === + +declare module JSX { +>JSX : any + + interface Element { } +>Element : Element + + interface IntrinsicElements { +>IntrinsicElements : IntrinsicElements + + div: any +>div : any + + h1: any +>h1 : any + } +} + +var CustomTag: "h1" = "h1"; +>CustomTag : "h1" +>"h1" : "h1" + + Hello World +> Hello World : JSX.Element +>CustomTag : "h1" +>CustomTag : "h1" + diff --git a/tests/baselines/reference/tsxDynamicTagName5.js b/tests/baselines/reference/tsxDynamicTagName5.js new file mode 100644 index 00000000000..03c9627c2c1 --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName5.js @@ -0,0 +1,41 @@ +//// [tests/cases/conformance/jsx/tsxDynamicTagName5.tsx] //// + +//// [react.d.ts] + +declare module 'react' { + class Component { } +} + +//// [app.tsx] +import * as React from 'react'; + +export class Text extends React.Component<{}, {}> { + _tagName: string = 'div'; + + render() { + return ( + + ); + } +} + +//// [app.jsx] +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var React = require('react'); +var Text = (function (_super) { + __extends(Text, _super); + function Text() { + _super.apply(this, arguments); + this._tagName = 'div'; + } + Text.prototype.render = function () { + return (); + }; + return Text; +}(React.Component)); +exports.Text = Text; diff --git a/tests/baselines/reference/tsxDynamicTagName5.symbols b/tests/baselines/reference/tsxDynamicTagName5.symbols new file mode 100644 index 00000000000..9abac5521c9 --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName5.symbols @@ -0,0 +1,34 @@ +=== tests/cases/conformance/jsx/react.d.ts === + +declare module 'react' { + class Component { } +>Component : Symbol(Component, Decl(react.d.ts, 1, 24)) +>T : Symbol(T, Decl(react.d.ts, 2, 17)) +>U : Symbol(U, Decl(react.d.ts, 2, 19)) +} + +=== tests/cases/conformance/jsx/app.tsx === +import * as React from 'react'; +>React : Symbol(React, Decl(app.tsx, 0, 6)) + +export class Text extends React.Component<{}, {}> { +>Text : Symbol(Text, Decl(app.tsx, 0, 31)) +>React.Component : Symbol(React.Component, Decl(react.d.ts, 1, 24)) +>React : Symbol(React, Decl(app.tsx, 0, 6)) +>Component : Symbol(React.Component, Decl(react.d.ts, 1, 24)) + + _tagName: string = 'div'; +>_tagName : Symbol(Text._tagName, Decl(app.tsx, 2, 51)) + + render() { +>render : Symbol(Text.render, Decl(app.tsx, 3, 27)) + + return ( + +>this._tagName : Symbol(Text._tagName, Decl(app.tsx, 2, 51)) +>this : Symbol(Text, Decl(app.tsx, 0, 31)) +>_tagName : Symbol(Text._tagName, Decl(app.tsx, 2, 51)) + + ); + } +} diff --git a/tests/baselines/reference/tsxDynamicTagName5.types b/tests/baselines/reference/tsxDynamicTagName5.types new file mode 100644 index 00000000000..ac4ee31141a --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName5.types @@ -0,0 +1,38 @@ +=== tests/cases/conformance/jsx/react.d.ts === + +declare module 'react' { + class Component { } +>Component : Component +>T : T +>U : U +} + +=== tests/cases/conformance/jsx/app.tsx === +import * as React from 'react'; +>React : typeof React + +export class Text extends React.Component<{}, {}> { +>Text : Text +>React.Component : React.Component<{}, {}> +>React : typeof React +>Component : typeof React.Component + + _tagName: string = 'div'; +>_tagName : string +>'div' : string + + render() { +>render : () => any + + return ( +>( ) : any + + +> : any +>this._tagName : string +>this : this +>_tagName : string + + ); + } +} diff --git a/tests/baselines/reference/tsxDynamicTagName6.js b/tests/baselines/reference/tsxDynamicTagName6.js new file mode 100644 index 00000000000..a7ec12b50b7 --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName6.js @@ -0,0 +1,15 @@ +//// [tsxDynamicTagName6.tsx] + +declare module JSX { + interface Element { } + interface IntrinsicElements { + div: any + } +} + +const t = {tag:'h1'} +const foo = // No error + +//// [tsxDynamicTagName6.jsx] +var t = { tag: 'h1' }; +var foo = ; // No error diff --git a/tests/baselines/reference/tsxDynamicTagName6.symbols b/tests/baselines/reference/tsxDynamicTagName6.symbols new file mode 100644 index 00000000000..f1afd91eacb --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName6.symbols @@ -0,0 +1,26 @@ +=== tests/cases/conformance/jsx/tsxDynamicTagName6.tsx === + +declare module JSX { +>JSX : Symbol(JSX, Decl(tsxDynamicTagName6.tsx, 0, 0)) + + interface Element { } +>Element : Symbol(Element, Decl(tsxDynamicTagName6.tsx, 1, 20)) + + interface IntrinsicElements { +>IntrinsicElements : Symbol(IntrinsicElements, Decl(tsxDynamicTagName6.tsx, 2, 22)) + + div: any +>div : Symbol(IntrinsicElements.div, Decl(tsxDynamicTagName6.tsx, 3, 30)) + } +} + +const t = {tag:'h1'} +>t : Symbol(t, Decl(tsxDynamicTagName6.tsx, 8, 5)) +>tag : Symbol(tag, Decl(tsxDynamicTagName6.tsx, 8, 11)) + +const foo = // No error +>foo : Symbol(foo, Decl(tsxDynamicTagName6.tsx, 9, 5)) +>t.tag : Symbol(tag, Decl(tsxDynamicTagName6.tsx, 8, 11)) +>t : Symbol(t, Decl(tsxDynamicTagName6.tsx, 8, 5)) +>tag : Symbol(tag, Decl(tsxDynamicTagName6.tsx, 8, 11)) + diff --git a/tests/baselines/reference/tsxDynamicTagName6.types b/tests/baselines/reference/tsxDynamicTagName6.types new file mode 100644 index 00000000000..5dadf6fe825 --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName6.types @@ -0,0 +1,29 @@ +=== tests/cases/conformance/jsx/tsxDynamicTagName6.tsx === + +declare module JSX { +>JSX : any + + interface Element { } +>Element : Element + + interface IntrinsicElements { +>IntrinsicElements : IntrinsicElements + + div: any +>div : any + } +} + +const t = {tag:'h1'} +>t : { tag: string; } +>{tag:'h1'} : { tag: string; } +>tag : string +>'h1' : string + +const foo = // No error +>foo : JSX.Element +> : JSX.Element +>t.tag : string +>t : { tag: string; } +>tag : string + diff --git a/tests/baselines/reference/tsxDynamicTagName7.errors.txt b/tests/baselines/reference/tsxDynamicTagName7.errors.txt new file mode 100644 index 00000000000..19f9bed3c27 --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName7.errors.txt @@ -0,0 +1,23 @@ +tests/cases/conformance/jsx/app.tsx(8,8): error TS2604: JSX element type 'this' does not have any construct or call signatures. + + +==== tests/cases/conformance/jsx/react.d.ts (0 errors) ==== + + declare module 'react' { + class Component { } + } + +==== tests/cases/conformance/jsx/app.tsx (1 errors) ==== + import * as React from 'react'; + + export class Text extends React.Component<{}, {}> { + _tagName: string = 'div'; + + render() { + return ( + // this should be an error + ~~~~ +!!! error TS2604: JSX element type 'this' does not have any construct or call signatures. + ); + } + } \ No newline at end of file diff --git a/tests/baselines/reference/tsxDynamicTagName7.js b/tests/baselines/reference/tsxDynamicTagName7.js new file mode 100644 index 00000000000..f8dffbfad7e --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName7.js @@ -0,0 +1,42 @@ +//// [tests/cases/conformance/jsx/tsxDynamicTagName7.tsx] //// + +//// [react.d.ts] + +declare module 'react' { + class Component { } +} + +//// [app.tsx] +import * as React from 'react'; + +export class Text extends React.Component<{}, {}> { + _tagName: string = 'div'; + + render() { + return ( + // this should be an error + ); + } +} + +//// [app.jsx] +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var React = require('react'); +var Text = (function (_super) { + __extends(Text, _super); + function Text() { + _super.apply(this, arguments); + this._tagName = 'div'; + } + Text.prototype.render = function () { + return ( // this should be an error + ); + }; + return Text; +}(React.Component)); +exports.Text = Text; diff --git a/tests/baselines/reference/tsxDynamicTagName8.js b/tests/baselines/reference/tsxDynamicTagName8.js new file mode 100644 index 00000000000..36d551b0ce7 --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName8.js @@ -0,0 +1,41 @@ +//// [tests/cases/conformance/jsx/tsxDynamicTagName8.tsx] //// + +//// [react.d.ts] + +declare module 'react' { + class Component { } +} + +//// [app.tsx] +import * as React from 'react'; + +export class Text extends React.Component<{}, {}> { + _tagName: string = 'div'; + + render() { + return ( + Hello world + ); + } +} + +//// [app.jsx] +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var React = require('react'); +var Text = (function (_super) { + __extends(Text, _super); + function Text() { + _super.apply(this, arguments); + this._tagName = 'div'; + } + Text.prototype.render = function () { + return ( Hello world ); + }; + return Text; +}(React.Component)); +exports.Text = Text; diff --git a/tests/baselines/reference/tsxDynamicTagName8.symbols b/tests/baselines/reference/tsxDynamicTagName8.symbols new file mode 100644 index 00000000000..87a71e740de --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName8.symbols @@ -0,0 +1,37 @@ +=== tests/cases/conformance/jsx/react.d.ts === + +declare module 'react' { + class Component { } +>Component : Symbol(Component, Decl(react.d.ts, 1, 24)) +>T : Symbol(T, Decl(react.d.ts, 2, 17)) +>U : Symbol(U, Decl(react.d.ts, 2, 19)) +} + +=== tests/cases/conformance/jsx/app.tsx === +import * as React from 'react'; +>React : Symbol(React, Decl(app.tsx, 0, 6)) + +export class Text extends React.Component<{}, {}> { +>Text : Symbol(Text, Decl(app.tsx, 0, 31)) +>React.Component : Symbol(React.Component, Decl(react.d.ts, 1, 24)) +>React : Symbol(React, Decl(app.tsx, 0, 6)) +>Component : Symbol(React.Component, Decl(react.d.ts, 1, 24)) + + _tagName: string = 'div'; +>_tagName : Symbol(Text._tagName, Decl(app.tsx, 2, 51)) + + render() { +>render : Symbol(Text.render, Decl(app.tsx, 3, 27)) + + return ( + Hello world +>this._tagName : Symbol(Text._tagName, Decl(app.tsx, 2, 51)) +>this : Symbol(Text, Decl(app.tsx, 0, 31)) +>_tagName : Symbol(Text._tagName, Decl(app.tsx, 2, 51)) +>this._tagName : Symbol(Text._tagName, Decl(app.tsx, 2, 51)) +>this : Symbol(Text, Decl(app.tsx, 0, 31)) +>_tagName : Symbol(Text._tagName, Decl(app.tsx, 2, 51)) + + ); + } +} diff --git a/tests/baselines/reference/tsxDynamicTagName8.types b/tests/baselines/reference/tsxDynamicTagName8.types new file mode 100644 index 00000000000..154e7e33fe0 --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName8.types @@ -0,0 +1,41 @@ +=== tests/cases/conformance/jsx/react.d.ts === + +declare module 'react' { + class Component { } +>Component : Component +>T : T +>U : U +} + +=== tests/cases/conformance/jsx/app.tsx === +import * as React from 'react'; +>React : typeof React + +export class Text extends React.Component<{}, {}> { +>Text : Text +>React.Component : React.Component<{}, {}> +>React : typeof React +>Component : typeof React.Component + + _tagName: string = 'div'; +>_tagName : string +>'div' : string + + render() { +>render : () => any + + return ( +>( Hello world ) : any + + Hello world +> Hello world : any +>this._tagName : string +>this : this +>_tagName : string +>this._tagName : string +>this : this +>_tagName : string + + ); + } +} diff --git a/tests/baselines/reference/tsxDynamicTagName9.js b/tests/baselines/reference/tsxDynamicTagName9.js new file mode 100644 index 00000000000..78abc446e3f --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName9.js @@ -0,0 +1,41 @@ +//// [tests/cases/conformance/jsx/tsxDynamicTagName9.tsx] //// + +//// [react.d.ts] + +declare module 'react' { + class Component { } +} + +//// [app.tsx] +import * as React from 'react'; + +export class Text extends React.Component<{}, {}> { + _tagName: "div" = 'div'; + + render() { + return ( + Hello world + ); + } +} + +//// [app.jsx] +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var React = require('react'); +var Text = (function (_super) { + __extends(Text, _super); + function Text() { + _super.apply(this, arguments); + this._tagName = 'div'; + } + Text.prototype.render = function () { + return ( Hello world ); + }; + return Text; +}(React.Component)); +exports.Text = Text; diff --git a/tests/baselines/reference/tsxDynamicTagName9.symbols b/tests/baselines/reference/tsxDynamicTagName9.symbols new file mode 100644 index 00000000000..436e1205751 --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName9.symbols @@ -0,0 +1,37 @@ +=== tests/cases/conformance/jsx/react.d.ts === + +declare module 'react' { + class Component { } +>Component : Symbol(Component, Decl(react.d.ts, 1, 24)) +>T : Symbol(T, Decl(react.d.ts, 2, 17)) +>U : Symbol(U, Decl(react.d.ts, 2, 19)) +} + +=== tests/cases/conformance/jsx/app.tsx === +import * as React from 'react'; +>React : Symbol(React, Decl(app.tsx, 0, 6)) + +export class Text extends React.Component<{}, {}> { +>Text : Symbol(Text, Decl(app.tsx, 0, 31)) +>React.Component : Symbol(React.Component, Decl(react.d.ts, 1, 24)) +>React : Symbol(React, Decl(app.tsx, 0, 6)) +>Component : Symbol(React.Component, Decl(react.d.ts, 1, 24)) + + _tagName: "div" = 'div'; +>_tagName : Symbol(Text._tagName, Decl(app.tsx, 2, 51)) + + render() { +>render : Symbol(Text.render, Decl(app.tsx, 3, 26)) + + return ( + Hello world +>this._tagName : Symbol(Text._tagName, Decl(app.tsx, 2, 51)) +>this : Symbol(Text, Decl(app.tsx, 0, 31)) +>_tagName : Symbol(Text._tagName, Decl(app.tsx, 2, 51)) +>this._tagName : Symbol(Text._tagName, Decl(app.tsx, 2, 51)) +>this : Symbol(Text, Decl(app.tsx, 0, 31)) +>_tagName : Symbol(Text._tagName, Decl(app.tsx, 2, 51)) + + ); + } +} diff --git a/tests/baselines/reference/tsxDynamicTagName9.types b/tests/baselines/reference/tsxDynamicTagName9.types new file mode 100644 index 00000000000..e500d3f0ab1 --- /dev/null +++ b/tests/baselines/reference/tsxDynamicTagName9.types @@ -0,0 +1,41 @@ +=== tests/cases/conformance/jsx/react.d.ts === + +declare module 'react' { + class Component { } +>Component : Component +>T : T +>U : U +} + +=== tests/cases/conformance/jsx/app.tsx === +import * as React from 'react'; +>React : typeof React + +export class Text extends React.Component<{}, {}> { +>Text : Text +>React.Component : React.Component<{}, {}> +>React : typeof React +>Component : typeof React.Component + + _tagName: "div" = 'div'; +>_tagName : "div" +>'div' : "div" + + render() { +>render : () => any + + return ( +>( Hello world ) : any + + Hello world +> Hello world : any +>this._tagName : "div" +>this : this +>_tagName : "div" +>this._tagName : "div" +>this : this +>_tagName : "div" + + ); + } +} diff --git a/tests/baselines/reference/tsxUnionTypeComponent2.errors.txt b/tests/baselines/reference/tsxUnionTypeComponent2.errors.txt index e5a5c77da4c..a43c45ec59e 100644 --- a/tests/baselines/reference/tsxUnionTypeComponent2.errors.txt +++ b/tests/baselines/reference/tsxUnionTypeComponent2.errors.txt @@ -5,9 +5,9 @@ tests/cases/conformance/jsx/file.tsx(8,2): error TS2604: JSX element type 'X' do import React = require('react'); - type Invalid1 = React.ComponentClass | string; + type Invalid1 = React.ComponentClass | number; - const X: Invalid1 = "Should fail to construct"; + const X: Invalid1 = 1; ; ~ diff --git a/tests/baselines/reference/tsxUnionTypeComponent2.js b/tests/baselines/reference/tsxUnionTypeComponent2.js index 18e86eb8b4c..b88816f285a 100644 --- a/tests/baselines/reference/tsxUnionTypeComponent2.js +++ b/tests/baselines/reference/tsxUnionTypeComponent2.js @@ -2,9 +2,9 @@ import React = require('react'); -type Invalid1 = React.ComponentClass | string; +type Invalid1 = React.ComponentClass | number; -const X: Invalid1 = "Should fail to construct"; +const X: Invalid1 = 1; ; @@ -14,5 +14,5 @@ const X: Invalid1 = "Should fail to construct"; //// [file.js] "use strict"; var React = require('react'); -var X = "Should fail to construct"; +var X = 1; React.createElement(X, null); diff --git a/tests/baselines/reference/umd-augmentation-2.js b/tests/baselines/reference/umd-augmentation-2.js index a4a98690b52..2656ae9d0e8 100644 --- a/tests/baselines/reference/umd-augmentation-2.js +++ b/tests/baselines/reference/umd-augmentation-2.js @@ -42,8 +42,8 @@ var t = p.x; //// [a.js] /// /// -var v = new exports.Math2d.Vector(3, 2); -var magnitude = exports.Math2d.getLength(v); +var v = new Math2d.Vector(3, 2); +var magnitude = Math2d.getLength(v); var p = v.translate(5, 5); p = v.reverse(); var t = p.x; diff --git a/tests/baselines/reference/umd-augmentation-4.js b/tests/baselines/reference/umd-augmentation-4.js index da0f2ec1777..69c27cfe484 100644 --- a/tests/baselines/reference/umd-augmentation-4.js +++ b/tests/baselines/reference/umd-augmentation-4.js @@ -48,8 +48,8 @@ var t = p.x; //// [a.js] /// /// -var v = new exports.Math2d.Vector(3, 2); -var magnitude = exports.Math2d.getLength(v); +var v = new Math2d.Vector(3, 2); +var magnitude = Math2d.getLength(v); var p = v.translate(5, 5); p = v.reverse(); var t = p.x; diff --git a/tests/baselines/reference/umd1.js b/tests/baselines/reference/umd1.js index 9b059da4887..c343e0539cc 100644 --- a/tests/baselines/reference/umd1.js +++ b/tests/baselines/reference/umd1.js @@ -16,6 +16,6 @@ let y: number = x.n; //// [a.js] /// -exports.Foo.fn(); +Foo.fn(); var x; var y = x.n; diff --git a/tests/baselines/reference/umd5.js b/tests/baselines/reference/umd5.js index f8e2321a0f1..d054daf93fd 100644 --- a/tests/baselines/reference/umd5.js +++ b/tests/baselines/reference/umd5.js @@ -23,4 +23,4 @@ Bar.fn(); var x; var y = x.n; // should error -var z = exports.Foo; +var z = Foo; diff --git a/tests/baselines/reference/umd6.js b/tests/baselines/reference/umd6.js index d4d84fd0384..d2ae5a4a6ca 100644 --- a/tests/baselines/reference/umd6.js +++ b/tests/baselines/reference/umd6.js @@ -15,4 +15,4 @@ let y: number = Foo.fn(); //// [a.js] /// -var y = exports.Foo.fn(); +var y = Foo.fn(); diff --git a/tests/baselines/reference/umd7.js b/tests/baselines/reference/umd7.js index 12d0a8651fc..acf1d011e4d 100644 --- a/tests/baselines/reference/umd7.js +++ b/tests/baselines/reference/umd7.js @@ -13,4 +13,4 @@ let y: number = Foo(); //// [a.js] /// -var y = exports.Foo(); +var y = Foo(); diff --git a/tests/baselines/reference/unionTypeReadonly.errors.txt b/tests/baselines/reference/unionTypeReadonly.errors.txt new file mode 100644 index 00000000000..0875b2b5af3 --- /dev/null +++ b/tests/baselines/reference/unionTypeReadonly.errors.txt @@ -0,0 +1,45 @@ +tests/cases/conformance/types/union/unionTypeReadonly.ts(17,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/conformance/types/union/unionTypeReadonly.ts(19,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/conformance/types/union/unionTypeReadonly.ts(21,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/conformance/types/union/unionTypeReadonly.ts(23,1): error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. +tests/cases/conformance/types/union/unionTypeReadonly.ts(25,15): error TS2339: Property 'value' does not exist on type 'Base | DifferentName'. + + +==== tests/cases/conformance/types/union/unionTypeReadonly.ts (5 errors) ==== + interface Base { + readonly value: number; + } + interface Identical { + readonly value: number; + } + interface Mutable { + value: number; + } + interface DifferentType { + readonly value: string; + } + interface DifferentName { + readonly other: number; + } + let base: Base; + base.value = 12 // error, lhs can't be a readonly property + ~~~~~~~~~~ +!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + let identical: Base | Identical; + identical.value = 12; // error, lhs can't be a readonly property + ~~~~~~~~~~~~~~~ +!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + let mutable: Base | Mutable; + mutable.value = 12; // error, lhs can't be a readonly property + ~~~~~~~~~~~~~ +!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + let differentType: Base | DifferentType; + differentType.value = 12; // error, lhs can't be a readonly property + ~~~~~~~~~~~~~~~~~~~ +!!! error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property. + let differentName: Base | DifferentName; + differentName.value = 12; // error, property 'value' doesn't exist + ~~~~~ +!!! error TS2339: Property 'value' does not exist on type 'Base | DifferentName'. + + \ No newline at end of file diff --git a/tests/baselines/reference/unionTypeReadonly.js b/tests/baselines/reference/unionTypeReadonly.js new file mode 100644 index 00000000000..cdc893c91d9 --- /dev/null +++ b/tests/baselines/reference/unionTypeReadonly.js @@ -0,0 +1,40 @@ +//// [unionTypeReadonly.ts] +interface Base { + readonly value: number; +} +interface Identical { + readonly value: number; +} +interface Mutable { + value: number; +} +interface DifferentType { + readonly value: string; +} +interface DifferentName { + readonly other: number; +} +let base: Base; +base.value = 12 // error, lhs can't be a readonly property +let identical: Base | Identical; +identical.value = 12; // error, lhs can't be a readonly property +let mutable: Base | Mutable; +mutable.value = 12; // error, lhs can't be a readonly property +let differentType: Base | DifferentType; +differentType.value = 12; // error, lhs can't be a readonly property +let differentName: Base | DifferentName; +differentName.value = 12; // error, property 'value' doesn't exist + + + +//// [unionTypeReadonly.js] +var base; +base.value = 12; // error, lhs can't be a readonly property +var identical; +identical.value = 12; // error, lhs can't be a readonly property +var mutable; +mutable.value = 12; // error, lhs can't be a readonly property +var differentType; +differentType.value = 12; // error, lhs can't be a readonly property +var differentName; +differentName.value = 12; // error, property 'value' doesn't exist diff --git a/tests/baselines/reference/unusedClassesinModule1.errors.txt b/tests/baselines/reference/unusedClassesinModule1.errors.txt new file mode 100644 index 00000000000..6f2f936ce25 --- /dev/null +++ b/tests/baselines/reference/unusedClassesinModule1.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/unusedClassesinModule1.ts(3,11): error TS6133: 'Calculator' is declared but never used. + + +==== tests/cases/compiler/unusedClassesinModule1.ts (1 errors) ==== + + module A { + class Calculator { + ~~~~~~~~~~ +!!! error TS6133: 'Calculator' is declared but never used. + public handelChar() { + } + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedClassesinModule1.js b/tests/baselines/reference/unusedClassesinModule1.js new file mode 100644 index 00000000000..d3fb726c2dd --- /dev/null +++ b/tests/baselines/reference/unusedClassesinModule1.js @@ -0,0 +1,20 @@ +//// [unusedClassesinModule1.ts] + +module A { + class Calculator { + public handelChar() { + } + } +} + +//// [unusedClassesinModule1.js] +var A; +(function (A) { + var Calculator = (function () { + function Calculator() { + } + Calculator.prototype.handelChar = function () { + }; + return Calculator; + }()); +})(A || (A = {})); diff --git a/tests/baselines/reference/unusedClassesinNamespace1.errors.txt b/tests/baselines/reference/unusedClassesinNamespace1.errors.txt new file mode 100644 index 00000000000..dc5dc397fec --- /dev/null +++ b/tests/baselines/reference/unusedClassesinNamespace1.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/unusedClassesinNamespace1.ts(3,11): error TS6133: 'c1' is declared but never used. + + +==== tests/cases/compiler/unusedClassesinNamespace1.ts (1 errors) ==== + + namespace Validation { + class c1 { + ~~ +!!! error TS6133: 'c1' is declared but never used. + + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedClassesinNamespace1.js b/tests/baselines/reference/unusedClassesinNamespace1.js new file mode 100644 index 00000000000..e49b9019a28 --- /dev/null +++ b/tests/baselines/reference/unusedClassesinNamespace1.js @@ -0,0 +1,17 @@ +//// [unusedClassesinNamespace1.ts] + +namespace Validation { + class c1 { + + } +} + +//// [unusedClassesinNamespace1.js] +var Validation; +(function (Validation) { + var c1 = (function () { + function c1() { + } + return c1; + }()); +})(Validation || (Validation = {})); diff --git a/tests/baselines/reference/unusedClassesinNamespace2.errors.txt b/tests/baselines/reference/unusedClassesinNamespace2.errors.txt new file mode 100644 index 00000000000..322b2697550 --- /dev/null +++ b/tests/baselines/reference/unusedClassesinNamespace2.errors.txt @@ -0,0 +1,16 @@ +tests/cases/compiler/unusedClassesinNamespace2.ts(3,11): error TS6133: 'c1' is declared but never used. + + +==== tests/cases/compiler/unusedClassesinNamespace2.ts (1 errors) ==== + + namespace Validation { + class c1 { + ~~ +!!! error TS6133: 'c1' is declared but never used. + + } + + export class c2 { + + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedClassesinNamespace2.js b/tests/baselines/reference/unusedClassesinNamespace2.js new file mode 100644 index 00000000000..03431e4fd04 --- /dev/null +++ b/tests/baselines/reference/unusedClassesinNamespace2.js @@ -0,0 +1,27 @@ +//// [unusedClassesinNamespace2.ts] + +namespace Validation { + class c1 { + + } + + export class c2 { + + } +} + +//// [unusedClassesinNamespace2.js] +var Validation; +(function (Validation) { + var c1 = (function () { + function c1() { + } + return c1; + }()); + var c2 = (function () { + function c2() { + } + return c2; + }()); + Validation.c2 = c2; +})(Validation || (Validation = {})); diff --git a/tests/baselines/reference/unusedClassesinNamespace3.js b/tests/baselines/reference/unusedClassesinNamespace3.js new file mode 100644 index 00000000000..bdb646e87b2 --- /dev/null +++ b/tests/baselines/reference/unusedClassesinNamespace3.js @@ -0,0 +1,30 @@ +//// [unusedClassesinNamespace3.ts] + +namespace Validation { + class c1 { + + } + + export class c2 { + + } + + export let a = new c1(); +} + +//// [unusedClassesinNamespace3.js] +var Validation; +(function (Validation) { + var c1 = (function () { + function c1() { + } + return c1; + }()); + var c2 = (function () { + function c2() { + } + return c2; + }()); + Validation.c2 = c2; + Validation.a = new c1(); +})(Validation || (Validation = {})); diff --git a/tests/baselines/reference/unusedClassesinNamespace3.symbols b/tests/baselines/reference/unusedClassesinNamespace3.symbols new file mode 100644 index 00000000000..d8eeb0b5460 --- /dev/null +++ b/tests/baselines/reference/unusedClassesinNamespace3.symbols @@ -0,0 +1,19 @@ +=== tests/cases/compiler/unusedClassesinNamespace3.ts === + +namespace Validation { +>Validation : Symbol(Validation, Decl(unusedClassesinNamespace3.ts, 0, 0)) + + class c1 { +>c1 : Symbol(c1, Decl(unusedClassesinNamespace3.ts, 1, 22)) + + } + + export class c2 { +>c2 : Symbol(c2, Decl(unusedClassesinNamespace3.ts, 4, 5)) + + } + + export let a = new c1(); +>a : Symbol(a, Decl(unusedClassesinNamespace3.ts, 10, 14)) +>c1 : Symbol(c1, Decl(unusedClassesinNamespace3.ts, 1, 22)) +} diff --git a/tests/baselines/reference/unusedClassesinNamespace3.types b/tests/baselines/reference/unusedClassesinNamespace3.types new file mode 100644 index 00000000000..cef64a4c4e3 --- /dev/null +++ b/tests/baselines/reference/unusedClassesinNamespace3.types @@ -0,0 +1,20 @@ +=== tests/cases/compiler/unusedClassesinNamespace3.ts === + +namespace Validation { +>Validation : typeof Validation + + class c1 { +>c1 : c1 + + } + + export class c2 { +>c2 : c2 + + } + + export let a = new c1(); +>a : c1 +>new c1() : c1 +>c1 : typeof c1 +} diff --git a/tests/baselines/reference/unusedClassesinNamespace4.errors.txt b/tests/baselines/reference/unusedClassesinNamespace4.errors.txt new file mode 100644 index 00000000000..2fd6e70524e --- /dev/null +++ b/tests/baselines/reference/unusedClassesinNamespace4.errors.txt @@ -0,0 +1,20 @@ +tests/cases/compiler/unusedClassesinNamespace4.ts(11,11): error TS6133: 'c3' is declared but never used. + + +==== tests/cases/compiler/unusedClassesinNamespace4.ts (1 errors) ==== + + namespace Validation { + class c1 { + + } + + export class c2 { + + } + + class c3 extends c1 { + ~~ +!!! error TS6133: 'c3' is declared but never used. + + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedClassesinNamespace4.js b/tests/baselines/reference/unusedClassesinNamespace4.js new file mode 100644 index 00000000000..65198c1c1aa --- /dev/null +++ b/tests/baselines/reference/unusedClassesinNamespace4.js @@ -0,0 +1,43 @@ +//// [unusedClassesinNamespace4.ts] + +namespace Validation { + class c1 { + + } + + export class c2 { + + } + + class c3 extends c1 { + + } +} + +//// [unusedClassesinNamespace4.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Validation; +(function (Validation) { + var c1 = (function () { + function c1() { + } + return c1; + }()); + var c2 = (function () { + function c2() { + } + return c2; + }()); + Validation.c2 = c2; + var c3 = (function (_super) { + __extends(c3, _super); + function c3() { + _super.apply(this, arguments); + } + return c3; + }(c1)); +})(Validation || (Validation = {})); diff --git a/tests/baselines/reference/unusedClassesinNamespace5.errors.txt b/tests/baselines/reference/unusedClassesinNamespace5.errors.txt new file mode 100644 index 00000000000..752036b2d03 --- /dev/null +++ b/tests/baselines/reference/unusedClassesinNamespace5.errors.txt @@ -0,0 +1,20 @@ +tests/cases/compiler/unusedClassesinNamespace5.ts(11,11): error TS6133: 'c3' is declared but never used. + + +==== tests/cases/compiler/unusedClassesinNamespace5.ts (1 errors) ==== + + namespace Validation { + class c1 { + + } + + export class c2 { + + } + + class c3 { + ~~ +!!! error TS6133: 'c3' is declared but never used. + public x: c1; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedClassesinNamespace5.js b/tests/baselines/reference/unusedClassesinNamespace5.js new file mode 100644 index 00000000000..037a3564bd7 --- /dev/null +++ b/tests/baselines/reference/unusedClassesinNamespace5.js @@ -0,0 +1,36 @@ +//// [unusedClassesinNamespace5.ts] + +namespace Validation { + class c1 { + + } + + export class c2 { + + } + + class c3 { + public x: c1; + } +} + +//// [unusedClassesinNamespace5.js] +var Validation; +(function (Validation) { + var c1 = (function () { + function c1() { + } + return c1; + }()); + var c2 = (function () { + function c2() { + } + return c2; + }()); + Validation.c2 = c2; + var c3 = (function () { + function c3() { + } + return c3; + }()); +})(Validation || (Validation = {})); diff --git a/tests/baselines/reference/unusedFunctionsinNamespaces1.errors.txt b/tests/baselines/reference/unusedFunctionsinNamespaces1.errors.txt new file mode 100644 index 00000000000..428eeae8de5 --- /dev/null +++ b/tests/baselines/reference/unusedFunctionsinNamespaces1.errors.txt @@ -0,0 +1,11 @@ +tests/cases/compiler/unusedFunctionsinNamespaces1.ts(3,14): error TS6133: 'function1' is declared but never used. + + +==== tests/cases/compiler/unusedFunctionsinNamespaces1.ts (1 errors) ==== + + namespace Validation { + function function1() { + ~~~~~~~~~ +!!! error TS6133: 'function1' is declared but never used. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedFunctionsinNamespaces1.js b/tests/baselines/reference/unusedFunctionsinNamespaces1.js new file mode 100644 index 00000000000..a6eec74b1f5 --- /dev/null +++ b/tests/baselines/reference/unusedFunctionsinNamespaces1.js @@ -0,0 +1,13 @@ +//// [unusedFunctionsinNamespaces1.ts] + +namespace Validation { + function function1() { + } +} + +//// [unusedFunctionsinNamespaces1.js] +var Validation; +(function (Validation) { + function function1() { + } +})(Validation || (Validation = {})); diff --git a/tests/baselines/reference/unusedFunctionsinNamespaces2.errors.txt b/tests/baselines/reference/unusedFunctionsinNamespaces2.errors.txt new file mode 100644 index 00000000000..2b0b6def378 --- /dev/null +++ b/tests/baselines/reference/unusedFunctionsinNamespaces2.errors.txt @@ -0,0 +1,11 @@ +tests/cases/compiler/unusedFunctionsinNamespaces2.ts(3,9): error TS6133: 'function1' is declared but never used. + + +==== tests/cases/compiler/unusedFunctionsinNamespaces2.ts (1 errors) ==== + + namespace Validation { + var function1 = function() { + ~~~~~~~~~ +!!! error TS6133: 'function1' is declared but never used. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedFunctionsinNamespaces2.js b/tests/baselines/reference/unusedFunctionsinNamespaces2.js new file mode 100644 index 00000000000..c908e38e7a6 --- /dev/null +++ b/tests/baselines/reference/unusedFunctionsinNamespaces2.js @@ -0,0 +1,13 @@ +//// [unusedFunctionsinNamespaces2.ts] + +namespace Validation { + var function1 = function() { + } +} + +//// [unusedFunctionsinNamespaces2.js] +var Validation; +(function (Validation) { + var function1 = function () { + }; +})(Validation || (Validation = {})); diff --git a/tests/baselines/reference/unusedFunctionsinNamespaces3.errors.txt b/tests/baselines/reference/unusedFunctionsinNamespaces3.errors.txt new file mode 100644 index 00000000000..cfbeecc3c49 --- /dev/null +++ b/tests/baselines/reference/unusedFunctionsinNamespaces3.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/unusedFunctionsinNamespaces3.ts(3,9): error TS6133: 'function1' is declared but never used. +tests/cases/compiler/unusedFunctionsinNamespaces3.ts(3,30): error TS6133: 'param1' is declared but never used. + + +==== tests/cases/compiler/unusedFunctionsinNamespaces3.ts (2 errors) ==== + + namespace Validation { + var function1 = function(param1:string) { + ~~~~~~~~~ +!!! error TS6133: 'function1' is declared but never used. + ~~~~~~ +!!! error TS6133: 'param1' is declared but never used. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedFunctionsinNamespaces3.js b/tests/baselines/reference/unusedFunctionsinNamespaces3.js new file mode 100644 index 00000000000..5501ed62a6f --- /dev/null +++ b/tests/baselines/reference/unusedFunctionsinNamespaces3.js @@ -0,0 +1,13 @@ +//// [unusedFunctionsinNamespaces3.ts] + +namespace Validation { + var function1 = function(param1:string) { + } +} + +//// [unusedFunctionsinNamespaces3.js] +var Validation; +(function (Validation) { + var function1 = function (param1) { + }; +})(Validation || (Validation = {})); diff --git a/tests/baselines/reference/unusedFunctionsinNamespaces4.errors.txt b/tests/baselines/reference/unusedFunctionsinNamespaces4.errors.txt new file mode 100644 index 00000000000..72ce63924fd --- /dev/null +++ b/tests/baselines/reference/unusedFunctionsinNamespaces4.errors.txt @@ -0,0 +1,15 @@ +tests/cases/compiler/unusedFunctionsinNamespaces4.ts(3,9): error TS6133: 'function1' is declared but never used. + + +==== tests/cases/compiler/unusedFunctionsinNamespaces4.ts (1 errors) ==== + + namespace Validation { + var function1 = function() { + ~~~~~~~~~ +!!! error TS6133: 'function1' is declared but never used. + } + + export function function2() { + + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedFunctionsinNamespaces4.js b/tests/baselines/reference/unusedFunctionsinNamespaces4.js new file mode 100644 index 00000000000..41557a62045 --- /dev/null +++ b/tests/baselines/reference/unusedFunctionsinNamespaces4.js @@ -0,0 +1,20 @@ +//// [unusedFunctionsinNamespaces4.ts] + +namespace Validation { + var function1 = function() { + } + + export function function2() { + + } +} + +//// [unusedFunctionsinNamespaces4.js] +var Validation; +(function (Validation) { + var function1 = function () { + }; + function function2() { + } + Validation.function2 = function2; +})(Validation || (Validation = {})); diff --git a/tests/baselines/reference/unusedFunctionsinNamespaces5.errors.txt b/tests/baselines/reference/unusedFunctionsinNamespaces5.errors.txt new file mode 100644 index 00000000000..239680499bd --- /dev/null +++ b/tests/baselines/reference/unusedFunctionsinNamespaces5.errors.txt @@ -0,0 +1,26 @@ +tests/cases/compiler/unusedFunctionsinNamespaces5.ts(10,14): error TS6133: 'function3' is declared but never used. +tests/cases/compiler/unusedFunctionsinNamespaces5.ts(14,14): error TS6133: 'function4' is declared but never used. + + +==== tests/cases/compiler/unusedFunctionsinNamespaces5.ts (2 errors) ==== + + namespace Validation { + var function1 = function() { + } + + export function function2() { + + } + + function function3() { + ~~~~~~~~~ +!!! error TS6133: 'function3' is declared but never used. + function1(); + } + + function function4() { + ~~~~~~~~~ +!!! error TS6133: 'function4' is declared but never used. + + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedFunctionsinNamespaces5.js b/tests/baselines/reference/unusedFunctionsinNamespaces5.js new file mode 100644 index 00000000000..4023876b359 --- /dev/null +++ b/tests/baselines/reference/unusedFunctionsinNamespaces5.js @@ -0,0 +1,33 @@ +//// [unusedFunctionsinNamespaces5.ts] + +namespace Validation { + var function1 = function() { + } + + export function function2() { + + } + + function function3() { + function1(); + } + + function function4() { + + } +} + +//// [unusedFunctionsinNamespaces5.js] +var Validation; +(function (Validation) { + var function1 = function () { + }; + function function2() { + } + Validation.function2 = function2; + function function3() { + function1(); + } + function function4() { + } +})(Validation || (Validation = {})); diff --git a/tests/baselines/reference/unusedFunctionsinNamespaces6.errors.txt b/tests/baselines/reference/unusedFunctionsinNamespaces6.errors.txt new file mode 100644 index 00000000000..f8f0d12dd51 --- /dev/null +++ b/tests/baselines/reference/unusedFunctionsinNamespaces6.errors.txt @@ -0,0 +1,25 @@ +tests/cases/compiler/unusedFunctionsinNamespaces6.ts(14,14): error TS6133: 'function4' is declared but never used. + + +==== tests/cases/compiler/unusedFunctionsinNamespaces6.ts (1 errors) ==== + + namespace Validation { + var function1 = function() { + } + + export function function2() { + + } + + function function3() { + function1(); + } + + function function4() { + ~~~~~~~~~ +!!! error TS6133: 'function4' is declared but never used. + + } + + export let a = function3; + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedFunctionsinNamespaces6.js b/tests/baselines/reference/unusedFunctionsinNamespaces6.js new file mode 100644 index 00000000000..81ff5d9ea54 --- /dev/null +++ b/tests/baselines/reference/unusedFunctionsinNamespaces6.js @@ -0,0 +1,36 @@ +//// [unusedFunctionsinNamespaces6.ts] + +namespace Validation { + var function1 = function() { + } + + export function function2() { + + } + + function function3() { + function1(); + } + + function function4() { + + } + + export let a = function3; +} + +//// [unusedFunctionsinNamespaces6.js] +var Validation; +(function (Validation) { + var function1 = function () { + }; + function function2() { + } + Validation.function2 = function2; + function function3() { + function1(); + } + function function4() { + } + Validation.a = function3; +})(Validation || (Validation = {})); diff --git a/tests/baselines/reference/unusedGetterInClass.js b/tests/baselines/reference/unusedGetterInClass.js new file mode 100644 index 00000000000..0920ace0195 --- /dev/null +++ b/tests/baselines/reference/unusedGetterInClass.js @@ -0,0 +1,23 @@ +//// [unusedGetterInClass.ts] + +class Employee { + private _fullName: string; + + get fullName(): string { + return this._fullName; + } +} + +//// [unusedGetterInClass.js] +var Employee = (function () { + function Employee() { + } + Object.defineProperty(Employee.prototype, "fullName", { + get: function () { + return this._fullName; + }, + enumerable: true, + configurable: true + }); + return Employee; +}()); diff --git a/tests/baselines/reference/unusedGetterInClass.symbols b/tests/baselines/reference/unusedGetterInClass.symbols new file mode 100644 index 00000000000..3d19dd41241 --- /dev/null +++ b/tests/baselines/reference/unusedGetterInClass.symbols @@ -0,0 +1,17 @@ +=== tests/cases/compiler/unusedGetterInClass.ts === + +class Employee { +>Employee : Symbol(Employee, Decl(unusedGetterInClass.ts, 0, 0)) + + private _fullName: string; +>_fullName : Symbol(Employee._fullName, Decl(unusedGetterInClass.ts, 1, 16)) + + get fullName(): string { +>fullName : Symbol(Employee.fullName, Decl(unusedGetterInClass.ts, 2, 30)) + + return this._fullName; +>this._fullName : Symbol(Employee._fullName, Decl(unusedGetterInClass.ts, 1, 16)) +>this : Symbol(Employee, Decl(unusedGetterInClass.ts, 0, 0)) +>_fullName : Symbol(Employee._fullName, Decl(unusedGetterInClass.ts, 1, 16)) + } +} diff --git a/tests/baselines/reference/unusedGetterInClass.types b/tests/baselines/reference/unusedGetterInClass.types new file mode 100644 index 00000000000..8ad7479c443 --- /dev/null +++ b/tests/baselines/reference/unusedGetterInClass.types @@ -0,0 +1,17 @@ +=== tests/cases/compiler/unusedGetterInClass.ts === + +class Employee { +>Employee : Employee + + private _fullName: string; +>_fullName : string + + get fullName(): string { +>fullName : string + + return this._fullName; +>this._fullName : string +>this : this +>_fullName : string + } +} diff --git a/tests/baselines/reference/unusedIdentifiersConsolidated1.errors.txt b/tests/baselines/reference/unusedIdentifiersConsolidated1.errors.txt new file mode 100644 index 00000000000..a174074bdf7 --- /dev/null +++ b/tests/baselines/reference/unusedIdentifiersConsolidated1.errors.txt @@ -0,0 +1,153 @@ +tests/cases/compiler/unusedIdentifiersConsolidated1.ts(2,18): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedIdentifiersConsolidated1.ts(3,9): error TS6133: 'unused' is declared but never used. +tests/cases/compiler/unusedIdentifiersConsolidated1.ts(6,32): error TS6133: 'unusedtypeparameter' is declared but never used. +tests/cases/compiler/unusedIdentifiersConsolidated1.ts(7,13): error TS6133: 'unusedprivatevariable' is declared but never used. +tests/cases/compiler/unusedIdentifiersConsolidated1.ts(12,17): error TS6133: 'message' is declared but never used. +tests/cases/compiler/unusedIdentifiersConsolidated1.ts(13,13): error TS6133: 'unused2' is declared but never used. +tests/cases/compiler/unusedIdentifiersConsolidated1.ts(17,20): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedIdentifiersConsolidated1.ts(18,13): error TS6133: 'unused' is declared but never used. +tests/cases/compiler/unusedIdentifiersConsolidated1.ts(25,13): error TS6133: 'unUsedPrivateFunction' is declared but never used. +tests/cases/compiler/unusedIdentifiersConsolidated1.ts(38,11): error TS6133: 'numberRegexp' is declared but never used. +tests/cases/compiler/unusedIdentifiersConsolidated1.ts(45,17): error TS6133: 'unUsedPrivateFunction' is declared but never used. +tests/cases/compiler/unusedIdentifiersConsolidated1.ts(58,15): error TS6133: 'usedLocallyInterface2' is declared but never used. +tests/cases/compiler/unusedIdentifiersConsolidated1.ts(65,11): error TS6133: 'dummy' is declared but never used. +tests/cases/compiler/unusedIdentifiersConsolidated1.ts(68,15): error TS6133: 'unusedInterface' is declared but never used. +tests/cases/compiler/unusedIdentifiersConsolidated1.ts(80,11): error TS6133: 'class3' is declared but never used. +tests/cases/compiler/unusedIdentifiersConsolidated1.ts(100,15): error TS6133: 'interface5' is declared but never used. + + +==== tests/cases/compiler/unusedIdentifiersConsolidated1.ts (16 errors) ==== + + function greeter(person: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + } + + class Dummy { + ~~~~~~~~~~~~~~~~~~~ +!!! error TS6133: 'unusedtypeparameter' is declared but never used. + private unusedprivatevariable: string; + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS6133: 'unusedprivatevariable' is declared but never used. + private greeting: string; + public unusedpublicvariable: string; + public typedvariable: usedtypeparameter; + + constructor(message: string) { + ~~~~~~~ +!!! error TS6133: 'message' is declared but never used. + var unused2 = 22; + ~~~~~~~ +!!! error TS6133: 'unused2' is declared but never used. + this.greeting = "Dummy Message"; + } + + public greeter(person: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + this.usedPrivateFunction(); + } + + private usedPrivateFunction() { + } + + private unUsedPrivateFunction() { + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS6133: 'unUsedPrivateFunction' is declared but never used. + } + } + + var user = "Jane User"; + var user2 = "Jane2 User2"; + + namespace Validation { + export interface StringValidator { + isAcceptable(s: string): boolean; + } + + const lettersRegexp = /^[A-Za-z]+$/; + const numberRegexp = /^[0-9]+$/; + ~~~~~~~~~~~~ +!!! error TS6133: 'numberRegexp' is declared but never used. + + export class LettersOnlyValidator implements StringValidator { + isAcceptable(s2: string) { + return lettersRegexp.test(s2); + } + + private unUsedPrivateFunction() { + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS6133: 'unUsedPrivateFunction' is declared but never used. + } + } + + export class ZipCodeValidator implements StringValidator { + isAcceptable(s3: string) { + return s3.length === 5; + } + } + + interface usedLocallyInterface { + } + + interface usedLocallyInterface2 { + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS6133: 'usedLocallyInterface2' is declared but never used. + someFunction(s1: string): void; + } + + export interface exportedInterface { + } + + class dummy implements usedLocallyInterface { + ~~~~~ +!!! error TS6133: 'dummy' is declared but never used. + } + + interface unusedInterface { + ~~~~~~~~~~~~~~~ +!!! error TS6133: 'unusedInterface' is declared but never used. + } + } + + + namespace Greeter { + class class1 { + } + + export class class2 extends class1 { + } + + class class3 { + ~~~~~~ +!!! error TS6133: 'class3' is declared but never used. + } + + export class class4 { + } + + interface interface1 { + } + + export interface interface2 extends interface1 { + } + + interface interface3 { + } + + export interface interface4 { + } + + export let a: interface3; + + interface interface5 { + ~~~~~~~~~~ +!!! error TS6133: 'interface5' is declared but never used. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedIdentifiersConsolidated1.js b/tests/baselines/reference/unusedIdentifiersConsolidated1.js new file mode 100644 index 00000000000..521f17bf5ef --- /dev/null +++ b/tests/baselines/reference/unusedIdentifiersConsolidated1.js @@ -0,0 +1,187 @@ +//// [unusedIdentifiersConsolidated1.ts] + +function greeter(person: string) { + var unused = 20; +} + +class Dummy { + private unusedprivatevariable: string; + private greeting: string; + public unusedpublicvariable: string; + public typedvariable: usedtypeparameter; + + constructor(message: string) { + var unused2 = 22; + this.greeting = "Dummy Message"; + } + + public greeter(person: string) { + var unused = 20; + this.usedPrivateFunction(); + } + + private usedPrivateFunction() { + } + + private unUsedPrivateFunction() { + } +} + +var user = "Jane User"; +var user2 = "Jane2 User2"; + +namespace Validation { + export interface StringValidator { + isAcceptable(s: string): boolean; + } + + const lettersRegexp = /^[A-Za-z]+$/; + const numberRegexp = /^[0-9]+$/; + + export class LettersOnlyValidator implements StringValidator { + isAcceptable(s2: string) { + return lettersRegexp.test(s2); + } + + private unUsedPrivateFunction() { + } + } + + export class ZipCodeValidator implements StringValidator { + isAcceptable(s3: string) { + return s3.length === 5; + } + } + + interface usedLocallyInterface { + } + + interface usedLocallyInterface2 { + someFunction(s1: string): void; + } + + export interface exportedInterface { + } + + class dummy implements usedLocallyInterface { + } + + interface unusedInterface { + } +} + + +namespace Greeter { + class class1 { + } + + export class class2 extends class1 { + } + + class class3 { + } + + export class class4 { + } + + interface interface1 { + } + + export interface interface2 extends interface1 { + } + + interface interface3 { + } + + export interface interface4 { + } + + export let a: interface3; + + interface interface5 { + } +} + +//// [unusedIdentifiersConsolidated1.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +function greeter(person) { + var unused = 20; +} +var Dummy = (function () { + function Dummy(message) { + var unused2 = 22; + this.greeting = "Dummy Message"; + } + Dummy.prototype.greeter = function (person) { + var unused = 20; + this.usedPrivateFunction(); + }; + Dummy.prototype.usedPrivateFunction = function () { + }; + Dummy.prototype.unUsedPrivateFunction = function () { + }; + return Dummy; +}()); +var user = "Jane User"; +var user2 = "Jane2 User2"; +var Validation; +(function (Validation) { + var lettersRegexp = /^[A-Za-z]+$/; + var numberRegexp = /^[0-9]+$/; + var LettersOnlyValidator = (function () { + function LettersOnlyValidator() { + } + LettersOnlyValidator.prototype.isAcceptable = function (s2) { + return lettersRegexp.test(s2); + }; + LettersOnlyValidator.prototype.unUsedPrivateFunction = function () { + }; + return LettersOnlyValidator; + }()); + Validation.LettersOnlyValidator = LettersOnlyValidator; + var ZipCodeValidator = (function () { + function ZipCodeValidator() { + } + ZipCodeValidator.prototype.isAcceptable = function (s3) { + return s3.length === 5; + }; + return ZipCodeValidator; + }()); + Validation.ZipCodeValidator = ZipCodeValidator; + var dummy = (function () { + function dummy() { + } + return dummy; + }()); +})(Validation || (Validation = {})); +var Greeter; +(function (Greeter) { + var class1 = (function () { + function class1() { + } + return class1; + }()); + var class2 = (function (_super) { + __extends(class2, _super); + function class2() { + _super.apply(this, arguments); + } + return class2; + }(class1)); + Greeter.class2 = class2; + var class3 = (function () { + function class3() { + } + return class3; + }()); + var class4 = (function () { + function class4() { + } + return class4; + }()); + Greeter.class4 = class4; +})(Greeter || (Greeter = {})); diff --git a/tests/baselines/reference/unusedImports1.errors.txt b/tests/baselines/reference/unusedImports1.errors.txt new file mode 100644 index 00000000000..f2d59c994b5 --- /dev/null +++ b/tests/baselines/reference/unusedImports1.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/file2.ts(1,9): error TS6133: 'Calculator' is declared but never used. + + +==== tests/cases/compiler/file1.ts (0 errors) ==== + + export class Calculator { + + } + +==== tests/cases/compiler/file2.ts (1 errors) ==== + import {Calculator} from "./file1" + ~~~~~~~~~~ +!!! error TS6133: 'Calculator' is declared but never used. \ No newline at end of file diff --git a/tests/baselines/reference/unusedImports1.js b/tests/baselines/reference/unusedImports1.js new file mode 100644 index 00000000000..afd6eb80843 --- /dev/null +++ b/tests/baselines/reference/unusedImports1.js @@ -0,0 +1,21 @@ +//// [tests/cases/compiler/unusedImports1.ts] //// + +//// [file1.ts] + +export class Calculator { + +} + +//// [file2.ts] +import {Calculator} from "./file1" + +//// [file1.js] +"use strict"; +var Calculator = (function () { + function Calculator() { + } + return Calculator; +}()); +exports.Calculator = Calculator; +//// [file2.js] +"use strict"; diff --git a/tests/baselines/reference/unusedImports10.errors.txt b/tests/baselines/reference/unusedImports10.errors.txt new file mode 100644 index 00000000000..c4937a420f9 --- /dev/null +++ b/tests/baselines/reference/unusedImports10.errors.txt @@ -0,0 +1,17 @@ +tests/cases/compiler/unusedImports10.ts(10,12): error TS6133: 'a' is declared but never used. + + +==== tests/cases/compiler/unusedImports10.ts (1 errors) ==== + + module A { + export class Calculator { + public handelChar() { + } + } + } + + module B { + import a = A; + ~ +!!! error TS6133: 'a' is declared but never used. + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedImports10.js b/tests/baselines/reference/unusedImports10.js new file mode 100644 index 00000000000..49365e6e3ff --- /dev/null +++ b/tests/baselines/reference/unusedImports10.js @@ -0,0 +1,25 @@ +//// [unusedImports10.ts] + +module A { + export class Calculator { + public handelChar() { + } + } +} + +module B { + import a = A; +} + +//// [unusedImports10.js] +var A; +(function (A) { + var Calculator = (function () { + function Calculator() { + } + Calculator.prototype.handelChar = function () { + }; + return Calculator; + }()); + A.Calculator = Calculator; +})(A || (A = {})); diff --git a/tests/baselines/reference/unusedImports2.errors.txt b/tests/baselines/reference/unusedImports2.errors.txt new file mode 100644 index 00000000000..d2b3a3c2bc5 --- /dev/null +++ b/tests/baselines/reference/unusedImports2.errors.txt @@ -0,0 +1,21 @@ +tests/cases/compiler/file2.ts(2,9): error TS6133: 'test' is declared but never used. + + +==== tests/cases/compiler/file1.ts (0 errors) ==== + + export class Calculator { + handleChar() {} + } + + export function test() { + + } + +==== tests/cases/compiler/file2.ts (1 errors) ==== + import {Calculator} from "./file1" + import {test} from "./file1" + ~~~~ +!!! error TS6133: 'test' is declared but never used. + + var x = new Calculator(); + x.handleChar(); \ No newline at end of file diff --git a/tests/baselines/reference/unusedImports2.js b/tests/baselines/reference/unusedImports2.js new file mode 100644 index 00000000000..f8918db5ab1 --- /dev/null +++ b/tests/baselines/reference/unusedImports2.js @@ -0,0 +1,36 @@ +//// [tests/cases/compiler/unusedImports2.ts] //// + +//// [file1.ts] + +export class Calculator { + handleChar() {} +} + +export function test() { + +} + +//// [file2.ts] +import {Calculator} from "./file1" +import {test} from "./file1" + +var x = new Calculator(); +x.handleChar(); + +//// [file1.js] +"use strict"; +var Calculator = (function () { + function Calculator() { + } + Calculator.prototype.handleChar = function () { }; + return Calculator; +}()); +exports.Calculator = Calculator; +function test() { +} +exports.test = test; +//// [file2.js] +"use strict"; +var file1_1 = require("./file1"); +var x = new file1_1.Calculator(); +x.handleChar(); diff --git a/tests/baselines/reference/unusedImports3.errors.txt b/tests/baselines/reference/unusedImports3.errors.txt new file mode 100644 index 00000000000..fe398ab4f8e --- /dev/null +++ b/tests/baselines/reference/unusedImports3.errors.txt @@ -0,0 +1,24 @@ +tests/cases/compiler/file2.ts(1,9): error TS6133: 'Calculator' is declared but never used. + + +==== tests/cases/compiler/file1.ts (0 errors) ==== + + export class Calculator { + handleChar() {} + } + + export function test() { + + } + + export function test2() { + + } + +==== tests/cases/compiler/file2.ts (1 errors) ==== + import {Calculator, test, test2} from "./file1" + ~~~~~~~~~~ +!!! error TS6133: 'Calculator' is declared but never used. + + test(); + test2(); \ No newline at end of file diff --git a/tests/baselines/reference/unusedImports3.js b/tests/baselines/reference/unusedImports3.js new file mode 100644 index 00000000000..5c0a3edf16b --- /dev/null +++ b/tests/baselines/reference/unusedImports3.js @@ -0,0 +1,42 @@ +//// [tests/cases/compiler/unusedImports3.ts] //// + +//// [file1.ts] + +export class Calculator { + handleChar() {} +} + +export function test() { + +} + +export function test2() { + +} + +//// [file2.ts] +import {Calculator, test, test2} from "./file1" + +test(); +test2(); + +//// [file1.js] +"use strict"; +var Calculator = (function () { + function Calculator() { + } + Calculator.prototype.handleChar = function () { }; + return Calculator; +}()); +exports.Calculator = Calculator; +function test() { +} +exports.test = test; +function test2() { +} +exports.test2 = test2; +//// [file2.js] +"use strict"; +var file1_1 = require("./file1"); +file1_1.test(); +file1_1.test2(); diff --git a/tests/baselines/reference/unusedImports4.errors.txt b/tests/baselines/reference/unusedImports4.errors.txt new file mode 100644 index 00000000000..872ef8e452e --- /dev/null +++ b/tests/baselines/reference/unusedImports4.errors.txt @@ -0,0 +1,25 @@ +tests/cases/compiler/file2.ts(1,21): error TS6133: 'test' is declared but never used. + + +==== tests/cases/compiler/file1.ts (0 errors) ==== + + export class Calculator { + handleChar() {} + } + + export function test() { + + } + + export function test2() { + + } + +==== tests/cases/compiler/file2.ts (1 errors) ==== + import {Calculator, test, test2} from "./file1" + ~~~~ +!!! error TS6133: 'test' is declared but never used. + + var x = new Calculator(); + x.handleChar(); + test2(); \ No newline at end of file diff --git a/tests/baselines/reference/unusedImports4.js b/tests/baselines/reference/unusedImports4.js new file mode 100644 index 00000000000..e95938091ae --- /dev/null +++ b/tests/baselines/reference/unusedImports4.js @@ -0,0 +1,44 @@ +//// [tests/cases/compiler/unusedImports4.ts] //// + +//// [file1.ts] + +export class Calculator { + handleChar() {} +} + +export function test() { + +} + +export function test2() { + +} + +//// [file2.ts] +import {Calculator, test, test2} from "./file1" + +var x = new Calculator(); +x.handleChar(); +test2(); + +//// [file1.js] +"use strict"; +var Calculator = (function () { + function Calculator() { + } + Calculator.prototype.handleChar = function () { }; + return Calculator; +}()); +exports.Calculator = Calculator; +function test() { +} +exports.test = test; +function test2() { +} +exports.test2 = test2; +//// [file2.js] +"use strict"; +var file1_1 = require("./file1"); +var x = new file1_1.Calculator(); +x.handleChar(); +file1_1.test2(); diff --git a/tests/baselines/reference/unusedImports5.errors.txt b/tests/baselines/reference/unusedImports5.errors.txt new file mode 100644 index 00000000000..deb9dd00f9c --- /dev/null +++ b/tests/baselines/reference/unusedImports5.errors.txt @@ -0,0 +1,25 @@ +tests/cases/compiler/file2.ts(1,27): error TS6133: 'test2' is declared but never used. + + +==== tests/cases/compiler/file1.ts (0 errors) ==== + + export class Calculator { + handleChar() {} + } + + export function test() { + + } + + export function test2() { + + } + +==== tests/cases/compiler/file2.ts (1 errors) ==== + import {Calculator, test, test2} from "./file1" + ~~~~~ +!!! error TS6133: 'test2' is declared but never used. + + var x = new Calculator(); + x.handleChar(); + test(); \ No newline at end of file diff --git a/tests/baselines/reference/unusedImports5.js b/tests/baselines/reference/unusedImports5.js new file mode 100644 index 00000000000..cf92d01eb75 --- /dev/null +++ b/tests/baselines/reference/unusedImports5.js @@ -0,0 +1,44 @@ +//// [tests/cases/compiler/unusedImports5.ts] //// + +//// [file1.ts] + +export class Calculator { + handleChar() {} +} + +export function test() { + +} + +export function test2() { + +} + +//// [file2.ts] +import {Calculator, test, test2} from "./file1" + +var x = new Calculator(); +x.handleChar(); +test(); + +//// [file1.js] +"use strict"; +var Calculator = (function () { + function Calculator() { + } + Calculator.prototype.handleChar = function () { }; + return Calculator; +}()); +exports.Calculator = Calculator; +function test() { +} +exports.test = test; +function test2() { +} +exports.test2 = test2; +//// [file2.js] +"use strict"; +var file1_1 = require("./file1"); +var x = new file1_1.Calculator(); +x.handleChar(); +file1_1.test(); diff --git a/tests/baselines/reference/unusedImports6.errors.txt b/tests/baselines/reference/unusedImports6.errors.txt new file mode 100644 index 00000000000..b27e50ab2d3 --- /dev/null +++ b/tests/baselines/reference/unusedImports6.errors.txt @@ -0,0 +1,25 @@ +tests/cases/compiler/file2.ts(1,8): error TS6133: 'd' is declared but never used. + + +==== tests/cases/compiler/file1.ts (0 errors) ==== + + export class Calculator { + handleChar() {} + } + + export function test() { + + } + + export default function test2() { + + } + +==== tests/cases/compiler/file2.ts (1 errors) ==== + import d from "./file1" + ~ +!!! error TS6133: 'd' is declared but never used. + + + + \ No newline at end of file diff --git a/tests/baselines/reference/unusedImports6.js b/tests/baselines/reference/unusedImports6.js new file mode 100644 index 00000000000..2e203a62a1b --- /dev/null +++ b/tests/baselines/reference/unusedImports6.js @@ -0,0 +1,41 @@ +//// [tests/cases/compiler/unusedImports6.ts] //// + +//// [file1.ts] + +export class Calculator { + handleChar() {} +} + +export function test() { + +} + +export default function test2() { + +} + +//// [file2.ts] +import d from "./file1" + + + + + +//// [file1.js] +"use strict"; +var Calculator = (function () { + function Calculator() { + } + Calculator.prototype.handleChar = function () { }; + return Calculator; +}()); +exports.Calculator = Calculator; +function test() { +} +exports.test = test; +function test2() { +} +exports.__esModule = true; +exports["default"] = test2; +//// [file2.js] +"use strict"; diff --git a/tests/baselines/reference/unusedImports7.errors.txt b/tests/baselines/reference/unusedImports7.errors.txt new file mode 100644 index 00000000000..1ea8ed60635 --- /dev/null +++ b/tests/baselines/reference/unusedImports7.errors.txt @@ -0,0 +1,23 @@ +tests/cases/compiler/file2.ts(1,13): error TS6133: 'n' is declared but never used. + + +==== tests/cases/compiler/file1.ts (0 errors) ==== + + export class Calculator { + handleChar() {} + } + + export function test() { + + } + + export default function test2() { + + } + +==== tests/cases/compiler/file2.ts (1 errors) ==== + import * as n from "./file1" + ~ +!!! error TS6133: 'n' is declared but never used. + + \ No newline at end of file diff --git a/tests/baselines/reference/unusedImports7.js b/tests/baselines/reference/unusedImports7.js new file mode 100644 index 00000000000..67524fcd22a --- /dev/null +++ b/tests/baselines/reference/unusedImports7.js @@ -0,0 +1,39 @@ +//// [tests/cases/compiler/unusedImports7.ts] //// + +//// [file1.ts] + +export class Calculator { + handleChar() {} +} + +export function test() { + +} + +export default function test2() { + +} + +//// [file2.ts] +import * as n from "./file1" + + + +//// [file1.js] +"use strict"; +var Calculator = (function () { + function Calculator() { + } + Calculator.prototype.handleChar = function () { }; + return Calculator; +}()); +exports.Calculator = Calculator; +function test() { +} +exports.test = test; +function test2() { +} +exports.__esModule = true; +exports["default"] = test2; +//// [file2.js] +"use strict"; diff --git a/tests/baselines/reference/unusedImports8.errors.txt b/tests/baselines/reference/unusedImports8.errors.txt new file mode 100644 index 00000000000..d82193106b7 --- /dev/null +++ b/tests/baselines/reference/unusedImports8.errors.txt @@ -0,0 +1,25 @@ +tests/cases/compiler/file2.ts(1,50): error TS6133: 't2' is declared but never used. + + +==== tests/cases/compiler/file1.ts (0 errors) ==== + + export class Calculator { + handleChar() {} + } + + export function test() { + + } + + export function test2() { + + } + +==== tests/cases/compiler/file2.ts (1 errors) ==== + import {Calculator as calc, test as t1, test2 as t2} from "./file1" + ~~ +!!! error TS6133: 't2' is declared but never used. + + var x = new calc(); + x.handleChar(); + t1(); \ No newline at end of file diff --git a/tests/baselines/reference/unusedImports8.js b/tests/baselines/reference/unusedImports8.js new file mode 100644 index 00000000000..2554472e6ce --- /dev/null +++ b/tests/baselines/reference/unusedImports8.js @@ -0,0 +1,44 @@ +//// [tests/cases/compiler/unusedImports8.ts] //// + +//// [file1.ts] + +export class Calculator { + handleChar() {} +} + +export function test() { + +} + +export function test2() { + +} + +//// [file2.ts] +import {Calculator as calc, test as t1, test2 as t2} from "./file1" + +var x = new calc(); +x.handleChar(); +t1(); + +//// [file1.js] +"use strict"; +var Calculator = (function () { + function Calculator() { + } + Calculator.prototype.handleChar = function () { }; + return Calculator; +}()); +exports.Calculator = Calculator; +function test() { +} +exports.test = test; +function test2() { +} +exports.test2 = test2; +//// [file2.js] +"use strict"; +var file1_1 = require("./file1"); +var x = new file1_1.Calculator(); +x.handleChar(); +file1_1.test(); diff --git a/tests/baselines/reference/unusedImports9.errors.txt b/tests/baselines/reference/unusedImports9.errors.txt new file mode 100644 index 00000000000..8503a35e290 --- /dev/null +++ b/tests/baselines/reference/unusedImports9.errors.txt @@ -0,0 +1,21 @@ +tests/cases/compiler/file2.ts(1,8): error TS6133: 'c' is declared but never used. + + +==== tests/cases/compiler/file2.ts (1 errors) ==== + import c = require('./file1') + ~ +!!! error TS6133: 'c' is declared but never used. +==== tests/cases/compiler/file1.ts (0 errors) ==== + + export class Calculator { + handleChar() {} + } + + export function test() { + + } + + export function test2() { + + } + \ No newline at end of file diff --git a/tests/baselines/reference/unusedImports9.js b/tests/baselines/reference/unusedImports9.js new file mode 100644 index 00000000000..cd19e167b19 --- /dev/null +++ b/tests/baselines/reference/unusedImports9.js @@ -0,0 +1,36 @@ +//// [tests/cases/compiler/unusedImports9.ts] //// + +//// [file1.ts] + +export class Calculator { + handleChar() {} +} + +export function test() { + +} + +export function test2() { + +} + +//// [file2.ts] +import c = require('./file1') + +//// [file1.js] +"use strict"; +var Calculator = (function () { + function Calculator() { + } + Calculator.prototype.handleChar = function () { }; + return Calculator; +}()); +exports.Calculator = Calculator; +function test() { +} +exports.test = test; +function test2() { +} +exports.test2 = test2; +//// [file2.js] +"use strict"; diff --git a/tests/baselines/reference/unusedInterfaceinNamespace1.errors.txt b/tests/baselines/reference/unusedInterfaceinNamespace1.errors.txt new file mode 100644 index 00000000000..3fa066e5aae --- /dev/null +++ b/tests/baselines/reference/unusedInterfaceinNamespace1.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/unusedInterfaceinNamespace1.ts(3,15): error TS6133: 'i1' is declared but never used. + + +==== tests/cases/compiler/unusedInterfaceinNamespace1.ts (1 errors) ==== + + namespace Validation { + interface i1 { + ~~ +!!! error TS6133: 'i1' is declared but never used. + + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedInterfaceinNamespace1.js b/tests/baselines/reference/unusedInterfaceinNamespace1.js new file mode 100644 index 00000000000..8b4334c13c7 --- /dev/null +++ b/tests/baselines/reference/unusedInterfaceinNamespace1.js @@ -0,0 +1,9 @@ +//// [unusedInterfaceinNamespace1.ts] + +namespace Validation { + interface i1 { + + } +} + +//// [unusedInterfaceinNamespace1.js] diff --git a/tests/baselines/reference/unusedInterfaceinNamespace2.errors.txt b/tests/baselines/reference/unusedInterfaceinNamespace2.errors.txt new file mode 100644 index 00000000000..0635e7be07b --- /dev/null +++ b/tests/baselines/reference/unusedInterfaceinNamespace2.errors.txt @@ -0,0 +1,16 @@ +tests/cases/compiler/unusedInterfaceinNamespace2.ts(3,15): error TS6133: 'i1' is declared but never used. + + +==== tests/cases/compiler/unusedInterfaceinNamespace2.ts (1 errors) ==== + + namespace Validation { + interface i1 { + ~~ +!!! error TS6133: 'i1' is declared but never used. + + } + + export interface i2 { + + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedInterfaceinNamespace2.js b/tests/baselines/reference/unusedInterfaceinNamespace2.js new file mode 100644 index 00000000000..fbec39921d3 --- /dev/null +++ b/tests/baselines/reference/unusedInterfaceinNamespace2.js @@ -0,0 +1,13 @@ +//// [unusedInterfaceinNamespace2.ts] + +namespace Validation { + interface i1 { + + } + + export interface i2 { + + } +} + +//// [unusedInterfaceinNamespace2.js] diff --git a/tests/baselines/reference/unusedInterfaceinNamespace3.errors.txt b/tests/baselines/reference/unusedInterfaceinNamespace3.errors.txt new file mode 100644 index 00000000000..8aa0e89ae1a --- /dev/null +++ b/tests/baselines/reference/unusedInterfaceinNamespace3.errors.txt @@ -0,0 +1,20 @@ +tests/cases/compiler/unusedInterfaceinNamespace3.ts(11,15): error TS6133: 'i3' is declared but never used. + + +==== tests/cases/compiler/unusedInterfaceinNamespace3.ts (1 errors) ==== + + namespace Validation { + interface i1 { + + } + + export interface i2 { + + } + + interface i3 extends i1 { + ~~ +!!! error TS6133: 'i3' is declared but never used. + + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedInterfaceinNamespace3.js b/tests/baselines/reference/unusedInterfaceinNamespace3.js new file mode 100644 index 00000000000..7409a3d8623 --- /dev/null +++ b/tests/baselines/reference/unusedInterfaceinNamespace3.js @@ -0,0 +1,17 @@ +//// [unusedInterfaceinNamespace3.ts] + +namespace Validation { + interface i1 { + + } + + export interface i2 { + + } + + interface i3 extends i1 { + + } +} + +//// [unusedInterfaceinNamespace3.js] diff --git a/tests/baselines/reference/unusedInterfaceinNamespace4.js b/tests/baselines/reference/unusedInterfaceinNamespace4.js new file mode 100644 index 00000000000..51e09a1565b --- /dev/null +++ b/tests/baselines/reference/unusedInterfaceinNamespace4.js @@ -0,0 +1,30 @@ +//// [unusedInterfaceinNamespace4.ts] + +namespace Validation { + interface i1 { + + } + + export interface i2 { + + } + + interface i3 extends i1 { + + } + + export class c1 implements i3 { + + } +} + +//// [unusedInterfaceinNamespace4.js] +var Validation; +(function (Validation) { + var c1 = (function () { + function c1() { + } + return c1; + }()); + Validation.c1 = c1; +})(Validation || (Validation = {})); diff --git a/tests/baselines/reference/unusedInterfaceinNamespace4.symbols b/tests/baselines/reference/unusedInterfaceinNamespace4.symbols new file mode 100644 index 00000000000..90b2ff5df70 --- /dev/null +++ b/tests/baselines/reference/unusedInterfaceinNamespace4.symbols @@ -0,0 +1,27 @@ +=== tests/cases/compiler/unusedInterfaceinNamespace4.ts === + +namespace Validation { +>Validation : Symbol(Validation, Decl(unusedInterfaceinNamespace4.ts, 0, 0)) + + interface i1 { +>i1 : Symbol(i1, Decl(unusedInterfaceinNamespace4.ts, 1, 22)) + + } + + export interface i2 { +>i2 : Symbol(i2, Decl(unusedInterfaceinNamespace4.ts, 4, 5)) + + } + + interface i3 extends i1 { +>i3 : Symbol(i3, Decl(unusedInterfaceinNamespace4.ts, 8, 5)) +>i1 : Symbol(i1, Decl(unusedInterfaceinNamespace4.ts, 1, 22)) + + } + + export class c1 implements i3 { +>c1 : Symbol(c1, Decl(unusedInterfaceinNamespace4.ts, 12, 5)) +>i3 : Symbol(i3, Decl(unusedInterfaceinNamespace4.ts, 8, 5)) + + } +} diff --git a/tests/baselines/reference/unusedInterfaceinNamespace4.types b/tests/baselines/reference/unusedInterfaceinNamespace4.types new file mode 100644 index 00000000000..1b1efebb299 --- /dev/null +++ b/tests/baselines/reference/unusedInterfaceinNamespace4.types @@ -0,0 +1,27 @@ +=== tests/cases/compiler/unusedInterfaceinNamespace4.ts === + +namespace Validation { +>Validation : typeof Validation + + interface i1 { +>i1 : i1 + + } + + export interface i2 { +>i2 : i2 + + } + + interface i3 extends i1 { +>i3 : i3 +>i1 : i1 + + } + + export class c1 implements i3 { +>c1 : c1 +>i3 : i3 + + } +} diff --git a/tests/baselines/reference/unusedInterfaceinNamespace5.js b/tests/baselines/reference/unusedInterfaceinNamespace5.js new file mode 100644 index 00000000000..bb29b33ebca --- /dev/null +++ b/tests/baselines/reference/unusedInterfaceinNamespace5.js @@ -0,0 +1,36 @@ +//// [unusedInterfaceinNamespace5.ts] + +namespace Validation { + interface i1 { + + } + + export interface i2 { + + } + + interface i3 extends i1 { + + } + + export class c1 implements i3 { + + } + + interface i4 { + + } + + export let c2:i4; +} + +//// [unusedInterfaceinNamespace5.js] +var Validation; +(function (Validation) { + var c1 = (function () { + function c1() { + } + return c1; + }()); + Validation.c1 = c1; +})(Validation || (Validation = {})); diff --git a/tests/baselines/reference/unusedInterfaceinNamespace5.symbols b/tests/baselines/reference/unusedInterfaceinNamespace5.symbols new file mode 100644 index 00000000000..156dc9a3ef1 --- /dev/null +++ b/tests/baselines/reference/unusedInterfaceinNamespace5.symbols @@ -0,0 +1,36 @@ +=== tests/cases/compiler/unusedInterfaceinNamespace5.ts === + +namespace Validation { +>Validation : Symbol(Validation, Decl(unusedInterfaceinNamespace5.ts, 0, 0)) + + interface i1 { +>i1 : Symbol(i1, Decl(unusedInterfaceinNamespace5.ts, 1, 22)) + + } + + export interface i2 { +>i2 : Symbol(i2, Decl(unusedInterfaceinNamespace5.ts, 4, 5)) + + } + + interface i3 extends i1 { +>i3 : Symbol(i3, Decl(unusedInterfaceinNamespace5.ts, 8, 5)) +>i1 : Symbol(i1, Decl(unusedInterfaceinNamespace5.ts, 1, 22)) + + } + + export class c1 implements i3 { +>c1 : Symbol(c1, Decl(unusedInterfaceinNamespace5.ts, 12, 5)) +>i3 : Symbol(i3, Decl(unusedInterfaceinNamespace5.ts, 8, 5)) + + } + + interface i4 { +>i4 : Symbol(i4, Decl(unusedInterfaceinNamespace5.ts, 16, 5)) + + } + + export let c2:i4; +>c2 : Symbol(c2, Decl(unusedInterfaceinNamespace5.ts, 22, 14)) +>i4 : Symbol(i4, Decl(unusedInterfaceinNamespace5.ts, 16, 5)) +} diff --git a/tests/baselines/reference/unusedInterfaceinNamespace5.types b/tests/baselines/reference/unusedInterfaceinNamespace5.types new file mode 100644 index 00000000000..db896be80ae --- /dev/null +++ b/tests/baselines/reference/unusedInterfaceinNamespace5.types @@ -0,0 +1,36 @@ +=== tests/cases/compiler/unusedInterfaceinNamespace5.ts === + +namespace Validation { +>Validation : typeof Validation + + interface i1 { +>i1 : i1 + + } + + export interface i2 { +>i2 : i2 + + } + + interface i3 extends i1 { +>i3 : i3 +>i1 : i1 + + } + + export class c1 implements i3 { +>c1 : c1 +>i3 : i3 + + } + + interface i4 { +>i4 : i4 + + } + + export let c2:i4; +>c2 : i4 +>i4 : i4 +} diff --git a/tests/baselines/reference/unusedLocalsInMethod1.errors.txt b/tests/baselines/reference/unusedLocalsInMethod1.errors.txt new file mode 100644 index 00000000000..18141e5acdd --- /dev/null +++ b/tests/baselines/reference/unusedLocalsInMethod1.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/unusedLocalsInMethod1.ts(4,13): error TS6133: 'x' is declared but never used. + + +==== tests/cases/compiler/unusedLocalsInMethod1.ts (1 errors) ==== + + class greeter { + public function1() { + var x = 10; + ~ +!!! error TS6133: 'x' is declared but never used. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedLocalsInMethod1.js b/tests/baselines/reference/unusedLocalsInMethod1.js new file mode 100644 index 00000000000..7f2e555ab62 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsInMethod1.js @@ -0,0 +1,17 @@ +//// [unusedLocalsInMethod1.ts] + +class greeter { + public function1() { + var x = 10; + } +} + +//// [unusedLocalsInMethod1.js] +var greeter = (function () { + function greeter() { + } + greeter.prototype.function1 = function () { + var x = 10; + }; + return greeter; +}()); diff --git a/tests/baselines/reference/unusedLocalsInMethod2.errors.txt b/tests/baselines/reference/unusedLocalsInMethod2.errors.txt new file mode 100644 index 00000000000..524580bcdf4 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsInMethod2.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/unusedLocalsInMethod2.ts(4,13): error TS6133: 'x' is declared but never used. + + +==== tests/cases/compiler/unusedLocalsInMethod2.ts (1 errors) ==== + + class greeter { + public function1() { + var x, y = 10; + ~ +!!! error TS6133: 'x' is declared but never used. + y++; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedLocalsInMethod2.js b/tests/baselines/reference/unusedLocalsInMethod2.js new file mode 100644 index 00000000000..b92de249750 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsInMethod2.js @@ -0,0 +1,19 @@ +//// [unusedLocalsInMethod2.ts] + +class greeter { + public function1() { + var x, y = 10; + y++; + } +} + +//// [unusedLocalsInMethod2.js] +var greeter = (function () { + function greeter() { + } + greeter.prototype.function1 = function () { + var x, y = 10; + y++; + }; + return greeter; +}()); diff --git a/tests/baselines/reference/unusedLocalsInMethod3.errors.txt b/tests/baselines/reference/unusedLocalsInMethod3.errors.txt new file mode 100644 index 00000000000..b82ceaedba2 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsInMethod3.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/unusedLocalsInMethod3.ts(4,13): error TS6133: 'x' is declared but never used. + + +==== tests/cases/compiler/unusedLocalsInMethod3.ts (1 errors) ==== + + class greeter { + public function1() { + var x, y; + ~ +!!! error TS6133: 'x' is declared but never used. + y = 1; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedLocalsInMethod3.js b/tests/baselines/reference/unusedLocalsInMethod3.js new file mode 100644 index 00000000000..ff148f7a78f --- /dev/null +++ b/tests/baselines/reference/unusedLocalsInMethod3.js @@ -0,0 +1,19 @@ +//// [unusedLocalsInMethod3.ts] + +class greeter { + public function1() { + var x, y; + y = 1; + } +} + +//// [unusedLocalsInMethod3.js] +var greeter = (function () { + function greeter() { + } + greeter.prototype.function1 = function () { + var x, y; + y = 1; + }; + return greeter; +}()); diff --git a/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration1.errors.txt b/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration1.errors.txt new file mode 100644 index 00000000000..fa8337c8f17 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration1.errors.txt @@ -0,0 +1,26 @@ +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration1.ts(2,18): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration1.ts(3,9): error TS6133: 'unused' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration1.ts(4,14): error TS6133: 'maker' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration1.ts(4,20): error TS6133: 'child' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration1.ts(5,13): error TS6133: 'unused2' is declared but never used. + + +==== tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration1.ts (5 errors) ==== + + function greeter(person: string, person2: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + function maker(child: string): void { + ~~~~~ +!!! error TS6133: 'maker' is declared but never used. + ~~~~~ +!!! error TS6133: 'child' is declared but never used. + var unused2 = 22; + ~~~~~~~ +!!! error TS6133: 'unused2' is declared but never used. + } + person2 = "dummy value"; + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration1.js b/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration1.js new file mode 100644 index 00000000000..a8da9dcfa87 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration1.js @@ -0,0 +1,18 @@ +//// [unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration1.ts] + +function greeter(person: string, person2: string) { + var unused = 20; + function maker(child: string): void { + var unused2 = 22; + } + person2 = "dummy value"; +} + +//// [unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration1.js] +function greeter(person, person2) { + var unused = 20; + function maker(child) { + var unused2 = 22; + } + person2 = "dummy value"; +} diff --git a/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.errors.txt b/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.errors.txt new file mode 100644 index 00000000000..0e56f97d1a3 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.errors.txt @@ -0,0 +1,35 @@ +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.ts(2,18): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.ts(3,9): error TS6133: 'unused' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.ts(4,14): error TS6133: 'maker' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.ts(4,20): error TS6133: 'child' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.ts(5,13): error TS6133: 'unused2' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.ts(7,21): error TS6133: 'child2' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.ts(8,13): error TS6133: 'unused3' is declared but never used. + + +==== tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.ts (7 errors) ==== + + function greeter(person: string, person2: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + function maker(child: string): void { + ~~~~~ +!!! error TS6133: 'maker' is declared but never used. + ~~~~~ +!!! error TS6133: 'child' is declared but never used. + var unused2 = 22; + ~~~~~~~ +!!! error TS6133: 'unused2' is declared but never used. + } + function maker2(child2: string): void { + ~~~~~~ +!!! error TS6133: 'child2' is declared but never used. + var unused3 = 23; + ~~~~~~~ +!!! error TS6133: 'unused3' is declared but never used. + } + maker2(person2); + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.js b/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.js new file mode 100644 index 00000000000..28b5057d640 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.js @@ -0,0 +1,24 @@ +//// [unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.ts] + +function greeter(person: string, person2: string) { + var unused = 20; + function maker(child: string): void { + var unused2 = 22; + } + function maker2(child2: string): void { + var unused3 = 23; + } + maker2(person2); +} + +//// [unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.js] +function greeter(person, person2) { + var unused = 20; + function maker(child) { + var unused2 = 22; + } + function maker2(child2) { + var unused3 = 23; + } + maker2(person2); +} diff --git a/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionExpression1.errors.txt b/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionExpression1.errors.txt new file mode 100644 index 00000000000..0b161952835 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionExpression1.errors.txt @@ -0,0 +1,26 @@ +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression1.ts(2,25): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression1.ts(3,9): error TS6133: 'unused' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression1.ts(4,14): error TS6133: 'maker' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression1.ts(4,20): error TS6133: 'child' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression1.ts(5,13): error TS6133: 'unused2' is declared but never used. + + +==== tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression1.ts (5 errors) ==== + + var greeter = function (person: string, person2: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + function maker(child: string): void { + ~~~~~ +!!! error TS6133: 'maker' is declared but never used. + ~~~~~ +!!! error TS6133: 'child' is declared but never used. + var unused2 = 22; + ~~~~~~~ +!!! error TS6133: 'unused2' is declared but never used. + } + person2 = "dummy value"; + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionExpression1.js b/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionExpression1.js new file mode 100644 index 00000000000..b9c76493239 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionExpression1.js @@ -0,0 +1,18 @@ +//// [unusedLocalsOnFunctionDeclarationWithinFunctionExpression1.ts] + +var greeter = function (person: string, person2: string) { + var unused = 20; + function maker(child: string): void { + var unused2 = 22; + } + person2 = "dummy value"; +} + +//// [unusedLocalsOnFunctionDeclarationWithinFunctionExpression1.js] +var greeter = function (person, person2) { + var unused = 20; + function maker(child) { + var unused2 = 22; + } + person2 = "dummy value"; +}; diff --git a/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.errors.txt b/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.errors.txt new file mode 100644 index 00000000000..7e772d98637 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.errors.txt @@ -0,0 +1,35 @@ +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.ts(2,25): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.ts(3,9): error TS6133: 'unused' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.ts(4,14): error TS6133: 'maker' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.ts(4,20): error TS6133: 'child' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.ts(5,13): error TS6133: 'unused2' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.ts(7,21): error TS6133: 'child2' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.ts(8,13): error TS6133: 'unused3' is declared but never used. + + +==== tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.ts (7 errors) ==== + + var greeter = function (person: string, person2: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + function maker(child: string): void { + ~~~~~ +!!! error TS6133: 'maker' is declared but never used. + ~~~~~ +!!! error TS6133: 'child' is declared but never used. + var unused2 = 22; + ~~~~~~~ +!!! error TS6133: 'unused2' is declared but never used. + } + function maker2(child2: string): void { + ~~~~~~ +!!! error TS6133: 'child2' is declared but never used. + var unused3 = 23; + ~~~~~~~ +!!! error TS6133: 'unused3' is declared but never used. + } + maker2(person2); + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.js b/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.js new file mode 100644 index 00000000000..e7930da686c --- /dev/null +++ b/tests/baselines/reference/unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.js @@ -0,0 +1,24 @@ +//// [unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.ts] + +var greeter = function (person: string, person2: string) { + var unused = 20; + function maker(child: string): void { + var unused2 = 22; + } + function maker2(child2: string): void { + var unused3 = 23; + } + maker2(person2); +} + +//// [unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.js] +var greeter = function (person, person2) { + var unused = 20; + function maker(child) { + var unused2 = 22; + } + function maker2(child2) { + var unused3 = 23; + } + maker2(person2); +}; diff --git a/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration1.errors.txt b/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration1.errors.txt new file mode 100644 index 00000000000..99a4fef8958 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration1.errors.txt @@ -0,0 +1,26 @@ +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration1.ts(2,18): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration1.ts(3,9): error TS6133: 'unused' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration1.ts(4,9): error TS6133: 'maker' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration1.ts(4,27): error TS6133: 'child' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration1.ts(5,13): error TS6133: 'unused2' is declared but never used. + + +==== tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration1.ts (5 errors) ==== + + function greeter(person: string, person2: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + var maker = function (child: string): void { + ~~~~~ +!!! error TS6133: 'maker' is declared but never used. + ~~~~~ +!!! error TS6133: 'child' is declared but never used. + var unused2 = 22; + ~~~~~~~ +!!! error TS6133: 'unused2' is declared but never used. + } + person2 = "dummy value"; + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration1.js b/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration1.js new file mode 100644 index 00000000000..880053a8667 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration1.js @@ -0,0 +1,18 @@ +//// [unusedLocalsOnFunctionExpressionWithinFunctionDeclaration1.ts] + +function greeter(person: string, person2: string) { + var unused = 20; + var maker = function (child: string): void { + var unused2 = 22; + } + person2 = "dummy value"; +} + +//// [unusedLocalsOnFunctionExpressionWithinFunctionDeclaration1.js] +function greeter(person, person2) { + var unused = 20; + var maker = function (child) { + var unused2 = 22; + }; + person2 = "dummy value"; +} diff --git a/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.errors.txt b/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.errors.txt new file mode 100644 index 00000000000..8eb1e73d87c --- /dev/null +++ b/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.errors.txt @@ -0,0 +1,35 @@ +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.ts(2,18): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.ts(3,9): error TS6133: 'unused' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.ts(4,9): error TS6133: 'maker' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.ts(4,26): error TS6133: 'child' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.ts(5,13): error TS6133: 'unused2' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.ts(7,27): error TS6133: 'child2' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.ts(8,13): error TS6133: 'unused3' is declared but never used. + + +==== tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.ts (7 errors) ==== + + function greeter(person: string, person2: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + var maker = function(child: string): void { + ~~~~~ +!!! error TS6133: 'maker' is declared but never used. + ~~~~~ +!!! error TS6133: 'child' is declared but never used. + var unused2 = 22; + ~~~~~~~ +!!! error TS6133: 'unused2' is declared but never used. + } + var maker2 = function(child2: string): void { + ~~~~~~ +!!! error TS6133: 'child2' is declared but never used. + var unused3 = 23; + ~~~~~~~ +!!! error TS6133: 'unused3' is declared but never used. + } + maker2(person2); + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.js b/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.js new file mode 100644 index 00000000000..fb37bf9cb5a --- /dev/null +++ b/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.js @@ -0,0 +1,24 @@ +//// [unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.ts] + +function greeter(person: string, person2: string) { + var unused = 20; + var maker = function(child: string): void { + var unused2 = 22; + } + var maker2 = function(child2: string): void { + var unused3 = 23; + } + maker2(person2); +} + +//// [unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.js] +function greeter(person, person2) { + var unused = 20; + var maker = function (child) { + var unused2 = 22; + }; + var maker2 = function (child2) { + var unused3 = 23; + }; + maker2(person2); +} diff --git a/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionExpression1.errors.txt b/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionExpression1.errors.txt new file mode 100644 index 00000000000..dd4778b4f3d --- /dev/null +++ b/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionExpression1.errors.txt @@ -0,0 +1,26 @@ +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression1.ts(2,25): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression1.ts(3,9): error TS6133: 'unused' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression1.ts(4,9): error TS6133: 'maker' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression1.ts(4,27): error TS6133: 'child' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression1.ts(5,13): error TS6133: 'unused2' is declared but never used. + + +==== tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression1.ts (5 errors) ==== + + var greeter = function (person: string, person2: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + var maker = function (child: string): void { + ~~~~~ +!!! error TS6133: 'maker' is declared but never used. + ~~~~~ +!!! error TS6133: 'child' is declared but never used. + var unused2 = 22; + ~~~~~~~ +!!! error TS6133: 'unused2' is declared but never used. + } + person2 = "dummy value"; + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionExpression1.js b/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionExpression1.js new file mode 100644 index 00000000000..299c0e97b94 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionExpression1.js @@ -0,0 +1,18 @@ +//// [unusedLocalsOnFunctionExpressionWithinFunctionExpression1.ts] + +var greeter = function (person: string, person2: string) { + var unused = 20; + var maker = function (child: string): void { + var unused2 = 22; + } + person2 = "dummy value"; +} + +//// [unusedLocalsOnFunctionExpressionWithinFunctionExpression1.js] +var greeter = function (person, person2) { + var unused = 20; + var maker = function (child) { + var unused2 = 22; + }; + person2 = "dummy value"; +}; diff --git a/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionExpression2.errors.txt b/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionExpression2.errors.txt new file mode 100644 index 00000000000..6d22b7a2bde --- /dev/null +++ b/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionExpression2.errors.txt @@ -0,0 +1,35 @@ +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression2.ts(2,25): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression2.ts(3,9): error TS6133: 'unused' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression2.ts(4,9): error TS6133: 'maker' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression2.ts(4,27): error TS6133: 'child' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression2.ts(5,13): error TS6133: 'unused2' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression2.ts(7,28): error TS6133: 'child2' is declared but never used. +tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression2.ts(8,13): error TS6133: 'unused3' is declared but never used. + + +==== tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression2.ts (7 errors) ==== + + var greeter = function (person: string, person2: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + var maker = function (child: string): void { + ~~~~~ +!!! error TS6133: 'maker' is declared but never used. + ~~~~~ +!!! error TS6133: 'child' is declared but never used. + var unused2 = 22; + ~~~~~~~ +!!! error TS6133: 'unused2' is declared but never used. + } + var maker2 = function (child2: string): void { + ~~~~~~ +!!! error TS6133: 'child2' is declared but never used. + var unused3 = 23; + ~~~~~~~ +!!! error TS6133: 'unused3' is declared but never used. + } + maker2(person2); + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionExpression2.js b/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionExpression2.js new file mode 100644 index 00000000000..00ba31b16d7 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsOnFunctionExpressionWithinFunctionExpression2.js @@ -0,0 +1,24 @@ +//// [unusedLocalsOnFunctionExpressionWithinFunctionExpression2.ts] + +var greeter = function (person: string, person2: string) { + var unused = 20; + var maker = function (child: string): void { + var unused2 = 22; + } + var maker2 = function (child2: string): void { + var unused3 = 23; + } + maker2(person2); +} + +//// [unusedLocalsOnFunctionExpressionWithinFunctionExpression2.js] +var greeter = function (person, person2) { + var unused = 20; + var maker = function (child) { + var unused2 = 22; + }; + var maker2 = function (child2) { + var unused3 = 23; + }; + maker2(person2); +}; diff --git a/tests/baselines/reference/unusedLocalsinConstructor1.errors.txt b/tests/baselines/reference/unusedLocalsinConstructor1.errors.txt new file mode 100644 index 00000000000..6fa3ef08839 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsinConstructor1.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/unusedLocalsinConstructor1.ts(4,13): error TS6133: 'unused' is declared but never used. + + +==== tests/cases/compiler/unusedLocalsinConstructor1.ts (1 errors) ==== + + class greeter { + constructor() { + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedLocalsinConstructor1.js b/tests/baselines/reference/unusedLocalsinConstructor1.js new file mode 100644 index 00000000000..28bd7573068 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsinConstructor1.js @@ -0,0 +1,15 @@ +//// [unusedLocalsinConstructor1.ts] + +class greeter { + constructor() { + var unused = 20; + } +} + +//// [unusedLocalsinConstructor1.js] +var greeter = (function () { + function greeter() { + var unused = 20; + } + return greeter; +}()); diff --git a/tests/baselines/reference/unusedLocalsinConstructor2.errors.txt b/tests/baselines/reference/unusedLocalsinConstructor2.errors.txt new file mode 100644 index 00000000000..44c0bddf87c --- /dev/null +++ b/tests/baselines/reference/unusedLocalsinConstructor2.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/unusedLocalsinConstructor2.ts(4,13): error TS6133: 'unused' is declared but never used. + + +==== tests/cases/compiler/unusedLocalsinConstructor2.ts (1 errors) ==== + + class greeter { + constructor() { + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + var used = "dummy"; + used = used + "second part"; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedLocalsinConstructor2.js b/tests/baselines/reference/unusedLocalsinConstructor2.js new file mode 100644 index 00000000000..2fda63d28a3 --- /dev/null +++ b/tests/baselines/reference/unusedLocalsinConstructor2.js @@ -0,0 +1,19 @@ +//// [unusedLocalsinConstructor2.ts] + +class greeter { + constructor() { + var unused = 20; + var used = "dummy"; + used = used + "second part"; + } +} + +//// [unusedLocalsinConstructor2.js] +var greeter = (function () { + function greeter() { + var unused = 20; + var used = "dummy"; + used = used + "second part"; + } + return greeter; +}()); diff --git a/tests/baselines/reference/unusedMethodsInInterface.js b/tests/baselines/reference/unusedMethodsInInterface.js new file mode 100644 index 00000000000..7a1142d99b9 --- /dev/null +++ b/tests/baselines/reference/unusedMethodsInInterface.js @@ -0,0 +1,8 @@ +//// [unusedMethodsInInterface.ts] + +interface I1 { + f1(); + f2(x: number, y: string); +} + +//// [unusedMethodsInInterface.js] diff --git a/tests/baselines/reference/unusedMethodsInInterface.symbols b/tests/baselines/reference/unusedMethodsInInterface.symbols new file mode 100644 index 00000000000..66e4c6cb100 --- /dev/null +++ b/tests/baselines/reference/unusedMethodsInInterface.symbols @@ -0,0 +1,13 @@ +=== tests/cases/compiler/unusedMethodsInInterface.ts === + +interface I1 { +>I1 : Symbol(I1, Decl(unusedMethodsInInterface.ts, 0, 0)) + + f1(); +>f1 : Symbol(I1.f1, Decl(unusedMethodsInInterface.ts, 1, 14)) + + f2(x: number, y: string); +>f2 : Symbol(I1.f2, Decl(unusedMethodsInInterface.ts, 2, 9)) +>x : Symbol(x, Decl(unusedMethodsInInterface.ts, 3, 7)) +>y : Symbol(y, Decl(unusedMethodsInInterface.ts, 3, 17)) +} diff --git a/tests/baselines/reference/unusedMethodsInInterface.types b/tests/baselines/reference/unusedMethodsInInterface.types new file mode 100644 index 00000000000..eb1befac9f0 --- /dev/null +++ b/tests/baselines/reference/unusedMethodsInInterface.types @@ -0,0 +1,13 @@ +=== tests/cases/compiler/unusedMethodsInInterface.ts === + +interface I1 { +>I1 : I1 + + f1(); +>f1 : () => any + + f2(x: number, y: string); +>f2 : (x: number, y: string) => any +>x : number +>y : string +} diff --git a/tests/baselines/reference/unusedModuleInModule.errors.txt b/tests/baselines/reference/unusedModuleInModule.errors.txt new file mode 100644 index 00000000000..2430b07c392 --- /dev/null +++ b/tests/baselines/reference/unusedModuleInModule.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/unusedModuleInModule.ts(3,12): error TS6133: 'B' is declared but never used. + + +==== tests/cases/compiler/unusedModuleInModule.ts (1 errors) ==== + + module A { + module B {} + ~ +!!! error TS6133: 'B' is declared but never used. + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedModuleInModule.js b/tests/baselines/reference/unusedModuleInModule.js new file mode 100644 index 00000000000..68042be9321 --- /dev/null +++ b/tests/baselines/reference/unusedModuleInModule.js @@ -0,0 +1,7 @@ +//// [unusedModuleInModule.ts] + +module A { + module B {} +} + +//// [unusedModuleInModule.js] diff --git a/tests/baselines/reference/unusedMultipleParameter1InContructor.errors.txt b/tests/baselines/reference/unusedMultipleParameter1InContructor.errors.txt new file mode 100644 index 00000000000..28cfc1d578f --- /dev/null +++ b/tests/baselines/reference/unusedMultipleParameter1InContructor.errors.txt @@ -0,0 +1,16 @@ +tests/cases/compiler/unusedMultipleParameter1InContructor.ts(3,17): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedMultipleParameter1InContructor.ts(4,13): error TS6133: 'unused' is declared but never used. + + +==== tests/cases/compiler/unusedMultipleParameter1InContructor.ts (2 errors) ==== + + class Dummy { + constructor(person: string, person2: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + person2 = "Dummy value"; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedMultipleParameter1InContructor.js b/tests/baselines/reference/unusedMultipleParameter1InContructor.js new file mode 100644 index 00000000000..e236ea3d26a --- /dev/null +++ b/tests/baselines/reference/unusedMultipleParameter1InContructor.js @@ -0,0 +1,17 @@ +//// [unusedMultipleParameter1InContructor.ts] + +class Dummy { + constructor(person: string, person2: string) { + var unused = 20; + person2 = "Dummy value"; + } +} + +//// [unusedMultipleParameter1InContructor.js] +var Dummy = (function () { + function Dummy(person, person2) { + var unused = 20; + person2 = "Dummy value"; + } + return Dummy; +}()); diff --git a/tests/baselines/reference/unusedMultipleParameter1InFunctionExpression.errors.txt b/tests/baselines/reference/unusedMultipleParameter1InFunctionExpression.errors.txt new file mode 100644 index 00000000000..d841f7064a1 --- /dev/null +++ b/tests/baselines/reference/unusedMultipleParameter1InFunctionExpression.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/unusedMultipleParameter1InFunctionExpression.ts(2,21): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedMultipleParameter1InFunctionExpression.ts(3,9): error TS6133: 'unused' is declared but never used. + + +==== tests/cases/compiler/unusedMultipleParameter1InFunctionExpression.ts (2 errors) ==== + + var func = function(person: string, person2: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + person2 = "Dummy value"; + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedMultipleParameter1InFunctionExpression.js b/tests/baselines/reference/unusedMultipleParameter1InFunctionExpression.js new file mode 100644 index 00000000000..55a697cc3e0 --- /dev/null +++ b/tests/baselines/reference/unusedMultipleParameter1InFunctionExpression.js @@ -0,0 +1,12 @@ +//// [unusedMultipleParameter1InFunctionExpression.ts] + +var func = function(person: string, person2: string) { + var unused = 20; + person2 = "Dummy value"; +} + +//// [unusedMultipleParameter1InFunctionExpression.js] +var func = function (person, person2) { + var unused = 20; + person2 = "Dummy value"; +}; diff --git a/tests/baselines/reference/unusedMultipleParameter2InContructor.errors.txt b/tests/baselines/reference/unusedMultipleParameter2InContructor.errors.txt new file mode 100644 index 00000000000..2397a849c5c --- /dev/null +++ b/tests/baselines/reference/unusedMultipleParameter2InContructor.errors.txt @@ -0,0 +1,19 @@ +tests/cases/compiler/unusedMultipleParameter2InContructor.ts(3,17): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedMultipleParameter2InContructor.ts(3,50): error TS6133: 'person3' is declared but never used. +tests/cases/compiler/unusedMultipleParameter2InContructor.ts(4,13): error TS6133: 'unused' is declared but never used. + + +==== tests/cases/compiler/unusedMultipleParameter2InContructor.ts (3 errors) ==== + + class Dummy { + constructor(person: string, person2: string, person3: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + ~~~~~~~ +!!! error TS6133: 'person3' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + person2 = "Dummy value"; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedMultipleParameter2InContructor.js b/tests/baselines/reference/unusedMultipleParameter2InContructor.js new file mode 100644 index 00000000000..8ffd4c36591 --- /dev/null +++ b/tests/baselines/reference/unusedMultipleParameter2InContructor.js @@ -0,0 +1,17 @@ +//// [unusedMultipleParameter2InContructor.ts] + +class Dummy { + constructor(person: string, person2: string, person3: string) { + var unused = 20; + person2 = "Dummy value"; + } +} + +//// [unusedMultipleParameter2InContructor.js] +var Dummy = (function () { + function Dummy(person, person2, person3) { + var unused = 20; + person2 = "Dummy value"; + } + return Dummy; +}()); diff --git a/tests/baselines/reference/unusedMultipleParameter2InFunctionExpression.errors.txt b/tests/baselines/reference/unusedMultipleParameter2InFunctionExpression.errors.txt new file mode 100644 index 00000000000..1a4e78cd9fa --- /dev/null +++ b/tests/baselines/reference/unusedMultipleParameter2InFunctionExpression.errors.txt @@ -0,0 +1,17 @@ +tests/cases/compiler/unusedMultipleParameter2InFunctionExpression.ts(2,21): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedMultipleParameter2InFunctionExpression.ts(2,54): error TS6133: 'person3' is declared but never used. +tests/cases/compiler/unusedMultipleParameter2InFunctionExpression.ts(3,9): error TS6133: 'unused' is declared but never used. + + +==== tests/cases/compiler/unusedMultipleParameter2InFunctionExpression.ts (3 errors) ==== + + var func = function(person: string, person2: string, person3: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + ~~~~~~~ +!!! error TS6133: 'person3' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + person2 = "Dummy value"; + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedMultipleParameter2InFunctionExpression.js b/tests/baselines/reference/unusedMultipleParameter2InFunctionExpression.js new file mode 100644 index 00000000000..1c35c1762f3 --- /dev/null +++ b/tests/baselines/reference/unusedMultipleParameter2InFunctionExpression.js @@ -0,0 +1,12 @@ +//// [unusedMultipleParameter2InFunctionExpression.ts] + +var func = function(person: string, person2: string, person3: string) { + var unused = 20; + person2 = "Dummy value"; +} + +//// [unusedMultipleParameter2InFunctionExpression.js] +var func = function (person, person2, person3) { + var unused = 20; + person2 = "Dummy value"; +}; diff --git a/tests/baselines/reference/unusedMultipleParameters1InFunctionDeclaration.errors.txt b/tests/baselines/reference/unusedMultipleParameters1InFunctionDeclaration.errors.txt new file mode 100644 index 00000000000..5ca5eb3bd0c --- /dev/null +++ b/tests/baselines/reference/unusedMultipleParameters1InFunctionDeclaration.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/unusedMultipleParameters1InFunctionDeclaration.ts(2,18): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedMultipleParameters1InFunctionDeclaration.ts(3,9): error TS6133: 'unused' is declared but never used. + + +==== tests/cases/compiler/unusedMultipleParameters1InFunctionDeclaration.ts (2 errors) ==== + + function greeter(person: string, person2: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + person2 = "dummy value"; + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedMultipleParameters1InFunctionDeclaration.js b/tests/baselines/reference/unusedMultipleParameters1InFunctionDeclaration.js new file mode 100644 index 00000000000..caac12c8735 --- /dev/null +++ b/tests/baselines/reference/unusedMultipleParameters1InFunctionDeclaration.js @@ -0,0 +1,12 @@ +//// [unusedMultipleParameters1InFunctionDeclaration.ts] + +function greeter(person: string, person2: string) { + var unused = 20; + person2 = "dummy value"; +} + +//// [unusedMultipleParameters1InFunctionDeclaration.js] +function greeter(person, person2) { + var unused = 20; + person2 = "dummy value"; +} diff --git a/tests/baselines/reference/unusedMultipleParameters1InMethodDeclaration.errors.txt b/tests/baselines/reference/unusedMultipleParameters1InMethodDeclaration.errors.txt new file mode 100644 index 00000000000..9e917be257e --- /dev/null +++ b/tests/baselines/reference/unusedMultipleParameters1InMethodDeclaration.errors.txt @@ -0,0 +1,16 @@ +tests/cases/compiler/unusedMultipleParameters1InMethodDeclaration.ts(3,20): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedMultipleParameters1InMethodDeclaration.ts(4,13): error TS6133: 'unused' is declared but never used. + + +==== tests/cases/compiler/unusedMultipleParameters1InMethodDeclaration.ts (2 errors) ==== + + class Dummy { + public greeter(person: string, person2: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + person2 = "dummy value"; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedMultipleParameters1InMethodDeclaration.js b/tests/baselines/reference/unusedMultipleParameters1InMethodDeclaration.js new file mode 100644 index 00000000000..bc78da7bd75 --- /dev/null +++ b/tests/baselines/reference/unusedMultipleParameters1InMethodDeclaration.js @@ -0,0 +1,19 @@ +//// [unusedMultipleParameters1InMethodDeclaration.ts] + +class Dummy { + public greeter(person: string, person2: string) { + var unused = 20; + person2 = "dummy value"; + } +} + +//// [unusedMultipleParameters1InMethodDeclaration.js] +var Dummy = (function () { + function Dummy() { + } + Dummy.prototype.greeter = function (person, person2) { + var unused = 20; + person2 = "dummy value"; + }; + return Dummy; +}()); diff --git a/tests/baselines/reference/unusedMultipleParameters2InFunctionDeclaration.errors.txt b/tests/baselines/reference/unusedMultipleParameters2InFunctionDeclaration.errors.txt new file mode 100644 index 00000000000..0c755b404cd --- /dev/null +++ b/tests/baselines/reference/unusedMultipleParameters2InFunctionDeclaration.errors.txt @@ -0,0 +1,17 @@ +tests/cases/compiler/unusedMultipleParameters2InFunctionDeclaration.ts(2,18): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedMultipleParameters2InFunctionDeclaration.ts(2,51): error TS6133: 'person3' is declared but never used. +tests/cases/compiler/unusedMultipleParameters2InFunctionDeclaration.ts(3,9): error TS6133: 'unused' is declared but never used. + + +==== tests/cases/compiler/unusedMultipleParameters2InFunctionDeclaration.ts (3 errors) ==== + + function greeter(person: string, person2: string, person3: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + ~~~~~~~ +!!! error TS6133: 'person3' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + person2 = "dummy value"; + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedMultipleParameters2InFunctionDeclaration.js b/tests/baselines/reference/unusedMultipleParameters2InFunctionDeclaration.js new file mode 100644 index 00000000000..1197cabf646 --- /dev/null +++ b/tests/baselines/reference/unusedMultipleParameters2InFunctionDeclaration.js @@ -0,0 +1,12 @@ +//// [unusedMultipleParameters2InFunctionDeclaration.ts] + +function greeter(person: string, person2: string, person3: string) { + var unused = 20; + person2 = "dummy value"; +} + +//// [unusedMultipleParameters2InFunctionDeclaration.js] +function greeter(person, person2, person3) { + var unused = 20; + person2 = "dummy value"; +} diff --git a/tests/baselines/reference/unusedMultipleParameters2InMethodDeclaration.errors.txt b/tests/baselines/reference/unusedMultipleParameters2InMethodDeclaration.errors.txt new file mode 100644 index 00000000000..ab3313dc98b --- /dev/null +++ b/tests/baselines/reference/unusedMultipleParameters2InMethodDeclaration.errors.txt @@ -0,0 +1,19 @@ +tests/cases/compiler/unusedMultipleParameters2InMethodDeclaration.ts(3,20): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedMultipleParameters2InMethodDeclaration.ts(3,53): error TS6133: 'person3' is declared but never used. +tests/cases/compiler/unusedMultipleParameters2InMethodDeclaration.ts(4,13): error TS6133: 'unused' is declared but never used. + + +==== tests/cases/compiler/unusedMultipleParameters2InMethodDeclaration.ts (3 errors) ==== + + class Dummy { + public greeter(person: string, person2: string, person3: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + ~~~~~~~ +!!! error TS6133: 'person3' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + person2 = "dummy value"; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedMultipleParameters2InMethodDeclaration.js b/tests/baselines/reference/unusedMultipleParameters2InMethodDeclaration.js new file mode 100644 index 00000000000..80f93990b5b --- /dev/null +++ b/tests/baselines/reference/unusedMultipleParameters2InMethodDeclaration.js @@ -0,0 +1,19 @@ +//// [unusedMultipleParameters2InMethodDeclaration.ts] + +class Dummy { + public greeter(person: string, person2: string, person3: string) { + var unused = 20; + person2 = "dummy value"; + } +} + +//// [unusedMultipleParameters2InMethodDeclaration.js] +var Dummy = (function () { + function Dummy() { + } + Dummy.prototype.greeter = function (person, person2, person3) { + var unused = 20; + person2 = "dummy value"; + }; + return Dummy; +}()); diff --git a/tests/baselines/reference/unusedNamespaceInModule.errors.txt b/tests/baselines/reference/unusedNamespaceInModule.errors.txt new file mode 100644 index 00000000000..78e389f4c47 --- /dev/null +++ b/tests/baselines/reference/unusedNamespaceInModule.errors.txt @@ -0,0 +1,11 @@ +tests/cases/compiler/unusedNamespaceInModule.ts(3,15): error TS6133: 'B' is declared but never used. + + +==== tests/cases/compiler/unusedNamespaceInModule.ts (1 errors) ==== + + module A { + namespace B { } + ~ +!!! error TS6133: 'B' is declared but never used. + export namespace C {} + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedNamespaceInModule.js b/tests/baselines/reference/unusedNamespaceInModule.js new file mode 100644 index 00000000000..238ff84767c --- /dev/null +++ b/tests/baselines/reference/unusedNamespaceInModule.js @@ -0,0 +1,8 @@ +//// [unusedNamespaceInModule.ts] + +module A { + namespace B { } + export namespace C {} +} + +//// [unusedNamespaceInModule.js] diff --git a/tests/baselines/reference/unusedNamespaceInNamespace.errors.txt b/tests/baselines/reference/unusedNamespaceInNamespace.errors.txt new file mode 100644 index 00000000000..53582b8bec7 --- /dev/null +++ b/tests/baselines/reference/unusedNamespaceInNamespace.errors.txt @@ -0,0 +1,11 @@ +tests/cases/compiler/unusedNamespaceInNamespace.ts(3,15): error TS6133: 'B' is declared but never used. + + +==== tests/cases/compiler/unusedNamespaceInNamespace.ts (1 errors) ==== + + namespace A { + namespace B { } + ~ +!!! error TS6133: 'B' is declared but never used. + export namespace C {} + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedNamespaceInNamespace.js b/tests/baselines/reference/unusedNamespaceInNamespace.js new file mode 100644 index 00000000000..1dc8103d77f --- /dev/null +++ b/tests/baselines/reference/unusedNamespaceInNamespace.js @@ -0,0 +1,8 @@ +//// [unusedNamespaceInNamespace.ts] + +namespace A { + namespace B { } + export namespace C {} +} + +//// [unusedNamespaceInNamespace.js] diff --git a/tests/baselines/reference/unusedParameterInCatchClause.errors.txt b/tests/baselines/reference/unusedParameterInCatchClause.errors.txt new file mode 100644 index 00000000000..e996763e2c6 --- /dev/null +++ b/tests/baselines/reference/unusedParameterInCatchClause.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/unusedParameterInCatchClause.ts(3,18): error TS6133: 'ex' is declared but never used. + + +==== tests/cases/compiler/unusedParameterInCatchClause.ts (1 errors) ==== + + function f1() { + try {} catch(ex){} + ~~ +!!! error TS6133: 'ex' is declared but never used. + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedParameterInCatchClause.js b/tests/baselines/reference/unusedParameterInCatchClause.js new file mode 100644 index 00000000000..153ee17926e --- /dev/null +++ b/tests/baselines/reference/unusedParameterInCatchClause.js @@ -0,0 +1,11 @@ +//// [unusedParameterInCatchClause.ts] + +function f1() { + try {} catch(ex){} +} + +//// [unusedParameterInCatchClause.js] +function f1() { + try { } + catch (ex) { } +} diff --git a/tests/baselines/reference/unusedParameterUsedInTypeOf.js b/tests/baselines/reference/unusedParameterUsedInTypeOf.js new file mode 100644 index 00000000000..fc2589c31ff --- /dev/null +++ b/tests/baselines/reference/unusedParameterUsedInTypeOf.js @@ -0,0 +1,10 @@ +//// [unusedParameterUsedInTypeOf.ts] + +function f1 (a: number, b: typeof a) { + b++; +} + +//// [unusedParameterUsedInTypeOf.js] +function f1(a, b) { + b++; +} diff --git a/tests/baselines/reference/unusedParameterUsedInTypeOf.symbols b/tests/baselines/reference/unusedParameterUsedInTypeOf.symbols new file mode 100644 index 00000000000..9730baca34f --- /dev/null +++ b/tests/baselines/reference/unusedParameterUsedInTypeOf.symbols @@ -0,0 +1,11 @@ +=== tests/cases/compiler/unusedParameterUsedInTypeOf.ts === + +function f1 (a: number, b: typeof a) { +>f1 : Symbol(f1, Decl(unusedParameterUsedInTypeOf.ts, 0, 0)) +>a : Symbol(a, Decl(unusedParameterUsedInTypeOf.ts, 1, 13)) +>b : Symbol(b, Decl(unusedParameterUsedInTypeOf.ts, 1, 23)) +>a : Symbol(a, Decl(unusedParameterUsedInTypeOf.ts, 1, 13)) + + b++; +>b : Symbol(b, Decl(unusedParameterUsedInTypeOf.ts, 1, 23)) +} diff --git a/tests/baselines/reference/unusedParameterUsedInTypeOf.types b/tests/baselines/reference/unusedParameterUsedInTypeOf.types new file mode 100644 index 00000000000..d3b5bb67661 --- /dev/null +++ b/tests/baselines/reference/unusedParameterUsedInTypeOf.types @@ -0,0 +1,12 @@ +=== tests/cases/compiler/unusedParameterUsedInTypeOf.ts === + +function f1 (a: number, b: typeof a) { +>f1 : (a: number, b: number) => void +>a : number +>b : number +>a : number + + b++; +>b++ : number +>b : number +} diff --git a/tests/baselines/reference/unusedParametersInLambda1.errors.txt b/tests/baselines/reference/unusedParametersInLambda1.errors.txt new file mode 100644 index 00000000000..2c54de1d571 --- /dev/null +++ b/tests/baselines/reference/unusedParametersInLambda1.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/unusedParametersInLambda1.ts(4,17): error TS6133: 'X' is declared but never used. + + +==== tests/cases/compiler/unusedParametersInLambda1.ts (1 errors) ==== + + class A { + public f1() { + return (X) => { + ~ +!!! error TS6133: 'X' is declared but never used. + } + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedParametersInLambda1.js b/tests/baselines/reference/unusedParametersInLambda1.js new file mode 100644 index 00000000000..c3ca54bd6a7 --- /dev/null +++ b/tests/baselines/reference/unusedParametersInLambda1.js @@ -0,0 +1,19 @@ +//// [unusedParametersInLambda1.ts] + +class A { + public f1() { + return (X) => { + } + } +} + +//// [unusedParametersInLambda1.js] +var A = (function () { + function A() { + } + A.prototype.f1 = function () { + return function (X) { + }; + }; + return A; +}()); diff --git a/tests/baselines/reference/unusedParametersInLambda2.errors.txt b/tests/baselines/reference/unusedParametersInLambda2.errors.txt new file mode 100644 index 00000000000..3044e6d9c88 --- /dev/null +++ b/tests/baselines/reference/unusedParametersInLambda2.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/unusedParametersInLambda2.ts(4,17): error TS6133: 'X' is declared but never used. + + +==== tests/cases/compiler/unusedParametersInLambda2.ts (1 errors) ==== + + class A { + public f1() { + return (X, Y) => { + ~ +!!! error TS6133: 'X' is declared but never used. + Y; + } + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedParametersInLambda2.js b/tests/baselines/reference/unusedParametersInLambda2.js new file mode 100644 index 00000000000..b7833af340e --- /dev/null +++ b/tests/baselines/reference/unusedParametersInLambda2.js @@ -0,0 +1,21 @@ +//// [unusedParametersInLambda2.ts] + +class A { + public f1() { + return (X, Y) => { + Y; + } + } +} + +//// [unusedParametersInLambda2.js] +var A = (function () { + function A() { + } + A.prototype.f1 = function () { + return function (X, Y) { + Y; + }; + }; + return A; +}()); diff --git a/tests/baselines/reference/unusedParametersinConstructor1.errors.txt b/tests/baselines/reference/unusedParametersinConstructor1.errors.txt new file mode 100644 index 00000000000..d09d5906ed1 --- /dev/null +++ b/tests/baselines/reference/unusedParametersinConstructor1.errors.txt @@ -0,0 +1,11 @@ +tests/cases/compiler/unusedParametersinConstructor1.ts(3,17): error TS6133: 'param1' is declared but never used. + + +==== tests/cases/compiler/unusedParametersinConstructor1.ts (1 errors) ==== + + class greeter { + constructor(param1: string) { + ~~~~~~ +!!! error TS6133: 'param1' is declared but never used. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedParametersinConstructor1.js b/tests/baselines/reference/unusedParametersinConstructor1.js new file mode 100644 index 00000000000..500d7a45eb2 --- /dev/null +++ b/tests/baselines/reference/unusedParametersinConstructor1.js @@ -0,0 +1,13 @@ +//// [unusedParametersinConstructor1.ts] + +class greeter { + constructor(param1: string) { + } +} + +//// [unusedParametersinConstructor1.js] +var greeter = (function () { + function greeter(param1) { + } + return greeter; +}()); diff --git a/tests/baselines/reference/unusedParametersinConstructor2.errors.txt b/tests/baselines/reference/unusedParametersinConstructor2.errors.txt new file mode 100644 index 00000000000..4566713f24f --- /dev/null +++ b/tests/baselines/reference/unusedParametersinConstructor2.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/unusedParametersinConstructor2.ts(3,17): error TS6133: 'param1' is declared but never used. + + +==== tests/cases/compiler/unusedParametersinConstructor2.ts (1 errors) ==== + + class greeter { + constructor(param1: string, param2: string) { + ~~~~~~ +!!! error TS6133: 'param1' is declared but never used. + param2 = param2 + "dummy value"; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedParametersinConstructor2.js b/tests/baselines/reference/unusedParametersinConstructor2.js new file mode 100644 index 00000000000..97bbf21ee04 --- /dev/null +++ b/tests/baselines/reference/unusedParametersinConstructor2.js @@ -0,0 +1,15 @@ +//// [unusedParametersinConstructor2.ts] + +class greeter { + constructor(param1: string, param2: string) { + param2 = param2 + "dummy value"; + } +} + +//// [unusedParametersinConstructor2.js] +var greeter = (function () { + function greeter(param1, param2) { + param2 = param2 + "dummy value"; + } + return greeter; +}()); diff --git a/tests/baselines/reference/unusedParametersinConstructor3.errors.txt b/tests/baselines/reference/unusedParametersinConstructor3.errors.txt new file mode 100644 index 00000000000..48891e5361e --- /dev/null +++ b/tests/baselines/reference/unusedParametersinConstructor3.errors.txt @@ -0,0 +1,15 @@ +tests/cases/compiler/unusedParametersinConstructor3.ts(3,17): error TS6133: 'param1' is declared but never used. +tests/cases/compiler/unusedParametersinConstructor3.ts(3,49): error TS6133: 'param3' is declared but never used. + + +==== tests/cases/compiler/unusedParametersinConstructor3.ts (2 errors) ==== + + class greeter { + constructor(param1: string, param2: string, param3: string) { + ~~~~~~ +!!! error TS6133: 'param1' is declared but never used. + ~~~~~~ +!!! error TS6133: 'param3' is declared but never used. + param2 = param2 + "dummy value"; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedParametersinConstructor3.js b/tests/baselines/reference/unusedParametersinConstructor3.js new file mode 100644 index 00000000000..06ac99229ac --- /dev/null +++ b/tests/baselines/reference/unusedParametersinConstructor3.js @@ -0,0 +1,15 @@ +//// [unusedParametersinConstructor3.ts] + +class greeter { + constructor(param1: string, param2: string, param3: string) { + param2 = param2 + "dummy value"; + } +} + +//// [unusedParametersinConstructor3.js] +var greeter = (function () { + function greeter(param1, param2, param3) { + param2 = param2 + "dummy value"; + } + return greeter; +}()); diff --git a/tests/baselines/reference/unusedPrivateMethodInClass1.errors.txt b/tests/baselines/reference/unusedPrivateMethodInClass1.errors.txt new file mode 100644 index 00000000000..40357c0b7f0 --- /dev/null +++ b/tests/baselines/reference/unusedPrivateMethodInClass1.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/unusedPrivateMethodInClass1.ts(3,13): error TS6133: 'function1' is declared but never used. + + +==== tests/cases/compiler/unusedPrivateMethodInClass1.ts (1 errors) ==== + + class greeter { + private function1() { + ~~~~~~~~~ +!!! error TS6133: 'function1' is declared but never used. + var y = 10; + y++; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedPrivateMethodInClass1.js b/tests/baselines/reference/unusedPrivateMethodInClass1.js new file mode 100644 index 00000000000..18e6fc339c3 --- /dev/null +++ b/tests/baselines/reference/unusedPrivateMethodInClass1.js @@ -0,0 +1,19 @@ +//// [unusedPrivateMethodInClass1.ts] + +class greeter { + private function1() { + var y = 10; + y++; + } +} + +//// [unusedPrivateMethodInClass1.js] +var greeter = (function () { + function greeter() { + } + greeter.prototype.function1 = function () { + var y = 10; + y++; + }; + return greeter; +}()); diff --git a/tests/baselines/reference/unusedPrivateMethodInClass2.errors.txt b/tests/baselines/reference/unusedPrivateMethodInClass2.errors.txt new file mode 100644 index 00000000000..36a7a3c40d0 --- /dev/null +++ b/tests/baselines/reference/unusedPrivateMethodInClass2.errors.txt @@ -0,0 +1,21 @@ +tests/cases/compiler/unusedPrivateMethodInClass2.ts(3,13): error TS6133: 'function1' is declared but never used. +tests/cases/compiler/unusedPrivateMethodInClass2.ts(8,13): error TS6133: 'function2' is declared but never used. + + +==== tests/cases/compiler/unusedPrivateMethodInClass2.ts (2 errors) ==== + + class greeter { + private function1() { + ~~~~~~~~~ +!!! error TS6133: 'function1' is declared but never used. + var y = 10; + y++; + } + + private function2() { + ~~~~~~~~~ +!!! error TS6133: 'function2' is declared but never used. + var y = 10; + y++; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedPrivateMethodInClass2.js b/tests/baselines/reference/unusedPrivateMethodInClass2.js new file mode 100644 index 00000000000..6a1dbd4df68 --- /dev/null +++ b/tests/baselines/reference/unusedPrivateMethodInClass2.js @@ -0,0 +1,28 @@ +//// [unusedPrivateMethodInClass2.ts] + +class greeter { + private function1() { + var y = 10; + y++; + } + + private function2() { + var y = 10; + y++; + } +} + +//// [unusedPrivateMethodInClass2.js] +var greeter = (function () { + function greeter() { + } + greeter.prototype.function1 = function () { + var y = 10; + y++; + }; + greeter.prototype.function2 = function () { + var y = 10; + y++; + }; + return greeter; +}()); diff --git a/tests/baselines/reference/unusedPrivateMethodInClass3.errors.txt b/tests/baselines/reference/unusedPrivateMethodInClass3.errors.txt new file mode 100644 index 00000000000..365cfb32135 --- /dev/null +++ b/tests/baselines/reference/unusedPrivateMethodInClass3.errors.txt @@ -0,0 +1,26 @@ +tests/cases/compiler/unusedPrivateMethodInClass3.ts(3,13): error TS6133: 'function1' is declared but never used. +tests/cases/compiler/unusedPrivateMethodInClass3.ts(8,13): error TS6133: 'function2' is declared but never used. + + +==== tests/cases/compiler/unusedPrivateMethodInClass3.ts (2 errors) ==== + + class greeter { + private function1() { + ~~~~~~~~~ +!!! error TS6133: 'function1' is declared but never used. + var y = 10; + y++; + } + + private function2() { + ~~~~~~~~~ +!!! error TS6133: 'function2' is declared but never used. + var y = 10; + y++; + } + + public function3() { + var y = 10; + y++; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedPrivateMethodInClass3.js b/tests/baselines/reference/unusedPrivateMethodInClass3.js new file mode 100644 index 00000000000..0009a52f8b6 --- /dev/null +++ b/tests/baselines/reference/unusedPrivateMethodInClass3.js @@ -0,0 +1,37 @@ +//// [unusedPrivateMethodInClass3.ts] + +class greeter { + private function1() { + var y = 10; + y++; + } + + private function2() { + var y = 10; + y++; + } + + public function3() { + var y = 10; + y++; + } +} + +//// [unusedPrivateMethodInClass3.js] +var greeter = (function () { + function greeter() { + } + greeter.prototype.function1 = function () { + var y = 10; + y++; + }; + greeter.prototype.function2 = function () { + var y = 10; + y++; + }; + greeter.prototype.function3 = function () { + var y = 10; + y++; + }; + return greeter; +}()); diff --git a/tests/baselines/reference/unusedPrivateMethodInClass4.errors.txt b/tests/baselines/reference/unusedPrivateMethodInClass4.errors.txt new file mode 100644 index 00000000000..324e7d17bbc --- /dev/null +++ b/tests/baselines/reference/unusedPrivateMethodInClass4.errors.txt @@ -0,0 +1,24 @@ +tests/cases/compiler/unusedPrivateMethodInClass4.ts(3,13): error TS6133: 'function1' is declared but never used. + + +==== tests/cases/compiler/unusedPrivateMethodInClass4.ts (1 errors) ==== + + class greeter { + private function1() { + ~~~~~~~~~ +!!! error TS6133: 'function1' is declared but never used. + var y = 10; + y++; + } + + private function2() { + var y = 10; + y++; + } + + public function3() { + var y = 10; + y++; + this.function2(); + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedPrivateMethodInClass4.js b/tests/baselines/reference/unusedPrivateMethodInClass4.js new file mode 100644 index 00000000000..6bf2b928fa4 --- /dev/null +++ b/tests/baselines/reference/unusedPrivateMethodInClass4.js @@ -0,0 +1,39 @@ +//// [unusedPrivateMethodInClass4.ts] + +class greeter { + private function1() { + var y = 10; + y++; + } + + private function2() { + var y = 10; + y++; + } + + public function3() { + var y = 10; + y++; + this.function2(); + } +} + +//// [unusedPrivateMethodInClass4.js] +var greeter = (function () { + function greeter() { + } + greeter.prototype.function1 = function () { + var y = 10; + y++; + }; + greeter.prototype.function2 = function () { + var y = 10; + y++; + }; + greeter.prototype.function3 = function () { + var y = 10; + y++; + this.function2(); + }; + return greeter; +}()); diff --git a/tests/baselines/reference/unusedPrivateVariableInClass1.errors.txt b/tests/baselines/reference/unusedPrivateVariableInClass1.errors.txt new file mode 100644 index 00000000000..bb971334135 --- /dev/null +++ b/tests/baselines/reference/unusedPrivateVariableInClass1.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/unusedPrivateVariableInClass1.ts(3,13): error TS6133: 'x' is declared but never used. + + +==== tests/cases/compiler/unusedPrivateVariableInClass1.ts (1 errors) ==== + + class greeter { + private x: string; + ~ +!!! error TS6133: 'x' is declared but never used. + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedPrivateVariableInClass1.js b/tests/baselines/reference/unusedPrivateVariableInClass1.js new file mode 100644 index 00000000000..464676490d8 --- /dev/null +++ b/tests/baselines/reference/unusedPrivateVariableInClass1.js @@ -0,0 +1,12 @@ +//// [unusedPrivateVariableInClass1.ts] + +class greeter { + private x: string; +} + +//// [unusedPrivateVariableInClass1.js] +var greeter = (function () { + function greeter() { + } + return greeter; +}()); diff --git a/tests/baselines/reference/unusedPrivateVariableInClass2.errors.txt b/tests/baselines/reference/unusedPrivateVariableInClass2.errors.txt new file mode 100644 index 00000000000..3b814e5ca7c --- /dev/null +++ b/tests/baselines/reference/unusedPrivateVariableInClass2.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/unusedPrivateVariableInClass2.ts(3,13): error TS6133: 'x' is declared but never used. +tests/cases/compiler/unusedPrivateVariableInClass2.ts(4,13): error TS6133: 'y' is declared but never used. + + +==== tests/cases/compiler/unusedPrivateVariableInClass2.ts (2 errors) ==== + + class greeter { + private x: string; + ~ +!!! error TS6133: 'x' is declared but never used. + private y: string; + ~ +!!! error TS6133: 'y' is declared but never used. + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedPrivateVariableInClass2.js b/tests/baselines/reference/unusedPrivateVariableInClass2.js new file mode 100644 index 00000000000..329e2bbe2b6 --- /dev/null +++ b/tests/baselines/reference/unusedPrivateVariableInClass2.js @@ -0,0 +1,13 @@ +//// [unusedPrivateVariableInClass2.ts] + +class greeter { + private x: string; + private y: string; +} + +//// [unusedPrivateVariableInClass2.js] +var greeter = (function () { + function greeter() { + } + return greeter; +}()); diff --git a/tests/baselines/reference/unusedPrivateVariableInClass3.errors.txt b/tests/baselines/reference/unusedPrivateVariableInClass3.errors.txt new file mode 100644 index 00000000000..5d5e18a2fdf --- /dev/null +++ b/tests/baselines/reference/unusedPrivateVariableInClass3.errors.txt @@ -0,0 +1,15 @@ +tests/cases/compiler/unusedPrivateVariableInClass3.ts(3,13): error TS6133: 'x' is declared but never used. +tests/cases/compiler/unusedPrivateVariableInClass3.ts(4,13): error TS6133: 'y' is declared but never used. + + +==== tests/cases/compiler/unusedPrivateVariableInClass3.ts (2 errors) ==== + + class greeter { + private x: string; + ~ +!!! error TS6133: 'x' is declared but never used. + private y: string; + ~ +!!! error TS6133: 'y' is declared but never used. + public z: string; + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedPrivateVariableInClass3.js b/tests/baselines/reference/unusedPrivateVariableInClass3.js new file mode 100644 index 00000000000..c72b9e61995 --- /dev/null +++ b/tests/baselines/reference/unusedPrivateVariableInClass3.js @@ -0,0 +1,14 @@ +//// [unusedPrivateVariableInClass3.ts] + +class greeter { + private x: string; + private y: string; + public z: string; +} + +//// [unusedPrivateVariableInClass3.js] +var greeter = (function () { + function greeter() { + } + return greeter; +}()); diff --git a/tests/baselines/reference/unusedPrivateVariableInClass4.errors.txt b/tests/baselines/reference/unusedPrivateVariableInClass4.errors.txt new file mode 100644 index 00000000000..83325cf2d8a --- /dev/null +++ b/tests/baselines/reference/unusedPrivateVariableInClass4.errors.txt @@ -0,0 +1,16 @@ +tests/cases/compiler/unusedPrivateVariableInClass4.ts(4,13): error TS6133: 'y' is declared but never used. + + +==== tests/cases/compiler/unusedPrivateVariableInClass4.ts (1 errors) ==== + + class greeter { + private x: string; + private y: string; + ~ +!!! error TS6133: 'y' is declared but never used. + public z: string; + + public method1() { + this.x = "dummy value"; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedPrivateVariableInClass4.js b/tests/baselines/reference/unusedPrivateVariableInClass4.js new file mode 100644 index 00000000000..878a7780e85 --- /dev/null +++ b/tests/baselines/reference/unusedPrivateVariableInClass4.js @@ -0,0 +1,21 @@ +//// [unusedPrivateVariableInClass4.ts] + +class greeter { + private x: string; + private y: string; + public z: string; + + public method1() { + this.x = "dummy value"; + } +} + +//// [unusedPrivateVariableInClass4.js] +var greeter = (function () { + function greeter() { + } + greeter.prototype.method1 = function () { + this.x = "dummy value"; + }; + return greeter; +}()); diff --git a/tests/baselines/reference/unusedPrivateVariableInClass5.errors.txt b/tests/baselines/reference/unusedPrivateVariableInClass5.errors.txt new file mode 100644 index 00000000000..741406c5284 --- /dev/null +++ b/tests/baselines/reference/unusedPrivateVariableInClass5.errors.txt @@ -0,0 +1,16 @@ +tests/cases/compiler/unusedPrivateVariableInClass5.ts(4,13): error TS6133: 'y' is declared but never used. + + +==== tests/cases/compiler/unusedPrivateVariableInClass5.ts (1 errors) ==== + + class greeter { + private x: string; + private y: string; + ~ +!!! error TS6133: 'y' is declared but never used. + public z: string; + + constructor() { + this.x = "dummy value"; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedPrivateVariableInClass5.js b/tests/baselines/reference/unusedPrivateVariableInClass5.js new file mode 100644 index 00000000000..4d9b3017222 --- /dev/null +++ b/tests/baselines/reference/unusedPrivateVariableInClass5.js @@ -0,0 +1,19 @@ +//// [unusedPrivateVariableInClass5.ts] + +class greeter { + private x: string; + private y: string; + public z: string; + + constructor() { + this.x = "dummy value"; + } +} + +//// [unusedPrivateVariableInClass5.js] +var greeter = (function () { + function greeter() { + this.x = "dummy value"; + } + return greeter; +}()); diff --git a/tests/baselines/reference/unusedSetterInClass.js b/tests/baselines/reference/unusedSetterInClass.js new file mode 100644 index 00000000000..aff12b7d043 --- /dev/null +++ b/tests/baselines/reference/unusedSetterInClass.js @@ -0,0 +1,23 @@ +//// [unusedSetterInClass.ts] + +class Employee { + private _fullName: string; + + set fullName(newName: string) { + this._fullName = newName; + } +} + +//// [unusedSetterInClass.js] +var Employee = (function () { + function Employee() { + } + Object.defineProperty(Employee.prototype, "fullName", { + set: function (newName) { + this._fullName = newName; + }, + enumerable: true, + configurable: true + }); + return Employee; +}()); diff --git a/tests/baselines/reference/unusedSetterInClass.symbols b/tests/baselines/reference/unusedSetterInClass.symbols new file mode 100644 index 00000000000..511b106aded --- /dev/null +++ b/tests/baselines/reference/unusedSetterInClass.symbols @@ -0,0 +1,19 @@ +=== tests/cases/compiler/unusedSetterInClass.ts === + +class Employee { +>Employee : Symbol(Employee, Decl(unusedSetterInClass.ts, 0, 0)) + + private _fullName: string; +>_fullName : Symbol(Employee._fullName, Decl(unusedSetterInClass.ts, 1, 16)) + + set fullName(newName: string) { +>fullName : Symbol(Employee.fullName, Decl(unusedSetterInClass.ts, 2, 30)) +>newName : Symbol(newName, Decl(unusedSetterInClass.ts, 4, 17)) + + this._fullName = newName; +>this._fullName : Symbol(Employee._fullName, Decl(unusedSetterInClass.ts, 1, 16)) +>this : Symbol(Employee, Decl(unusedSetterInClass.ts, 0, 0)) +>_fullName : Symbol(Employee._fullName, Decl(unusedSetterInClass.ts, 1, 16)) +>newName : Symbol(newName, Decl(unusedSetterInClass.ts, 4, 17)) + } +} diff --git a/tests/baselines/reference/unusedSetterInClass.types b/tests/baselines/reference/unusedSetterInClass.types new file mode 100644 index 00000000000..9a74ef383ae --- /dev/null +++ b/tests/baselines/reference/unusedSetterInClass.types @@ -0,0 +1,20 @@ +=== tests/cases/compiler/unusedSetterInClass.ts === + +class Employee { +>Employee : Employee + + private _fullName: string; +>_fullName : string + + set fullName(newName: string) { +>fullName : string +>newName : string + + this._fullName = newName; +>this._fullName = newName : string +>this._fullName : string +>this : this +>_fullName : string +>newName : string + } +} diff --git a/tests/baselines/reference/unusedSingleParameterInContructor.errors.txt b/tests/baselines/reference/unusedSingleParameterInContructor.errors.txt new file mode 100644 index 00000000000..2549266dfc2 --- /dev/null +++ b/tests/baselines/reference/unusedSingleParameterInContructor.errors.txt @@ -0,0 +1,15 @@ +tests/cases/compiler/unusedSingleParameterInContructor.ts(3,17): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedSingleParameterInContructor.ts(4,13): error TS6133: 'unused' is declared but never used. + + +==== tests/cases/compiler/unusedSingleParameterInContructor.ts (2 errors) ==== + + class Dummy { + constructor(person: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedSingleParameterInContructor.js b/tests/baselines/reference/unusedSingleParameterInContructor.js new file mode 100644 index 00000000000..172f9e20ab8 --- /dev/null +++ b/tests/baselines/reference/unusedSingleParameterInContructor.js @@ -0,0 +1,15 @@ +//// [unusedSingleParameterInContructor.ts] + +class Dummy { + constructor(person: string) { + var unused = 20; + } +} + +//// [unusedSingleParameterInContructor.js] +var Dummy = (function () { + function Dummy(person) { + var unused = 20; + } + return Dummy; +}()); diff --git a/tests/baselines/reference/unusedSingleParameterInFunctionDeclaration.errors.txt b/tests/baselines/reference/unusedSingleParameterInFunctionDeclaration.errors.txt new file mode 100644 index 00000000000..e29269e9b05 --- /dev/null +++ b/tests/baselines/reference/unusedSingleParameterInFunctionDeclaration.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/unusedSingleParameterInFunctionDeclaration.ts(2,18): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedSingleParameterInFunctionDeclaration.ts(3,9): error TS6133: 'unused' is declared but never used. + + +==== tests/cases/compiler/unusedSingleParameterInFunctionDeclaration.ts (2 errors) ==== + + function greeter(person: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedSingleParameterInFunctionDeclaration.js b/tests/baselines/reference/unusedSingleParameterInFunctionDeclaration.js new file mode 100644 index 00000000000..0ee7c3d608a --- /dev/null +++ b/tests/baselines/reference/unusedSingleParameterInFunctionDeclaration.js @@ -0,0 +1,10 @@ +//// [unusedSingleParameterInFunctionDeclaration.ts] + +function greeter(person: string) { + var unused = 20; +} + +//// [unusedSingleParameterInFunctionDeclaration.js] +function greeter(person) { + var unused = 20; +} diff --git a/tests/baselines/reference/unusedSingleParameterInFunctionExpression.errors.txt b/tests/baselines/reference/unusedSingleParameterInFunctionExpression.errors.txt new file mode 100644 index 00000000000..ad3e5e67a72 --- /dev/null +++ b/tests/baselines/reference/unusedSingleParameterInFunctionExpression.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/unusedSingleParameterInFunctionExpression.ts(2,21): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedSingleParameterInFunctionExpression.ts(3,9): error TS6133: 'unused' is declared but never used. + + +==== tests/cases/compiler/unusedSingleParameterInFunctionExpression.ts (2 errors) ==== + + var func = function(person: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedSingleParameterInFunctionExpression.js b/tests/baselines/reference/unusedSingleParameterInFunctionExpression.js new file mode 100644 index 00000000000..578707e43cc --- /dev/null +++ b/tests/baselines/reference/unusedSingleParameterInFunctionExpression.js @@ -0,0 +1,10 @@ +//// [unusedSingleParameterInFunctionExpression.ts] + +var func = function(person: string) { + var unused = 20; +} + +//// [unusedSingleParameterInFunctionExpression.js] +var func = function (person) { + var unused = 20; +}; diff --git a/tests/baselines/reference/unusedSingleParameterInMethodDeclaration.errors.txt b/tests/baselines/reference/unusedSingleParameterInMethodDeclaration.errors.txt new file mode 100644 index 00000000000..af806bbadfb --- /dev/null +++ b/tests/baselines/reference/unusedSingleParameterInMethodDeclaration.errors.txt @@ -0,0 +1,15 @@ +tests/cases/compiler/unusedSingleParameterInMethodDeclaration.ts(3,20): error TS6133: 'person' is declared but never used. +tests/cases/compiler/unusedSingleParameterInMethodDeclaration.ts(4,13): error TS6133: 'unused' is declared but never used. + + +==== tests/cases/compiler/unusedSingleParameterInMethodDeclaration.ts (2 errors) ==== + + class Dummy { + public greeter(person: string) { + ~~~~~~ +!!! error TS6133: 'person' is declared but never used. + var unused = 20; + ~~~~~~ +!!! error TS6133: 'unused' is declared but never used. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedSingleParameterInMethodDeclaration.js b/tests/baselines/reference/unusedSingleParameterInMethodDeclaration.js new file mode 100644 index 00000000000..993866086db --- /dev/null +++ b/tests/baselines/reference/unusedSingleParameterInMethodDeclaration.js @@ -0,0 +1,17 @@ +//// [unusedSingleParameterInMethodDeclaration.ts] + +class Dummy { + public greeter(person: string) { + var unused = 20; + } +} + +//// [unusedSingleParameterInMethodDeclaration.js] +var Dummy = (function () { + function Dummy() { + } + Dummy.prototype.greeter = function (person) { + var unused = 20; + }; + return Dummy; +}()); diff --git a/tests/baselines/reference/unusedTypeParameterInFunction1.errors.txt b/tests/baselines/reference/unusedTypeParameterInFunction1.errors.txt new file mode 100644 index 00000000000..afbdb09c162 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInFunction1.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/unusedTypeParameterInFunction1.ts(2,13): error TS6133: 'T' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameterInFunction1.ts (1 errors) ==== + + function f1() { + ~ +!!! error TS6133: 'T' is declared but never used. + + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameterInFunction1.js b/tests/baselines/reference/unusedTypeParameterInFunction1.js new file mode 100644 index 00000000000..6ecf90343b7 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInFunction1.js @@ -0,0 +1,9 @@ +//// [unusedTypeParameterInFunction1.ts] + +function f1() { + +} + +//// [unusedTypeParameterInFunction1.js] +function f1() { +} diff --git a/tests/baselines/reference/unusedTypeParameterInFunction2.errors.txt b/tests/baselines/reference/unusedTypeParameterInFunction2.errors.txt new file mode 100644 index 00000000000..0097cc99810 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInFunction2.errors.txt @@ -0,0 +1,11 @@ +tests/cases/compiler/unusedTypeParameterInFunction2.ts(2,16): error TS6133: 'Y' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameterInFunction2.ts (1 errors) ==== + + function f1() { + ~ +!!! error TS6133: 'Y' is declared but never used. + var a: X; + a; + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameterInFunction2.js b/tests/baselines/reference/unusedTypeParameterInFunction2.js new file mode 100644 index 00000000000..7c3eaa91127 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInFunction2.js @@ -0,0 +1,12 @@ +//// [unusedTypeParameterInFunction2.ts] + +function f1() { + var a: X; + a; +} + +//// [unusedTypeParameterInFunction2.js] +function f1() { + var a; + a; +} diff --git a/tests/baselines/reference/unusedTypeParameterInFunction3.errors.txt b/tests/baselines/reference/unusedTypeParameterInFunction3.errors.txt new file mode 100644 index 00000000000..7a2e33769da --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInFunction3.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/unusedTypeParameterInFunction3.ts(2,16): error TS6133: 'Y' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameterInFunction3.ts (1 errors) ==== + + function f1() { + ~ +!!! error TS6133: 'Y' is declared but never used. + var a: X; + var b: Z; + a; + b; + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameterInFunction3.js b/tests/baselines/reference/unusedTypeParameterInFunction3.js new file mode 100644 index 00000000000..335a5668acc --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInFunction3.js @@ -0,0 +1,16 @@ +//// [unusedTypeParameterInFunction3.ts] + +function f1() { + var a: X; + var b: Z; + a; + b; +} + +//// [unusedTypeParameterInFunction3.js] +function f1() { + var a; + var b; + a; + b; +} diff --git a/tests/baselines/reference/unusedTypeParameterInFunction4.errors.txt b/tests/baselines/reference/unusedTypeParameterInFunction4.errors.txt new file mode 100644 index 00000000000..7840ff31df3 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInFunction4.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/unusedTypeParameterInFunction4.ts(2,13): error TS6133: 'X' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameterInFunction4.ts (1 errors) ==== + + function f1() { + ~ +!!! error TS6133: 'X' is declared but never used. + var a: Y; + var b: Z; + a; + b; + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameterInFunction4.js b/tests/baselines/reference/unusedTypeParameterInFunction4.js new file mode 100644 index 00000000000..e6b26dfbd4e --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInFunction4.js @@ -0,0 +1,16 @@ +//// [unusedTypeParameterInFunction4.ts] + +function f1() { + var a: Y; + var b: Z; + a; + b; +} + +//// [unusedTypeParameterInFunction4.js] +function f1() { + var a; + var b; + a; + b; +} diff --git a/tests/baselines/reference/unusedTypeParameterInInterface1.errors.txt b/tests/baselines/reference/unusedTypeParameterInInterface1.errors.txt new file mode 100644 index 00000000000..fbe6ef3f0d1 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInInterface1.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/unusedTypeParameterInInterface1.ts(2,15): error TS6133: 'T' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameterInInterface1.ts (1 errors) ==== + + interface int { + ~ +!!! error TS6133: 'T' is declared but never used. + + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameterInInterface1.js b/tests/baselines/reference/unusedTypeParameterInInterface1.js new file mode 100644 index 00000000000..8f9a6962b35 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInInterface1.js @@ -0,0 +1,7 @@ +//// [unusedTypeParameterInInterface1.ts] + +interface int { + +} + +//// [unusedTypeParameterInInterface1.js] diff --git a/tests/baselines/reference/unusedTypeParameterInInterface2.errors.txt b/tests/baselines/reference/unusedTypeParameterInInterface2.errors.txt new file mode 100644 index 00000000000..ed3e5847774 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInInterface2.errors.txt @@ -0,0 +1,11 @@ +tests/cases/compiler/unusedTypeParameterInInterface2.ts(2,18): error TS6133: 'U' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameterInInterface2.ts (1 errors) ==== + + interface int { + ~ +!!! error TS6133: 'U' is declared but never used. + f1(a: T): string; + c: V; + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameterInInterface2.js b/tests/baselines/reference/unusedTypeParameterInInterface2.js new file mode 100644 index 00000000000..d5a4c490d27 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInInterface2.js @@ -0,0 +1,8 @@ +//// [unusedTypeParameterInInterface2.ts] + +interface int { + f1(a: T): string; + c: V; +} + +//// [unusedTypeParameterInInterface2.js] diff --git a/tests/baselines/reference/unusedTypeParameterInLambda1.errors.txt b/tests/baselines/reference/unusedTypeParameterInLambda1.errors.txt new file mode 100644 index 00000000000..a84df63b317 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInLambda1.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/unusedTypeParameterInLambda1.ts(4,17): error TS6133: 'T' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameterInLambda1.ts (1 errors) ==== + + class A { + public f1() { + return () => { + ~ +!!! error TS6133: 'T' is declared but never used. + + } + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameterInLambda1.js b/tests/baselines/reference/unusedTypeParameterInLambda1.js new file mode 100644 index 00000000000..0f55a4a32a1 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInLambda1.js @@ -0,0 +1,20 @@ +//// [unusedTypeParameterInLambda1.ts] + +class A { + public f1() { + return () => { + + } + } +} + +//// [unusedTypeParameterInLambda1.js] +var A = (function () { + function A() { + } + A.prototype.f1 = function () { + return function () { + }; + }; + return A; +}()); diff --git a/tests/baselines/reference/unusedTypeParameterInLambda2.errors.txt b/tests/baselines/reference/unusedTypeParameterInLambda2.errors.txt new file mode 100644 index 00000000000..c1104743472 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInLambda2.errors.txt @@ -0,0 +1,15 @@ +tests/cases/compiler/unusedTypeParameterInLambda2.ts(4,17): error TS6133: 'T' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameterInLambda2.ts (1 errors) ==== + + class A { + public f1() { + return () => { + ~ +!!! error TS6133: 'T' is declared but never used. + var a: X; + a; + } + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameterInLambda2.js b/tests/baselines/reference/unusedTypeParameterInLambda2.js new file mode 100644 index 00000000000..16545eb13f2 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInLambda2.js @@ -0,0 +1,23 @@ +//// [unusedTypeParameterInLambda2.ts] + +class A { + public f1() { + return () => { + var a: X; + a; + } + } +} + +//// [unusedTypeParameterInLambda2.js] +var A = (function () { + function A() { + } + A.prototype.f1 = function () { + return function () { + var a; + a; + }; + }; + return A; +}()); diff --git a/tests/baselines/reference/unusedTypeParameterInLambda3.errors.txt b/tests/baselines/reference/unusedTypeParameterInLambda3.errors.txt new file mode 100644 index 00000000000..5477f611e72 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInLambda3.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/unusedTypeParameterInLambda3.ts(5,15): error TS6133: 'U' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameterInLambda3.ts (1 errors) ==== + class A { + public x: T; + } + + var y: new (a:T)=>void; + ~ +!!! error TS6133: 'U' is declared but never used. + \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameterInLambda3.js b/tests/baselines/reference/unusedTypeParameterInLambda3.js new file mode 100644 index 00000000000..27899320fc2 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInLambda3.js @@ -0,0 +1,15 @@ +//// [unusedTypeParameterInLambda3.ts] +class A { + public x: T; +} + +var y: new (a:T)=>void; + + +//// [unusedTypeParameterInLambda3.js] +var A = (function () { + function A() { + } + return A; +}()); +var y; diff --git a/tests/baselines/reference/unusedTypeParameterInMethod1.errors.txt b/tests/baselines/reference/unusedTypeParameterInMethod1.errors.txt new file mode 100644 index 00000000000..3b39d9b35ec --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInMethod1.errors.txt @@ -0,0 +1,15 @@ +tests/cases/compiler/unusedTypeParameterInMethod1.ts(3,15): error TS6133: 'X' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameterInMethod1.ts (1 errors) ==== + + class A { + public f1() { + ~ +!!! error TS6133: 'X' is declared but never used. + var a: Y; + var b: Z; + a; + b; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameterInMethod1.js b/tests/baselines/reference/unusedTypeParameterInMethod1.js new file mode 100644 index 00000000000..e5ab22095b8 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInMethod1.js @@ -0,0 +1,23 @@ +//// [unusedTypeParameterInMethod1.ts] + +class A { + public f1() { + var a: Y; + var b: Z; + a; + b; + } +} + +//// [unusedTypeParameterInMethod1.js] +var A = (function () { + function A() { + } + A.prototype.f1 = function () { + var a; + var b; + a; + b; + }; + return A; +}()); diff --git a/tests/baselines/reference/unusedTypeParameterInMethod2.errors.txt b/tests/baselines/reference/unusedTypeParameterInMethod2.errors.txt new file mode 100644 index 00000000000..f1dafb5a19e --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInMethod2.errors.txt @@ -0,0 +1,15 @@ +tests/cases/compiler/unusedTypeParameterInMethod2.ts(3,18): error TS6133: 'Y' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameterInMethod2.ts (1 errors) ==== + + class A { + public f1() { + ~ +!!! error TS6133: 'Y' is declared but never used. + var a: X; + var b: Z; + a; + b; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameterInMethod2.js b/tests/baselines/reference/unusedTypeParameterInMethod2.js new file mode 100644 index 00000000000..9fb785634c6 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInMethod2.js @@ -0,0 +1,23 @@ +//// [unusedTypeParameterInMethod2.ts] + +class A { + public f1() { + var a: X; + var b: Z; + a; + b; + } +} + +//// [unusedTypeParameterInMethod2.js] +var A = (function () { + function A() { + } + A.prototype.f1 = function () { + var a; + var b; + a; + b; + }; + return A; +}()); diff --git a/tests/baselines/reference/unusedTypeParameterInMethod3.errors.txt b/tests/baselines/reference/unusedTypeParameterInMethod3.errors.txt new file mode 100644 index 00000000000..04a43e3d011 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInMethod3.errors.txt @@ -0,0 +1,15 @@ +tests/cases/compiler/unusedTypeParameterInMethod3.ts(3,21): error TS6133: 'Z' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameterInMethod3.ts (1 errors) ==== + + class A { + public f1() { + ~ +!!! error TS6133: 'Z' is declared but never used. + var a: X; + var b: Y; + a; + b; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameterInMethod3.js b/tests/baselines/reference/unusedTypeParameterInMethod3.js new file mode 100644 index 00000000000..b81d0796dc4 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInMethod3.js @@ -0,0 +1,23 @@ +//// [unusedTypeParameterInMethod3.ts] + +class A { + public f1() { + var a: X; + var b: Y; + a; + b; + } +} + +//// [unusedTypeParameterInMethod3.js] +var A = (function () { + function A() { + } + A.prototype.f1 = function () { + var a; + var b; + a; + b; + }; + return A; +}()); diff --git a/tests/baselines/reference/unusedTypeParameterInMethod4.errors.txt b/tests/baselines/reference/unusedTypeParameterInMethod4.errors.txt new file mode 100644 index 00000000000..9026aaad321 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInMethod4.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/unusedTypeParameterInMethod4.ts(3,15): error TS6133: 'X' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameterInMethod4.ts (1 errors) ==== + + class A { + public f1() { + ~ +!!! error TS6133: 'X' is declared but never used. + + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameterInMethod4.js b/tests/baselines/reference/unusedTypeParameterInMethod4.js new file mode 100644 index 00000000000..4db72f193a2 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInMethod4.js @@ -0,0 +1,16 @@ +//// [unusedTypeParameterInMethod4.ts] + +class A { + public f1() { + + } +} + +//// [unusedTypeParameterInMethod4.js] +var A = (function () { + function A() { + } + A.prototype.f1 = function () { + }; + return A; +}()); diff --git a/tests/baselines/reference/unusedTypeParameterInMethod5.errors.txt b/tests/baselines/reference/unusedTypeParameterInMethod5.errors.txt new file mode 100644 index 00000000000..20d95ec4bb5 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInMethod5.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/unusedTypeParameterInMethod5.ts(3,26): error TS6133: 'X' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameterInMethod5.ts (1 errors) ==== + + class A { + public f1 = function() { + ~ +!!! error TS6133: 'X' is declared but never used. + + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameterInMethod5.js b/tests/baselines/reference/unusedTypeParameterInMethod5.js new file mode 100644 index 00000000000..e1863b4cbb1 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameterInMethod5.js @@ -0,0 +1,16 @@ +//// [unusedTypeParameterInMethod5.ts] + +class A { + public f1 = function() { + + } +} + +//// [unusedTypeParameterInMethod5.js] +var A = (function () { + function A() { + this.f1 = function () { + }; + } + return A; +}()); diff --git a/tests/baselines/reference/unusedTypeParameters1.errors.txt b/tests/baselines/reference/unusedTypeParameters1.errors.txt new file mode 100644 index 00000000000..15d85d0e815 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameters1.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/unusedTypeParameters1.ts(2,15): error TS6133: 'typeparameter1' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameters1.ts (1 errors) ==== + + class greeter { + ~~~~~~~~~~~~~~ +!!! error TS6133: 'typeparameter1' is declared but never used. + + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameters1.js b/tests/baselines/reference/unusedTypeParameters1.js new file mode 100644 index 00000000000..27de80a9ecc --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameters1.js @@ -0,0 +1,12 @@ +//// [unusedTypeParameters1.ts] + +class greeter { + +} + +//// [unusedTypeParameters1.js] +var greeter = (function () { + function greeter() { + } + return greeter; +}()); diff --git a/tests/baselines/reference/unusedTypeParameters2.errors.txt b/tests/baselines/reference/unusedTypeParameters2.errors.txt new file mode 100644 index 00000000000..a82a119d2ca --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameters2.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/unusedTypeParameters2.ts(2,15): error TS6133: 'typeparameter1' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameters2.ts (1 errors) ==== + + class greeter { + ~~~~~~~~~~~~~~ +!!! error TS6133: 'typeparameter1' is declared but never used. + private x: typeparameter2; + + public function1() { + this.x; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameters2.js b/tests/baselines/reference/unusedTypeParameters2.js new file mode 100644 index 00000000000..b28aa5074e7 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameters2.js @@ -0,0 +1,19 @@ +//// [unusedTypeParameters2.ts] + +class greeter { + private x: typeparameter2; + + public function1() { + this.x; + } +} + +//// [unusedTypeParameters2.js] +var greeter = (function () { + function greeter() { + } + greeter.prototype.function1 = function () { + this.x; + }; + return greeter; +}()); diff --git a/tests/baselines/reference/unusedTypeParameters3.errors.txt b/tests/baselines/reference/unusedTypeParameters3.errors.txt new file mode 100644 index 00000000000..0b051ad476b --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameters3.errors.txt @@ -0,0 +1,17 @@ +tests/cases/compiler/unusedTypeParameters3.ts(2,15): error TS6133: 'typeparameter1' is declared but never used. +tests/cases/compiler/unusedTypeParameters3.ts(2,47): error TS6133: 'typeparameter3' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameters3.ts (2 errors) ==== + + class greeter { + ~~~~~~~~~~~~~~ +!!! error TS6133: 'typeparameter1' is declared but never used. + ~~~~~~~~~~~~~~ +!!! error TS6133: 'typeparameter3' is declared but never used. + private x: typeparameter2; + + public function1() { + this.x; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameters3.js b/tests/baselines/reference/unusedTypeParameters3.js new file mode 100644 index 00000000000..0552acaf540 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameters3.js @@ -0,0 +1,19 @@ +//// [unusedTypeParameters3.ts] + +class greeter { + private x: typeparameter2; + + public function1() { + this.x; + } +} + +//// [unusedTypeParameters3.js] +var greeter = (function () { + function greeter() { + } + greeter.prototype.function1 = function () { + this.x; + }; + return greeter; +}()); diff --git a/tests/baselines/reference/unusedTypeParameters4.errors.txt b/tests/baselines/reference/unusedTypeParameters4.errors.txt new file mode 100644 index 00000000000..3aad5d5a346 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameters4.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/unusedTypeParameters4.ts(3,13): error TS6133: 'U' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameters4.ts (1 errors) ==== + + var x: { + new (a: T): void; + ~ +!!! error TS6133: 'U' is declared but never used. + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameters4.js b/tests/baselines/reference/unusedTypeParameters4.js new file mode 100644 index 00000000000..4e679ed3f6b --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameters4.js @@ -0,0 +1,8 @@ +//// [unusedTypeParameters4.ts] + +var x: { + new (a: T): void; +} + +//// [unusedTypeParameters4.js] +var x; diff --git a/tests/baselines/reference/unusedTypeParameters5.errors.txt b/tests/baselines/reference/unusedTypeParameters5.errors.txt new file mode 100644 index 00000000000..ed150710d94 --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameters5.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/unusedTypeParameters5.ts(7,16): error TS6133: 'K' is declared but never used. + + +==== tests/cases/compiler/unusedTypeParameters5.ts (1 errors) ==== + + class A { + public x: Dummy; + } + + var x: { + new (a: T): A; + ~ +!!! error TS6133: 'K' is declared but never used. + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedTypeParameters5.js b/tests/baselines/reference/unusedTypeParameters5.js new file mode 100644 index 00000000000..75dfd892eff --- /dev/null +++ b/tests/baselines/reference/unusedTypeParameters5.js @@ -0,0 +1,17 @@ +//// [unusedTypeParameters5.ts] + +class A { + public x: Dummy; +} + +var x: { + new (a: T): A; +} + +//// [unusedTypeParameters5.js] +var A = (function () { + function A() { + } + return A; +}()); +var x; diff --git a/tests/baselines/reference/unusedVariablesinBlocks1.errors.txt b/tests/baselines/reference/unusedVariablesinBlocks1.errors.txt new file mode 100644 index 00000000000..4f4291395f3 --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinBlocks1.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/unusedVariablesinBlocks1.ts(3,9): error TS6133: 'x' is declared but never used. + + +==== tests/cases/compiler/unusedVariablesinBlocks1.ts (1 errors) ==== + + function f1 () { + let x = 10; + ~ +!!! error TS6133: 'x' is declared but never used. + { + let x = 11; + x++; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedVariablesinBlocks1.js b/tests/baselines/reference/unusedVariablesinBlocks1.js new file mode 100644 index 00000000000..d569485aa82 --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinBlocks1.js @@ -0,0 +1,18 @@ +//// [unusedVariablesinBlocks1.ts] + +function f1 () { + let x = 10; + { + let x = 11; + x++; + } +} + +//// [unusedVariablesinBlocks1.js] +function f1() { + var x = 10; + { + var x_1 = 11; + x_1++; + } +} diff --git a/tests/baselines/reference/unusedVariablesinBlocks2.errors.txt b/tests/baselines/reference/unusedVariablesinBlocks2.errors.txt new file mode 100644 index 00000000000..70af896324c --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinBlocks2.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/unusedVariablesinBlocks2.ts(5,13): error TS6133: 'x' is declared but never used. + + +==== tests/cases/compiler/unusedVariablesinBlocks2.ts (1 errors) ==== + + function f1 () { + let x = 10; + { + let x = 11; + ~ +!!! error TS6133: 'x' is declared but never used. + } + x++; + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedVariablesinBlocks2.js b/tests/baselines/reference/unusedVariablesinBlocks2.js new file mode 100644 index 00000000000..0f4cb346398 --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinBlocks2.js @@ -0,0 +1,18 @@ +//// [unusedVariablesinBlocks2.ts] + +function f1 () { + let x = 10; + { + let x = 11; + } + x++; +} + +//// [unusedVariablesinBlocks2.js] +function f1() { + var x = 10; + { + var x_1 = 11; + } + x++; +} diff --git a/tests/baselines/reference/unusedVariablesinForLoop.errors.txt b/tests/baselines/reference/unusedVariablesinForLoop.errors.txt new file mode 100644 index 00000000000..b44e9dfdab1 --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinForLoop.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/unusedVariablesinForLoop.ts(3,13): error TS6133: 'i' is declared but never used. + + +==== tests/cases/compiler/unusedVariablesinForLoop.ts (1 errors) ==== + + function f1 () { + for(var i = 0; ;) { + ~ +!!! error TS6133: 'i' is declared but never used. + + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedVariablesinForLoop.js b/tests/baselines/reference/unusedVariablesinForLoop.js new file mode 100644 index 00000000000..a87e395d6e7 --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinForLoop.js @@ -0,0 +1,13 @@ +//// [unusedVariablesinForLoop.ts] + +function f1 () { + for(var i = 0; ;) { + + } +} + +//// [unusedVariablesinForLoop.js] +function f1() { + for (var i = 0;;) { + } +} diff --git a/tests/baselines/reference/unusedVariablesinForLoop2.errors.txt b/tests/baselines/reference/unusedVariablesinForLoop2.errors.txt new file mode 100644 index 00000000000..71974af00f4 --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinForLoop2.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/unusedVariablesinForLoop2.ts(3,16): error TS6133: 'elem' is declared but never used. + + +==== tests/cases/compiler/unusedVariablesinForLoop2.ts (1 errors) ==== + + function f1 () { + for (const elem in ["a", "b", "c"]) { + ~~~~ +!!! error TS6133: 'elem' is declared but never used. + + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedVariablesinForLoop2.js b/tests/baselines/reference/unusedVariablesinForLoop2.js new file mode 100644 index 00000000000..523fdb18f9e --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinForLoop2.js @@ -0,0 +1,13 @@ +//// [unusedVariablesinForLoop2.ts] + +function f1 () { + for (const elem in ["a", "b", "c"]) { + + } +} + +//// [unusedVariablesinForLoop2.js] +function f1() { + for (var elem in ["a", "b", "c"]) { + } +} diff --git a/tests/baselines/reference/unusedVariablesinForLoop3.errors.txt b/tests/baselines/reference/unusedVariablesinForLoop3.errors.txt new file mode 100644 index 00000000000..dbaf91ae70d --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinForLoop3.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/unusedVariablesinForLoop3.ts(3,16): error TS6133: 'elem' is declared but never used. + + +==== tests/cases/compiler/unusedVariablesinForLoop3.ts (1 errors) ==== + + function f1 () { + for (const elem of ["a", "b", "c"]) { + ~~~~ +!!! error TS6133: 'elem' is declared but never used. + + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedVariablesinForLoop3.js b/tests/baselines/reference/unusedVariablesinForLoop3.js new file mode 100644 index 00000000000..833214f3ba5 --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinForLoop3.js @@ -0,0 +1,14 @@ +//// [unusedVariablesinForLoop3.ts] + +function f1 () { + for (const elem of ["a", "b", "c"]) { + + } +} + +//// [unusedVariablesinForLoop3.js] +function f1() { + for (var _i = 0, _a = ["a", "b", "c"]; _i < _a.length; _i++) { + var elem = _a[_i]; + } +} diff --git a/tests/baselines/reference/unusedVariablesinForLoop4.errors.txt b/tests/baselines/reference/unusedVariablesinForLoop4.errors.txt new file mode 100644 index 00000000000..d54500d353d --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinForLoop4.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/unusedVariablesinForLoop4.ts(5,13): error TS6133: 'x' is declared but never used. + + +==== tests/cases/compiler/unusedVariablesinForLoop4.ts (1 errors) ==== + + function f1 () { + for (const elem of ["a", "b", "c"]) { + elem; + var x = 20; + ~ +!!! error TS6133: 'x' is declared but never used. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedVariablesinForLoop4.js b/tests/baselines/reference/unusedVariablesinForLoop4.js new file mode 100644 index 00000000000..6ec7f6fec55 --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinForLoop4.js @@ -0,0 +1,17 @@ +//// [unusedVariablesinForLoop4.ts] + +function f1 () { + for (const elem of ["a", "b", "c"]) { + elem; + var x = 20; + } +} + +//// [unusedVariablesinForLoop4.js] +function f1() { + for (var _i = 0, _a = ["a", "b", "c"]; _i < _a.length; _i++) { + var elem = _a[_i]; + elem; + var x = 20; + } +} diff --git a/tests/baselines/reference/unusedVariablesinModules1.errors.txt b/tests/baselines/reference/unusedVariablesinModules1.errors.txt new file mode 100644 index 00000000000..00faee6a6b3 --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinModules1.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/unusedVariablesinModules1.ts(4,5): error TS6133: 'x' is declared but never used. + + +==== tests/cases/compiler/unusedVariablesinModules1.ts (1 errors) ==== + + export {}; + + var x: string; + ~ +!!! error TS6133: 'x' is declared but never used. + + export var y: string; \ No newline at end of file diff --git a/tests/baselines/reference/unusedVariablesinModules1.js b/tests/baselines/reference/unusedVariablesinModules1.js new file mode 100644 index 00000000000..18622a32ba9 --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinModules1.js @@ -0,0 +1,11 @@ +//// [unusedVariablesinModules1.ts] + +export {}; + +var x: string; + +export var y: string; + +//// [unusedVariablesinModules1.js] +"use strict"; +var x; diff --git a/tests/baselines/reference/unusedVariablesinNamespaces1.errors.txt b/tests/baselines/reference/unusedVariablesinNamespaces1.errors.txt new file mode 100644 index 00000000000..39c1cdc4e08 --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinNamespaces1.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/unusedVariablesinNamespaces1.ts(3,11): error TS6133: 'lettersRegexp' is declared but never used. + + +==== tests/cases/compiler/unusedVariablesinNamespaces1.ts (1 errors) ==== + + namespace Validation { + const lettersRegexp = /^[A-Za-z]+$/; + ~~~~~~~~~~~~~ +!!! error TS6133: 'lettersRegexp' is declared but never used. + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedVariablesinNamespaces1.js b/tests/baselines/reference/unusedVariablesinNamespaces1.js new file mode 100644 index 00000000000..a6dca8e413f --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinNamespaces1.js @@ -0,0 +1,11 @@ +//// [unusedVariablesinNamespaces1.ts] + +namespace Validation { + const lettersRegexp = /^[A-Za-z]+$/; +} + +//// [unusedVariablesinNamespaces1.js] +var Validation; +(function (Validation) { + var lettersRegexp = /^[A-Za-z]+$/; +})(Validation || (Validation = {})); diff --git a/tests/baselines/reference/unusedVariablesinNamespaces2.errors.txt b/tests/baselines/reference/unusedVariablesinNamespaces2.errors.txt new file mode 100644 index 00000000000..43d41e6338b --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinNamespaces2.errors.txt @@ -0,0 +1,17 @@ +tests/cases/compiler/unusedVariablesinNamespaces2.ts(4,11): error TS6133: 'numberRegexp' is declared but never used. + + +==== tests/cases/compiler/unusedVariablesinNamespaces2.ts (1 errors) ==== + + namespace Validation { + const lettersRegexp = /^[A-Za-z]+$/; + const numberRegexp = /^[0-9]+$/; + ~~~~~~~~~~~~ +!!! error TS6133: 'numberRegexp' is declared but never used. + + export class LettersOnlyValidator { + isAcceptable(s2: string) { + return lettersRegexp.test(s2); + } + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedVariablesinNamespaces2.js b/tests/baselines/reference/unusedVariablesinNamespaces2.js new file mode 100644 index 00000000000..b0b64fa644d --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinNamespaces2.js @@ -0,0 +1,28 @@ +//// [unusedVariablesinNamespaces2.ts] + +namespace Validation { + const lettersRegexp = /^[A-Za-z]+$/; + const numberRegexp = /^[0-9]+$/; + + export class LettersOnlyValidator { + isAcceptable(s2: string) { + return lettersRegexp.test(s2); + } + } +} + +//// [unusedVariablesinNamespaces2.js] +var Validation; +(function (Validation) { + var lettersRegexp = /^[A-Za-z]+$/; + var numberRegexp = /^[0-9]+$/; + var LettersOnlyValidator = (function () { + function LettersOnlyValidator() { + } + LettersOnlyValidator.prototype.isAcceptable = function (s2) { + return lettersRegexp.test(s2); + }; + return LettersOnlyValidator; + }()); + Validation.LettersOnlyValidator = LettersOnlyValidator; +})(Validation || (Validation = {})); diff --git a/tests/baselines/reference/unusedVariablesinNamespaces3.errors.txt b/tests/baselines/reference/unusedVariablesinNamespaces3.errors.txt new file mode 100644 index 00000000000..a0a274c6b2a --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinNamespaces3.errors.txt @@ -0,0 +1,18 @@ +tests/cases/compiler/unusedVariablesinNamespaces3.ts(4,11): error TS6133: 'numberRegexp' is declared but never used. + + +==== tests/cases/compiler/unusedVariablesinNamespaces3.ts (1 errors) ==== + + namespace Validation { + const lettersRegexp = /^[A-Za-z]+$/; + const numberRegexp = /^[0-9]+$/; + ~~~~~~~~~~~~ +!!! error TS6133: 'numberRegexp' is declared but never used. + export const anotherUnusedVariable = "Dummy value"; + + export class LettersOnlyValidator { + isAcceptable(s2: string) { + return lettersRegexp.test(s2); + } + } + } \ No newline at end of file diff --git a/tests/baselines/reference/unusedVariablesinNamespaces3.js b/tests/baselines/reference/unusedVariablesinNamespaces3.js new file mode 100644 index 00000000000..16a92a475d9 --- /dev/null +++ b/tests/baselines/reference/unusedVariablesinNamespaces3.js @@ -0,0 +1,30 @@ +//// [unusedVariablesinNamespaces3.ts] + +namespace Validation { + const lettersRegexp = /^[A-Za-z]+$/; + const numberRegexp = /^[0-9]+$/; + export const anotherUnusedVariable = "Dummy value"; + + export class LettersOnlyValidator { + isAcceptable(s2: string) { + return lettersRegexp.test(s2); + } + } +} + +//// [unusedVariablesinNamespaces3.js] +var Validation; +(function (Validation) { + var lettersRegexp = /^[A-Za-z]+$/; + var numberRegexp = /^[0-9]+$/; + Validation.anotherUnusedVariable = "Dummy value"; + var LettersOnlyValidator = (function () { + function LettersOnlyValidator() { + } + LettersOnlyValidator.prototype.isAcceptable = function (s2) { + return lettersRegexp.test(s2); + }; + return LettersOnlyValidator; + }()); + Validation.LettersOnlyValidator = LettersOnlyValidator; +})(Validation || (Validation = {})); diff --git a/tests/baselines/reference/varArgConstructorMemberParameter.errors.txt b/tests/baselines/reference/varArgConstructorMemberParameter.errors.txt index e3257b870d6..9fb55a4d5fc 100644 --- a/tests/baselines/reference/varArgConstructorMemberParameter.errors.txt +++ b/tests/baselines/reference/varArgConstructorMemberParameter.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/varArgConstructorMemberParameter.ts(10,25): error TS1005: ',' expected. +tests/cases/compiler/varArgConstructorMemberParameter.ts(10,18): error TS1317: A parameter property cannot be declared using a rest parameter. ==== tests/cases/compiler/varArgConstructorMemberParameter.ts (1 errors) ==== @@ -12,7 +12,7 @@ tests/cases/compiler/varArgConstructorMemberParameter.ts(10,25): error TS1005: ' class Foo3 { constructor (public ...args: string[]) { } - ~~~ -!!! error TS1005: ',' expected. + ~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS1317: A parameter property cannot be declared using a rest parameter. } \ No newline at end of file diff --git a/tests/baselines/reference/varArgConstructorMemberParameter.js b/tests/baselines/reference/varArgConstructorMemberParameter.js index 620642a7514..2715ed9e542 100644 --- a/tests/baselines/reference/varArgConstructorMemberParameter.js +++ b/tests/baselines/reference/varArgConstructorMemberParameter.js @@ -29,11 +29,12 @@ var Foo2 = (function () { return Foo2; }()); var Foo3 = (function () { - function Foo3(public) { + function Foo3() { var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; } + this.args = args; } return Foo3; }()); diff --git a/tests/cases/compiler/classExpressionWithStaticPropertiesES61.ts b/tests/cases/compiler/classExpressionWithStaticPropertiesES61.ts index 8df07b9569a..3f9fc43835e 100644 --- a/tests/cases/compiler/classExpressionWithStaticPropertiesES61.ts +++ b/tests/cases/compiler/classExpressionWithStaticPropertiesES61.ts @@ -1,2 +1,6 @@ //@target: es6 -var v = class C { static a = 1; static b = 2 }; \ No newline at end of file +var v = class C { + static a = 1; + static b = 2; + static c = C.a + 3; +}; \ No newline at end of file diff --git a/tests/cases/compiler/classExpressionWithStaticPropertiesES62.ts b/tests/cases/compiler/classExpressionWithStaticPropertiesES62.ts index ee0430eb793..afb87b10de9 100644 --- a/tests/cases/compiler/classExpressionWithStaticPropertiesES62.ts +++ b/tests/cases/compiler/classExpressionWithStaticPropertiesES62.ts @@ -1,2 +1,9 @@ //@target: es6 -var v = class C { static a = 1; static b }; \ No newline at end of file +var v = class C { + static a = 1; + static b + static c = { + x: "hi" + } + static d = C.c.x + " world"; + }; \ No newline at end of file diff --git a/tests/cases/compiler/classExpressionWithStaticPropertiesES63.ts b/tests/cases/compiler/classExpressionWithStaticPropertiesES63.ts new file mode 100644 index 00000000000..939a344f9bb --- /dev/null +++ b/tests/cases/compiler/classExpressionWithStaticPropertiesES63.ts @@ -0,0 +1,11 @@ +//@target: es6 + +declare var console: any; +const arr: {y(): number}[] = []; +for (let i = 0; i < 3; i++) { + arr.push(class C { + static x = i; + static y = () => C.x * 2; + }); +} +arr.forEach(C => console.log(C.y())); \ No newline at end of file diff --git a/tests/cases/compiler/jsFileClassSelfReferencedProperty.ts b/tests/cases/compiler/jsFileClassSelfReferencedProperty.ts new file mode 100644 index 00000000000..8d6cecdb200 --- /dev/null +++ b/tests/cases/compiler/jsFileClassSelfReferencedProperty.ts @@ -0,0 +1,9 @@ +// @allowJs: true +// @noEmit: true + +// @filename: foo.js +export class StackOverflowTest { + constructor () { + this.testStackOverflow = this.testStackOverflow.bind(this) + } +} diff --git a/tests/cases/compiler/promiseType.ts b/tests/cases/compiler/promiseType.ts new file mode 100644 index 00000000000..c1b795b6cc7 --- /dev/null +++ b/tests/cases/compiler/promiseType.ts @@ -0,0 +1,94 @@ +// @target: es6 +declare var p: Promise; + +const a = p.then(); +const b = p.then(b => 1); +const c = p.then(b => 1, e => 'error'); +const d = p.then(b => 1, e => { }); +const e = p.then(b => 1, e => { throw Error(); }); +const f = p.then(b => 1, e => Promise.reject(Error())); +const g = p.catch(e => 'error'); +const h = p.catch(e => { }); +const i = p.catch(e => { throw Error(); }); +const j = p.catch(e => Promise.reject(Error())); + +async function A() { + const a = await p; + return a; +} + +async function B() { + const a = await p; + return 1; +} + +// NOTE: This reports a "No best comment type exists among return expressions." error, and is +// ignored to get the types result for the test. +// async function C() { +// try { +// const a = await p; +// return 1; +// } +// catch (e) { +// return 'error'; +// } +// } + +async function D() { + try { + const a = await p; + return 1; + } + catch (e) { + } +} + +async function E() { + try { + const a = await p; + return 1; + } + catch (e) { + throw Error(); + } +} + +async function F() { + try { + const a = await p; + return 1; + } + catch (e) { + return Promise.reject(Error()); + } +} + +async function G() { + try { + const a = await p; + return a; + } + catch (e) { + return; + } +} + +async function H() { + try { + const a = await p; + return a; + } + catch (e) { + throw Error(); + } +} + +async function I() { + try { + const a = await p; + return a; + } + catch (e) { + return Promise.reject(Error()); + } +} \ No newline at end of file diff --git a/tests/cases/compiler/signaturesUseJSDocForOptionalParameters.ts b/tests/cases/compiler/signaturesUseJSDocForOptionalParameters.ts new file mode 100644 index 00000000000..a6f9c9fb394 --- /dev/null +++ b/tests/cases/compiler/signaturesUseJSDocForOptionalParameters.ts @@ -0,0 +1,17 @@ +// @allowJs: true +// @out: out_1.js +// @filename: jsDocOptionality.js +function MyClass() { + this.prop = null; +} +/** + * @param {string} required + * @param {string} [notRequired] + * @returns {MyClass} + */ +MyClass.prototype.optionalParam = function(required, notRequired) { + return this; +}; +let pInst = new MyClass(); +let c1 = pInst.optionalParam('hello') +let c2 = pInst.optionalParam('hello', null) diff --git a/tests/cases/compiler/unusedClassesinModule1.ts b/tests/cases/compiler/unusedClassesinModule1.ts new file mode 100644 index 00000000000..0efc4966388 --- /dev/null +++ b/tests/cases/compiler/unusedClassesinModule1.ts @@ -0,0 +1,9 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +module A { + class Calculator { + public handelChar() { + } + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedClassesinNamespace1.ts b/tests/cases/compiler/unusedClassesinNamespace1.ts new file mode 100644 index 00000000000..da1feef9195 --- /dev/null +++ b/tests/cases/compiler/unusedClassesinNamespace1.ts @@ -0,0 +1,8 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + class c1 { + + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedClassesinNamespace2.ts b/tests/cases/compiler/unusedClassesinNamespace2.ts new file mode 100644 index 00000000000..83d60ff1628 --- /dev/null +++ b/tests/cases/compiler/unusedClassesinNamespace2.ts @@ -0,0 +1,12 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + class c1 { + + } + + export class c2 { + + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedClassesinNamespace3.ts b/tests/cases/compiler/unusedClassesinNamespace3.ts new file mode 100644 index 00000000000..9d39af37ea2 --- /dev/null +++ b/tests/cases/compiler/unusedClassesinNamespace3.ts @@ -0,0 +1,14 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + class c1 { + + } + + export class c2 { + + } + + export let a = new c1(); +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedClassesinNamespace4.ts b/tests/cases/compiler/unusedClassesinNamespace4.ts new file mode 100644 index 00000000000..390df8f7229 --- /dev/null +++ b/tests/cases/compiler/unusedClassesinNamespace4.ts @@ -0,0 +1,16 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + class c1 { + + } + + export class c2 { + + } + + class c3 extends c1 { + + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedClassesinNamespace5.ts b/tests/cases/compiler/unusedClassesinNamespace5.ts new file mode 100644 index 00000000000..43265e8fc40 --- /dev/null +++ b/tests/cases/compiler/unusedClassesinNamespace5.ts @@ -0,0 +1,16 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + class c1 { + + } + + export class c2 { + + } + + class c3 { + public x: c1; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedFunctionsinNamespaces1.ts b/tests/cases/compiler/unusedFunctionsinNamespaces1.ts new file mode 100644 index 00000000000..3e4a1814ba8 --- /dev/null +++ b/tests/cases/compiler/unusedFunctionsinNamespaces1.ts @@ -0,0 +1,7 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + function function1() { + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedFunctionsinNamespaces2.ts b/tests/cases/compiler/unusedFunctionsinNamespaces2.ts new file mode 100644 index 00000000000..5f38bbaaaac --- /dev/null +++ b/tests/cases/compiler/unusedFunctionsinNamespaces2.ts @@ -0,0 +1,7 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + var function1 = function() { + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedFunctionsinNamespaces3.ts b/tests/cases/compiler/unusedFunctionsinNamespaces3.ts new file mode 100644 index 00000000000..c20759494f6 --- /dev/null +++ b/tests/cases/compiler/unusedFunctionsinNamespaces3.ts @@ -0,0 +1,7 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + var function1 = function(param1:string) { + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedFunctionsinNamespaces4.ts b/tests/cases/compiler/unusedFunctionsinNamespaces4.ts new file mode 100644 index 00000000000..b8855ba2650 --- /dev/null +++ b/tests/cases/compiler/unusedFunctionsinNamespaces4.ts @@ -0,0 +1,11 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + var function1 = function() { + } + + export function function2() { + + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedFunctionsinNamespaces5.ts b/tests/cases/compiler/unusedFunctionsinNamespaces5.ts new file mode 100644 index 00000000000..f1d516fa66f --- /dev/null +++ b/tests/cases/compiler/unusedFunctionsinNamespaces5.ts @@ -0,0 +1,19 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + var function1 = function() { + } + + export function function2() { + + } + + function function3() { + function1(); + } + + function function4() { + + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedFunctionsinNamespaces6.ts b/tests/cases/compiler/unusedFunctionsinNamespaces6.ts new file mode 100644 index 00000000000..19f1591249c --- /dev/null +++ b/tests/cases/compiler/unusedFunctionsinNamespaces6.ts @@ -0,0 +1,21 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + var function1 = function() { + } + + export function function2() { + + } + + function function3() { + function1(); + } + + function function4() { + + } + + export let a = function3; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedGetterInClass.ts b/tests/cases/compiler/unusedGetterInClass.ts new file mode 100644 index 00000000000..e5259f91cdc --- /dev/null +++ b/tests/cases/compiler/unusedGetterInClass.ts @@ -0,0 +1,11 @@ +//@target: ES5 +//@noUnusedLocals:true +//@noUnusedParameters:true + +class Employee { + private _fullName: string; + + get fullName(): string { + return this._fullName; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedIdentifiersConsolidated1.ts b/tests/cases/compiler/unusedIdentifiersConsolidated1.ts new file mode 100644 index 00000000000..7c6e9b2e695 --- /dev/null +++ b/tests/cases/compiler/unusedIdentifiersConsolidated1.ts @@ -0,0 +1,104 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function greeter(person: string) { + var unused = 20; +} + +class Dummy { + private unusedprivatevariable: string; + private greeting: string; + public unusedpublicvariable: string; + public typedvariable: usedtypeparameter; + + constructor(message: string) { + var unused2 = 22; + this.greeting = "Dummy Message"; + } + + public greeter(person: string) { + var unused = 20; + this.usedPrivateFunction(); + } + + private usedPrivateFunction() { + } + + private unUsedPrivateFunction() { + } +} + +var user = "Jane User"; +var user2 = "Jane2 User2"; + +namespace Validation { + export interface StringValidator { + isAcceptable(s: string): boolean; + } + + const lettersRegexp = /^[A-Za-z]+$/; + const numberRegexp = /^[0-9]+$/; + + export class LettersOnlyValidator implements StringValidator { + isAcceptable(s2: string) { + return lettersRegexp.test(s2); + } + + private unUsedPrivateFunction() { + } + } + + export class ZipCodeValidator implements StringValidator { + isAcceptable(s3: string) { + return s3.length === 5; + } + } + + interface usedLocallyInterface { + } + + interface usedLocallyInterface2 { + someFunction(s1: string): void; + } + + export interface exportedInterface { + } + + class dummy implements usedLocallyInterface { + } + + interface unusedInterface { + } +} + + +namespace Greeter { + class class1 { + } + + export class class2 extends class1 { + } + + class class3 { + } + + export class class4 { + } + + interface interface1 { + } + + export interface interface2 extends interface1 { + } + + interface interface3 { + } + + export interface interface4 { + } + + export let a: interface3; + + interface interface5 { + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedImports1.ts b/tests/cases/compiler/unusedImports1.ts new file mode 100644 index 00000000000..30fff0c1ed1 --- /dev/null +++ b/tests/cases/compiler/unusedImports1.ts @@ -0,0 +1,10 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +// @Filename: file1.ts +export class Calculator { + +} + +// @Filename: file2.ts +import {Calculator} from "./file1" \ No newline at end of file diff --git a/tests/cases/compiler/unusedImports10.ts b/tests/cases/compiler/unusedImports10.ts new file mode 100644 index 00000000000..1cccfbd38bb --- /dev/null +++ b/tests/cases/compiler/unusedImports10.ts @@ -0,0 +1,13 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +module A { + export class Calculator { + public handelChar() { + } + } +} + +module B { + import a = A; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedImports2.ts b/tests/cases/compiler/unusedImports2.ts new file mode 100644 index 00000000000..00e7fcff33b --- /dev/null +++ b/tests/cases/compiler/unusedImports2.ts @@ -0,0 +1,18 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +// @Filename: file1.ts +export class Calculator { + handleChar() {} +} + +export function test() { + +} + +// @Filename: file2.ts +import {Calculator} from "./file1" +import {test} from "./file1" + +var x = new Calculator(); +x.handleChar(); \ No newline at end of file diff --git a/tests/cases/compiler/unusedImports3.ts b/tests/cases/compiler/unusedImports3.ts new file mode 100644 index 00000000000..349c2c9abe8 --- /dev/null +++ b/tests/cases/compiler/unusedImports3.ts @@ -0,0 +1,21 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +// @Filename: file1.ts +export class Calculator { + handleChar() {} +} + +export function test() { + +} + +export function test2() { + +} + +// @Filename: file2.ts +import {Calculator, test, test2} from "./file1" + +test(); +test2(); \ No newline at end of file diff --git a/tests/cases/compiler/unusedImports4.ts b/tests/cases/compiler/unusedImports4.ts new file mode 100644 index 00000000000..472c5965850 --- /dev/null +++ b/tests/cases/compiler/unusedImports4.ts @@ -0,0 +1,22 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +// @Filename: file1.ts +export class Calculator { + handleChar() {} +} + +export function test() { + +} + +export function test2() { + +} + +// @Filename: file2.ts +import {Calculator, test, test2} from "./file1" + +var x = new Calculator(); +x.handleChar(); +test2(); \ No newline at end of file diff --git a/tests/cases/compiler/unusedImports5.ts b/tests/cases/compiler/unusedImports5.ts new file mode 100644 index 00000000000..85943691ce2 --- /dev/null +++ b/tests/cases/compiler/unusedImports5.ts @@ -0,0 +1,22 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +// @Filename: file1.ts +export class Calculator { + handleChar() {} +} + +export function test() { + +} + +export function test2() { + +} + +// @Filename: file2.ts +import {Calculator, test, test2} from "./file1" + +var x = new Calculator(); +x.handleChar(); +test(); \ No newline at end of file diff --git a/tests/cases/compiler/unusedImports6.ts b/tests/cases/compiler/unusedImports6.ts new file mode 100644 index 00000000000..6ff45cc1b29 --- /dev/null +++ b/tests/cases/compiler/unusedImports6.ts @@ -0,0 +1,21 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +// @Filename: file1.ts +export class Calculator { + handleChar() {} +} + +export function test() { + +} + +export default function test2() { + +} + +// @Filename: file2.ts +import d from "./file1" + + + diff --git a/tests/cases/compiler/unusedImports7.ts b/tests/cases/compiler/unusedImports7.ts new file mode 100644 index 00000000000..94df3581745 --- /dev/null +++ b/tests/cases/compiler/unusedImports7.ts @@ -0,0 +1,19 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +// @Filename: file1.ts +export class Calculator { + handleChar() {} +} + +export function test() { + +} + +export default function test2() { + +} + +// @Filename: file2.ts +import * as n from "./file1" + diff --git a/tests/cases/compiler/unusedImports8.ts b/tests/cases/compiler/unusedImports8.ts new file mode 100644 index 00000000000..e8bd982d038 --- /dev/null +++ b/tests/cases/compiler/unusedImports8.ts @@ -0,0 +1,22 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +// @Filename: file1.ts +export class Calculator { + handleChar() {} +} + +export function test() { + +} + +export function test2() { + +} + +// @Filename: file2.ts +import {Calculator as calc, test as t1, test2 as t2} from "./file1" + +var x = new calc(); +x.handleChar(); +t1(); \ No newline at end of file diff --git a/tests/cases/compiler/unusedImports9.ts b/tests/cases/compiler/unusedImports9.ts new file mode 100644 index 00000000000..2e13e216c15 --- /dev/null +++ b/tests/cases/compiler/unusedImports9.ts @@ -0,0 +1,18 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +// @Filename: file1.ts +export class Calculator { + handleChar() {} +} + +export function test() { + +} + +export function test2() { + +} + +// @Filename: file2.ts +import c = require('./file1') \ No newline at end of file diff --git a/tests/cases/compiler/unusedInterfaceinNamespace1.ts b/tests/cases/compiler/unusedInterfaceinNamespace1.ts new file mode 100644 index 00000000000..db50d0da2b6 --- /dev/null +++ b/tests/cases/compiler/unusedInterfaceinNamespace1.ts @@ -0,0 +1,8 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + interface i1 { + + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedInterfaceinNamespace2.ts b/tests/cases/compiler/unusedInterfaceinNamespace2.ts new file mode 100644 index 00000000000..d0b6eb239ef --- /dev/null +++ b/tests/cases/compiler/unusedInterfaceinNamespace2.ts @@ -0,0 +1,12 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + interface i1 { + + } + + export interface i2 { + + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedInterfaceinNamespace3.ts b/tests/cases/compiler/unusedInterfaceinNamespace3.ts new file mode 100644 index 00000000000..48c615be903 --- /dev/null +++ b/tests/cases/compiler/unusedInterfaceinNamespace3.ts @@ -0,0 +1,16 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + interface i1 { + + } + + export interface i2 { + + } + + interface i3 extends i1 { + + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedInterfaceinNamespace4.ts b/tests/cases/compiler/unusedInterfaceinNamespace4.ts new file mode 100644 index 00000000000..e643f812227 --- /dev/null +++ b/tests/cases/compiler/unusedInterfaceinNamespace4.ts @@ -0,0 +1,20 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + interface i1 { + + } + + export interface i2 { + + } + + interface i3 extends i1 { + + } + + export class c1 implements i3 { + + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedInterfaceinNamespace5.ts b/tests/cases/compiler/unusedInterfaceinNamespace5.ts new file mode 100644 index 00000000000..901124e0f39 --- /dev/null +++ b/tests/cases/compiler/unusedInterfaceinNamespace5.ts @@ -0,0 +1,26 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + interface i1 { + + } + + export interface i2 { + + } + + interface i3 extends i1 { + + } + + export class c1 implements i3 { + + } + + interface i4 { + + } + + export let c2:i4; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedLocalsInMethod1.ts b/tests/cases/compiler/unusedLocalsInMethod1.ts new file mode 100644 index 00000000000..7da21b2c1af --- /dev/null +++ b/tests/cases/compiler/unusedLocalsInMethod1.ts @@ -0,0 +1,8 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + public function1() { + var x = 10; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedLocalsInMethod2.ts b/tests/cases/compiler/unusedLocalsInMethod2.ts new file mode 100644 index 00000000000..a376e6de0ac --- /dev/null +++ b/tests/cases/compiler/unusedLocalsInMethod2.ts @@ -0,0 +1,9 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + public function1() { + var x, y = 10; + y++; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedLocalsInMethod3.ts b/tests/cases/compiler/unusedLocalsInMethod3.ts new file mode 100644 index 00000000000..5d949110573 --- /dev/null +++ b/tests/cases/compiler/unusedLocalsInMethod3.ts @@ -0,0 +1,9 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + public function1() { + var x, y; + y = 1; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration1.ts b/tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration1.ts new file mode 100644 index 00000000000..0c325f198fa --- /dev/null +++ b/tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration1.ts @@ -0,0 +1,10 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function greeter(person: string, person2: string) { + var unused = 20; + function maker(child: string): void { + var unused2 = 22; + } + person2 = "dummy value"; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.ts b/tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.ts new file mode 100644 index 00000000000..00615f034b7 --- /dev/null +++ b/tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionDeclaration2.ts @@ -0,0 +1,13 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function greeter(person: string, person2: string) { + var unused = 20; + function maker(child: string): void { + var unused2 = 22; + } + function maker2(child2: string): void { + var unused3 = 23; + } + maker2(person2); +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression1.ts b/tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression1.ts new file mode 100644 index 00000000000..fd0e0f190e9 --- /dev/null +++ b/tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression1.ts @@ -0,0 +1,10 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +var greeter = function (person: string, person2: string) { + var unused = 20; + function maker(child: string): void { + var unused2 = 22; + } + person2 = "dummy value"; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.ts b/tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.ts new file mode 100644 index 00000000000..73adf038564 --- /dev/null +++ b/tests/cases/compiler/unusedLocalsOnFunctionDeclarationWithinFunctionExpression2.ts @@ -0,0 +1,13 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +var greeter = function (person: string, person2: string) { + var unused = 20; + function maker(child: string): void { + var unused2 = 22; + } + function maker2(child2: string): void { + var unused3 = 23; + } + maker2(person2); +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration1.ts b/tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration1.ts new file mode 100644 index 00000000000..9417b13b65a --- /dev/null +++ b/tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration1.ts @@ -0,0 +1,10 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function greeter(person: string, person2: string) { + var unused = 20; + var maker = function (child: string): void { + var unused2 = 22; + } + person2 = "dummy value"; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.ts b/tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.ts new file mode 100644 index 00000000000..7971ce5a30a --- /dev/null +++ b/tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionDeclaration2.ts @@ -0,0 +1,13 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function greeter(person: string, person2: string) { + var unused = 20; + var maker = function(child: string): void { + var unused2 = 22; + } + var maker2 = function(child2: string): void { + var unused3 = 23; + } + maker2(person2); +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression1.ts b/tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression1.ts new file mode 100644 index 00000000000..edeb341ee7d --- /dev/null +++ b/tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression1.ts @@ -0,0 +1,10 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +var greeter = function (person: string, person2: string) { + var unused = 20; + var maker = function (child: string): void { + var unused2 = 22; + } + person2 = "dummy value"; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression2.ts b/tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression2.ts new file mode 100644 index 00000000000..b407755c259 --- /dev/null +++ b/tests/cases/compiler/unusedLocalsOnFunctionExpressionWithinFunctionExpression2.ts @@ -0,0 +1,13 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +var greeter = function (person: string, person2: string) { + var unused = 20; + var maker = function (child: string): void { + var unused2 = 22; + } + var maker2 = function (child2: string): void { + var unused3 = 23; + } + maker2(person2); +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedLocalsinConstructor1.ts b/tests/cases/compiler/unusedLocalsinConstructor1.ts new file mode 100644 index 00000000000..fca303d2b9f --- /dev/null +++ b/tests/cases/compiler/unusedLocalsinConstructor1.ts @@ -0,0 +1,8 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + constructor() { + var unused = 20; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedLocalsinConstructor2.ts b/tests/cases/compiler/unusedLocalsinConstructor2.ts new file mode 100644 index 00000000000..2e67d98d56e --- /dev/null +++ b/tests/cases/compiler/unusedLocalsinConstructor2.ts @@ -0,0 +1,10 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + constructor() { + var unused = 20; + var used = "dummy"; + used = used + "second part"; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedMethodsInInterface.ts b/tests/cases/compiler/unusedMethodsInInterface.ts new file mode 100644 index 00000000000..29769bc5b11 --- /dev/null +++ b/tests/cases/compiler/unusedMethodsInInterface.ts @@ -0,0 +1,7 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +interface I1 { + f1(); + f2(x: number, y: string); +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedModuleInModule.ts b/tests/cases/compiler/unusedModuleInModule.ts new file mode 100644 index 00000000000..dc5f55398a7 --- /dev/null +++ b/tests/cases/compiler/unusedModuleInModule.ts @@ -0,0 +1,6 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +module A { + module B {} +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedMultipleParameter1InContructor.ts b/tests/cases/compiler/unusedMultipleParameter1InContructor.ts new file mode 100644 index 00000000000..b9565cafca6 --- /dev/null +++ b/tests/cases/compiler/unusedMultipleParameter1InContructor.ts @@ -0,0 +1,9 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class Dummy { + constructor(person: string, person2: string) { + var unused = 20; + person2 = "Dummy value"; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedMultipleParameter1InFunctionExpression.ts b/tests/cases/compiler/unusedMultipleParameter1InFunctionExpression.ts new file mode 100644 index 00000000000..3892db7e39d --- /dev/null +++ b/tests/cases/compiler/unusedMultipleParameter1InFunctionExpression.ts @@ -0,0 +1,7 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +var func = function(person: string, person2: string) { + var unused = 20; + person2 = "Dummy value"; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedMultipleParameter2InContructor.ts b/tests/cases/compiler/unusedMultipleParameter2InContructor.ts new file mode 100644 index 00000000000..34d54c714af --- /dev/null +++ b/tests/cases/compiler/unusedMultipleParameter2InContructor.ts @@ -0,0 +1,9 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class Dummy { + constructor(person: string, person2: string, person3: string) { + var unused = 20; + person2 = "Dummy value"; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedMultipleParameter2InFunctionExpression.ts b/tests/cases/compiler/unusedMultipleParameter2InFunctionExpression.ts new file mode 100644 index 00000000000..4d5bb2a103b --- /dev/null +++ b/tests/cases/compiler/unusedMultipleParameter2InFunctionExpression.ts @@ -0,0 +1,7 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +var func = function(person: string, person2: string, person3: string) { + var unused = 20; + person2 = "Dummy value"; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedMultipleParameters1InFunctionDeclaration.ts b/tests/cases/compiler/unusedMultipleParameters1InFunctionDeclaration.ts new file mode 100644 index 00000000000..bc63d72f015 --- /dev/null +++ b/tests/cases/compiler/unusedMultipleParameters1InFunctionDeclaration.ts @@ -0,0 +1,7 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function greeter(person: string, person2: string) { + var unused = 20; + person2 = "dummy value"; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedMultipleParameters1InMethodDeclaration.ts b/tests/cases/compiler/unusedMultipleParameters1InMethodDeclaration.ts new file mode 100644 index 00000000000..c74e702bbae --- /dev/null +++ b/tests/cases/compiler/unusedMultipleParameters1InMethodDeclaration.ts @@ -0,0 +1,9 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class Dummy { + public greeter(person: string, person2: string) { + var unused = 20; + person2 = "dummy value"; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedMultipleParameters2InFunctionDeclaration.ts b/tests/cases/compiler/unusedMultipleParameters2InFunctionDeclaration.ts new file mode 100644 index 00000000000..ad20d044ecc --- /dev/null +++ b/tests/cases/compiler/unusedMultipleParameters2InFunctionDeclaration.ts @@ -0,0 +1,7 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function greeter(person: string, person2: string, person3: string) { + var unused = 20; + person2 = "dummy value"; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedMultipleParameters2InMethodDeclaration.ts b/tests/cases/compiler/unusedMultipleParameters2InMethodDeclaration.ts new file mode 100644 index 00000000000..4ede3cd47a4 --- /dev/null +++ b/tests/cases/compiler/unusedMultipleParameters2InMethodDeclaration.ts @@ -0,0 +1,9 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class Dummy { + public greeter(person: string, person2: string, person3: string) { + var unused = 20; + person2 = "dummy value"; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedNamespaceInModule.ts b/tests/cases/compiler/unusedNamespaceInModule.ts new file mode 100644 index 00000000000..adca8a84187 --- /dev/null +++ b/tests/cases/compiler/unusedNamespaceInModule.ts @@ -0,0 +1,7 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +module A { + namespace B { } + export namespace C {} +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedNamespaceInNamespace.ts b/tests/cases/compiler/unusedNamespaceInNamespace.ts new file mode 100644 index 00000000000..8de3768a201 --- /dev/null +++ b/tests/cases/compiler/unusedNamespaceInNamespace.ts @@ -0,0 +1,7 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace A { + namespace B { } + export namespace C {} +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedParameterInCatchClause.ts b/tests/cases/compiler/unusedParameterInCatchClause.ts new file mode 100644 index 00000000000..3034ab0aef8 --- /dev/null +++ b/tests/cases/compiler/unusedParameterInCatchClause.ts @@ -0,0 +1,6 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function f1() { + try {} catch(ex){} +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedParameterUsedInTypeOf.ts b/tests/cases/compiler/unusedParameterUsedInTypeOf.ts new file mode 100644 index 00000000000..b69b2412314 --- /dev/null +++ b/tests/cases/compiler/unusedParameterUsedInTypeOf.ts @@ -0,0 +1,7 @@ +//@target: ES5 +//@noUnusedLocals:true +//@noUnusedParameters:true + +function f1 (a: number, b: typeof a) { + b++; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedParametersInLambda1.ts b/tests/cases/compiler/unusedParametersInLambda1.ts new file mode 100644 index 00000000000..431ac1eb1dc --- /dev/null +++ b/tests/cases/compiler/unusedParametersInLambda1.ts @@ -0,0 +1,9 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class A { + public f1() { + return (X) => { + } + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedParametersInLambda2.ts b/tests/cases/compiler/unusedParametersInLambda2.ts new file mode 100644 index 00000000000..ed4dfb3404b --- /dev/null +++ b/tests/cases/compiler/unusedParametersInLambda2.ts @@ -0,0 +1,10 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class A { + public f1() { + return (X, Y) => { + Y; + } + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedParametersinConstructor1.ts b/tests/cases/compiler/unusedParametersinConstructor1.ts new file mode 100644 index 00000000000..421636d661b --- /dev/null +++ b/tests/cases/compiler/unusedParametersinConstructor1.ts @@ -0,0 +1,7 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + constructor(param1: string) { + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedParametersinConstructor2.ts b/tests/cases/compiler/unusedParametersinConstructor2.ts new file mode 100644 index 00000000000..d6812f438c5 --- /dev/null +++ b/tests/cases/compiler/unusedParametersinConstructor2.ts @@ -0,0 +1,8 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + constructor(param1: string, param2: string) { + param2 = param2 + "dummy value"; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedParametersinConstructor3.ts b/tests/cases/compiler/unusedParametersinConstructor3.ts new file mode 100644 index 00000000000..e6295cd49fa --- /dev/null +++ b/tests/cases/compiler/unusedParametersinConstructor3.ts @@ -0,0 +1,8 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + constructor(param1: string, param2: string, param3: string) { + param2 = param2 + "dummy value"; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedPrivateMethodInClass1.ts b/tests/cases/compiler/unusedPrivateMethodInClass1.ts new file mode 100644 index 00000000000..e31dec6033b --- /dev/null +++ b/tests/cases/compiler/unusedPrivateMethodInClass1.ts @@ -0,0 +1,9 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + private function1() { + var y = 10; + y++; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedPrivateMethodInClass2.ts b/tests/cases/compiler/unusedPrivateMethodInClass2.ts new file mode 100644 index 00000000000..5039c265890 --- /dev/null +++ b/tests/cases/compiler/unusedPrivateMethodInClass2.ts @@ -0,0 +1,14 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + private function1() { + var y = 10; + y++; + } + + private function2() { + var y = 10; + y++; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedPrivateMethodInClass3.ts b/tests/cases/compiler/unusedPrivateMethodInClass3.ts new file mode 100644 index 00000000000..a35cd4512ec --- /dev/null +++ b/tests/cases/compiler/unusedPrivateMethodInClass3.ts @@ -0,0 +1,19 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + private function1() { + var y = 10; + y++; + } + + private function2() { + var y = 10; + y++; + } + + public function3() { + var y = 10; + y++; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedPrivateMethodInClass4.ts b/tests/cases/compiler/unusedPrivateMethodInClass4.ts new file mode 100644 index 00000000000..5e2741a12bc --- /dev/null +++ b/tests/cases/compiler/unusedPrivateMethodInClass4.ts @@ -0,0 +1,20 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + private function1() { + var y = 10; + y++; + } + + private function2() { + var y = 10; + y++; + } + + public function3() { + var y = 10; + y++; + this.function2(); + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedPrivateVariableInClass1.ts b/tests/cases/compiler/unusedPrivateVariableInClass1.ts new file mode 100644 index 00000000000..0877b7cd868 --- /dev/null +++ b/tests/cases/compiler/unusedPrivateVariableInClass1.ts @@ -0,0 +1,6 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + private x: string; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedPrivateVariableInClass2.ts b/tests/cases/compiler/unusedPrivateVariableInClass2.ts new file mode 100644 index 00000000000..acaf1e80412 --- /dev/null +++ b/tests/cases/compiler/unusedPrivateVariableInClass2.ts @@ -0,0 +1,7 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + private x: string; + private y: string; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedPrivateVariableInClass3.ts b/tests/cases/compiler/unusedPrivateVariableInClass3.ts new file mode 100644 index 00000000000..6cfa3184f44 --- /dev/null +++ b/tests/cases/compiler/unusedPrivateVariableInClass3.ts @@ -0,0 +1,8 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + private x: string; + private y: string; + public z: string; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedPrivateVariableInClass4.ts b/tests/cases/compiler/unusedPrivateVariableInClass4.ts new file mode 100644 index 00000000000..23598d5a491 --- /dev/null +++ b/tests/cases/compiler/unusedPrivateVariableInClass4.ts @@ -0,0 +1,12 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + private x: string; + private y: string; + public z: string; + + public method1() { + this.x = "dummy value"; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedPrivateVariableInClass5.ts b/tests/cases/compiler/unusedPrivateVariableInClass5.ts new file mode 100644 index 00000000000..51e64afca1d --- /dev/null +++ b/tests/cases/compiler/unusedPrivateVariableInClass5.ts @@ -0,0 +1,12 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + private x: string; + private y: string; + public z: string; + + constructor() { + this.x = "dummy value"; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedSetterInClass.ts b/tests/cases/compiler/unusedSetterInClass.ts new file mode 100644 index 00000000000..a8e45bab434 --- /dev/null +++ b/tests/cases/compiler/unusedSetterInClass.ts @@ -0,0 +1,11 @@ +//@target: ES5 +//@noUnusedLocals:true +//@noUnusedParameters:true + +class Employee { + private _fullName: string; + + set fullName(newName: string) { + this._fullName = newName; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedSingleParameterInContructor.ts b/tests/cases/compiler/unusedSingleParameterInContructor.ts new file mode 100644 index 00000000000..0f8f756fb48 --- /dev/null +++ b/tests/cases/compiler/unusedSingleParameterInContructor.ts @@ -0,0 +1,8 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class Dummy { + constructor(person: string) { + var unused = 20; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedSingleParameterInFunctionDeclaration.ts b/tests/cases/compiler/unusedSingleParameterInFunctionDeclaration.ts new file mode 100644 index 00000000000..8122065d7ca --- /dev/null +++ b/tests/cases/compiler/unusedSingleParameterInFunctionDeclaration.ts @@ -0,0 +1,6 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function greeter(person: string) { + var unused = 20; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedSingleParameterInFunctionExpression.ts b/tests/cases/compiler/unusedSingleParameterInFunctionExpression.ts new file mode 100644 index 00000000000..f4a749c33af --- /dev/null +++ b/tests/cases/compiler/unusedSingleParameterInFunctionExpression.ts @@ -0,0 +1,6 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +var func = function(person: string) { + var unused = 20; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedSingleParameterInMethodDeclaration.ts b/tests/cases/compiler/unusedSingleParameterInMethodDeclaration.ts new file mode 100644 index 00000000000..2dee007f210 --- /dev/null +++ b/tests/cases/compiler/unusedSingleParameterInMethodDeclaration.ts @@ -0,0 +1,8 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class Dummy { + public greeter(person: string) { + var unused = 20; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedTypeParameterInFunction1.ts b/tests/cases/compiler/unusedTypeParameterInFunction1.ts new file mode 100644 index 00000000000..421d2aa7b37 --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameterInFunction1.ts @@ -0,0 +1,6 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function f1() { + +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedTypeParameterInFunction2.ts b/tests/cases/compiler/unusedTypeParameterInFunction2.ts new file mode 100644 index 00000000000..76eeb11bb34 --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameterInFunction2.ts @@ -0,0 +1,7 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function f1() { + var a: X; + a; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedTypeParameterInFunction3.ts b/tests/cases/compiler/unusedTypeParameterInFunction3.ts new file mode 100644 index 00000000000..37f01468156 --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameterInFunction3.ts @@ -0,0 +1,9 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function f1() { + var a: X; + var b: Z; + a; + b; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedTypeParameterInFunction4.ts b/tests/cases/compiler/unusedTypeParameterInFunction4.ts new file mode 100644 index 00000000000..56549d93976 --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameterInFunction4.ts @@ -0,0 +1,9 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function f1() { + var a: Y; + var b: Z; + a; + b; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedTypeParameterInInterface1.ts b/tests/cases/compiler/unusedTypeParameterInInterface1.ts new file mode 100644 index 00000000000..2098e5d4bc5 --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameterInInterface1.ts @@ -0,0 +1,6 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +interface int { + +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedTypeParameterInInterface2.ts b/tests/cases/compiler/unusedTypeParameterInInterface2.ts new file mode 100644 index 00000000000..cdcd45a7f30 --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameterInInterface2.ts @@ -0,0 +1,7 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +interface int { + f1(a: T): string; + c: V; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedTypeParameterInLambda1.ts b/tests/cases/compiler/unusedTypeParameterInLambda1.ts new file mode 100644 index 00000000000..dd4dbe7824a --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameterInLambda1.ts @@ -0,0 +1,10 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class A { + public f1() { + return () => { + + } + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedTypeParameterInLambda2.ts b/tests/cases/compiler/unusedTypeParameterInLambda2.ts new file mode 100644 index 00000000000..73177a8b09d --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameterInLambda2.ts @@ -0,0 +1,11 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class A { + public f1() { + return () => { + var a: X; + a; + } + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedTypeParameterInLambda3.ts b/tests/cases/compiler/unusedTypeParameterInLambda3.ts new file mode 100644 index 00000000000..eb6582caf4e --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameterInLambda3.ts @@ -0,0 +1,7 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true +class A { + public x: T; +} + +var y: new (a:T)=>void; diff --git a/tests/cases/compiler/unusedTypeParameterInMethod1.ts b/tests/cases/compiler/unusedTypeParameterInMethod1.ts new file mode 100644 index 00000000000..f58bde3d2a1 --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameterInMethod1.ts @@ -0,0 +1,11 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class A { + public f1() { + var a: Y; + var b: Z; + a; + b; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedTypeParameterInMethod2.ts b/tests/cases/compiler/unusedTypeParameterInMethod2.ts new file mode 100644 index 00000000000..f344d188b0a --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameterInMethod2.ts @@ -0,0 +1,11 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class A { + public f1() { + var a: X; + var b: Z; + a; + b; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedTypeParameterInMethod3.ts b/tests/cases/compiler/unusedTypeParameterInMethod3.ts new file mode 100644 index 00000000000..9734136bd03 --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameterInMethod3.ts @@ -0,0 +1,11 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class A { + public f1() { + var a: X; + var b: Y; + a; + b; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedTypeParameterInMethod4.ts b/tests/cases/compiler/unusedTypeParameterInMethod4.ts new file mode 100644 index 00000000000..ef487d11118 --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameterInMethod4.ts @@ -0,0 +1,8 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class A { + public f1() { + + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedTypeParameterInMethod5.ts b/tests/cases/compiler/unusedTypeParameterInMethod5.ts new file mode 100644 index 00000000000..73cedcf402e --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameterInMethod5.ts @@ -0,0 +1,8 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class A { + public f1 = function() { + + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedTypeParameters1.ts b/tests/cases/compiler/unusedTypeParameters1.ts new file mode 100644 index 00000000000..cec2be7efda --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameters1.ts @@ -0,0 +1,6 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedTypeParameters2.ts b/tests/cases/compiler/unusedTypeParameters2.ts new file mode 100644 index 00000000000..c1018578147 --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameters2.ts @@ -0,0 +1,10 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + private x: typeparameter2; + + public function1() { + this.x; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedTypeParameters3.ts b/tests/cases/compiler/unusedTypeParameters3.ts new file mode 100644 index 00000000000..ea67756d5ad --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameters3.ts @@ -0,0 +1,10 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class greeter { + private x: typeparameter2; + + public function1() { + this.x; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedTypeParameters4.ts b/tests/cases/compiler/unusedTypeParameters4.ts new file mode 100644 index 00000000000..1b470c4ae28 --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameters4.ts @@ -0,0 +1,6 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +var x: { + new (a: T): void; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedTypeParameters5.ts b/tests/cases/compiler/unusedTypeParameters5.ts new file mode 100644 index 00000000000..7a5025a7907 --- /dev/null +++ b/tests/cases/compiler/unusedTypeParameters5.ts @@ -0,0 +1,10 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +class A { + public x: Dummy; +} + +var x: { + new (a: T): A; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedVariablesinBlocks1.ts b/tests/cases/compiler/unusedVariablesinBlocks1.ts new file mode 100644 index 00000000000..b937fbd8ac1 --- /dev/null +++ b/tests/cases/compiler/unusedVariablesinBlocks1.ts @@ -0,0 +1,10 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function f1 () { + let x = 10; + { + let x = 11; + x++; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedVariablesinBlocks2.ts b/tests/cases/compiler/unusedVariablesinBlocks2.ts new file mode 100644 index 00000000000..248e6302cd0 --- /dev/null +++ b/tests/cases/compiler/unusedVariablesinBlocks2.ts @@ -0,0 +1,10 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function f1 () { + let x = 10; + { + let x = 11; + } + x++; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedVariablesinForLoop.ts b/tests/cases/compiler/unusedVariablesinForLoop.ts new file mode 100644 index 00000000000..01f8a4bdfc5 --- /dev/null +++ b/tests/cases/compiler/unusedVariablesinForLoop.ts @@ -0,0 +1,8 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function f1 () { + for(var i = 0; ;) { + + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedVariablesinForLoop2.ts b/tests/cases/compiler/unusedVariablesinForLoop2.ts new file mode 100644 index 00000000000..b5d3496608d --- /dev/null +++ b/tests/cases/compiler/unusedVariablesinForLoop2.ts @@ -0,0 +1,8 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function f1 () { + for (const elem in ["a", "b", "c"]) { + + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedVariablesinForLoop3.ts b/tests/cases/compiler/unusedVariablesinForLoop3.ts new file mode 100644 index 00000000000..c08f225e7be --- /dev/null +++ b/tests/cases/compiler/unusedVariablesinForLoop3.ts @@ -0,0 +1,8 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function f1 () { + for (const elem of ["a", "b", "c"]) { + + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedVariablesinForLoop4.ts b/tests/cases/compiler/unusedVariablesinForLoop4.ts new file mode 100644 index 00000000000..ac75e065b9e --- /dev/null +++ b/tests/cases/compiler/unusedVariablesinForLoop4.ts @@ -0,0 +1,9 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +function f1 () { + for (const elem of ["a", "b", "c"]) { + elem; + var x = 20; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedVariablesinModules1.ts b/tests/cases/compiler/unusedVariablesinModules1.ts new file mode 100644 index 00000000000..92a5a14590d --- /dev/null +++ b/tests/cases/compiler/unusedVariablesinModules1.ts @@ -0,0 +1,8 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +export {}; + +var x: string; + +export var y: string; \ No newline at end of file diff --git a/tests/cases/compiler/unusedVariablesinNamespaces1.ts b/tests/cases/compiler/unusedVariablesinNamespaces1.ts new file mode 100644 index 00000000000..04febf70260 --- /dev/null +++ b/tests/cases/compiler/unusedVariablesinNamespaces1.ts @@ -0,0 +1,6 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + const lettersRegexp = /^[A-Za-z]+$/; +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedVariablesinNamespaces2.ts b/tests/cases/compiler/unusedVariablesinNamespaces2.ts new file mode 100644 index 00000000000..2178da8fbda --- /dev/null +++ b/tests/cases/compiler/unusedVariablesinNamespaces2.ts @@ -0,0 +1,13 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + const lettersRegexp = /^[A-Za-z]+$/; + const numberRegexp = /^[0-9]+$/; + + export class LettersOnlyValidator { + isAcceptable(s2: string) { + return lettersRegexp.test(s2); + } + } +} \ No newline at end of file diff --git a/tests/cases/compiler/unusedVariablesinNamespaces3.ts b/tests/cases/compiler/unusedVariablesinNamespaces3.ts new file mode 100644 index 00000000000..9952da92a7f --- /dev/null +++ b/tests/cases/compiler/unusedVariablesinNamespaces3.ts @@ -0,0 +1,14 @@ +//@noUnusedLocals:true +//@noUnusedParameters:true + +namespace Validation { + const lettersRegexp = /^[A-Za-z]+$/; + const numberRegexp = /^[0-9]+$/; + export const anotherUnusedVariable = "Dummy value"; + + export class LettersOnlyValidator { + isAcceptable(s2: string) { + return lettersRegexp.test(s2); + } + } +} \ No newline at end of file diff --git a/tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts b/tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts index 02fc84b380a..6a153034b32 100644 --- a/tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts +++ b/tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration4.ts @@ -26,7 +26,7 @@ a6([1, 2, "string"]); // Error, parameter type is number[] var temp = [1, 2, 3]; class C { - constructor(public ...temp) { } // Error, rest parameter can't have accessibilityModifier + constructor(public ...temp) { } // Error, rest parameter can't have properties } // Rest parameter with generic diff --git a/tests/cases/conformance/jsx/tsxDynamicTagName1.tsx b/tests/cases/conformance/jsx/tsxDynamicTagName1.tsx new file mode 100644 index 00000000000..1a54b55f94e --- /dev/null +++ b/tests/cases/conformance/jsx/tsxDynamicTagName1.tsx @@ -0,0 +1,4 @@ +// @jsx: preserve + +var CustomTag = "h1"; + Hello World // No error \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxDynamicTagName2.tsx b/tests/cases/conformance/jsx/tsxDynamicTagName2.tsx new file mode 100644 index 00000000000..0d5810bbd9a --- /dev/null +++ b/tests/cases/conformance/jsx/tsxDynamicTagName2.tsx @@ -0,0 +1,11 @@ +// @jsx: preserve + +declare module JSX { + interface Element { } + interface IntrinsicElements { + div: any + } +} + +var customTag = "h1"; + Hello World // This should be an error. The lower-case is look up as an intrinsic element name \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxDynamicTagName3.tsx b/tests/cases/conformance/jsx/tsxDynamicTagName3.tsx new file mode 100644 index 00000000000..09e05800ca5 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxDynamicTagName3.tsx @@ -0,0 +1,11 @@ +// @jsx: preserve + +declare module JSX { + interface Element { } + interface IntrinsicElements { + div: any + } +} + +var CustomTag: "h1" = "h1"; + Hello World // This should be an error. we will try look up string literal type in JSX.IntrinsicElements \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxDynamicTagName4.tsx b/tests/cases/conformance/jsx/tsxDynamicTagName4.tsx new file mode 100644 index 00000000000..18ea11a6647 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxDynamicTagName4.tsx @@ -0,0 +1,12 @@ +// @jsx: preserve + +declare module JSX { + interface Element { } + interface IntrinsicElements { + div: any + h1: any + } +} + +var CustomTag: "h1" = "h1"; + Hello World \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxDynamicTagName5.tsx b/tests/cases/conformance/jsx/tsxDynamicTagName5.tsx new file mode 100644 index 00000000000..b8e98cc1103 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxDynamicTagName5.tsx @@ -0,0 +1,19 @@ +// @jsx: preserve + +//@filename: react.d.ts +declare module 'react' { + class Component { } +} + +//@filename: app.tsx +import * as React from 'react'; + +export class Text extends React.Component<{}, {}> { + _tagName: string = 'div'; + + render() { + return ( + + ); + } +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxDynamicTagName6.tsx b/tests/cases/conformance/jsx/tsxDynamicTagName6.tsx new file mode 100644 index 00000000000..7657f7a82b3 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxDynamicTagName6.tsx @@ -0,0 +1,11 @@ +// @jsx: preserve + +declare module JSX { + interface Element { } + interface IntrinsicElements { + div: any + } +} + +const t = {tag:'h1'} +const foo = // No error \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxDynamicTagName7.tsx b/tests/cases/conformance/jsx/tsxDynamicTagName7.tsx new file mode 100644 index 00000000000..52ff5f4ec24 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxDynamicTagName7.tsx @@ -0,0 +1,19 @@ +// @jsx: preserve + +//@filename: react.d.ts +declare module 'react' { + class Component { } +} + +//@filename: app.tsx +import * as React from 'react'; + +export class Text extends React.Component<{}, {}> { + _tagName: string = 'div'; + + render() { + return ( + // this should be an error + ); + } +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxDynamicTagName8.tsx b/tests/cases/conformance/jsx/tsxDynamicTagName8.tsx new file mode 100644 index 00000000000..ee3bfaa0dfa --- /dev/null +++ b/tests/cases/conformance/jsx/tsxDynamicTagName8.tsx @@ -0,0 +1,19 @@ +// @jsx: preserve + +//@filename: react.d.ts +declare module 'react' { + class Component { } +} + +//@filename: app.tsx +import * as React from 'react'; + +export class Text extends React.Component<{}, {}> { + _tagName: string = 'div'; + + render() { + return ( + Hello world + ); + } +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxDynamicTagName9.tsx b/tests/cases/conformance/jsx/tsxDynamicTagName9.tsx new file mode 100644 index 00000000000..397fbdcd837 --- /dev/null +++ b/tests/cases/conformance/jsx/tsxDynamicTagName9.tsx @@ -0,0 +1,19 @@ +// @jsx: preserve + +//@filename: react.d.ts +declare module 'react' { + class Component { } +} + +//@filename: app.tsx +import * as React from 'react'; + +export class Text extends React.Component<{}, {}> { + _tagName: "div" = 'div'; + + render() { + return ( + Hello world + ); + } +} \ No newline at end of file diff --git a/tests/cases/conformance/jsx/tsxUnionTypeComponent2.tsx b/tests/cases/conformance/jsx/tsxUnionTypeComponent2.tsx index 39807219661..dbd14f6c27f 100644 --- a/tests/cases/conformance/jsx/tsxUnionTypeComponent2.tsx +++ b/tests/cases/conformance/jsx/tsxUnionTypeComponent2.tsx @@ -5,9 +5,9 @@ import React = require('react'); -type Invalid1 = React.ComponentClass | string; +type Invalid1 = React.ComponentClass | number; -const X: Invalid1 = "Should fail to construct"; +const X: Invalid1 = 1; ; diff --git a/tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts b/tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts new file mode 100644 index 00000000000..e659c6f6f56 --- /dev/null +++ b/tests/cases/conformance/types/intersection/intersectionTypeReadonly.ts @@ -0,0 +1,25 @@ +interface Base { + readonly value: number; +} +interface Identical { + readonly value: number; +} +interface Mutable { + value: number; +} +interface DifferentType { + readonly value: string; +} +interface DifferentName { + readonly other: number; +} +let base: Base; +base.value = 12 // error, lhs can't be a readonly property +let identical: Base & Identical; +identical.value = 12; // error, lhs can't be a readonly property +let mutable: Base & Mutable; +mutable.value = 12; // error, lhs can't be a readonly property +let differentType: Base & DifferentType; +differentType.value = 12; // error, lhs can't be a readonly property +let differentName: Base & DifferentName; +differentName.value = 12; // error, property 'value' doesn't exist diff --git a/tests/cases/conformance/types/union/unionTypeReadonly.ts b/tests/cases/conformance/types/union/unionTypeReadonly.ts new file mode 100644 index 00000000000..89cf1cbfd37 --- /dev/null +++ b/tests/cases/conformance/types/union/unionTypeReadonly.ts @@ -0,0 +1,26 @@ +interface Base { + readonly value: number; +} +interface Identical { + readonly value: number; +} +interface Mutable { + value: number; +} +interface DifferentType { + readonly value: string; +} +interface DifferentName { + readonly other: number; +} +let base: Base; +base.value = 12 // error, lhs can't be a readonly property +let identical: Base | Identical; +identical.value = 12; // error, lhs can't be a readonly property +let mutable: Base | Mutable; +mutable.value = 12; // error, lhs can't be a readonly property +let differentType: Base | DifferentType; +differentType.value = 12; // error, lhs can't be a readonly property +let differentName: Base | DifferentName; +differentName.value = 12; // error, property 'value' doesn't exist + diff --git a/tests/cases/fourslash/cancellationWhenfindingAllRefsOnDefinition.ts b/tests/cases/fourslash/cancellationWhenfindingAllRefsOnDefinition.ts index 48a698c5a47..d3d18b2dabb 100644 --- a/tests/cases/fourslash/cancellationWhenfindingAllRefsOnDefinition.ts +++ b/tests/cases/fourslash/cancellationWhenfindingAllRefsOnDefinition.ts @@ -7,7 +7,7 @@ //// //// } //// -//// public /*1*/start(){ +//// public /**/[|start|](){ //// return this; //// } //// @@ -20,19 +20,14 @@ ////import Second = require("./findAllRefsOnDefinition-import"); //// ////var second = new Second.Test() -////second.start(); +////second.[|start|](); ////second.stop(); -goTo.file("findAllRefsOnDefinition-import.ts"); -goTo.marker("1"); - -verify.referencesCountIs(2); +verify.rangesReferenceEachOther(); cancellation.setCancelled(); -goTo.marker("1"); -verifyOperationIsCancelled(() => verify.referencesCountIs(0) ); +verifyOperationIsCancelled(() => verify.rangesReferenceEachOther()); // verify that internal state is still correct cancellation.resetCancelled(); -goTo.marker("1"); -verify.referencesCountIs(2); +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/commentBraceCompletionPosition.ts b/tests/cases/fourslash/commentBraceCompletionPosition.ts index 23b8240dcaf..b92c49d3a14 100644 --- a/tests/cases/fourslash/commentBraceCompletionPosition.ts +++ b/tests/cases/fourslash/commentBraceCompletionPosition.ts @@ -14,10 +14,10 @@ //// } goTo.marker('1'); -verify.not.isValidBraceCompletionAtPostion('('); +verify.not.isValidBraceCompletionAtPosition('('); goTo.marker('2'); -verify.not.isValidBraceCompletionAtPostion('('); +verify.not.isValidBraceCompletionAtPosition('('); goTo.marker('3'); -verify.not.isValidBraceCompletionAtPostion('('); \ No newline at end of file +verify.not.isValidBraceCompletionAtPosition('('); \ No newline at end of file diff --git a/tests/cases/fourslash/findAllRefsForDefaultExport07.ts b/tests/cases/fourslash/findAllRefsForDefaultExport07.ts index 9534a671316..88d0a775026 100644 --- a/tests/cases/fourslash/findAllRefsForDefaultExport07.ts +++ b/tests/cases/fourslash/findAllRefsForDefaultExport07.ts @@ -8,11 +8,9 @@ //// ////var y = DefaultExportedFunction(); //// -////namespace /**/DefaultExportedFunction { +////namespace [|DefaultExportedFunction|] { ////} // The namespace and function do not merge, // so the namespace should be all alone. - -goTo.marker(); -verify.referencesCountIs(1); +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/findAllRefsForDefaultExport08.ts b/tests/cases/fourslash/findAllRefsForDefaultExport08.ts index 80eabbe53f4..b7ae7f4d534 100644 --- a/tests/cases/fourslash/findAllRefsForDefaultExport08.ts +++ b/tests/cases/fourslash/findAllRefsForDefaultExport08.ts @@ -7,11 +7,10 @@ //// ////var y = new DefaultExportedClass; //// -////namespace /**/DefaultExportedClass { +////namespace [|DefaultExportedClass|] { ////} // The namespace and class do not merge, // so the namespace should be all alone. -goTo.marker(); -verify.referencesCountIs(1); +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/findAllRefsForVariableInImplementsClause01.ts b/tests/cases/fourslash/findAllRefsForVariableInImplementsClause01.ts index 93f8cec8109..f8326eade58 100644 --- a/tests/cases/fourslash/findAllRefsForVariableInImplementsClause01.ts +++ b/tests/cases/fourslash/findAllRefsForVariableInImplementsClause01.ts @@ -1,10 +1,7 @@ /// - ////var Base = class { }; -////class C extends Base implements [|Base|] { } +////class C extends Base implements /**/Base { } -let ranges = test.ranges(); -for (let range of ranges) { - verify.referencesCountIs(0); -} \ No newline at end of file +goTo.marker(); +verify.referencesAre([]); diff --git a/tests/cases/fourslash/findAllRefsInsideWithBlock.ts b/tests/cases/fourslash/findAllRefsInsideWithBlock.ts index fc8a94eaa2d..c95925ff863 100644 --- a/tests/cases/fourslash/findAllRefsInsideWithBlock.ts +++ b/tests/cases/fourslash/findAllRefsInsideWithBlock.ts @@ -1,16 +1,12 @@ /// -////var x = 0; +////var [|x|] = 0; //// ////with ({}) { //// var y = x; // Reference of x here should not be picked //// /*2*/y++; // also reference for y should be ignored ////} //// -////x = /*1*/x + 1; +////[|x|] = [|x|] + 1; -goTo.marker('1'); -verify.referencesCountIs(3); - -goTo.marker('2'); -verify.referencesCountIs(0); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName05.ts b/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName05.ts index f7e3b80fe45..e33c73ff838 100644 --- a/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName05.ts +++ b/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName05.ts @@ -10,4 +10,4 @@ ////} goTo.marker(); -verify.referencesCountIs(0); \ No newline at end of file +verify.referencesAre([]); \ No newline at end of file diff --git a/tests/cases/fourslash/findAllRefsOnDecorators.ts b/tests/cases/fourslash/findAllRefsOnDecorators.ts index 3225bc108ce..b58e15b9571 100644 --- a/tests/cases/fourslash/findAllRefsOnDecorators.ts +++ b/tests/cases/fourslash/findAllRefsOnDecorators.ts @@ -1,19 +1,16 @@ /// // @Filename: a.ts -////function decorator(target) { +////function [|decorator|](target) { //// return target; ////} -////decorator(); +////[|decorator|](); // @Filename: b.ts -////@deco/*1*/rator @decorator("again") +////@[|decorator|] @[|decorator|]("again") ////class C { -//// @decorator +//// @[|decorator|] //// method() {} ////} -goTo.file("b.ts"); -goTo.marker("1"); - -verify.referencesCountIs(5); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/findAllRefsOnDefinition.ts b/tests/cases/fourslash/findAllRefsOnDefinition.ts index a25a6e1285f..cb829807602 100644 --- a/tests/cases/fourslash/findAllRefsOnDefinition.ts +++ b/tests/cases/fourslash/findAllRefsOnDefinition.ts @@ -7,7 +7,7 @@ //// //// } //// -//// public /*1*/start(){ +//// public [|start|](){ //// return this; //// } //// @@ -20,10 +20,7 @@ ////import Second = require("./findAllRefsOnDefinition-import"); //// ////var second = new Second.Test() -////second.start(); +////second.[|start|](); ////second.stop(); -goTo.file("findAllRefsOnDefinition-import.ts"); -goTo.marker("1"); - -verify.referencesCountIs(2); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/findAllRefsOnDefinition2.ts b/tests/cases/fourslash/findAllRefsOnDefinition2.ts index c9a116d4622..8edfd7f8cd7 100644 --- a/tests/cases/fourslash/findAllRefsOnDefinition2.ts +++ b/tests/cases/fourslash/findAllRefsOnDefinition2.ts @@ -3,7 +3,7 @@ //@Filename: findAllRefsOnDefinition2-import.ts ////export module Test{ //// -//// export interface /*1*/start { } +//// export interface [|start|] { } //// //// export interface stop { } ////} @@ -11,10 +11,7 @@ //@Filename: findAllRefsOnDefinition2.ts ////import Second = require("./findAllRefsOnDefinition2-import"); //// -////var start: Second.Test.start; +////var start: Second.Test.[|start|]; ////var stop: Second.Test.stop; -goTo.file("findAllRefsOnDefinition2-import.ts"); -goTo.marker("1"); - -verify.referencesCountIs(2); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/findAllRefsOnImportAliases.ts b/tests/cases/fourslash/findAllRefsOnImportAliases.ts index 8460e3f39b2..cd258e80316 100644 --- a/tests/cases/fourslash/findAllRefsOnImportAliases.ts +++ b/tests/cases/fourslash/findAllRefsOnImportAliases.ts @@ -1,29 +1,15 @@ /// //@Filename: a.ts -////export class /*1*/Class{ +////export class [|Class|] { ////} //@Filename: b.ts -////import { /*2*/Class } from "./a"; +////import { [|Class|] } from "./a"; //// -////var c = new /*3*/Class(); +////var c = new [|Class|](); //@Filename: c.ts -////export { /*4*/Class } from "./a"; - -goTo.file("a.ts"); -goTo.marker("1"); -verify.referencesCountIs(4); - -goTo.file("b.ts"); -goTo.marker("2"); -verify.referencesCountIs(4); - -goTo.marker("3"); -verify.referencesCountIs(4); - -goTo.file("c.ts"); -goTo.marker("4"); -verify.referencesCountIs(4); +////export { [|Class|] } from "./a"; +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/findAllRefsOnImportAliases2.ts b/tests/cases/fourslash/findAllRefsOnImportAliases2.ts index ab7a99e1e74..67c4d14b5d9 100644 --- a/tests/cases/fourslash/findAllRefsOnImportAliases2.ts +++ b/tests/cases/fourslash/findAllRefsOnImportAliases2.ts @@ -1,31 +1,15 @@ /// //@Filename: a.ts -////export class /*1*/Class{ +////export class [|Class|] { ////} //@Filename: b.ts -////import { /*2*/Class as /*3*/C2} from "./a"; +////import { [|Class|] as [|C2|] } from "./a"; //// -////var c = new C2(); +////var c = new [|C2|](); //@Filename: c.ts -////export { /*4*/Class as /*5*/C3 } from "./a"; +////export { [|Class|] as [|C3|] } from "./a"; -goTo.file("a.ts"); -goTo.marker("1"); -verify.referencesCountIs(3); - -goTo.file("b.ts"); -goTo.marker("2"); -verify.referencesCountIs(3); - -goTo.marker("3"); -verify.referencesCountIs(2); - -goTo.file("c.ts"); -goTo.marker("4"); -verify.referencesCountIs(3); - -goTo.marker("5"); -verify.referencesCountIs(1); +verify.rangesWithSameTextReferenceEachOther(); diff --git a/tests/cases/fourslash/findAllRefsThisKeyword.ts b/tests/cases/fourslash/findAllRefsThisKeyword.ts new file mode 100644 index 00000000000..f08a70ccf65 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsThisKeyword.ts @@ -0,0 +1,33 @@ +/// +// @noLib: true + +////[|this|]; +////function f([|this|]) { +//// return [|this|]; +//// function g([|this|]) { return [|this|]; } +////} +////class C { +//// static x() { +//// [|this|]; +//// } +//// static y() { +//// () => [|this|]; +//// } +//// constructor() { +//// [|this|]; +//// } +//// method() { +//// () => [|this|]; +//// } +////} +////// These are *not* real uses of the 'this' keyword, they are identifiers. +////const x = { [|this|]: 0 } +////x.[|this|]; + +const [global, f0, f1, g0, g1, x, y, constructor, method, propDef, propUse] = test.ranges(); +verify.referencesOf(global, [global]); +verify.rangesReferenceEachOther([f0, f1]); +verify.rangesReferenceEachOther([g0, g1]); +verify.rangesReferenceEachOther([x, y]); +verify.rangesReferenceEachOther([constructor, method]); +verify.rangesReferenceEachOther([propDef, propUse]); diff --git a/tests/cases/fourslash/findAllRefsThisKeywordMultipleFiles.ts b/tests/cases/fourslash/findAllRefsThisKeywordMultipleFiles.ts index 4b9f7a450ec..a4bab7f876c 100644 --- a/tests/cases/fourslash/findAllRefsThisKeywordMultipleFiles.ts +++ b/tests/cases/fourslash/findAllRefsThisKeywordMultipleFiles.ts @@ -1,18 +1,15 @@ /// // @Filename: file1.ts -////this; this; +////[|this|]; [|this|]; // @Filename: file2.ts -////this; -////this; +////[|this|]; +////[|this|]; // @Filename: file3.ts -//// ((x = this, y) => t/**/his)(this, this); +//// ((x = [|this|], y) => [|this|])([|this|], [|this|]); +//// // different 'this' +//// function f(this) { return this; } -goTo.file("file1.ts"); -goTo.marker(); - -// TODO (drosen): The CURRENT behavior is that findAllRefs doesn't work on 'this' or 'super' keywords. -// This should change down the line. -verify.referencesCountIs(0); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/findAllRefsWithShorthandPropertyAssignment.ts b/tests/cases/fourslash/findAllRefsWithShorthandPropertyAssignment.ts index 7a1f7a0225f..0dc050602c5 100644 --- a/tests/cases/fourslash/findAllRefsWithShorthandPropertyAssignment.ts +++ b/tests/cases/fourslash/findAllRefsWithShorthandPropertyAssignment.ts @@ -1,19 +1,14 @@ /// -//// var /*1*/name = "Foo"; +//// var [|name|] = "Foo"; //// -//// var obj = { /*2*/name }; -//// var obj1 = { /*3*/name:name }; -//// obj./*4*/name; +//// var obj = { [|name|] }; +//// var obj1 = { [|name|]:[|name|] }; +//// obj.[|name|]; -goTo.marker('1'); -verify.referencesCountIs(3); - -goTo.marker('2'); -verify.referencesCountIs(4); - -goTo.marker('3'); -verify.referencesCountIs(1); - -goTo.marker('4'); -verify.referencesCountIs(2); +const [r0, r1, r2, r3, r4] = test.ranges(); +verify.referencesOf(r0, [r0, r1, r3]); +verify.referencesOf(r1, [r0, r1, r3, r4]); +verify.referencesOf(r2, [r2]); +verify.referencesOf(r3, [r0, r1, r3]); +verify.referencesOf(r4, [r1, r4]); diff --git a/tests/cases/fourslash/findAllRefsWithShorthandPropertyAssignment2.ts b/tests/cases/fourslash/findAllRefsWithShorthandPropertyAssignment2.ts index b3f283f1272..59ba87fabb6 100644 --- a/tests/cases/fourslash/findAllRefsWithShorthandPropertyAssignment2.ts +++ b/tests/cases/fourslash/findAllRefsWithShorthandPropertyAssignment2.ts @@ -1,22 +1,16 @@ /// -//// var /*1*/dx = "Foo"; +//// var [|dx|] = "Foo"; //// -//// module M { export var /*2*/dx; } +//// module M { export var [|dx|]; } //// module M { //// var z = 100; -//// export var y = { /*3*/dx, z }; +//// export var y = { [|dx|], z }; //// } -//// M.y./*4*/dx; +//// M.y.[|dx|]; -goTo.marker('1'); -verify.referencesCountIs(1); - -goTo.marker('2'); -verify.referencesCountIs(2); - -goTo.marker('3'); -verify.referencesCountIs(3); - -goTo.marker('4'); -verify.referencesCountIs(2); \ No newline at end of file +const [r0, r1, r2, r3] = test.ranges(); +verify.referencesOf(r0, [r0]); +verify.referencesOf(r1, [r1, r2]); +verify.referencesOf(r2, [r1, r2, r3]); +verify.referencesOf(r3, [r2, r3]); diff --git a/tests/cases/fourslash/findReferencesAcrossMultipleProjects.ts b/tests/cases/fourslash/findReferencesAcrossMultipleProjects.ts index 0ef7745f8f9..a9915fc4b3d 100644 --- a/tests/cases/fourslash/findReferencesAcrossMultipleProjects.ts +++ b/tests/cases/fourslash/findReferencesAcrossMultipleProjects.ts @@ -1,17 +1,14 @@ /// //@Filename: a.ts -////var /*1*/x: number; +////var [|x|]: number; //@Filename: b.ts /////// -////x++; +////[|x|]++; //@Filename: c.ts /////// -////x++; +////[|x|]++; -goTo.file("a.ts"); -goTo.marker("1"); - -verify.referencesCountIs(3); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/findReferencesAfterEdit.ts b/tests/cases/fourslash/findReferencesAfterEdit.ts index 5eca1a3b8f2..6140ca9a767 100644 --- a/tests/cases/fourslash/findReferencesAfterEdit.ts +++ b/tests/cases/fourslash/findReferencesAfterEdit.ts @@ -2,21 +2,19 @@ // @Filename: a.ts ////interface A { -//// foo: string; +//// [|foo|]: string; ////} // @Filename: b.ts /////// -/////*0*/ +/////**/ ////function foo(x: A) { -//// x.f/*1*/oo +//// x.[|foo|] ////} -goTo.marker("1"); -verify.referencesCountIs(2); +verify.rangesReferenceEachOther(); -goTo.marker("0"); +goTo.marker(""); edit.insert("\r\n"); -goTo.marker("1"); -verify.referencesCountIs(2); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/findReferencesJSXTagName.ts b/tests/cases/fourslash/findReferencesJSXTagName.ts index a6170b4fc8f..24760046eb2 100644 --- a/tests/cases/fourslash/findReferencesJSXTagName.ts +++ b/tests/cases/fourslash/findReferencesJSXTagName.ts @@ -1,22 +1,14 @@ /// // @Filename: index.tsx -////import { /*1*/SubmissionComp } from "./RedditSubmission" +////import { [|SubmissionComp|] } from "./RedditSubmission" ////function displaySubreddit(subreddit: string) { //// let components = submissions -//// .map((value, index) => ); +//// .map((value, index) => <[|SubmissionComp|] key={ index } elementPosition= { index } {...value.data} />); ////} // @Filename: RedditSubmission.ts -////export const /*3*/SubmissionComp = (submission: SubmissionProps) => +////export const [|SubmissionComp|] = (submission: SubmissionProps) => ////
; - -goTo.marker("1"); -verify.referencesCountIs(3); - -goTo.marker("2"); -verify.referencesCountIs(3); - -goTo.marker("3"); -verify.referencesCountIs(3); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/findReferencesJSXTagName2.ts b/tests/cases/fourslash/findReferencesJSXTagName2.ts index a7bb7fd97dd..4ce08647c52 100644 --- a/tests/cases/fourslash/findReferencesJSXTagName2.ts +++ b/tests/cases/fourslash/findReferencesJSXTagName2.ts @@ -1,11 +1,7 @@ /// // @Filename: index.tsx -////const /*1*/obj = {Component: () =>
}; -////const element = ; +////const [|obj|] = {Component: () =>
}; +////const element = <[|obj|].Component/>; -goTo.marker("1"); -verify.referencesCountIs(2); - -goTo.marker("2"); -verify.referencesCountIs(2); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/formatWithBaseIndent.ts b/tests/cases/fourslash/formatWithBaseIndent.ts new file mode 100644 index 00000000000..660131996c9 --- /dev/null +++ b/tests/cases/fourslash/formatWithBaseIndent.ts @@ -0,0 +1,264 @@ +/// + +//// +/////*1*/ module classes { +/////*2*/ class Bar { +//// +/////*3*/ constructor() { +/////*4*/ } +//// +/////*5*/private foo: string = ""; +//// +/////*6*/ private f() { +/////*7*/ var a: any[] = [[1, 2], [3, 4], 5]; +/////*8*/ return ((1 + 1)); +/////*9*/ } +//// +/////*10*/ private f2() { +/////*11*/ if (true) { } { }; +/////*12*/ } +/////*13*/ } +/////*14*/ } +//// +//// +/////*15*/ module interfaces { +/////*16*/ interface Foo { +//// +/////*17*/ x: number; +//// +/////*18*/ foo(): number; +/////*19*/ } +/////*20*/ } +//// +//// +/////*21*/ module nestedModules { +/////*22*/ module Foo2 { +/////*23*/ function f() { +/////*24*/ } +/////*25*/ var x: number; +/////*26*/} +/////*27*/ } +//// +//// +/////*28*/ module Enums { +/////*29*/ enum Foo3 { +/////*30*/ val1 , +/////*31*/ val2, +/////*32*/ } +/////*33*/ } +//// +//// +/////*34*/ function controlStatements() { +/////*35*/ for (var i = 0; i < 10; i++) { +/////*36*/ } +//// +/////*37*/ for (var e in foo.bar) { +/////*38*/ } +//// +/////*39*/with (foo.bar) { +/////*40*/ } +//// +/////*41*/ while (false) { +/////*42*/ } +//// +/////*43*/ do { +/////*44*/ } while (false); +//// +/////*45*/ switch (foo.bar) { +/////*46*/ } +//// +/////*47*/ switch (foo.bar) { +/////*48*/ case 1: +/////*49*/ break; +/////*50*/ default: +/////*51*/ break; +/////*52*/ } +/////*53*/ } +//// +//// +/////*54*/ function tryCatch() { +/////*55*/try { +/////*56*/} +/////*57*/catch (err) { +/////*58*/ } +/////*59*/ } +//// +//// +/////*60*/ function tryFinally() { +/////*61*/ try { +/////*62*/ } +/////*63*/ finally { +/////*64*/ } +/////*65*/ } +//// +//// +/////*66*/ function tryCatchFinally() { +/////*67*/ try { +/////*68*/ } +/////*69*/ catch (err) { +/////*70*/ } +/////*71*/ finally { +/////*72*/ } +/////*73*/ } +//// +//// +/////*74*/ class indentBeforeCurly +/////*75*/ { +/////*76*/ } +//// +//// +/////*77*/ function argumentsListIndentation(bar, +/////*78*/ blah, +/////*79*/ ); +//// +//// +/////*80*/ function blockIndentAfterIndentedParameter1(bar, +/////*81*/ blah) { +/////*82*/ } +//// +//// +/////*83*/ function blockIndentAfterIndentedParameter2(bar, +/////*84*/ blah) { +/////*85*/ if (foo) { +/////*86*/ } +/////*87*/} +//// +/////*88*/ var templateLiterals = `abcdefghi +/////*89*/jklmnop +/////*90*/qrstuvwxyz`; + +var originalOptions = format.copyFormatOptions(); +var copy = format.copyFormatOptions(); +copy.BaseIndentSize = 10; +copy.IndentSize = 4; + +format.setFormatOptions(copy); +format.document(); + +verify.currentFileContentIs(` + module classes { + class Bar { + + constructor() { + } + + private foo: string = ""; + + private f() { + var a: any[] = [[1, 2], [3, 4], 5]; + return ((1 + 1)); + } + + private f2() { + if (true) { } { }; + } + } + } + + + module interfaces { + interface Foo { + + x: number; + + foo(): number; + } + } + + + module nestedModules { + module Foo2 { + function f() { + } + var x: number; + } + } + + + module Enums { + enum Foo3 { + val1, + val2, + } + } + + + function controlStatements() { + for (var i = 0; i < 10; i++) { + } + + for (var e in foo.bar) { + } + + with (foo.bar) { + } + + while (false) { + } + + do { + } while (false); + + switch (foo.bar) { + } + + switch (foo.bar) { + case 1: + break; + default: + break; + } + } + + + function tryCatch() { + try { + } + catch (err) { + } + } + + + function tryFinally() { + try { + } + finally { + } + } + + + function tryCatchFinally() { + try { + } + catch (err) { + } + finally { + } + } + + + class indentBeforeCurly { + } + + + function argumentsListIndentation(bar, + blah, + ); + + + function blockIndentAfterIndentedParameter1(bar, + blah) { + } + + + function blockIndentAfterIndentedParameter2(bar, + blah) { + if (foo) { + } + } + + var templateLiterals = \`abcdefghi +jklmnop +qrstuvwxyz\`;`); + +format.setFormatOptions(originalOptions); \ No newline at end of file diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index dd8a61ac458..9ce3197a46f 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -68,6 +68,7 @@ declare namespace FourSlashInterface { data?: any; } interface EditorOptions { + BaseIndentSize?: number, IndentSize: number; TabSize: number; NewLineCharacter: string; @@ -84,7 +85,7 @@ declare namespace FourSlashInterface { InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; - [s: string]: boolean | number | string; + [s: string]: boolean | number | string | undefined; } interface Range { fileName: string; @@ -100,6 +101,7 @@ declare namespace FourSlashInterface { markers(): Marker[]; marker(name?: string): Marker; ranges(): Range[]; + rangesByText(): { [text: string]: Range[] }; markerByName(s: string): Marker; } class goTo { @@ -134,13 +136,13 @@ declare namespace FourSlashInterface { typeDefinitionCountIs(expectedCount: number): void; definitionLocationExists(): void; verifyDefinitionsName(name: string, containerName: string): void; - isValidBraceCompletionAtPostion(openingBrace?: string): void; + isValidBraceCompletionAtPosition(openingBrace?: string): void; } class verify extends verifyNegatable { assertHasRanges(ranges: Range[]): void; caretAtMarker(markerName?: string): void; indentationIs(numberOfSpaces: number): void; - indentationAtPositionIs(fileName: string, position: number, numberOfSpaces: number, indentStyle?: ts.IndentStyle): void; + indentationAtPositionIs(fileName: string, position: number, numberOfSpaces: number, indentStyle?: ts.IndentStyle, baseIndentSize?: number): void; textAtCaretIs(text: string): void; /** * Compiles the current file and evaluates 'expr' in a context containing @@ -152,7 +154,6 @@ declare namespace FourSlashInterface { currentFileContentIs(text: string): void; verifyGetEmitOutputForCurrentFile(expected: string): void; verifyGetEmitOutputContentsForCurrentFile(expected: ts.OutputFile[]): void; - referencesCountIs(count: number): void; /** * Asserts that the given ranges are the references from the current position. * If ranges have markers, those markers may have "isDefinition" and "isWriteAccess" data @@ -170,6 +171,7 @@ declare namespace FourSlashInterface { * If `ranges` is omitted, this is `test.ranges()`. */ rangesReferenceEachOther(ranges?: Range[]): void; + rangesWithSameTextReferenceEachOther(): void; currentParameterHelpArgumentNameIs(name: string): void; currentParameterSpanIs(parameter: string): void; currentParameterHelpArgumentDocCommentIs(docComment: string): void; @@ -216,7 +218,7 @@ declare namespace FourSlashInterface { }[]): void; renameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string): void; renameInfoFailed(message?: string): void; - renameLocations(findInStrings: boolean, findInComments: boolean): void; + renameLocations(findInStrings: boolean, findInComments: boolean, ranges?: Range[]): void; verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: { start: number; length: number; diff --git a/tests/cases/fourslash/goToDefinitionThis.ts b/tests/cases/fourslash/goToDefinitionThis.ts new file mode 100644 index 00000000000..300e3423d81 --- /dev/null +++ b/tests/cases/fourslash/goToDefinitionThis.ts @@ -0,0 +1,20 @@ +/// + +// @noLib: true +////function f(/*fnDecl*/this: number) { +//// return /*fnUse*/this; +////} +/////*cls*/class C { +//// constructor() { return /*clsUse*/this; } +//// get self(/*getterDecl*/this: number) { return /*getterUse*/this; } +////} + +function verifyDefinition(a, b) { + goTo.marker(a); + goTo.definition(); + verify.caretAtMarker(b); +} + +verifyDefinition("fnUse", "fnDecl"); +verifyDefinition("clsUse", "cls"); +verifyDefinition("getterUse", "getterDecl"); diff --git a/tests/cases/fourslash/hoverOverComment.ts b/tests/cases/fourslash/hoverOverComment.ts index a9549a932f7..c0e585ca3b6 100644 --- a/tests/cases/fourslash/hoverOverComment.ts +++ b/tests/cases/fourslash/hoverOverComment.ts @@ -8,4 +8,4 @@ goTo.marker(); verify.quickInfoIs(""); verify.verifyDefinitionsName("", ""); verify.typeDefinitionCountIs(0); -verify.referencesCountIs(0); +verify.referencesAre([]); diff --git a/tests/cases/fourslash/indentationWithBaseIndent.ts b/tests/cases/fourslash/indentationWithBaseIndent.ts new file mode 100644 index 00000000000..53ee01c9a3c --- /dev/null +++ b/tests/cases/fourslash/indentationWithBaseIndent.ts @@ -0,0 +1,211 @@ +/// + +//// +////{| "indent": 10 , "baseIndentSize": 10 |} +//// module classes { +////{| "indent": 14 , "baseIndentSize": 10 |} +//// class Bar { +////{| "indent": 18 , "baseIndentSize": 10 |} +//// +//// constructor() { +////{| "indent": 22, "baseIndentSize": 10 |} +//// } +//// +//// private foo: string = ""; +////{| "indent": 18, "baseIndentSize": 10 |} +//// +//// private f() { +//// var a: any[] = [[1, 2], [3, 4], 5]; +////{| "indent": 22, "baseIndentSize": 10 |} +//// return ((1 + 1)); +//// } +//// +////{| "indent": 18, "baseIndentSize": 10 |} +//// private f2() { +//// if (true) { } { }; +//// } +//// } +//// } +//// +//// +//// module interfaces { +////{| "indent": 14 , "baseIndentSize": 10 |} +//// interface Foo { +////{| "indent": 18 , "baseIndentSize": 10 |} +//// +//// x: number; +////{| "indent": 18 , "baseIndentSize": 10 |} +//// +//// foo(): number; +////{| "indent": 18 , "baseIndentSize": 10 |} +//// } +//// } +//// +//// +//// module nestedModules { +//// module Foo2 { +////{| "indent": 18 , "baseIndentSize": 10 |} +//// function f() { +//// } +////{| "indent": 18 , "baseIndentSize": 10 |} +//// var x: number; +////{| "indent": 18 , "baseIndentSize": 10 |} +//// } +//// } +//// +//// +//// module Enums { +//// enum Foo3 { +////{| "indent": 18 , "baseIndentSize": 10 |} +//// val1, +////{| "indent": 18 , "baseIndentSize": 10 |} +//// val2, +////{| "indent": 18 , "baseIndentSize": 10 |} +//// } +////{| "indent": 14 , "baseIndentSize": 10 |} +//// } +//// +//// +//// function controlStatements() { +//// for (var i = 0; i < 10; i++) { +////{| "indent": 18 , "baseIndentSize": 10 |} +//// } +//// +//// for (var e in foo.bar) { +////{| "indent": 18 , "baseIndentSize": 10 |} +//// } +//// +//// with (foo.bar) { +////{| "indent": 18 , "baseIndentSize": 10 |} +//// } +//// +//// while (false) { +////{| "indent": 18 , "baseIndentSize": 10 |} +//// } +//// +//// do { +////{| "indent": 18 , "baseIndentSize": 10 |} +//// } while (false); +//// +//// switch (foo.bar) { +////{| "indent": 18 , "baseIndentSize": 10 |} +//// } +//// +//// switch (foo.bar) { +////{| "indent": 18 , "baseIndentSize": 10 |} +//// case 1: +////{| "indent": 22 , "baseIndentSize": 10 |} +//// break; +//// default: +////{| "indent": 22 , "baseIndentSize": 10 |} +//// break; +//// } +//// } +//// +//// +//// function tryCatch() { +////{| "indent": 14 , "baseIndentSize": 10 |} +//// try { +////{| "indent": 18 , "baseIndentSize": 10 |} +//// } +////{| "indent": 14 , "baseIndentSize": 10 |} +//// catch (err) { +////{| "indent": 18, "baseIndentSize": 10 |} +//// } +////{| "indent": 14, "baseIndentSize": 10 |} +//// } +//// +//// +//// function tryFinally() { +////{| "indent": 14 , "baseIndentSize": 10 |} +//// try { +////{| "indent": 18 , "baseIndentSize": 10 |} +//// } +////{| "indent": 14 , "baseIndentSize": 10 |} +//// finally { +////{| "indent": 18 , "baseIndentSize": 10 |} +//// } +////{| "indent": 14 , "baseIndentSize": 10 |} +//// } +//// +//// +//// function tryCatchFinally() { +////{| "indent": 14 , "baseIndentSize": 10 |} +//// try { +////{| "indent": 18 , "baseIndentSize": 10 |} +//// } +////{| "indent": 14 , "baseIndentSize": 10 |} +//// catch (err) { +////{| "indent": 18 , "baseIndentSize": 10 |} +//// } +////{| "indent": 14 , "baseIndentSize": 10 |} +//// finally { +////{| "indent": 18 , "baseIndentSize": 10 |} +//// } +////{| "indent": 14 , "baseIndentSize": 10 |} +//// } +//// +//// +//// class indentBeforeCurly +////{| "indent": 10 , "baseIndentSize": 10 |} +////{| "indent": 10 , "baseIndentSize": 10 |} +//// { +////{| "indent": 14 , "baseIndentSize": 10 |} +//// } +////{| "indent": 10 , "baseIndentSize": 10 |} +//// +//// +//// function argumentsListIndentation(bar, +//// blah, +//// {| "indent": 14 , "baseIndentSize": 10 |} +//// ); +//// +//// +//// function blockIndentAfterIndentedParameter1(bar, +//// blah) { +////{| "indent": 14 , "baseIndentSize": 10 |} +//// } +//// +//// +//// function blockIndentAfterIndentedParameter2(bar, +//// blah) { +//// if (foo) { +////{| "indent": 18 , "baseIndentSize": 10 |} +//// } +////} +////{| "indent": 10 , "baseIndentSize": 10 |} +//// +//// var templateLiterals = `abcdefghi +////{| "indent": 0 , "baseIndentSize": 10 |} +////jklmnop +////{| "indent": 0 , "baseIndentSize": 10 |} +////qrstuvwxyz`; +////{| "indent": 10 , "baseIndentSize": 10 |} +//// +//// +//// module changeBaseIndentSizeInSameFile { +////{| "indent": 21 , "baseIndentSize": 17 |} +//// interface Foo { +////{| "indent": 25 , "baseIndentSize": 17 |} +//// +//// x: number; +////{| "indent": 25 , "baseIndentSize": 10 |} +//// +//// foo(): number; +////{| "indent": 25 , "baseIndentSize": 10 |} +//// } +////{| "indent": 21 , "baseIndentSize": 10 |} +//// } +////{| "indent": 17 , "baseIndentSize": 17 |} +//// +//// +////// Note: Do not add more tests at the end of this file, as +////// the purpose of this test is to verify smart indent +////// works for unterminated function arguments at the end of a file. +//// function unterminatedListIndentation(a, +////{| "indent": 14 , "baseIndentSize": 10 |} + +debugger; +test.markers().forEach(marker => { + verify.indentationAtPositionIs(marker.fileName, marker.position, marker.data.indent, ts.IndentStyle.Smart, marker.data.baseIndentSize); +}); diff --git a/tests/cases/fourslash/jsxBraceCompletionPosition.ts b/tests/cases/fourslash/jsxBraceCompletionPosition.ts index c1c331435ce..91ee96cc5b7 100644 --- a/tests/cases/fourslash/jsxBraceCompletionPosition.ts +++ b/tests/cases/fourslash/jsxBraceCompletionPosition.ts @@ -19,29 +19,29 @@ ////
goTo.marker('1'); -verify.not.isValidBraceCompletionAtPostion('('); -verify.isValidBraceCompletionAtPostion('{'); +verify.not.isValidBraceCompletionAtPosition('('); +verify.isValidBraceCompletionAtPosition('{'); goTo.marker('2'); -verify.not.isValidBraceCompletionAtPostion('('); -verify.not.isValidBraceCompletionAtPostion('{'); +verify.not.isValidBraceCompletionAtPosition('('); +verify.not.isValidBraceCompletionAtPosition('{'); goTo.marker('3'); -verify.not.isValidBraceCompletionAtPostion('('); -verify.isValidBraceCompletionAtPostion('{'); +verify.not.isValidBraceCompletionAtPosition('('); +verify.isValidBraceCompletionAtPosition('{'); goTo.marker('4'); -verify.not.isValidBraceCompletionAtPostion('('); -verify.isValidBraceCompletionAtPostion('{'); +verify.not.isValidBraceCompletionAtPosition('('); +verify.isValidBraceCompletionAtPosition('{'); goTo.marker('5'); -verify.not.isValidBraceCompletionAtPostion('('); -verify.isValidBraceCompletionAtPostion('{'); +verify.not.isValidBraceCompletionAtPosition('('); +verify.isValidBraceCompletionAtPosition('{'); goTo.marker('6'); -verify.not.isValidBraceCompletionAtPostion('('); -verify.isValidBraceCompletionAtPostion('{'); +verify.not.isValidBraceCompletionAtPosition('('); +verify.isValidBraceCompletionAtPosition('{'); goTo.marker('7'); -verify.not.isValidBraceCompletionAtPostion('('); -verify.isValidBraceCompletionAtPostion('{'); \ No newline at end of file +verify.not.isValidBraceCompletionAtPosition('('); +verify.isValidBraceCompletionAtPosition('{'); \ No newline at end of file diff --git a/tests/cases/fourslash/localGetReferences.ts b/tests/cases/fourslash/localGetReferences.ts index e5873efeeb4..ada4947acde 100644 --- a/tests/cases/fourslash/localGetReferences.ts +++ b/tests/cases/fourslash/localGetReferences.ts @@ -2,35 +2,39 @@ // @Filename: localGetReferences_1.ts ////// Comment Refence Test: g/*1*/lobalVar -////var g/*3*/lobalVar: n/*2*/umber = 2; +////// References to a variable declared in global. +////var [|globalVar|]: n/*2*/umber = 2; //// ////class fooCls { -//// static clsS/*5*/Var = 1; -//// //Declare -//// cls/*4*/Var = 1; +//// // References to static variable declared in a class. +//// static [|clsSVar|] = 1; +//// // References to a variable declared in a class. +//// [|clsVar|] = 1; //// -//// constructor (public clsParam: number) { +//// constructor (public [|clsParam|]: number) { //// //Increments -//// globalVar++; -//// this.clsVar++; -//// fooCls.clsSVar++; -//// this.cls/*7*/Param++; +//// [|globalVar|]++; +//// this.[|clsVar|]++; +//// fooCls.[|clsSVar|]++; +//// // References to a class parameter. +//// this.[|clsParam|]++; //// modTest.modVar++; //// } ////} //// -////function foo(/*8*/x: number) { -//// //Declare -//// var fn/*6*/Var = 1; +////// References to a function parameter. +////function [|foo|]([|x|]: number) { +//// // References to a variable declared in a function. +//// var [|fnVar|] = 1; //// //// //Increments -//// fooCls.clsSVar++; -//// globalVar++; +//// fooCls.[|clsSVar|]++; +//// [|globalVar|]++; //// modTest.modVar++; -//// fnVar++; +//// [|fnVar|]++; //// //// //Return -//// return x++; +//// return [|x|]++; ////} //// ////module modTest { @@ -38,25 +42,25 @@ //// export var modVar:number; //// //// //Increments -//// globalVar++; -//// fooCls.clsSVar++; +//// [|globalVar|]++; +//// fooCls.[|clsSVar|]++; //// modVar++; //// //// class testCls { -//// static boo = foo; +//// static boo = [|foo|]; //// } //// //// function testFn(){ -//// static boo = foo; +//// static boo = [|foo|]; //// //// //Increments -//// globalVar++; -//// fooCls.clsSVar++; +//// [|globalVar|]++; +//// fooCls.[|clsSVar|]++; //// modVar++; //// } //// //// module testMod { -//// var boo = foo; +//// var boo = [|foo|]; //// } ////} //// @@ -64,24 +68,27 @@ ////var clsTest: fooCls; //// //////Arguments -////clsTest = new fooCls(globalV/*10*/ar); -////foo(glo/*9*/balVar); +////// References to a class argument. +////clsTest = new fooCls([|globalVar|]); +////// References to a function argument. +////[|foo|]([|globalVar|]); //// //////Increments -////fooCls.clsSVar++; +////fooCls.[|clsSVar|]++; ////modTest.modVar++; -////globalVar = globalVar + globalVar; +////[|globalVar|] = [|globalVar|] + [|globalVar|]; //// //////ETC - Other cases -////globalVar = 3; -/////*11*/foo = foo + 1; -/////*12*/err = err++; -/////*13*/ +////[|globalVar|] = 3; +////// References to illegal assignment. +////[|foo|] = [|foo|] + 1; +/////*3*/err = err++; +/////*4*/ //////Shadowed fn Parameter -////function shdw(globa/*14*/lVar: number) { +////function shdw([|{| "shadow": true |}globalVar|]: number) { //// //Increments -//// globalVar++; -//// return globalVar; +//// [|{| "shadow": true |}globalVar|]++; +//// return [|{| "shadow": true |}globalVar|]; ////} //// //////Remotes @@ -110,11 +117,12 @@ ////array.forEach( //// //// -////function(str) { +////function([|str|]) { //// //// //// -//// return /*15*/str + " "; +//// // Reference misses function parameter. +//// return [|str|] + " "; //// ////}); @@ -162,7 +170,7 @@ //// class remotetestCls { //// static remoteboo = remotefoo; //// } -//// +////` //// function remotetestFn(){ //// static remoteboo = remotefoo; //// @@ -179,60 +187,30 @@ // References to comment. goTo.marker("1"); -verify.referencesCountIs(0); +verify.referencesAre([]); // References to type. goTo.marker("2"); -verify.referencesCountIs(0); - -// References to a variable declared in global. -goTo.marker("3"); -verify.referencesCountIs(11); - -// References to a variable declared in a class. -goTo.marker("4"); -verify.referencesCountIs(2); - -// References to static variable declared in a class. -goTo.marker("5"); -verify.referencesCountIs(6); - -// References to a variable declared in a function. -goTo.marker("6"); -verify.referencesCountIs(2); - -// References to a class parameter. -goTo.marker("7"); -verify.referencesCountIs(2); - -// References to a function parameter. -goTo.marker("8"); -verify.referencesCountIs(2); - -// References to a function argument. -goTo.marker("9"); -verify.referencesCountIs(11); - -// References to a class argument. -goTo.marker("10"); -verify.referencesCountIs(11); - -// References to illegal assignment. -goTo.marker("11"); -verify.referencesCountIs(7); +verify.referencesAre([]); // References to unresolved symbol. -goTo.marker("12"); -verify.referencesCountIs(0); +goTo.marker("3"); +verify.referencesAre([]); // References to no context. -goTo.marker("13"); -verify.referencesCountIs(0); +goTo.marker("4"); +verify.referencesAre([]); -// References to shadowed function parameter. -goTo.marker("14"); -verify.referencesCountIs(3); - -// Reference misses function parameter. -goTo.marker("15"); -verify.referencesCountIs(2); \ No newline at end of file +const rangesByText = test.rangesByText(); +for (const text in rangesByText) { + const ranges = rangesByText[text]; + if (text === "globalVar") { + function isShadow(r) { + return r.marker && r.marker.data && r.marker.data.shadow; + } + verify.rangesReferenceEachOther(ranges.filter(isShadow)); + verify.rangesReferenceEachOther(ranges.filter(r => !isShadow(r))); + } else { + verify.rangesReferenceEachOther(ranges); + } +} diff --git a/tests/cases/fourslash/quickInfoForRequire.ts b/tests/cases/fourslash/quickInfoForRequire.ts index 8e714c08736..cb5a0b6e8ec 100644 --- a/tests/cases/fourslash/quickInfoForRequire.ts +++ b/tests/cases/fourslash/quickInfoForRequire.ts @@ -8,4 +8,4 @@ goTo.marker('1'); verify.quickInfoIs('module a'); -verify.referencesCountIs(0); \ No newline at end of file +verify.referencesAre([]); \ No newline at end of file diff --git a/tests/cases/fourslash/quickInfoOnThis.ts b/tests/cases/fourslash/quickInfoOnThis.ts index 4191c0846ec..14737486b87 100644 --- a/tests/cases/fourslash/quickInfoOnThis.ts +++ b/tests/cases/fourslash/quickInfoOnThis.ts @@ -25,7 +25,7 @@ goTo.marker('0'); verify.quickInfoIs('this: this'); goTo.marker('1'); -verify.quickInfoIs('void'); +verify.quickInfoIs('this: void'); goTo.marker('2'); verify.quickInfoIs('this: this'); goTo.marker('3'); diff --git a/tests/cases/fourslash/quickInfoOnThis3.ts b/tests/cases/fourslash/quickInfoOnThis3.ts index 6988ac14860..239e49d5dc0 100644 --- a/tests/cases/fourslash/quickInfoOnThis3.ts +++ b/tests/cases/fourslash/quickInfoOnThis3.ts @@ -20,7 +20,7 @@ verify.quickInfoIs('any'); goTo.marker('2'); verify.quickInfoIs('(parameter) this: void'); goTo.marker('3'); -verify.quickInfoIs('void'); +verify.quickInfoIs('this: void'); goTo.marker('4'); verify.quickInfoIs('(parameter) this: Restricted'); goTo.marker('5'); diff --git a/tests/cases/fourslash/referenceInParameterPropertyDeclaration.ts b/tests/cases/fourslash/referenceInParameterPropertyDeclaration.ts index 4e86e7a4915..68a9f73b1d6 100644 --- a/tests/cases/fourslash/referenceInParameterPropertyDeclaration.ts +++ b/tests/cases/fourslash/referenceInParameterPropertyDeclaration.ts @@ -2,23 +2,19 @@ // @Filename: file1.ts //// class Foo { -//// constructor(private /*0*/privateParam: number, -//// public /*1*/publicParam: string, -//// protected /*2*/protectedParam: boolean) { +//// constructor(private [|privateParam|]: number, +//// public [|publicParam|]: string, +//// protected [|protectedParam|]: boolean) { //// -//// let localPrivate = /*3*/privateParam; -//// this./*4*/privateParam += 10; +//// let localPrivate = [|privateParam|]; +//// this.[|privateParam|] += 10; //// -//// let localPublic = /*5*/publicParam; -//// this./*6*/publicParam += " Hello!"; +//// let localPublic = [|publicParam|]; +//// this.[|publicParam|] += " Hello!"; //// -//// let localProtected = /*7*/protectedParam; -//// this./*8*/protectedParam = false; +//// let localProtected = [|protectedParam|]; +//// this.[|protectedParam|] = false; //// } //// } -let markers = test.markers() -for (let marker of markers) { - goTo.position(marker.position); - verify.referencesCountIs(3); -} \ No newline at end of file +verify.rangesWithSameTextReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesBloomFilters.ts b/tests/cases/fourslash/referencesBloomFilters.ts index 3961d557e89..7d99ccdfd3c 100644 --- a/tests/cases/fourslash/referencesBloomFilters.ts +++ b/tests/cases/fourslash/referencesBloomFilters.ts @@ -3,18 +3,15 @@ // Ensure BloomFilter building logic is correct, by having one reference per file // @Filename: declaration.ts -////var container = { /*1*/searchProp : 1 }; +////var container = { [|searchProp|] : 1 }; // @Filename: expression.ts -////function blah() { return (1 + 2 + container./*2*/searchProp()) === 2; }; +////function blah() { return (1 + 2 + container.[|searchProp|]()) === 2; }; // @Filename: stringIndexer.ts -////function blah2() { container[/*3*/"searchProp"] }; +////function blah2() { container["[|searchProp|]"] }; // @Filename: redeclaration.ts -////container = { /*4*/"searchProp" : 18 }; +////container = { "[|searchProp|]" : 18 }; -test.markers().forEach(m => { - goTo.position(m.position, m.fileName); - verify.referencesCountIs(4); -}); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesBloomFilters2.ts b/tests/cases/fourslash/referencesBloomFilters2.ts index ef7643e0215..c42e5d4eaf1 100644 --- a/tests/cases/fourslash/referencesBloomFilters2.ts +++ b/tests/cases/fourslash/referencesBloomFilters2.ts @@ -3,18 +3,15 @@ // Ensure BloomFilter building logic is correct, by having one reference per file // @Filename: declaration.ts -////var container = { /*1*/42 : 1 }; +////var container = { [|42|]: 1 }; // @Filename: expression.ts -////function blah() { return (container[/*2*/42]) === 2; }; +////function blah() { return (container[[|42|]]) === 2; }; // @Filename: stringIndexer.ts -////function blah2() { container[/*3*/"42"] }; +////function blah2() { container["[|42|]"] }; // @Filename: redeclaration.ts -////container = { /*4*/"42" : 18 }; +////container = { "[|42|]" : 18 }; -test.markers().forEach(m => { - goTo.position(m.position, m.fileName); - verify.referencesCountIs(4); -}); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesBloomFilters3.ts b/tests/cases/fourslash/referencesBloomFilters3.ts index 65215469950..9703baceb12 100644 --- a/tests/cases/fourslash/referencesBloomFilters3.ts +++ b/tests/cases/fourslash/referencesBloomFilters3.ts @@ -4,13 +4,9 @@ // @Filename: declaration.ts -////enum Test { /*1*/"42" = 1 }; +////enum Test { "[|42|]" = 1 }; // @Filename: expression.ts -////(Test[/*2*/42]); +////(Test[[|42|]]); - -test.markers().forEach(m => { - goTo.position(m.position, m.fileName); - verify.referencesCountIs(2); -}); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForAmbients.ts b/tests/cases/fourslash/referencesForAmbients.ts index deea6ec3d29..da3f3f43aae 100644 --- a/tests/cases/fourslash/referencesForAmbients.ts +++ b/tests/cases/fourslash/referencesForAmbients.ts @@ -1,30 +1,21 @@ /// -////declare module /*1*/"foo" { -//// var f: number; +////declare module "[|foo|]" { +//// var [|f|]: number; ////} //// -////declare module "bar" { -//// export import foo = require(/*2*/"foo"); -//// var f2: typeof foo./*4*/f; +////declare module "[|bar|]" { +//// export import [|foo|] = require("[|foo|]"); +//// var f2: typeof [|foo|].[|f|]; ////} //// ////declare module "baz" { -//// import bar = require(/*3*/"bar"); -//// var f2: typeof bar./*5*/foo; +//// import bar = require("[|bar|]"); +//// var f2: typeof bar.[|foo|]; ////} -goTo.marker("1"); -verify.referencesCountIs(2); - -goTo.marker("2"); -verify.referencesCountIs(2); - -goTo.marker("3"); -verify.referencesCountIs(2); - -goTo.marker("4"); -verify.referencesCountIs(2); - -goTo.marker("5"); -verify.referencesCountIs(3); \ No newline at end of file +const [moduleFoo0, f0, moduleBar0, foo0, moduleFoo1, foo1, f1, moduleBar1, foo2] = test.ranges(); +verify.rangesReferenceEachOther([moduleFoo0, moduleFoo1]); +verify.rangesReferenceEachOther([moduleBar0, moduleBar1]); +verify.rangesReferenceEachOther([foo0, foo1, foo2]); +verify.rangesReferenceEachOther([f0, f1]); diff --git a/tests/cases/fourslash/referencesForClassLocal.ts b/tests/cases/fourslash/referencesForClassLocal.ts index 3351bcd1afb..bdde0e7f126 100644 --- a/tests/cases/fourslash/referencesForClassLocal.ts +++ b/tests/cases/fourslash/referencesForClassLocal.ts @@ -5,14 +5,14 @@ ////var n = 14; //// ////class foo { -//// private /*1*/n = 0; +//// private [|n|] = 0; //// //// public bar() { -//// this.n = 9; +//// this.[|n|] = 9; //// } //// //// constructor() { -//// this./*2*/n = 4; +//// this.[|n|] = 4; //// } //// //// public bar2() { @@ -20,8 +20,4 @@ //// } ////} -goTo.marker("1"); -verify.referencesCountIs(3); - -goTo.marker("2"); -verify.referencesCountIs(3); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForClassMembers.ts b/tests/cases/fourslash/referencesForClassMembers.ts index 851c1b39ab0..0208b13589d 100644 --- a/tests/cases/fourslash/referencesForClassMembers.ts +++ b/tests/cases/fourslash/referencesForClassMembers.ts @@ -1,32 +1,16 @@ /// ////class Base { -//// /*1*/a: number; -//// /*2*/method(): void { } +//// [|a|]: number; +//// [|method|](): void { } ////} ////class MyClass extends Base { -//// /*3*/a; -//// /*4*/method() { } +//// [|a|]; +//// [|method|]() { } ////} //// ////var c: MyClass; -////c./*5*/a; -////c./*6*/method(); +////c.[|a|]; +////c.[|method|](); -goTo.marker("1"); -verify.referencesCountIs(3); - -goTo.marker("2"); -verify.referencesCountIs(3); - -goTo.marker("3"); -verify.referencesCountIs(3); - -goTo.marker("4"); -verify.referencesCountIs(3); - -goTo.marker("5"); -verify.referencesCountIs(3); - -goTo.marker("6"); -verify.referencesCountIs(3); +verify.rangesWithSameTextReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForClassMembersExtendingAbstractClass.ts b/tests/cases/fourslash/referencesForClassMembersExtendingAbstractClass.ts index fcabff979fb..46115f9da17 100644 --- a/tests/cases/fourslash/referencesForClassMembersExtendingAbstractClass.ts +++ b/tests/cases/fourslash/referencesForClassMembersExtendingAbstractClass.ts @@ -1,32 +1,16 @@ /// ////abstract class Base { -//// abstract /*1*/a: number; -//// abstract /*2*/method(): void; +//// abstract [|a|]: number; +//// abstract [|method|](): void; ////} ////class MyClass extends Base { -//// /*3*/a; -//// /*4*/method() { } +//// [|a|]; +//// [|method|]() { } ////} //// ////var c: MyClass; -////c./*5*/a; -////c./*6*/method(); +////c.[|a|]; +////c.[|method|](); -goTo.marker("1"); -verify.referencesCountIs(3); - -goTo.marker("2"); -verify.referencesCountIs(3); - -goTo.marker("3"); -verify.referencesCountIs(3); - -goTo.marker("4"); -verify.referencesCountIs(3); - -goTo.marker("5"); -verify.referencesCountIs(3); - -goTo.marker("6"); -verify.referencesCountIs(3); +verify.rangesWithSameTextReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForClassMembersExtendingGenericClass.ts b/tests/cases/fourslash/referencesForClassMembersExtendingGenericClass.ts index f0185fb39aa..2b701f25cc1 100644 --- a/tests/cases/fourslash/referencesForClassMembersExtendingGenericClass.ts +++ b/tests/cases/fourslash/referencesForClassMembersExtendingGenericClass.ts @@ -1,32 +1,16 @@ /// ////class Base { -//// /*1*/a: this; -//// /*2*/method(a?:T, b?:U): this { } +//// [|a|]: this; +//// [|method|](a?:T, b?:U): this { } ////} ////class MyClass extends Base { -//// /*3*/a; -//// /*4*/method() { } +//// [|a|]; +//// [|method|]() { } ////} //// ////var c: MyClass; -////c./*5*/a; -////c./*6*/method(); +////c.[|a|]; +////c.[|method|](); -goTo.marker("1"); -verify.referencesCountIs(3); - -goTo.marker("2"); -verify.referencesCountIs(3); - -goTo.marker("3"); -verify.referencesCountIs(3); - -goTo.marker("4"); -verify.referencesCountIs(3); - -goTo.marker("5"); -verify.referencesCountIs(3); - -goTo.marker("6"); -verify.referencesCountIs(3); +verify.rangesWithSameTextReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForClassParameter.ts b/tests/cases/fourslash/referencesForClassParameter.ts index 48cdbbf1e41..ce383b36503 100644 --- a/tests/cases/fourslash/referencesForClassParameter.ts +++ b/tests/cases/fourslash/referencesForClassParameter.ts @@ -7,20 +7,16 @@ ////class p { } //// ////class foo { -//// constructor (public p: any) { +//// constructor (public [|p|]: any) { //// } //// //// public f(p) { -//// this./*1*/p = p; +//// this.[|p|] = p; //// } //// ////} //// ////var n = new foo(undefined); -////n./*2*/p = null; +////n.[|p|] = null; -goTo.marker("1"); -verify.referencesCountIs(3); - -goTo.marker("2"); -verify.referencesCountIs(3); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForContextuallyTypedObjectLiteralProperties.ts b/tests/cases/fourslash/referencesForContextuallyTypedObjectLiteralProperties.ts index 15dd5720019..65bd7eebfb5 100644 --- a/tests/cases/fourslash/referencesForContextuallyTypedObjectLiteralProperties.ts +++ b/tests/cases/fourslash/referencesForContextuallyTypedObjectLiteralProperties.ts @@ -1,32 +1,28 @@ /// -////interface IFoo { /*1*/xy: number; } +////interface IFoo { [|xy|]: number; } //// ////// Assignment -////var a1: IFoo = { /*2*/xy: 0 }; -////var a2: IFoo = { xy: 0 }; +////var a1: IFoo = { [|xy|]: 0 }; +////var a2: IFoo = { [|xy|]: 0 }; //// ////// Function call ////function consumer(f: IFoo) { } -////consumer({ xy: 1 }); +////consumer({ [|xy|]: 1 }); //// ////// Type cast -////var c = { xy: 0 }; +////var c = { [|xy|]: 0 }; //// ////// Array literal -////var ar: IFoo[] = [{ xy: 1 }, { /*3*/xy: 2 }]; +////var ar: IFoo[] = [{ [|xy|]: 1 }, { [|xy|]: 2 }]; //// ////// Nested object literal -////var ob: { ifoo: IFoo } = { ifoo: { xy: 0 } }; +////var ob: { ifoo: IFoo } = { ifoo: { [|xy|]: 0 } }; //// ////// Widened type -////var w: IFoo = { /*4*/xy: undefined }; +////var w: IFoo = { [|xy|]: undefined }; //// ////// Untped -- should not be included ////var u = { xy: 0 }; - -test.markers().forEach((m) => { - goTo.position(m.position, m.fileName); - verify.referencesCountIs(9); -}); +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForContextuallyTypedUnionProperties.ts b/tests/cases/fourslash/referencesForContextuallyTypedUnionProperties.ts index f9c479de769..c0e4a5f90ea 100644 --- a/tests/cases/fourslash/referencesForContextuallyTypedUnionProperties.ts +++ b/tests/cases/fourslash/referencesForContextuallyTypedUnionProperties.ts @@ -2,39 +2,42 @@ ////interface A { //// a: number; -//// common: string; +//// [|common|]: string; ////} //// ////interface B { //// b: number; -//// common: number; +//// [|common|]: number; ////} //// ////// Assignment -////var v1: A | B = { a: 0, /*1*/common: "" }; -////var v2: A | B = { b: 0, /*2*/common: 3 }; +////var v1: A | B = { a: 0, [|common|]: "" }; +////var v2: A | B = { b: 0, [|common|]: 3 }; //// ////// Function call ////function consumer(f: A | B) { } -////consumer({ a: 0, b: 0, /*3*/common: 1 }); +////consumer({ a: 0, b: 0, [|common|]: 1 }); //// ////// Type cast -////var c = { /*4*/common: 0, b: 0 }; +////var c = { [|common|]: 0, b: 0 }; //// ////// Array literal -////var ar: Array = [{ a: 0, /*5*/common: "" }, { b: 0, /*6*/common: 0 }]; +////var ar: Array = [{ a: 0, [|common|]: "" }, { b: 0, [|common|]: 0 }]; //// ////// Nested object literal -////var ob: { aorb: A|B } = { aorb: { b: 0, /*7*/common: 0 } }; +////var ob: { aorb: A|B } = { aorb: { b: 0, [|common|]: 0 } }; //// ////// Widened type -////var w: A|B = { a:0, /*8*/common: undefined }; +////var w: A|B = { a:0, [|common|]: undefined }; //// ////// Untped -- should not be included ////var u1 = { a: 0, b: 0, common: "" }; ////var u2 = { b: 0, common: 0 }; -test.markers().forEach((m) => { - goTo.position(m.position, m.fileName); - verify.referencesCountIs(10); // 8 contextually typed common, and 2 in definition (A.common, B.common) -}); +const all = test.ranges(); +const [aCommon, bCommon, ...unionRefs] = all; +verify.referencesOf(aCommon, [aCommon, ...unionRefs]); +verify.referencesOf(bCommon, [bCommon, ...unionRefs]); +for (const ref of unionRefs) { + verify.referencesOf(ref, all); +} diff --git a/tests/cases/fourslash/referencesForContextuallyTypedUnionProperties2.ts b/tests/cases/fourslash/referencesForContextuallyTypedUnionProperties2.ts index bbcc482a6e7..de9ffbfd3be 100644 --- a/tests/cases/fourslash/referencesForContextuallyTypedUnionProperties2.ts +++ b/tests/cases/fourslash/referencesForContextuallyTypedUnionProperties2.ts @@ -6,35 +6,32 @@ ////} //// ////interface B { -//// /*1*/b: number; +//// [|b|]: number; //// common: number; ////} //// ////// Assignment ////var v1: A | B = { a: 0, common: "" }; -////var v2: A | B = { /*2*/b: 0, common: 3 }; +////var v2: A | B = { [|b|]: 0, common: 3 }; //// ////// Function call ////function consumer(f: A | B) { } -////consumer({ a: 0, /*3*/b: 0, common: 1 }); +////consumer({ a: 0, [|b|]: 0, common: 1 }); //// ////// Type cast -////var c = { common: 0, /*4*/b: 0 }; +////var c = { common: 0, [|b|]: 0 }; //// ////// Array literal -////var ar: Array = [{ a: 0, common: "" }, { /*5*/b: 0, common: 0 }]; +////var ar: Array = [{ a: 0, common: "" }, { [|b|]: 0, common: 0 }]; //// ////// Nested object literal -////var ob: { aorb: A|B } = { aorb: { /*6*/b: 0, common: 0 } }; +////var ob: { aorb: A|B } = { aorb: { [|b|]: 0, common: 0 } }; //// ////// Widened type -////var w: A|B = { /*7*/b:undefined, common: undefined }; +////var w: A|B = { [|b|]:undefined, common: undefined }; //// ////// Untped -- should not be included ////var u1 = { a: 0, b: 0, common: "" }; ////var u2 = { b: 0, common: 0 }; -test.markers().forEach((m) => { - goTo.position(m.position, m.fileName); - verify.referencesCountIs(7); -}); +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForEnums.ts b/tests/cases/fourslash/referencesForEnums.ts index fe1fd592dbb..3b979bc5096 100644 --- a/tests/cases/fourslash/referencesForEnums.ts +++ b/tests/cases/fourslash/referencesForEnums.ts @@ -1,22 +1,14 @@ /// ////enum E { -//// /*value1*/value1 = 1, -//// "value2" = value1, -//// 111 = 11 +//// [|value1|] = 1, +//// "[|value2|]" = [|value1|], +//// [|111|] = 11 ////} //// -////E.value1; -////E["value2"]; -////E./*value2*/value2; -////E[/*value3*/111]; +////E.[|value1|]; +////E["[|value2|]"]; +////E.[|value2|]; +////E[[|111|]]; - -goTo.marker("value1"); -verify.referencesCountIs(3); - -goTo.marker("value2"); -verify.referencesCountIs(3); - -goTo.marker("value3"); -verify.referencesCountIs(2); \ No newline at end of file +verify.rangesWithSameTextReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForExportedValues.ts b/tests/cases/fourslash/referencesForExportedValues.ts index dc7c52174af..315d0b1b585 100644 --- a/tests/cases/fourslash/referencesForExportedValues.ts +++ b/tests/cases/fourslash/referencesForExportedValues.ts @@ -1,16 +1,13 @@ /// ////module M { -//// export var /*1*/variable = 0; +//// export var [|variable|] = 0; //// //// // local use -//// var x = /*2*/variable; +//// var x = [|variable|]; ////} //// ////// external use -////M./*3*/variable +////M.[|variable|] -test.markers().forEach((m) => { - goTo.position(m.position, m.fileName); - verify.referencesCountIs(3); -}); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForExternalModuleNames.ts b/tests/cases/fourslash/referencesForExternalModuleNames.ts index 7da6091d9e2..ee783c8bd7e 100644 --- a/tests/cases/fourslash/referencesForExternalModuleNames.ts +++ b/tests/cases/fourslash/referencesForExternalModuleNames.ts @@ -3,16 +3,12 @@ // Global interface reference. // @Filename: referencesForGlobals_1.ts -////declare module /*1*/"foo" { +////declare module "[|foo|]" { //// var f: number; ////} // @Filename: referencesForGlobals_2.ts -////import f = require(/*2*/"foo"); +////import f = require("[|foo|]"); -goTo.marker("1"); -verify.referencesCountIs(2); - -goTo.marker("2"); -verify.referencesCountIs(2); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForFunctionOverloads.ts b/tests/cases/fourslash/referencesForFunctionOverloads.ts index 2a4981ff4a3..d6873643cd4 100644 --- a/tests/cases/fourslash/referencesForFunctionOverloads.ts +++ b/tests/cases/fourslash/referencesForFunctionOverloads.ts @@ -2,16 +2,9 @@ // Function overloads should be highlighted together. -////function /*1*/foo(x: string); -////function /*2*/foo(x: string, y: number) { -//// /*3*/foo('', 43); +////function [|foo|](x: string); +////function [|foo|](x: string, y: number) { +//// [|foo|]('', 43); ////} -goTo.marker("1"); -verify.referencesCountIs(3); - -goTo.marker("2"); -verify.referencesCountIs(3); - -goTo.marker("3"); -verify.referencesCountIs(3); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForFunctionParameter.ts b/tests/cases/fourslash/referencesForFunctionParameter.ts index fd9189d1b72..64d33ca9a60 100644 --- a/tests/cases/fourslash/referencesForFunctionParameter.ts +++ b/tests/cases/fourslash/referencesForFunctionParameter.ts @@ -3,13 +3,9 @@ ////var x; ////var n; //// -////function n(x: number, /*1*/n: number) { -//// /*2*/n = 32; -//// x = n; +////function n(x: number, [|n|]: number) { +//// [|n|] = 32; +//// x = [|n|]; ////} -goTo.marker("1"); -verify.referencesCountIs(3); - -goTo.marker("2"); -verify.referencesCountIs(3); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForGlobals.ts b/tests/cases/fourslash/referencesForGlobals.ts index a4efddae3d7..f4d7c479767 100644 --- a/tests/cases/fourslash/referencesForGlobals.ts +++ b/tests/cases/fourslash/referencesForGlobals.ts @@ -3,7 +3,7 @@ // Global variable reference. // @Filename: referencesForGlobals_1.ts -////var /*1*/global = 2; +////var [|global|] = 2; //// ////class foo { //// constructor (public global) { } @@ -13,20 +13,16 @@ //// ////class bar { //// constructor () { -//// var n = global; +//// var n = [|global|]; //// //// var f = new foo(''); //// f.global = ''; //// } ////} //// -////var k = global; +////var k = [|global|]; // @Filename: referencesForGlobals_2.ts -////var m = global; +////var m = [|global|]; -// this line triggers a semantic/syntactic error check, remove line when 788570 is fixed -edit.insert(''); - -goTo.marker("1"); -verify.referencesCountIs(4); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForGlobals2.ts b/tests/cases/fourslash/referencesForGlobals2.ts index a0a35d8a08f..7c6baf5bf67 100644 --- a/tests/cases/fourslash/referencesForGlobals2.ts +++ b/tests/cases/fourslash/referencesForGlobals2.ts @@ -3,15 +3,11 @@ // Global class reference. // @Filename: referencesForGlobals_1.ts -////class /*2*/globalClass { +////class [|globalClass|] { //// public f() { } ////} // @Filename: referencesForGlobals_2.ts -////var c = /*1*/globalClass(); +////var c = [|globalClass|](); -goTo.marker("1"); -verify.referencesCountIs(2); - -goTo.marker("2"); -verify.referencesCountIs(2); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForGlobals3.ts b/tests/cases/fourslash/referencesForGlobals3.ts index 636e14bf629..67e209aaad3 100644 --- a/tests/cases/fourslash/referencesForGlobals3.ts +++ b/tests/cases/fourslash/referencesForGlobals3.ts @@ -3,15 +3,11 @@ // Global interface reference. // @Filename: referencesForGlobals_1.ts -////interface /*2*/globalInterface { +////interface [|globalInterface|] { //// f(); ////} // @Filename: referencesForGlobals_2.ts -////var i: /*1*/globalInterface; +////var i: [|globalInterface|]; -goTo.marker("1"); -verify.referencesCountIs(2); - -goTo.marker("2"); -verify.referencesCountIs(2); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForGlobals4.ts b/tests/cases/fourslash/referencesForGlobals4.ts index ee12a1754cd..d7acfbd2df4 100644 --- a/tests/cases/fourslash/referencesForGlobals4.ts +++ b/tests/cases/fourslash/referencesForGlobals4.ts @@ -3,15 +3,11 @@ // Global module reference. // @Filename: referencesForGlobals_1.ts -////module /*2*/globalModule { +////module [|globalModule|] { //// export f() { }; ////} // @Filename: referencesForGlobals_2.ts -////var m = /*1*/globalModule; +////var m = [|globalModule|]; -goTo.marker("1"); -verify.referencesCountIs(2); - -goTo.marker("2"); -verify.referencesCountIs(2); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForGlobals5.ts b/tests/cases/fourslash/referencesForGlobals5.ts index 9c800f116be..4db2410f638 100644 --- a/tests/cases/fourslash/referencesForGlobals5.ts +++ b/tests/cases/fourslash/referencesForGlobals5.ts @@ -7,13 +7,9 @@ //// export var x; ////} //// -////import /*2*/globalAlias = globalModule; +////import [|globalAlias|] = globalModule; // @Filename: referencesForGlobals_2.ts -////var m = /*1*/globalAlias; +////var m = [|globalAlias|]; -goTo.marker("1"); -verify.referencesCountIs(2); - -goTo.marker("2"); -verify.referencesCountIs(2); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForGlobalsInExternalModule.ts b/tests/cases/fourslash/referencesForGlobalsInExternalModule.ts index b76007624bb..c2f70420402 100644 --- a/tests/cases/fourslash/referencesForGlobalsInExternalModule.ts +++ b/tests/cases/fourslash/referencesForGlobalsInExternalModule.ts @@ -2,23 +2,20 @@ // Global variable reference. -////var /*1*/topLevelVar = 2; -////var topLevelVar2 = topLevelVar; +////var [|topLevelVar|] = 2; +////var topLevelVar2 = [|topLevelVar|]; //// -////class /*2*/topLevelClass { } -////var c = new topLevelClass(); +////class [|topLevelClass|] { } +////var c = new [|topLevelClass|](); //// -////interface topLevelInterface { } -////var i: /*3*/topLevelInterface; +////interface [|topLevelInterface|] { } +////var i: [|topLevelInterface|]; //// -////module topLevelModule { +////module [|topLevelModule|] { //// export var x; ////} -////var x = /*4*/topLevelModule.x; +////var x = [|topLevelModule|].x; //// ////export = x; -test.markers().forEach(m => { - goTo.position(m.position, m.fileName); - verify.referencesCountIs(2); -}); \ No newline at end of file +verify.rangesWithSameTextReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForIllegalAssignment.ts b/tests/cases/fourslash/referencesForIllegalAssignment.ts index 403bf0432a7..59cb6f4f273 100644 --- a/tests/cases/fourslash/referencesForIllegalAssignment.ts +++ b/tests/cases/fourslash/referencesForIllegalAssignment.ts @@ -2,20 +2,13 @@ ////f/*1*/oo = fo/*2*/o; -////var /*3*/bar = function () { }; -////ba/*4*/r = b/*5*/ar + 1; +////var [|bar|] = function () { }; +////[|bar|] = [|bar|] + 1; goTo.marker("1"); -verify.referencesCountIs(0); +verify.referencesAre([]); goTo.marker("2"); -verify.referencesCountIs(0); +verify.referencesAre([]); -goTo.marker("3"); -verify.referencesCountIs(3); - -goTo.marker("4"); -verify.referencesCountIs(3); - -goTo.marker("5"); -verify.referencesCountIs(3); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForImports.ts b/tests/cases/fourslash/referencesForImports.ts index 58ad1cc5a0d..0203bcee096 100644 --- a/tests/cases/fourslash/referencesForImports.ts +++ b/tests/cases/fourslash/referencesForImports.ts @@ -5,19 +5,11 @@ //// export = $; ////} +////import [|$|] = require("jquery"); +////[|$|]("a"); -////import /*1*/$ = require("jquery"); -/////*2*/$("a"); +////import [|$|] = require("jquery"); - -////import /*3*/$ = require("jquery"); - - -goTo.marker("1"); -verify.referencesCountIs(2); - -goTo.marker("2"); -verify.referencesCountIs(2); - -goTo.marker("3"); -verify.referencesCountIs(1); \ No newline at end of file +const [r0, r1, r2] = test.ranges(); +verify.rangesReferenceEachOther([r0, r1]); +verify.referencesOf(r2, [r2]); diff --git a/tests/cases/fourslash/referencesForIndexProperty.ts b/tests/cases/fourslash/referencesForIndexProperty.ts index 89084a2ef05..49d12c25819 100644 --- a/tests/cases/fourslash/referencesForIndexProperty.ts +++ b/tests/cases/fourslash/referencesForIndexProperty.ts @@ -3,16 +3,12 @@ // References a class property using string index access ////class Foo { -//// property: number; -//// method(): void { } +//// [|property|]: number; +//// [|method|](): void { } ////} //// ////var f: Foo; -////f[/*1*/"property"]; -////f[/*2*/"method"]; +////f["[|property|]"]; +////f["[|method|]"]; -goTo.marker("1"); -verify.referencesCountIs(2); - -goTo.marker("2"); -verify.referencesCountIs(2); +verify.rangesWithSameTextReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForIndexProperty2.ts b/tests/cases/fourslash/referencesForIndexProperty2.ts index 9dcba3163c6..ad440d84493 100644 --- a/tests/cases/fourslash/referencesForIndexProperty2.ts +++ b/tests/cases/fourslash/referencesForIndexProperty2.ts @@ -3,7 +3,7 @@ // References to a unknown index property ////var a; -////a[/*1*/"blah"]; +////a[/**/"blah"]; -goTo.marker("1"); -verify.referencesCountIs(0); \ No newline at end of file +goTo.marker(""); +verify.referencesAre([]); diff --git a/tests/cases/fourslash/referencesForIndexProperty3.ts b/tests/cases/fourslash/referencesForIndexProperty3.ts index 07081f8c17d..1fdee9b6602 100644 --- a/tests/cases/fourslash/referencesForIndexProperty3.ts +++ b/tests/cases/fourslash/referencesForIndexProperty3.ts @@ -3,17 +3,13 @@ // References to a property of the apparent type using string indexer ////interface Object { -//// toMyString(); +//// [|toMyString|](); ////} //// ////var y: Object; -////y./*1*/toMyString(); +////y.[|toMyString|](); //// ////var x = {}; -////x[/*2*/"toMyString"](); +////x["[|toMyString|]"](); -goTo.marker("1"); -verify.referencesCountIs(3); - -goTo.marker("2"); -verify.referencesCountIs(3); +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForInheritedProperties.ts b/tests/cases/fourslash/referencesForInheritedProperties.ts index a11d86ef5e1..19fef4066ee 100644 --- a/tests/cases/fourslash/referencesForInheritedProperties.ts +++ b/tests/cases/fourslash/referencesForInheritedProperties.ts @@ -1,15 +1,15 @@ /// ////interface interface1 { -//// /*1*/doStuff(): void; +//// [|doStuff|](): void; ////} //// ////interface interface2 extends interface1{ -//// /*2*/doStuff(): void; +//// [|doStuff|](): void; ////} //// ////class class1 implements interface2 { -//// /*3*/doStuff() { +//// [|doStuff|]() { //// //// } ////} @@ -19,9 +19,6 @@ ////} //// ////var v: class2; -////v./*4*/doStuff(); +////v.[|doStuff|](); -test.markers().forEach(m=> { - goTo.position(m.position, m.fileName); - verify.referencesCountIs(4); -}); +verify.rangesWithSameTextReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForInheritedProperties2.ts b/tests/cases/fourslash/referencesForInheritedProperties2.ts index 2203b005284..33a7f26aaea 100644 --- a/tests/cases/fourslash/referencesForInheritedProperties2.ts +++ b/tests/cases/fourslash/referencesForInheritedProperties2.ts @@ -3,18 +3,18 @@ // extends statement in a diffrent declaration ////interface interface1 { -//// /*1*/doStuff(): void; +//// [|doStuff|](): void; ////} //// ////interface interface2 { -//// /*2*/doStuff(): void; +//// [|doStuff|](): void; ////} //// ////interface interface2 extends interface1 { ////} //// ////class class1 implements interface2 { -//// /*3*/doStuff() { +//// [|doStuff|]() { //// //// } ////} @@ -24,9 +24,6 @@ ////} //// ////var v: class2; -////v./*4*/doStuff(); +////v.[|doStuff|](); -test.markers().forEach(m=> { - goTo.position(m.position, m.fileName); - verify.referencesCountIs(4); -}); +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForInheritedProperties3.ts b/tests/cases/fourslash/referencesForInheritedProperties3.ts index 134f75da84b..3a2d11da692 100644 --- a/tests/cases/fourslash/referencesForInheritedProperties3.ts +++ b/tests/cases/fourslash/referencesForInheritedProperties3.ts @@ -1,15 +1,12 @@ /// //// interface interface1 extends interface1 { -//// /*1*/doStuff(): void; -//// /*2*/propName: string; +//// [|doStuff|](): void; +//// [|propName|]: string; //// } //// //// var v: interface1; -//// v./*3*/propName; -//// v./*4*/doStuff(); +//// v.[|propName|]; +//// v.[|doStuff|](); -test.markers().forEach(m => { - goTo.position(m.position, m.fileName); - verify.referencesCountIs(2); -}); \ No newline at end of file +verify.rangesWithSameTextReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForInheritedProperties4.ts b/tests/cases/fourslash/referencesForInheritedProperties4.ts index 10dcc9c77a2..96010d05086 100644 --- a/tests/cases/fourslash/referencesForInheritedProperties4.ts +++ b/tests/cases/fourslash/referencesForInheritedProperties4.ts @@ -1,15 +1,12 @@ /// //// class class1 extends class1 { -//// /*1*/doStuff() { } -//// /*2*/propName: string; +//// [|doStuff|]() { } +//// [|propName|]: string; //// } //// //// var c: class1; -//// c./*3*/doStuff(); -//// c./*4*/propName; +//// c.[|doStuff|](); +//// c.[|propName|]; -test.markers().forEach(m => { - goTo.position(m.position, m.fileName); - verify.referencesCountIs(2); -}); \ No newline at end of file +verify.rangesWithSameTextReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForInheritedProperties5.ts b/tests/cases/fourslash/referencesForInheritedProperties5.ts index 722c5c96f0a..bbb86f0defb 100644 --- a/tests/cases/fourslash/referencesForInheritedProperties5.ts +++ b/tests/cases/fourslash/referencesForInheritedProperties5.ts @@ -1,19 +1,16 @@ /// //// interface interface1 extends interface1 { -//// /*1*/doStuff(): void; -//// /*2*/propName: string; +//// [|doStuff|](): void; +//// [|propName|]: string; //// } //// interface interface2 extends interface1 { -//// /*3*/doStuff(): void; -//// /*4*/propName: string; +//// [|doStuff|](): void; +//// [|propName|]: string; //// } //// //// var v: interface1; -//// v./*5*/propName; -//// v./*6*/doStuff(); +//// v.[|propName|]; +//// v.[|doStuff|](); -test.markers().forEach(m => { - goTo.position(m.position, m.fileName); - verify.referencesCountIs(3); -}); \ No newline at end of file +verify.rangesWithSameTextReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForInheritedProperties6.ts b/tests/cases/fourslash/referencesForInheritedProperties6.ts index ddd52447dc1..ff008cceb43 100644 --- a/tests/cases/fourslash/referencesForInheritedProperties6.ts +++ b/tests/cases/fourslash/referencesForInheritedProperties6.ts @@ -1,32 +1,16 @@ /// //// class class1 extends class1 { -//// /*1*/doStuff() { } -//// /*2*/propName: string; +//// [|doStuff|]() { } +//// [|propName|]: string; //// } //// class class2 extends class1 { -//// /*3*/doStuff() { } -//// /*4*/propName: string; +//// [|doStuff|]() { } +//// [|propName|]: string; //// } //// //// var v: class2; -//// v./*5*/propName; -//// v./*6*/doStuff(); +//// v.[|propName|]; +//// v.[|doStuff|](); -goTo.marker("1"); -verify.referencesCountIs(3); - -goTo.marker("2"); -verify.referencesCountIs(3); - -goTo.marker("3"); -verify.referencesCountIs(3); - -goTo.marker("4"); -verify.referencesCountIs(3); - -goTo.marker("5"); -verify.referencesCountIs(3); - -goTo.marker("6"); -verify.referencesCountIs(3); \ No newline at end of file +verify.rangesWithSameTextReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForInheritedProperties7.ts b/tests/cases/fourslash/referencesForInheritedProperties7.ts index 5747e99615f..ec92a06f0a3 100644 --- a/tests/cases/fourslash/referencesForInheritedProperties7.ts +++ b/tests/cases/fourslash/referencesForInheritedProperties7.ts @@ -1,42 +1,30 @@ /// //// class class1 extends class1 { -//// /*1*/doStuff() { } -//// /*2*/propName: string; +//// [|doStuff|]() { } +//// [|propName|]: string; //// } //// interface interface1 extends interface1 { -//// /*3*/doStuff(): void; -//// /*4*/propName: string; +//// [|doStuff|](): void; +//// [|propName|]: string; //// } //// class class2 extends class1 implements interface1 { -//// /*5*/doStuff() { } -//// /*6*/propName: string; +//// [|doStuff|]() { } +//// [|propName|]: string; //// } //// //// var v: class2; -//// v./*7*/propName; -//// v./*8*/doStuff(); +//// v.[|propName|]; +//// v.[|doStuff|](); -goTo.marker("1"); -verify.referencesCountIs(3); - -goTo.marker("2"); -verify.referencesCountIs(3); - -goTo.marker("3"); -verify.referencesCountIs(3); - -goTo.marker("4"); -verify.referencesCountIs(3); - -goTo.marker("5"); -verify.referencesCountIs(4); - -goTo.marker("6"); -verify.referencesCountIs(4); - -goTo.marker("7"); -verify.referencesCountIs(4); - -goTo.marker("8"); -verify.referencesCountIs(4); \ No newline at end of file +const [r0, r1, r2, r3, r4, r5, r6, r7] = test.ranges(); +verify.referencesOf(r0, [r0, r4, r7]); +verify.referencesOf(r1, [r1, r5, r6]); +verify.referencesOf(r2, [r2, r4, r7]); +verify.referencesOf(r3, [r3, r5, r6]); +const allDoStuff = [r0, r2, r4, r7]; +verify.referencesOf(r4, allDoStuff); +const allPropName = [r1, r3, r5, r6]; +verify.referencesOf(r5, allPropName); +verify.referencesOf(r6, allPropName); +verify.referencesOf(r7, allDoStuff); diff --git a/tests/cases/fourslash/referencesForInheritedProperties8.ts b/tests/cases/fourslash/referencesForInheritedProperties8.ts index f34b327a472..964309fc477 100644 --- a/tests/cases/fourslash/referencesForInheritedProperties8.ts +++ b/tests/cases/fourslash/referencesForInheritedProperties8.ts @@ -1,27 +1,16 @@ /// //// interface C extends D { -//// /*0*/propD: number; +//// [|propD|]: number; //// } //// interface D extends C { -//// /*1*/propD: string; -//// /*3*/propC: number; +//// [|propD|]: string; +//// [|propC|]: number; //// } //// var d: D; -//// d./*2*/propD; -//// d./*4*/propC; +//// d.[|propD|]; +//// d.[|propC|]; -goTo.marker("0"); -verify.referencesCountIs(3); - -goTo.marker("1"); -verify.referencesCountIs(3); - -goTo.marker("2"); -verify.referencesCountIs(3); - -goTo.marker("3"); -verify.referencesCountIs(2); - -goTo.marker("4"); -verify.referencesCountIs(2); \ No newline at end of file +const [d0, d1, c0, d2, c1] = test.ranges(); +verify.rangesReferenceEachOther([d0, d1, d2]); +verify.rangesReferenceEachOther([c0, c1]); diff --git a/tests/cases/fourslash/referencesForInheritedProperties9.ts b/tests/cases/fourslash/referencesForInheritedProperties9.ts index b348d6e8cf6..7d4330d0aa6 100644 --- a/tests/cases/fourslash/referencesForInheritedProperties9.ts +++ b/tests/cases/fourslash/referencesForInheritedProperties9.ts @@ -1,21 +1,16 @@ /// //// class D extends C { -//// /*0*/prop1: string; +//// [|prop1|]: string; //// } //// //// class C extends D { -//// /*1*/prop1: string; +//// [|prop1|]: string; //// } //// //// var c: C; -//// c./*2*/prop1; +//// c.[|prop1|]; -goTo.marker("0"); -verify.referencesCountIs(1); - -goTo.marker("1"); -verify.referencesCountIs(2) - -goTo.marker("2"); -verify.referencesCountIs(2) \ No newline at end of file +const [r0, r1, r2] = test.ranges(); +verify.referencesOf(r0, [r0]); +verify.rangesReferenceEachOther([r1, r2]); diff --git a/tests/cases/fourslash/referencesForLabel.ts b/tests/cases/fourslash/referencesForLabel.ts index f79e038ca0a..14b58fd1d92 100644 --- a/tests/cases/fourslash/referencesForLabel.ts +++ b/tests/cases/fourslash/referencesForLabel.ts @@ -2,22 +2,14 @@ // Valid References for a label -/////*1*/label: while (true) { -//// if (false) break /*2*/label; -//// if (true) continue /*3*/label; +////[|label|]: while (true) { +//// if (false) break [|label|]; +//// if (true) continue [|label|]; ////} //// -/////*4*/label: while (false) { } +////[|label|]: while (false) { } ////var label = "label"; -goTo.marker("1"); -verify.referencesCountIs(3); - -goTo.marker("2"); -verify.referencesCountIs(3); - -goTo.marker("3"); -verify.referencesCountIs(3); - -goTo.marker("4"); -verify.referencesCountIs(1); \ No newline at end of file +const [r0, r1, r2, r3] = test.ranges(); +verify.rangesReferenceEachOther([r0, r1, r2]); +verify.referencesOf(r3, [r3]); diff --git a/tests/cases/fourslash/referencesForLabel2.ts b/tests/cases/fourslash/referencesForLabel2.ts index ccb441d60b9..841e35ad700 100644 --- a/tests/cases/fourslash/referencesForLabel2.ts +++ b/tests/cases/fourslash/referencesForLabel2.ts @@ -4,9 +4,9 @@ ////var label = "label"; ////while (true) { -//// if (false) break /*1*/label; +//// if (false) break /**/label; //// if (true) continue label; ////} -goTo.marker("1"); -verify.referencesCountIs(0); +goTo.marker(); +verify.referencesAre([]); diff --git a/tests/cases/fourslash/referencesForLabel3.ts b/tests/cases/fourslash/referencesForLabel3.ts index 9c621909c34..fb7a51f858e 100644 --- a/tests/cases/fourslash/referencesForLabel3.ts +++ b/tests/cases/fourslash/referencesForLabel3.ts @@ -2,9 +2,9 @@ // References to unused label -/////*1*/label: while (true) { +////[|label|]: while (true) { //// var label = "label"; ////} -goTo.marker("1"); -verify.referencesCountIs(1); +const [label] = test.ranges(); +verify.referencesOf(label, [label]); diff --git a/tests/cases/fourslash/referencesForLabel4.ts b/tests/cases/fourslash/referencesForLabel4.ts index d9817b2d857..5462500f53c 100644 --- a/tests/cases/fourslash/referencesForLabel4.ts +++ b/tests/cases/fourslash/referencesForLabel4.ts @@ -2,14 +2,10 @@ // References to a label outside function bounderies -/////*1*/label: function foo(label) { +////[|label|]: function foo(label) { //// while (true) { -//// break /*2*/label; +//// break [|label|]; //// } ////} -goTo.marker("1"); -verify.referencesCountIs(2); - -goTo.marker("2"); -verify.referencesCountIs(2); +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForLabel5.ts b/tests/cases/fourslash/referencesForLabel5.ts index dba59ec79ab..48d5aab04c2 100644 --- a/tests/cases/fourslash/referencesForLabel5.ts +++ b/tests/cases/fourslash/referencesForLabel5.ts @@ -2,27 +2,16 @@ // References to shadowed label -/////*outer1*/label: while (true) { -//// if (false) break /*outer2*/label; +////[|label|]: while (true) { +//// if (false) break [|label|]; //// function blah() { -/////*inner1*/label: while (true) { -//// if (false) break /*inner2*/label; +////[|label|]: while (true) { +//// if (false) break [|label|]; //// } //// } -//// if (false) break /*outer3*/label; +//// if (false) break [|label|]; //// } -goTo.marker("outer1"); -verify.referencesCountIs(3); - -goTo.marker("outer2"); -verify.referencesCountIs(3); - -goTo.marker("outer3"); -verify.referencesCountIs(3); - -goTo.marker("inner1"); -verify.referencesCountIs(2); - -goTo.marker("inner2"); -verify.referencesCountIs(2); +const [outer1, outer2, inner1, inner2, outer3] = test.ranges(); +verify.rangesReferenceEachOther([outer1, outer2, outer3]); +verify.rangesReferenceEachOther([inner1, inner2]); diff --git a/tests/cases/fourslash/referencesForLabel6.ts b/tests/cases/fourslash/referencesForLabel6.ts index a9aab59c467..aea45805756 100644 --- a/tests/cases/fourslash/referencesForLabel6.ts +++ b/tests/cases/fourslash/referencesForLabel6.ts @@ -1,14 +1,12 @@ /// -// References to lable wiht close names +// References to labels with close names -/////*1*/labela: while (true) { -/////*2*/labelb: while (false) { break labelb; } +////[|labela|]: while (true) { +////[|labelb|]: while (false) { break [|labelb|]; } //// break labelc; ////} -goTo.marker("1"); -verify.referencesCountIs(1); - -goTo.marker("2"); -verify.referencesCountIs(2); \ No newline at end of file +const [a, b, useB] = test.ranges(); +verify.referencesOf(a, [a]); +verify.rangesReferenceEachOther([b, useB]); diff --git a/tests/cases/fourslash/referencesForMergedDeclarations.ts b/tests/cases/fourslash/referencesForMergedDeclarations.ts index a475780b66e..8a0a5d4c680 100644 --- a/tests/cases/fourslash/referencesForMergedDeclarations.ts +++ b/tests/cases/fourslash/referencesForMergedDeclarations.ts @@ -1,21 +1,20 @@ /// -////interface /*type1*/Foo { +////interface [|Foo|] { ////} //// -////module /*namespace1*/Foo { +////module [|Foo|] { //// export interface Bar { } ////} //// -////function /*value1*/Foo(): void { +////function [|Foo|](): void { ////} //// -////var f1: /*namespace2*/Foo.Bar; -////var f2: /*type2*/Foo; -/////*value2*/Foo.bind(this); +////var f1: [|Foo|].Bar; +////var f2: [|Foo|]; +////[|Foo|].bind(this); - -test.markers().forEach(m => { - goTo.position(m.position, m.fileName); - verify.referencesCountIs(2); -}); +const [type1, namespace1, value1, namespace2, type2, value2] = test.ranges(); +verify.rangesReferenceEachOther([type1, type2]); +verify.rangesReferenceEachOther([namespace1, namespace2]); +verify.rangesReferenceEachOther([value1, value2]); diff --git a/tests/cases/fourslash/referencesForMergedDeclarations2.ts b/tests/cases/fourslash/referencesForMergedDeclarations2.ts index f7dbdc289d4..75d485002a4 100644 --- a/tests/cases/fourslash/referencesForMergedDeclarations2.ts +++ b/tests/cases/fourslash/referencesForMergedDeclarations2.ts @@ -6,16 +6,9 @@ //// ////function ATest() { } //// -////import /*definition*/alias = ATest; +////import [|alias|] = ATest; // definition //// -////var a: /*namespace*/alias.Bar; -/////*value*/alias.call(this); +////var a: [|alias|].Bar; // namespace +////[|alias|].call(this); // value -goTo.marker("definition"); -verify.referencesCountIs(3); - -goTo.marker("namespace"); -verify.referencesCountIs(3); - -goTo.marker("value"); -verify.referencesCountIs(3); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForMergedDeclarations3.ts b/tests/cases/fourslash/referencesForMergedDeclarations3.ts index 80cf1fb9e42..181d68e79b3 100644 --- a/tests/cases/fourslash/referencesForMergedDeclarations3.ts +++ b/tests/cases/fourslash/referencesForMergedDeclarations3.ts @@ -2,38 +2,24 @@ // class and uninstanciated module -////class testClass { +////class [|testClass|] { //// static staticMethod() { } //// method() { } ////} //// -////module testClass { +////module [|testClass|] { //// export interface Bar { //// //// } ////} //// -////var c1: /*class1*/testClass; -////var c2: /*module*/testClass.Bar; -/////*class2*/testClass.staticMethod(); -/////*class3*/testClass.prototype.method(); -/////*class4*/testClass.bind(this); -////new /*class5*/testClass(); +////var c1: [|testClass|]; +////var c2: [|testClass|].Bar; +////[|testClass|].staticMethod(); +////[|testClass|].prototype.method(); +////[|testClass|].bind(this); +////new [|testClass|](); -goTo.marker("module"); -verify.referencesCountIs(2); - -goTo.marker("class1"); -verify.referencesCountIs(6); - -goTo.marker("class2"); -verify.referencesCountIs(6); - -goTo.marker("class3"); -verify.referencesCountIs(6); - -goTo.marker("class4"); -verify.referencesCountIs(6); - -goTo.marker("class5"); -verify.referencesCountIs(6); \ No newline at end of file +const [class0, module0, class1, module1, class2, class3, class4, class5] = test.ranges(); +verify.rangesReferenceEachOther([module0, module1]); +verify.rangesReferenceEachOther([class0, class1, class2, class3, class4, class5]); diff --git a/tests/cases/fourslash/referencesForMergedDeclarations4.ts b/tests/cases/fourslash/referencesForMergedDeclarations4.ts index 88faf672fcc..d35cbea745d 100644 --- a/tests/cases/fourslash/referencesForMergedDeclarations4.ts +++ b/tests/cases/fourslash/referencesForMergedDeclarations4.ts @@ -2,28 +2,24 @@ // class and instanciated module -////class testClass { +////class [|testClass|] { //// static staticMethod() { } //// method() { } ////} //// -////module testClass { +////module [|testClass|] { //// export interface Bar { //// //// } //// export var s = 0; ////} //// -////var c1: /*1*/testClass; -////var c2: /*2*/testClass.Bar; -/////*3*/testClass.staticMethod(); -/////*4*/testClass.prototype.method(); -/////*5*/testClass.bind(this); -/////*6*/testClass.s; -////new /*7*/testClass(); +////var c1: [|testClass|]; +////var c2: [|testClass|].Bar; +////[|testClass|].staticMethod(); +////[|testClass|].prototype.method(); +////[|testClass|].bind(this); +////[|testClass|].s; +////new [|testClass|](); -// Instanciated Module and class intersect in the value space, so we consider them all one group -test.markers().forEach(m => { - goTo.position(m.position, m.fileName); - verify.referencesCountIs(9); -}); +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForMergedDeclarations5.ts b/tests/cases/fourslash/referencesForMergedDeclarations5.ts index deb7ad321c9..8fe33ca31e4 100644 --- a/tests/cases/fourslash/referencesForMergedDeclarations5.ts +++ b/tests/cases/fourslash/referencesForMergedDeclarations5.ts @@ -1,10 +1,10 @@ /// -////interface Foo { } -////module Foo { export interface Bar { } } -////function Foo() { } +////interface [|Foo|] { } +////module [|Foo|] { export interface Bar { } } +////function [|Foo|]() { } //// -////export = /*1*/Foo; +////export = [|Foo|]; -goTo.marker("1"); -verify.referencesCountIs(4); \ No newline at end of file +const [r0, r1, r2, r3] = test.ranges(); +verify.referencesOf(r3, [r0, r1, r2, r3]); diff --git a/tests/cases/fourslash/referencesForMergedDeclarations6.ts b/tests/cases/fourslash/referencesForMergedDeclarations6.ts index ae0e3992146..e4b5b9111c6 100644 --- a/tests/cases/fourslash/referencesForMergedDeclarations6.ts +++ b/tests/cases/fourslash/referencesForMergedDeclarations6.ts @@ -1,14 +1,13 @@ /// ////interface Foo { } -////module Foo { +////module [|Foo|] { //// export interface Bar { } //// export module Bar { export interface Baz { } } //// export function Bar() { } ////} //// ////// module -////import a1 = /*1*/Foo; +////import a1 = [|Foo|]; -goTo.marker("1"); -verify.referencesCountIs(2); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForMergedDeclarations7.ts b/tests/cases/fourslash/referencesForMergedDeclarations7.ts index 1c6d730797f..bc56b5d6f9d 100644 --- a/tests/cases/fourslash/referencesForMergedDeclarations7.ts +++ b/tests/cases/fourslash/referencesForMergedDeclarations7.ts @@ -2,13 +2,13 @@ ////interface Foo { } ////module Foo { -//// export interface Bar { } -//// export module Bar { export interface Baz { } } -//// export function Bar() { } +//// export interface [|Bar|] { } +//// export module [|Bar|] { export interface Baz { } } +//// export function [|Bar|]() { } ////} //// ////// module, value and type -////import a2 = Foo./*1*/Bar; +////import a2 = Foo.[|Bar|]; -goTo.marker("1"); -verify.referencesCountIs(4); \ No newline at end of file +const [r0, r1, r2, r3] = test.ranges(); +verify.referencesOf(r3, [r0, r1, r2, r3]); diff --git a/tests/cases/fourslash/referencesForMergedDeclarations8.ts b/tests/cases/fourslash/referencesForMergedDeclarations8.ts index 9e7a821a024..b5b1428b7c9 100644 --- a/tests/cases/fourslash/referencesForMergedDeclarations8.ts +++ b/tests/cases/fourslash/referencesForMergedDeclarations8.ts @@ -3,12 +3,11 @@ ////interface Foo { } ////module Foo { //// export interface Bar { } -//// export module Bar { export interface Baz { } } +//// export module [|Bar|] { export interface Baz { } } //// export function Bar() { } ////} //// ////// module -////import a3 = Foo./*1*/Bar.Baz; +////import a3 = Foo.[|Bar|].Baz; -goTo.marker("1"); -verify.referencesCountIs(2); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForNoContext.ts b/tests/cases/fourslash/referencesForNoContext.ts index ee9391e5416..4631ce50c16 100644 --- a/tests/cases/fourslash/referencesForNoContext.ts +++ b/tests/cases/fourslash/referencesForNoContext.ts @@ -22,13 +22,13 @@ ////} goTo.marker("1"); -verify.referencesCountIs(0); +verify.referencesAre([]); goTo.marker("2"); -verify.referencesCountIs(0); +verify.referencesAre([]); goTo.marker("3"); -verify.referencesCountIs(0); +verify.referencesAre([]); goTo.marker("4"); -verify.referencesCountIs(0); +verify.referencesAre([]); diff --git a/tests/cases/fourslash/referencesForNumericLiteralPropertyNames.ts b/tests/cases/fourslash/referencesForNumericLiteralPropertyNames.ts index e2a781ff58c..5e6e8172092 100644 --- a/tests/cases/fourslash/referencesForNumericLiteralPropertyNames.ts +++ b/tests/cases/fourslash/referencesForNumericLiteralPropertyNames.ts @@ -1,15 +1,12 @@ /// ////class Foo { -//// public /*1*/12: any; +//// public [|12|]: any; ////} //// ////var x: Foo; -////x[/*2*/12]; -////x = { "12": 0 }; -////x = { /*3*/12: 0 }; +////x[[|12|]]; +////x = { "[|12|]": 0 }; +////x = { [|12|]: 0 }; -test.markers().forEach((m) => { - goTo.position(m.position, m.fileName); - verify.referencesCountIs(4); -}); +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForObjectLiteralProperties.ts b/tests/cases/fourslash/referencesForObjectLiteralProperties.ts index 8515a5487b7..f2a815e845b 100644 --- a/tests/cases/fourslash/referencesForObjectLiteralProperties.ts +++ b/tests/cases/fourslash/referencesForObjectLiteralProperties.ts @@ -2,14 +2,10 @@ // References to an object literal property -////var x = { /*1*/add: 0, b: "string" }; -////x["add"]; -////x./*2*/add; +////var x = { [|add|]: 0, b: "string" }; +////x["[|add|]"]; +////x.[|add|]; ////var y = x; -////y.add; +////y.[|add|]; -goTo.marker("1"); -verify.referencesCountIs(4); - -goTo.marker("2"); -verify.referencesCountIs(4); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForOverrides.ts b/tests/cases/fourslash/referencesForOverrides.ts index 2b67269a6f3..4896bd1cd39 100644 --- a/tests/cases/fourslash/referencesForOverrides.ts +++ b/tests/cases/fourslash/referencesForOverrides.ts @@ -3,82 +3,76 @@ ////module FindRef3 { //// module SimpleClassTest { //// export class Foo { -//// public foo(): void { +//// public [|foo|](): void { //// } //// } //// export class Bar extends Foo { -//// public foo(): void { +//// public [|foo|](): void { //// } //// } //// } //// //// module SimpleInterfaceTest { //// export interface IFoo { -//// foo(): void; +//// [|ifoo|](): void; //// } //// export interface IBar extends IFoo { -//// foo(): void; +//// [|ifoo|](): void; //// } //// } //// //// module SimpleClassInterfaceTest { //// export interface IFoo { -//// foo(): void; +//// [|icfoo|](): void; //// } //// export class Bar implements IFoo { -//// public foo(): void { +//// public [|icfoo|](): void { //// } //// } //// } //// //// module Test { //// export interface IBase { -//// field: string; -//// method(): void; +//// [|field|]: string; +//// [|method|](): void; //// } //// //// export interface IBlah extends IBase { -//// field: string; +//// [|field|]: string; //// } //// //// export interface IBlah2 extends IBlah { -//// field: string; +//// [|field|]: string; //// } //// //// export interface IDerived extends IBlah2 { -//// method(): void; +//// [|method|](): void; //// } //// //// export class Bar implements IDerived { -//// public field: string; -//// public method(): void { } +//// public [|field|]: string; +//// public [|method|](): void { } //// } //// //// export class BarBlah extends Bar { -//// public field: string; +//// public [|field|]: string; //// } //// } //// //// function test() { //// var x = new SimpleClassTest.Bar(); -//// x.fo/*1*/o(); +//// x.[|foo|](); //// //// var y: SimpleInterfaceTest.IBar = null; -//// y.fo/*2*/o(); +//// y.[|ifoo|](); +//// +//// var w: SimpleClassInterfaceTest.Bar = null; +//// w.[|icfoo|](); //// //// var z = new Test.BarBlah(); -//// z.fi/*3*/eld = ""; +//// z.[|field|] = ""; +//// z.[|method|](); //// } ////} -// References to a field declared in a base class. -goTo.marker("1"); -verify.referencesCountIs(3); - -// References to a field declared in a base interface. -goTo.marker("2"); -verify.referencesCountIs(3); - -// References to a field declared in a chain of base class and interfaces. -goTo.marker("3"); -verify.referencesCountIs(6); +verify.rangesWithSameTextReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForPropertiesOfGenericType.ts b/tests/cases/fourslash/referencesForPropertiesOfGenericType.ts index c611c40fc89..a8b08eae506 100644 --- a/tests/cases/fourslash/referencesForPropertiesOfGenericType.ts +++ b/tests/cases/fourslash/referencesForPropertiesOfGenericType.ts @@ -1,15 +1,13 @@ /// ////interface IFoo { -//// /*1*/doSomething(v: T): T; +//// [|doSomething|](v: T): T; ////} //// ////var x: IFoo; -////x.doSomething("ss"); +////x.[|doSomething|]("ss"); //// ////var y: IFoo; -////y.doSomething(12); +////y.[|doSomething|](12); - -goTo.marker("1"); -verify.referencesCountIs(3); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesForStatic.ts b/tests/cases/fourslash/referencesForStatic.ts index 34b34e2d474..c6594006708 100644 --- a/tests/cases/fourslash/referencesForStatic.ts +++ b/tests/cases/fourslash/referencesForStatic.ts @@ -6,35 +6,28 @@ ////var n = 43; //// ////class foo { -//// static n = ''; +//// static [|n|] = ''; //// //// public bar() { -//// foo./*1*/n = "'"; -//// if(foo.n) { -//// var x = foo.n; +//// foo.[|n|] = "'"; +//// if(foo.[|n|]) { +//// var x = foo.[|n|]; //// } //// } ////} //// ////class foo2 { -//// private x = foo./*2*/n; +//// private x = foo.[|n|]; //// constructor() { -//// foo./*3*/n = x; +//// foo.[|n|] = x; //// } //// //// function b(n) { -//// n = foo.n; +//// n = foo.[|n|]; //// } ////} // @Filename: referencesOnStatic_2.ts -////var q = foo.n; +////var q = foo.[|n|]; -goTo.marker("1"); -verify.referencesCountIs(8); - -goTo.marker("2"); -verify.referencesCountIs(8); - -goTo.marker("3"); -verify.referencesCountIs(8); \ No newline at end of file +verify.rangesReferenceEachOther(); diff --git a/tests/cases/fourslash/referencesInComment.ts b/tests/cases/fourslash/referencesInComment.ts index 00f7ba26860..c53a2e6d9b3 100644 --- a/tests/cases/fourslash/referencesInComment.ts +++ b/tests/cases/fourslash/referencesInComment.ts @@ -6,5 +6,5 @@ ////var bar = 0; for (const marker of test.markers()) { - verify.referencesCountIs(0); + verify.referencesAre([]); } diff --git a/tests/cases/fourslash/remoteGetReferences.ts b/tests/cases/fourslash/remoteGetReferences.ts index cdc4ab035a3..d9b6c6e852c 100644 --- a/tests/cases/fourslash/remoteGetReferences.ts +++ b/tests/cases/fourslash/remoteGetReferences.ts @@ -86,19 +86,19 @@ //// //////Remotes //////Type test -////var remoteclsTest: rem/*2*/otefooCls; +////var remoteclsTest: [|remotefooCls|]; //// //////Arguments -////remoteclsTest = new remotefooCls(remoteglo/*4*/balVar); -////remotefoo(remotegl/*3*/obalVar); +////remoteclsTest = new [|remotefooCls|]([|remoteglobalVar|]); +////remotefoo([|remoteglobalVar|]); //// //////Increments -////remotefooCls.remoteclsSVar++; +////[|remotefooCls|].[|remoteclsSVar|]++; ////remotemodTest.remotemodVar++; -/////*1*/remoteglobalVar = remoteglobalVar + remoteglobalVar; +////[|remoteglobalVar|] = [|remoteglobalVar|] + [|remoteglobalVar|]; //// //////ETC - Other cases -////remoteglobalVar = 3; +////[|remoteglobalVar|] = 3; //// //////Find References misses method param ////var @@ -119,18 +119,18 @@ ////}); // @Filename: remoteGetReferences_2.ts -////var remoteglobalVar: number = 2; +////var [|remoteglobalVar|]: number = 2; //// -////class remotefooCls { +////class [|remotefooCls|] { //// //Declare -//// rem/*5*/oteclsVar = 1; -//// static r/*6*/emoteclsSVar = 1; +//// [|remoteclsVar|] = 1; +//// static [|remoteclsSVar|] = 1; //// //// constructor(public remoteclsParam: number) { //// //Increments -//// remoteglobalVar++; -//// this.remoteclsVar++; -//// remotefooCls.remoteclsSVar++; +//// [|remoteglobalVar|]++; +//// this.[|remoteclsVar|]++; +//// [|remotefooCls|].[|remoteclsSVar|]++; //// this.remoteclsParam++; //// remotemodTest.remotemodVar++; //// } @@ -141,8 +141,8 @@ //// var remotefnVar = 1; //// //// //Increments -//// remotefooCls.remoteclsSVar++; -//// remoteglobalVar++; +//// [|remotefooCls|].[|remoteclsSVar|]++; +//// [|remoteglobalVar|]++; //// remotemodTest.remotemodVar++; //// remotefnVar++; //// @@ -155,8 +155,8 @@ //// export var remotemodVar: number; //// //// //Increments -//// remoteglobalVar++; -//// remotefooCls.remoteclsSVar++; +//// [|remoteglobalVar|]++; +//// [|remotefooCls|].[|remoteclsSVar|]++; //// remotemodVar++; //// //// class remotetestCls { @@ -167,8 +167,8 @@ //// static remoteboo = remotefoo; //// //// //Increments -//// remoteglobalVar++; -//// remotefooCls.remoteclsSVar++; +//// [|remoteglobalVar|]++; +//// [|remotefooCls|].[|remoteclsSVar|]++; //// remotemodVar++; //// } //// @@ -177,26 +177,4 @@ //// } ////} -// References to a variable declared in global. -goTo.marker("1"); -verify.referencesCountIs(11); - -// References to a type. -goTo.marker("2"); -verify.referencesCountIs(8); - -// References to a function argument. -goTo.marker("3"); -verify.referencesCountIs(11); - -// References to a class argument. -goTo.marker("4"); -verify.referencesCountIs(11); - -// References to a variable declared in a class. -goTo.marker("5"); -verify.referencesCountIs(2); - -// References to static variable declared in a class. -goTo.marker("6"); -verify.referencesCountIs(6); \ No newline at end of file +verify.rangesWithSameTextReferenceEachOther(); diff --git a/tests/cases/fourslash/renameThis.ts b/tests/cases/fourslash/renameThis.ts new file mode 100644 index 00000000000..f567cace70d --- /dev/null +++ b/tests/cases/fourslash/renameThis.ts @@ -0,0 +1,22 @@ +/// + +////function f([|this|]) { +//// return [|this|]; +////} +////this/**/; +////const _ = { [|this|]: 0 }.[|this|]; + +let [r0, r1, r2, r3] = test.ranges() +for (let range of [r0, r1]) { + goTo.position(range.start); + verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false, [r0, r1]); +} + +// Trying to rename a non-parameter 'this' should fail +goTo.marker(); +verify.renameInfoFailed("You cannot rename this element."); + +for (let range of [r2, r3]) { + goTo.position(range.start); + verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false, [r2, r3]); +} diff --git a/tests/cases/fourslash/stringBraceCompletionPosition.ts b/tests/cases/fourslash/stringBraceCompletionPosition.ts index 09a9a86b0f1..5df80e2c676 100644 --- a/tests/cases/fourslash/stringBraceCompletionPosition.ts +++ b/tests/cases/fourslash/stringBraceCompletionPosition.ts @@ -6,11 +6,11 @@ //// /*3*/"; goTo.marker('1'); -verify.not.isValidBraceCompletionAtPostion('('); +verify.not.isValidBraceCompletionAtPosition('('); goTo.marker('2'); -verify.not.isValidBraceCompletionAtPostion('('); +verify.not.isValidBraceCompletionAtPosition('('); goTo.marker('3'); -verify.not.isValidBraceCompletionAtPostion('('); +verify.not.isValidBraceCompletionAtPosition('('); diff --git a/tests/cases/fourslash/stringTemplateBraceCompletionPosition.ts b/tests/cases/fourslash/stringTemplateBraceCompletionPosition.ts index 33bcd4d0625..73c945e932c 100644 --- a/tests/cases/fourslash/stringTemplateBraceCompletionPosition.ts +++ b/tests/cases/fourslash/stringTemplateBraceCompletionPosition.ts @@ -4,13 +4,13 @@ //// var y = `hello /*2*/world, ${100}how /*3*/are you{ 200 } to/*4*/day!?` goTo.marker('1'); -verify.not.isValidBraceCompletionAtPostion('('); +verify.not.isValidBraceCompletionAtPosition('('); goTo.marker('2'); -verify.not.isValidBraceCompletionAtPostion('('); +verify.not.isValidBraceCompletionAtPosition('('); goTo.marker('3'); -verify.not.isValidBraceCompletionAtPostion('('); +verify.not.isValidBraceCompletionAtPosition('('); goTo.marker('4'); -verify.not.isValidBraceCompletionAtPostion('('); +verify.not.isValidBraceCompletionAtPosition('('); diff --git a/tests/cases/fourslash/validBraceCompletionPosition.ts b/tests/cases/fourslash/validBraceCompletionPosition.ts index 57c30c27c21..1d281be705d 100644 --- a/tests/cases/fourslash/validBraceCompletionPosition.ts +++ b/tests/cases/fourslash/validBraceCompletionPosition.ts @@ -8,16 +8,16 @@ //// var x = /*5*/{ a:true } goTo.marker('1'); -verify.isValidBraceCompletionAtPostion('('); +verify.isValidBraceCompletionAtPosition('('); goTo.marker('2'); -verify.isValidBraceCompletionAtPostion('('); +verify.isValidBraceCompletionAtPosition('('); goTo.marker('3'); -verify.isValidBraceCompletionAtPostion('('); +verify.isValidBraceCompletionAtPosition('('); goTo.marker('4'); -verify.isValidBraceCompletionAtPostion('('); +verify.isValidBraceCompletionAtPosition('('); goTo.marker('5'); -verify.isValidBraceCompletionAtPostion('('); \ No newline at end of file +verify.isValidBraceCompletionAtPosition('('); \ No newline at end of file diff --git a/tests/cases/project/emitDecoratorMetadataCommonJSISolatedModules.json b/tests/cases/project/emitDecoratorMetadataCommonJSISolatedModules.json new file mode 100644 index 00000000000..27b2e09172b --- /dev/null +++ b/tests/cases/project/emitDecoratorMetadataCommonJSISolatedModules.json @@ -0,0 +1,6 @@ +{ + "scenario": "Emit decorator metadata when commonJS and isolatedModules are on", + "projectRoot": "tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModule", + "baselineCheck": true, + "runTest": true +} \ No newline at end of file diff --git a/tests/cases/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve.json b/tests/cases/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve.json new file mode 100644 index 00000000000..8930951b9a4 --- /dev/null +++ b/tests/cases/project/emitDecoratorMetadataCommonJSISolatedModulesNoResolve.json @@ -0,0 +1,6 @@ +{ + "scenario": "Emit decorator metadata when commonJS and isolatedModules are on", + "projectRoot": "tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModuleNoResolve", + "baselineCheck": true, + "runTest": true +} \ No newline at end of file diff --git a/tests/cases/project/emitDecoratorMetadataSystemJS.json b/tests/cases/project/emitDecoratorMetadataSystemJS.json new file mode 100644 index 00000000000..1ed6b13dcb3 --- /dev/null +++ b/tests/cases/project/emitDecoratorMetadataSystemJS.json @@ -0,0 +1,6 @@ +{ + "scenario": "Emit decorator metadata when commonJS and isolatedModules are on", + "projectRoot": "tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJS", + "baselineCheck": true, + "runTest": true +} \ No newline at end of file diff --git a/tests/cases/project/emitDecoratorMetadataSystemJSISolatedModules.json b/tests/cases/project/emitDecoratorMetadataSystemJSISolatedModules.json new file mode 100644 index 00000000000..da18f2602af --- /dev/null +++ b/tests/cases/project/emitDecoratorMetadataSystemJSISolatedModules.json @@ -0,0 +1,6 @@ +{ + "scenario": "Emit decorator metadata when commonJS and isolatedModules are on", + "projectRoot": "tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJSIsolatedModule", + "baselineCheck": true, + "runTest": true +} \ No newline at end of file diff --git a/tests/cases/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve.json b/tests/cases/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve.json new file mode 100644 index 00000000000..d87a1361cdd --- /dev/null +++ b/tests/cases/project/emitDecoratorMetadataSystemJSISolatedModulesNoResolve.json @@ -0,0 +1,6 @@ +{ + "scenario": "Emit decorator metadata when commonJS and isolatedModules are on", + "projectRoot": "tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJSIsolatedModuleNoResolve", + "baselineCheck": true, + "runTest": true +} \ No newline at end of file diff --git a/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModule/main.ts b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModule/main.ts new file mode 100644 index 00000000000..f75e8a4d9d6 --- /dev/null +++ b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModule/main.ts @@ -0,0 +1,8 @@ +import * as ng from "angular2/core"; + +declare function foo(...args: any[]); + +@foo +export class MyClass1 { + constructor(private _elementRef: ng.ElementRef){} +} \ No newline at end of file diff --git a/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModule/tsconfig.json b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModule/tsconfig.json new file mode 100644 index 00000000000..27d98c7f2c9 --- /dev/null +++ b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModule/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compileOnSave": true, + "compilerOptions": { + "target": "es5", + "module": "commonjs", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "isolatedModules": true + }, + "files": [ + "main.ts" + ] +} \ No newline at end of file diff --git a/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModuleNoResolve/main.ts b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModuleNoResolve/main.ts new file mode 100644 index 00000000000..f75e8a4d9d6 --- /dev/null +++ b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModuleNoResolve/main.ts @@ -0,0 +1,8 @@ +import * as ng from "angular2/core"; + +declare function foo(...args: any[]); + +@foo +export class MyClass1 { + constructor(private _elementRef: ng.ElementRef){} +} \ No newline at end of file diff --git a/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModuleNoResolve/tsconfig.json b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModuleNoResolve/tsconfig.json new file mode 100644 index 00000000000..a34d38cb68e --- /dev/null +++ b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataCommonJSIsolatedModuleNoResolve/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compileOnSave": true, + "compilerOptions": { + "target": "es5", + "module": "commonjs", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "isolatedModules": true, + "noResolve": true + }, + "files": [ + "main.ts" + ] +} \ No newline at end of file diff --git a/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJS/main.ts b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJS/main.ts new file mode 100644 index 00000000000..f75e8a4d9d6 --- /dev/null +++ b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJS/main.ts @@ -0,0 +1,8 @@ +import * as ng from "angular2/core"; + +declare function foo(...args: any[]); + +@foo +export class MyClass1 { + constructor(private _elementRef: ng.ElementRef){} +} \ No newline at end of file diff --git a/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJS/tsconfig.json b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJS/tsconfig.json new file mode 100644 index 00000000000..6c78695c505 --- /dev/null +++ b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJS/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compileOnSave": true, + "compilerOptions": { + "target": "es5", + "module": "system", + "emitDecoratorMetadata": true, + "experimentalDecorators": true + }, + "files": [ + "main.ts" + ] +} \ No newline at end of file diff --git a/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJSIsolatedModule/main.ts b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJSIsolatedModule/main.ts new file mode 100644 index 00000000000..f75e8a4d9d6 --- /dev/null +++ b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJSIsolatedModule/main.ts @@ -0,0 +1,8 @@ +import * as ng from "angular2/core"; + +declare function foo(...args: any[]); + +@foo +export class MyClass1 { + constructor(private _elementRef: ng.ElementRef){} +} \ No newline at end of file diff --git a/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJSIsolatedModule/tsconfig.json b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJSIsolatedModule/tsconfig.json new file mode 100644 index 00000000000..2a8dcffba74 --- /dev/null +++ b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJSIsolatedModule/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compileOnSave": true, + "compilerOptions": { + "target": "es5", + "module": "system", + "moduleResolution": "node", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "isolatedModules": true + }, + "files": [ + "main.ts" + ] +} \ No newline at end of file diff --git a/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJSIsolatedModuleNoResolve/main.ts b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJSIsolatedModuleNoResolve/main.ts new file mode 100644 index 00000000000..f75e8a4d9d6 --- /dev/null +++ b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJSIsolatedModuleNoResolve/main.ts @@ -0,0 +1,8 @@ +import * as ng from "angular2/core"; + +declare function foo(...args: any[]); + +@foo +export class MyClass1 { + constructor(private _elementRef: ng.ElementRef){} +} \ No newline at end of file diff --git a/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJSIsolatedModuleNoResolve/tsconfig.json b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJSIsolatedModuleNoResolve/tsconfig.json new file mode 100644 index 00000000000..b76669d9329 --- /dev/null +++ b/tests/cases/projects/decoratorMetadata/emitDecoratorMetadataSystemJSIsolatedModuleNoResolve/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compileOnSave": true, + "compilerOptions": { + "target": "es5", + "module": "system", + "moduleResolution": "node", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "isolatedModules": true, + "noResolve": true + }, + "files": [ + "main.ts" + ] +} \ No newline at end of file diff --git a/tests/cases/unittests/moduleResolution.ts b/tests/cases/unittests/moduleResolution.ts index 16fc7df8d70..70cb4715c48 100644 --- a/tests/cases/unittests/moduleResolution.ts +++ b/tests/cases/unittests/moduleResolution.ts @@ -589,7 +589,7 @@ import b = require("./moduleB.ts"); const file1: File = { name: "/root/folder1/file1.ts" }; const file2: File = { name: "/root/generated/folder1/file2.ts" }; // load remapped file as module const file3: File = { name: "/root/generated/folder2/file3/index.d.ts" }; // load folder a module - const file4Typings: File = { name: "/root/generated/folder2/file4/package.json", content: JSON.stringify({ typings: "dist/types.d.ts" })}; + const file4Typings: File = { name: "/root/generated/folder2/file4/package.json", content: JSON.stringify({ typings: "dist/types.d.ts" }) }; const file4: File = { name: "/root/generated/folder2/file4/dist/types.d.ts" }; // load file pointed by typings const file5: File = { name: "/root/someanotherfolder/file5/index.d.ts" }; // load remapped module from folder const file6: File = { name: "/root/node_modules/file6.ts" }; // fallback to node @@ -957,7 +957,7 @@ import b = require("./moduleB.ts"); describe("Type reference directive resolution: ", () => { function test(typesRoot: string, typeDirective: string, primary: boolean, initialFile: File, targetFile: File, ...otherFiles: File[]) { const host = createModuleResolutionHost(/*hasDirectoryExists*/ false, ...[initialFile, targetFile].concat(...otherFiles)); - const result = resolveTypeReferenceDirective(typeDirective, initialFile.name, {typeRoots: [typesRoot]}, host); + const result = resolveTypeReferenceDirective(typeDirective, initialFile.name, { typeRoots: [typesRoot] }, host); assert(result.resolvedTypeReferenceDirective.resolvedFileName !== undefined, "expected type directive to be resolved"); assert.equal(result.resolvedTypeReferenceDirective.resolvedFileName, targetFile.name, "unexpected result of type reference resolution"); assert.equal(result.resolvedTypeReferenceDirective.primary, primary, "unexpected 'primary' value"); @@ -972,7 +972,7 @@ import b = require("./moduleB.ts"); { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/src/types/lib/typings/lib.d.ts" }; - const package = { name: "/root/src/types/lib/package.json", content: JSON.stringify({types: "typings/lib.d.ts"}) }; + const package = { name: "/root/src/types/lib/package.json", content: JSON.stringify({ types: "typings/lib.d.ts" }) }; test(/*typesRoot*/"/root/src/types", /* typeDirective */"lib", /*primary*/ true, f1, f2, package); } { @@ -983,7 +983,7 @@ import b = require("./moduleB.ts"); { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/src/node_modules/lib/typings/lib.d.ts" }; - const package = { name: "/root/src/node_modules/lib/package.json", content: JSON.stringify({types: "typings/lib.d.ts"}) }; + const package = { name: "/root/src/node_modules/lib/package.json", content: JSON.stringify({ types: "typings/lib.d.ts" }) }; test(/*typesRoot*/"/root/src/types", /* typeDirective */"lib", /*primary*/ false, f1, f2, package); } { @@ -994,7 +994,7 @@ import b = require("./moduleB.ts"); { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/src/node_modules/@types/lib/typings/lib.d.ts" }; - const package = { name: "/root/src/node_modules/@types/lib/package.json", content: JSON.stringify({types: "typings/lib.d.ts"}) }; + const package = { name: "/root/src/node_modules/@types/lib/package.json", content: JSON.stringify({ types: "typings/lib.d.ts" }) }; test(/*typesRoot*/"/root/src/types", /* typeDirective */"lib", /*primary*/ false, f1, f2, package); } }); @@ -1012,7 +1012,7 @@ import b = require("./moduleB.ts"); { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/node_modules/lib/typings/lib.d.ts" }; - const package = { name: "/root/node_modules/lib/package.json", content: JSON.stringify({typings: "typings/lib.d.ts"}) }; + const package = { name: "/root/node_modules/lib/package.json", content: JSON.stringify({ typings: "typings/lib.d.ts" }) }; test(/*typesRoot*/"/root/src/types", /* typeDirective */"lib", /*primary*/ false, f1, f2, package); } { @@ -1023,7 +1023,7 @@ import b = require("./moduleB.ts"); { const f1 = { name: "/root/src/app.ts" }; const f2 = { name: "/root/node_modules/@types/lib/typings/lib.d.ts" }; - const package = { name: "/root/node_modules/@types/lib/package.json", content: JSON.stringify({typings: "typings/lib.d.ts"}) }; + const package = { name: "/root/node_modules/@types/lib/package.json", content: JSON.stringify({ typings: "typings/lib.d.ts" }) }; test(/*typesRoot*/"/root/src/types", /* typeDirective */"lib", /*primary*/ false, f1, f2, package); } }); diff --git a/tests/cases/unittests/session.ts b/tests/cases/unittests/session.ts index 6a5fa33d29c..a687d8cac93 100644 --- a/tests/cases/unittests/session.ts +++ b/tests/cases/unittests/session.ts @@ -171,7 +171,7 @@ namespace ts.server { describe("send", () => { it("is an overrideable handle which sends protocol messages over the wire", () => { - const msg = {seq: 0, type: "none"}; + const msg = { seq: 0, type: "none" }; const strmsg = JSON.stringify(msg); const len = 1 + Utils.byteLength(strmsg, "utf8"); const resultMsg = `Content-Length: ${len}\r\n\r\n${strmsg}\n`; @@ -267,7 +267,7 @@ namespace ts.server { constructor() { super(mockHost, nullCancellationToken, Utils.byteLength, process.hrtime, mockLogger); this.addProtocolHandler(this.customHandler, () => { - return {response: undefined, responseRequired: true}; + return { response: undefined, responseRequired: true }; }); } send(msg: protocol.Message) { @@ -341,7 +341,7 @@ namespace ts.server { handleRequest(msg: protocol.Request) { let response: protocol.Response; try { - ({response} = this.executeCommand(msg)); + ({ response } = this.executeCommand(msg)); } catch (e) { this.output(undefined, msg.command, msg.seq, e.toString()); diff --git a/tests/cases/unittests/transpile.ts b/tests/cases/unittests/transpile.ts index 5900a29bb5d..1766e3280d4 100644 --- a/tests/cases/unittests/transpile.ts +++ b/tests/cases/unittests/transpile.ts @@ -239,195 +239,233 @@ var x = 0;`, { }); transpilesCorrectly("Supports setting 'allowJs'", "x;", { - options: { compilerOptions: { allowJs: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { allowJs: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'allowSyntheticDefaultImports'", "x;", { - options: { compilerOptions: { allowSyntheticDefaultImports: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { allowSyntheticDefaultImports: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'allowUnreachableCode'", "x;", { - options: { compilerOptions: { allowUnreachableCode: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { allowUnreachableCode: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'allowUnusedLabels'", "x;", { - options: { compilerOptions: { allowUnusedLabels: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { allowUnusedLabels: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'baseUrl'", "x;", { - options: { compilerOptions: { baseUrl: "./folder/baseUrl" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { baseUrl: "./folder/baseUrl" }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'charset'", "x;", { - options: { compilerOptions: { charset: "en-us" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { charset: "en-us" }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'declaration'", "x;", { - options: { compilerOptions: { declaration: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { declaration: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'declarationDir'", "x;", { - options: { compilerOptions: { declarationDir: "out/declarations" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { declarationDir: "out/declarations" }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'emitBOM'", "x;", { - options: { compilerOptions: { emitBOM: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { emitBOM: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'emitDecoratorMetadata'", "x;", { - options: { compilerOptions: { emitDecoratorMetadata: true, experimentalDecorators: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { emitDecoratorMetadata: true, experimentalDecorators: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'experimentalDecorators'", "x;", { - options: { compilerOptions: { experimentalDecorators: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { experimentalDecorators: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'forceConsistentCasingInFileNames'", "x;", { - options: { compilerOptions: { forceConsistentCasingInFileNames: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { forceConsistentCasingInFileNames: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'isolatedModules'", "x;", { - options: { compilerOptions: { isolatedModules: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { isolatedModules: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'jsx'", "x;", { - options: { compilerOptions: { jsx: 1 }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { jsx: 1 }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'lib'", "x;", { - options: { compilerOptions: { lib: ["es2015", "dom"] }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { lib: ["es2015", "dom"] }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'locale'", "x;", { - options: { compilerOptions: { locale: "en-us" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { locale: "en-us" }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'module'", "x;", { - options: { compilerOptions: { module: ModuleKind.CommonJS }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { module: ModuleKind.CommonJS }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'moduleResolution'", "x;", { - options: { compilerOptions: { moduleResolution: ModuleResolutionKind.NodeJs }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { moduleResolution: ModuleResolutionKind.NodeJs }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'newLine'", "x;", { - options: { compilerOptions: { newLine: NewLineKind.CarriageReturnLineFeed }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { newLine: NewLineKind.CarriageReturnLineFeed }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noEmit'", "x;", { - options: { compilerOptions: { noEmit: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noEmit: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noEmitHelpers'", "x;", { - options: { compilerOptions: { noEmitHelpers: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noEmitHelpers: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noEmitOnError'", "x;", { - options: { compilerOptions: { noEmitOnError: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noEmitOnError: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noErrorTruncation'", "x;", { - options: { compilerOptions: { noErrorTruncation: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noErrorTruncation: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noFallthroughCasesInSwitch'", "x;", { - options: { compilerOptions: { noFallthroughCasesInSwitch: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noFallthroughCasesInSwitch: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noImplicitAny'", "x;", { - options: { compilerOptions: { noImplicitAny: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noImplicitAny: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noImplicitReturns'", "x;", { - options: { compilerOptions: { noImplicitReturns: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noImplicitReturns: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noImplicitThis'", "x;", { - options: { compilerOptions: { noImplicitThis: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noImplicitThis: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noImplicitUseStrict'", "x;", { - options: { compilerOptions: { noImplicitUseStrict: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noImplicitUseStrict: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noLib'", "x;", { - options: { compilerOptions: { noLib: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noLib: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'noResolve'", "x;", { - options: { compilerOptions: { noResolve: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { noResolve: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'out'", "x;", { - options: { compilerOptions: { out: "./out" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { out: "./out" }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'outDir'", "x;", { - options: { compilerOptions: { outDir: "./outDir" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { outDir: "./outDir" }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'outFile'", "x;", { - options: { compilerOptions: { outFile: "./outFile" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { outFile: "./outFile" }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'paths'", "x;", { - options: { compilerOptions: { paths: { "*": ["./generated*"] } }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { paths: { "*": ["./generated*"] } }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'preserveConstEnums'", "x;", { - options: { compilerOptions: { preserveConstEnums: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { preserveConstEnums: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'reactNamespace'", "x;", { - options: { compilerOptions: { reactNamespace: "react" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { reactNamespace: "react" }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'removeComments'", "x;", { - options: { compilerOptions: { removeComments: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { removeComments: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'rootDir'", "x;", { - options: { compilerOptions: { rootDir: "./rootDir" }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { rootDir: "./rootDir" }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'rootDirs'", "x;", { - options: { compilerOptions: { rootDirs: ["./a", "./b"] }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { rootDirs: ["./a", "./b"] }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'skipLibCheck'", "x;", { - options: { compilerOptions: { skipLibCheck: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { skipLibCheck: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'skipDefaultLibCheck'", "x;", { - options: { compilerOptions: { skipDefaultLibCheck: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { skipDefaultLibCheck: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'strictNullChecks'", "x;", { - options: { compilerOptions: { strictNullChecks: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { strictNullChecks: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'stripInternal'", "x;", { - options: { compilerOptions: { stripInternal: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { stripInternal: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'suppressExcessPropertyErrors'", "x;", { - options: { compilerOptions: { suppressExcessPropertyErrors: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { suppressExcessPropertyErrors: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'suppressImplicitAnyIndexErrors'", "x;", { - options: { compilerOptions: { suppressImplicitAnyIndexErrors: true }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { suppressImplicitAnyIndexErrors: true }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'target'", "x;", { - options: { compilerOptions: { target: 2 }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { target: 2 }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'types'", "x;", { - options: { compilerOptions: { types: ["jquery", "jasmine"] }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { types: ["jquery", "jasmine"] }, fileName: "input.js", reportDiagnostics: true } }); transpilesCorrectly("Supports setting 'typeRoots'", "x;", { - options: { compilerOptions: { typeRoots: ["./folder"] }, fileName: "input.js", reportDiagnostics: true } + options: { compilerOptions: { typeRoots: ["./folder"] }, fileName: "input.js", reportDiagnostics: true } + }); + + transpilesCorrectly("Correctly serialize metadata when transpile with CommonJS option", + `import * as ng from "angular2/core";` + + `declare function foo(...args: any[]);` + + `@foo` + + `export class MyClass1 {` + + ` constructor(private _elementRef: ng.ElementRef){}` + + `}`, { + options: { + compilerOptions: { + target: ScriptTarget.ES5, + module: ModuleKind.CommonJS, + moduleResolution: ModuleResolutionKind.NodeJs, + emitDecoratorMetadata: true, + experimentalDecorators: true, + isolatedModules: true, + } + } + }); + + transpilesCorrectly("Correctly serialize metadata when transpile with System option", + `import * as ng from "angular2/core";` + + `declare function foo(...args: any[]);` + + `@foo` + + `export class MyClass1 {` + + ` constructor(private _elementRef: ng.ElementRef){}` + + `}`, { + options: { + compilerOptions: { + target: ScriptTarget.ES5, + module: ModuleKind.System, + moduleResolution: ModuleResolutionKind.NodeJs, + emitDecoratorMetadata: true, + experimentalDecorators: true, + isolatedModules: true, + } + } }); }); } diff --git a/tslint.json b/tslint.json index f789af46cea..ee116c6fcb0 100644 --- a/tslint.json +++ b/tslint.json @@ -44,6 +44,7 @@ "type-operator-spacing": true, "prefer-const": true, "no-in-operator": true, - "no-increment-decrement": true + "no-increment-decrement": true, + "object-literal-surrounding-space": true } }