TypeScript/Gulpfile.js

641 lines
27 KiB
TypeScript
Raw Normal View History

/// <reference path="scripts/types/ambient.d.ts" />
// @ts-check
const path = require("path");
const log = require("fancy-log"); // was `require("gulp-util").log (see https://github.com/gulpjs/gulp-util)
const fs = require("fs");
const child_process = require("child_process");
const runSequence = require("run-sequence");
const newer = require("gulp-newer");
const insert = require("gulp-insert");
const { append } = require("gulp-insert");
const sourcemaps = require("gulp-sourcemaps");
const del = require("del");
const fold = require("travis-fold");
const rename = require("gulp-rename");
const mkdirp = require("./scripts/build/mkdirp");
const gulp = require("./scripts/build/gulp");
const getDirSize = require("./scripts/build/getDirSize");
const project = require("./scripts/build/project");
const replace = require("./scripts/build/replace");
const convertConstEnums = require("./scripts/build/convertConstEnum");
const needsUpdate = require("./scripts/build/needsUpdate");
const getDiffTool = require("./scripts/build/getDiffTool");
const baselineAccept = require("./scripts/build/baselineAccept");
const cmdLineOptions = require("./scripts/build/options");
2018-06-19 08:00:30 +02:00
const exec = require("./scripts/build/exec");
const browserify = require("./scripts/build/browserify");
2018-07-10 21:00:30 +02:00
const prepend = require("./scripts/build/prepend");
const { removeSourceMaps } = require("./scripts/build/sourcemaps");
const { CancellationTokenSource, CancelError, delay, Semaphore } = require("prex");
const { libraryTargets, generateLibs } = require("./scripts/build/lib");
const { runConsoleTests, cleanTestDirs, writeTestConfigFile, refBaseline, localBaseline, refRwcBaseline, localRwcBaseline } = require("./scripts/build/tests");
Error.stackTraceLimit = 1000;
// Constants
const host = cmdLineOptions.host;
const copyright = "CopyrightNotice.txt";
project.addTypeScript("lkg", "./lib/typescript.js");
project.addTypeScript("built", "./built/local/typescriptServices.js");
project.addTypeScript("default", "lkg"); // Compile using the LKG compiler by default
const scriptsProject = "scripts/tsconfig.json";
const configurePrereleaseJs = "scripts/configurePrerelease.js";
const processDiagnosticMessagesJs = "scripts/processDiagnosticMessages.js";
const generateLocalizedDiagnosticMessagesJs = "scripts/generateLocalizedDiagnosticMessages.js";
const buildProtocolJs = "scripts/buildProtocol.js";
const produceLKGJs = "scripts/produceLKG.js";
const word2mdJs = "scripts/word2md.js";
2018-07-10 21:00:30 +02:00
const scriptsTaskAliases = [configurePrereleaseJs, processDiagnosticMessagesJs, generateLocalizedDiagnosticMessagesJs, produceLKGJs, buildProtocolJs, word2mdJs];
gulp.task("scripts", /*help*/ false, () => project.compile(scriptsProject), { aliases: scriptsTaskAliases });
gulp.task("clean:scripts", /*help*/ false, () => project.clean(scriptsProject), { aliases: scriptsTaskAliases.map(alias => `clean:${alias}`)});
// Nightly management tasks
gulp.task(
"configure-nightly",
"Runs scripts/configurePrerelease.ts to prepare a build for nightly publishing",
[configurePrereleaseJs],
2018-06-19 08:00:30 +02:00
() => exec(host, [configurePrereleaseJs, "dev", "package.json", "src/compiler/core.ts"]));
gulp.task(
"publish-nightly",
"Runs `npm publish --tag next` to create a new nightly build on npm",
["LKG"],
() => runSequence("clean", "runtests-parallel",
2018-06-19 08:00:30 +02:00
() => exec("npm", ["publish", "--tag", "next"])));
const importDefinitelyTypedTestsProject = "scripts/importDefinitelyTypedTests/tsconfig.json";
const importDefinitelyTypedTestsJs = "scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.js";
gulp.task(importDefinitelyTypedTestsJs, /*help*/ false, () => project.compile(importDefinitelyTypedTestsProject));
2018-07-10 21:00:30 +02:00
gulp.task(`clean:${importDefinitelyTypedTestsJs}`, /*help*/ false, () => project.clean(importDefinitelyTypedTestsProject));
gulp.task(
"importDefinitelyTypedTests",
"Runs scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.ts to copy DT's tests to the TS-internal RWC tests",
[importDefinitelyTypedTestsJs],
2018-06-19 08:00:30 +02:00
() => exec(host, [importDefinitelyTypedTestsJs, "./", "../DefinitelyTyped"]));
gulp.task(
"lib",
"Builds the library targets",
() => generateLibs([copyright]));
// The generated diagnostics map; built for the compiler and for the "generate-diagnostics" task
const diagnosticInformationMapTs = "src/compiler/diagnosticInformationMap.generated.ts";
const diagnosticMessagesJson = "src/compiler/diagnosticMessages.json";
const diagnosticMessagesGeneratedJson = "src/compiler/diagnosticMessages.generated.json";
gulp.task(diagnosticInformationMapTs, /*help*/ false, [processDiagnosticMessagesJs], () => {
if (needsUpdate(diagnosticMessagesJson, [diagnosticMessagesGeneratedJson, diagnosticInformationMapTs])) {
2018-06-19 08:00:30 +02:00
return exec(host, [processDiagnosticMessagesJs, diagnosticMessagesJson]);
}
});
2018-07-10 21:00:30 +02:00
gulp.task(`clean:${diagnosticInformationMapTs}`, /*help*/ false, () => del([diagnosticInformationMapTs, diagnosticMessagesGeneratedJson]));
const builtGeneratedDiagnosticMessagesJson = "built/local/diagnosticMessages.generated.json";
gulp.task(builtGeneratedDiagnosticMessagesJson, /*help*/ false, [diagnosticInformationMapTs], () =>
gulp.src([diagnosticMessagesGeneratedJson], { base: "src/compiler" })
.pipe(newer(builtGeneratedDiagnosticMessagesJson))
.pipe(gulp.dest("built/local")));
gulp.task(
"generate-diagnostics",
"Generates a diagnostic file in TypeScript based on an input JSON file",
[diagnosticInformationMapTs]);
// Localize diagnostics
/**
* .lcg file is what localization team uses to know what messages to localize.
* The file is always generated in 'enu/diagnosticMessages.generated.json.lcg'
*/
const generatedLCGFile = "built/local/enu/diagnosticMessages.generated.json.lcg";
/**
* The localization target produces the two following transformations:
* 1. 'src\loc\lcl\<locale>\diagnosticMessages.generated.json.lcl' => 'built\local\<locale>\diagnosticMessages.generated.json'
* convert localized resources into a .json file the compiler can understand
* 2. 'src\compiler\diagnosticMessages.generated.json' => 'built\local\ENU\diagnosticMessages.generated.json.lcg'
* generate the lcg file (source of messages to localize) from the diagnosticMessages.generated.json
*/
const localizationTargets = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]
.map(f => f.toLowerCase())
.map(f => `built/local/${f}/diagnosticMessages.generated.json`)
.concat(generatedLCGFile);
gulp.task(generatedLCGFile, /*help*/ false, [generateLocalizedDiagnosticMessagesJs, diagnosticInformationMapTs], (done) => {
if (needsUpdate(diagnosticMessagesGeneratedJson, generatedLCGFile)) {
2018-06-19 08:00:30 +02:00
return exec(host, [generateLocalizedDiagnosticMessagesJs, "src/loc/lcl", "built/local", diagnosticMessagesGeneratedJson], { ignoreExitCode: true });
}
});
gulp.task("localize", /*help*/ false, [generatedLCGFile]);
const servicesProject = "src/services/tsconfig.json";
const typescriptServicesProject = "built/local/typescriptServices.tsconfig.json";
gulp.task(typescriptServicesProject, /*help*/ false, () => {
// NOTE: flatten services so that we can properly strip @internal
project.flatten(servicesProject, typescriptServicesProject, {
compilerOptions: {
2018-07-10 21:00:30 +02:00
"removeComments": false,
"stripInternal": true,
"declaration": true,
2018-07-10 21:00:30 +02:00
"outFile": "typescriptServices.out.js" // must align with same task in jakefile. We fix this name below.
}
});
});
const typescriptServicesJs = "built/local/typescriptServices.js";
const typescriptServicesDts = "built/local/typescriptServices.d.ts";
gulp.task(typescriptServicesJs, /*help*/ false, ["lib", "generate-diagnostics", typescriptServicesProject], () =>
2018-07-10 21:00:30 +02:00
project.compile(typescriptServicesProject, {
js: files => files
.pipe(prepend.file(copyright))
.pipe(rename("typescriptServices.js")),
dts: files => files
.pipe(removeSourceMaps())
.pipe(prepend.file(copyright))
.pipe(convertConstEnums())
.pipe(rename("typescriptServices.d.ts"))
}),
{ aliases: [typescriptServicesDts] });
const typescriptJs = "built/local/typescript.js";
gulp.task(typescriptJs, /*help*/ false, [typescriptServicesJs], () =>
gulp.src([typescriptServicesJs], { base: "built/local" })
.pipe(newer(typescriptJs))
.pipe(rename("typescript.js"))
.pipe(gulp.dest("built/local")))
const typescriptDts = "built/local/typescript.d.ts";
gulp.task(typescriptDts, /*help*/ false, [typescriptServicesDts], () =>
gulp.src([typescriptServicesDts], { base: "built/local" })
.pipe(newer(typescriptDts))
.pipe(append("\nexport = ts;"))
.pipe(rename("typescript.d.ts"))
.pipe(gulp.dest("built/local")));
const typescriptStandaloneDts = "built/local/typescript_standalone.d.ts";
gulp.task(typescriptStandaloneDts, /*help*/ false, [typescriptServicesDts], () =>
gulp.src([typescriptServicesDts], { base: "built/local" })
.pipe(newer(typescriptStandaloneDts))
.pipe(replace(/declare (namespace|module) ts/g, 'declare module "typescript"'))
.pipe(rename("typescript_standalone.d.ts"))
.pipe(gulp.dest("built/local")));
// build all 'typescriptServices'-related outputs
gulp.task("services", /*help*/ false, [typescriptServicesJs, typescriptServicesDts, typescriptJs, typescriptDts, typescriptStandaloneDts]);
2018-07-10 21:00:30 +02:00
const useCompiler = cmdLineOptions.lkg ? "lkg" : "built";
const useCompilerDeps = cmdLineOptions.lkg ? ["lib", "generate-diagnostics"] : [typescriptServicesJs];
const tscProject = "src/tsc/tsconfig.json";
const tscJs = "built/local/tsc.js";
2018-07-10 21:00:30 +02:00
gulp.task(tscJs, /*help*/ false, useCompilerDeps, () =>
project.compile(tscProject, {
typescript: useCompiler,
js: files => files.pipe(prepend.file(copyright))
}));
const tscReleaseProject = "src/tsc/tsconfig.release.json";
const tscReleaseJs = "built/local/tsc.release.js";
2018-07-10 21:00:30 +02:00
gulp.task(tscReleaseJs, /*help*/ false, () =>
project.compile(tscReleaseProject, {
js: files => files.pipe(prepend.file(copyright))
}));
const cancellationTokenProject = "src/cancellationToken/tsconfig.json";
const cancellationTokenJs = "built/local/cancellationToken.js";
2018-07-10 21:00:30 +02:00
gulp.task(cancellationTokenJs, /*help*/ false, useCompilerDeps, () => project.compile(cancellationTokenProject, { typescript: useCompiler }));
const typingsInstallerProject = "src/typingsInstaller/tsconfig.json";
const typingsInstallerJs = "built/local/typingsInstaller.js";
2018-07-10 21:00:30 +02:00
gulp.task(typingsInstallerJs, /*help*/ false, useCompilerDeps, () => project.compile(typingsInstallerProject, { typescript: useCompiler }));
const tsserverProject = "src/tsserver/tsconfig.json";
const tsserverJs = "built/local/tsserver.js";
2018-07-10 21:00:30 +02:00
gulp.task(tsserverJs, /*help*/ false, useCompilerDeps, () => project.compile(tsserverProject, { typescript: useCompiler }));
2019-01-25 19:52:00 +01:00
gulp.task(
"tsserver",
"Builds the language server",
[tsserverJs]);
const watchGuardProject = "src/watchGuard/tsconfig.json";
const watchGuardJs = "built/local/watchGuard.js";
2018-07-10 21:00:30 +02:00
gulp.task(watchGuardJs, /*help*/ false, useCompilerDeps, () => project.compile(watchGuardProject, { typescript: useCompiler }));
const typesMapJson = "built/local/typesMap.json";
gulp.task(typesMapJson, /*help*/ false, [], () =>
gulp.src("src/server/typesMap.json")
.pipe(newer(typesMapJson))
.pipe(insert.transform(contents => (JSON.parse(contents), contents)))
.pipe(gulp.dest("built/local")));
const tsserverlibraryProject = "built/local/tsserverlibrary.tsconfig.json";
gulp.task(tsserverlibraryProject, /*help*/ false, () => {
// NOTE: flatten tsserverlibrary so that we can properly strip @internal
project.flatten("src/tsserver/tsconfig.json", tsserverlibraryProject, {
exclude: ["src/tsserver/server.ts"],
compilerOptions: {
2018-07-10 21:00:30 +02:00
"removeComments": false,
"stripInternal": true,
2018-07-10 21:00:30 +02:00
"declarationMap": false,
"outFile": "tsserverlibrary.out.js" // must align with same task in jakefile. We fix this name below.
}
});
});
const tsserverlibraryJs = "built/local/tsserverlibrary.js";
const tsserverlibraryDts = "built/local/tsserverlibrary.d.ts";
2018-07-10 21:00:30 +02:00
gulp.task(tsserverlibraryJs, /*help*/ false, useCompilerDeps.concat([tsserverlibraryProject]), () =>
project.compile(tsserverlibraryProject, {
2018-07-10 21:00:30 +02:00
js: files => files
.pipe(prepend.file(copyright))
.pipe(rename("tsserverlibrary.js")),
dts: files => files
2018-07-10 21:00:30 +02:00
.pipe(removeSourceMaps())
.pipe(prepend.file(copyright))
.pipe(convertConstEnums())
2018-07-10 21:00:30 +02:00
.pipe(append("\nexport = ts;\nexport as namespace ts;"))
.pipe(rename("tsserverlibrary.d.ts")),
typescript: useCompiler
}), { aliases: [tsserverlibraryDts] });
gulp.task(
"lssl",
"Builds language service server library",
[tsserverlibraryDts]);
gulp.task(
"local",
"Builds the full compiler and services",
[tscJs, "services", tsserverJs, builtGeneratedDiagnosticMessagesJson, tsserverlibraryDts, "localize"]);
gulp.task(
"tsc",
"Builds only the compiler",
[tscJs]);
// Generate Markdown spec
const specMd = "doc/spec.md";
gulp.task(specMd, /*help*/ false, [word2mdJs], () =>
exec("cscript", ["//nologo", word2mdJs, path.resolve("doc/TypeScript Language Specification.docx"), path.resolve(specMd)]));
gulp.task(
"generate-spec",
"Generates a Markdown version of the Language Specification",
[specMd]);
gulp.task("produce-LKG", /*help*/ false, ["scripts", "local", cancellationTokenJs, typingsInstallerJs, watchGuardJs, tscReleaseJs], () => {
const expectedFiles = [
tscReleaseJs,
typescriptServicesJs,
tsserverJs,
typescriptJs,
typescriptDts,
typescriptServicesDts,
tsserverlibraryDts,
tsserverlibraryDts,
typingsInstallerJs,
cancellationTokenJs
].concat(libraryTargets);
const missingFiles = expectedFiles
.concat(localizationTargets)
.filter(f => !fs.existsSync(f));
if (missingFiles.length > 0) {
throw new Error("Cannot replace the LKG unless all built targets are present in directory 'built/local/'. The following files are missing:\n" + missingFiles.join("\n"));
}
const sizeBefore = getDirSize("lib");
return exec(host, [produceLKGJs]).then(() => {
const sizeAfter = getDirSize("lib");
if (sizeAfter > (sizeBefore * 1.10)) {
throw new Error("The lib folder increased by 10% or more. This likely indicates a bug.");
}
});
});
gulp.task(
"LKG",
"Makes a new LKG out of the built js files",
() => runSequence("clean-built", "produce-LKG"));
// Task to build the tests infrastructure using the built compiler
const testRunnerProject = "src/testRunner/tsconfig.json";
const runJs = "built/local/run.js";
2018-07-10 21:00:30 +02:00
gulp.task(runJs, /*help*/ false, useCompilerDeps, () => project.compile(testRunnerProject, { typescript: useCompiler }));
gulp.task(
"tests",
"Builds the test infrastructure using the built compiler",
2018-07-10 21:00:30 +02:00
[runJs, tsserverlibraryDts]);
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.",
2018-07-10 21:00:30 +02:00
["build-rules", "tests", "services", tsserverlibraryDts],
() => runConsoleTests(runJs, "min", /*runInParallel*/ true, /*watchMode*/ false));
gulp.task(
"runtests",
"Runs the tests using the built run.js file. Optional arguments are: --t[ests]=regex --r[eporter]=[list|spec|json|<more>] --d[ebug]=true --color[s]=false --lint=true.",
2018-07-10 21:00:30 +02:00
["build-rules", "tests", "services", tsserverlibraryDts],
() => runConsoleTests(runJs, "mocha-fivemat-progress-reporter", /*runInParallel*/ false, /*watchMode*/ false));
const webTestServerProject = "tests/webTestServer.tsconfig.json";
const webTestServerJs = "tests/webTestServer.js";
2018-07-10 21:00:30 +02:00
gulp.task(webTestServerJs, /*help*/ false, useCompilerDeps, () => project.compile(webTestServerProject, { typescript: useCompiler }));
gulp.task(`clean:${webTestServerJs}`, /*help*/ false, () => project.clean(webTestServerProject));
[Release-2.0] Merge master into Release-2.0 (#10347) * Change getUnionType to default to no subtype reduction * Remove unnecessary subtype reduction operations * Use binary searching in union types to improve performance * Optimize type inference * Fixed broken singleAsteriskRegex. Fixes #9918 (#9920) * Lock ts-node to 1.1.0 while perf issue is investigated (#9933) * Fix typo in comment for MAX_SAFE_INTEGER * In ts.performance.now, bind window.performance.now Using an arrow function. Previously, it was set directly to window.performance.now, which fails when used on Chrome. * Add lint enforcing line endings (#9942) * Add servicesSources to the list of prerequisites for running tests * Support emitting static properties for classes with no name * Add assertion whitespace lint rule (#9931) * Add assertion whitespace lint rule * Fix typo * Add the word `Rule` to Jakefile * Limit travis build matrix (#9968) * Convert getErrorBaseline to use canonical diagnostic formatting (#9708) * Convert getErrorBaseline to use canonical diagnostic formatting * Fix lint * Found another clone of format diagnostic - consolidate * Fully declone * Unify nodeKind implementations for navigationBar and navigateTo * Fix test and rename a function * Fix lint errors * Remove hardcoded port, use the custom port * Unlock ts-node version (#9960) * Allow an abstract class to appear in a local scope * JSDoc understands string literal types Unfortunately, I didn't find a way to reuse the normal string literal type, so I had to extend the existing JSDoc type hierarchy. Otherwise, this feature is very simple. * Update baselines to be current * Add find and findIndex to ReadonlyArray * The optional this should be readonly too. * Update baseline source location * Re-add concat overload to support inferring tuples * Update baselines with new concat overload * Update LastJSDoc[Tag]Node * Display enum member types using qualified names * Accept new baselines * Fix lint error * null/undefined are allowed as index expressions `null` and `undefined` are not allowed with `--strictNullChecks` turned on. Previously, they were disallowed whether or not it was on. * Use correct nullable terminology * Get rid of port parameter * Remove [port] in usage message * Properly reset type guards in loops * Add regression test * Introduce the `EntityNameExpression` type * Allow `export =` and `export default` to alias any EntityNameExpression, not just identifiers. * Lint tests helper files * recreate program if baseUrl or paths changed in tsconfig * Simplify some code * Have travis use a newer image for the OSX build (#10034) Suggested by travis support for stopping the randomly-halting-builds issue. * Correctly check for ambient class flag * Use "best choice type" for || and ?: operators * jsx opening element formatting * change error message for unused parameter property fix * Fix issue related to this and #8383 * Add additional tests * Accept new baselines * Provide `realpath` for module resolution in LSHost * Add test * Add test baselines * Accept new baselines * CR feedback * Remove `SupportedExpressionWithTypeArguments` type; just check that the expression of each `ExpressionWithTypeArguments` is an `EntityNameExpression`. * Fix bug * Fix #10083 - allowSyntheticDefaultImports alters getExternalModuleMember (#10096) * Use recursion, and fix error for undefined node * Rename function * Fix lint error * Narrowing type parameter intersects w/narrowed types This makes sure that a union type that includes a type parameter is still usable as the actual type that the type guard narrows to. * Add a helper function `getOrUpdateProperty` to prevent unprotected access to Maps. * Limit type guards as assertions to incomplete types in loops * Accept new baselines * Fix linting error * Allow JS multiple declarations of ctor properties When a property is declared in the constructor and on the prototype of an ES6 class, the property's symbol is discarded in favour of the method's symbol. That because the usual use for this pattern is to bind an instance function: `this.m = this.m.bind(this)`. In this case the type you want really is the method's type. * Use {} type facts for unconstrained type params Previously it was using TypeFacts.All. But the constraint of an unconstrained type parameter is actually {}. * Fix newline lint * Test that declares conflicting method first * [Release-2.0] Fix 9662: Visual Studio 2015 with TS2.0 gives incorrect @types path resolution errors (#9867) * Change the shape of the shim layer to support getAutomaticTypeDirectives * Change the key for looking up automatic type-directives * Update baselines from change look-up name of type-directives * Add @currentDirectory into the test * Update baselines * Fix linting error * Address PR: fix spelling mistake * Instead of return path of the type directive names just return type directive names * Remove unused reference files: these tests produce erros so they will not produce these files (#9233) * Add string-literal completion test for jsdoc * Support other (new) literal types in jsdoc * Don't allow properties inherited from Object to be automatically included in TSX attributes * Add new test baseline and delete else in binder The extra `else` caused a ton of test failures! * Fix lint * Port PR #10016 to Master (#10100) * Treat namespaceExportDeclaration as declaration * Update baselines * wip - add tests * Add tests * Show "export namespace" for quick-info * Fix more lint * Try using runtests-parallel for CI (#9970) * Try using runtests-parallel for CI * Put worker count setting into .travis.yml * Reduce worker count to 4 - 8 wasnt much different from 4-6 but had contention issues causing timeouts * Fix lssl task (#9967) * Surface noErrorTruncation option * Stricter check for discriminant properties in type guards * Add tests * Emit more efficient/concise "empty" ES6 ctor When there are property assignments in a the class body of an inheriting class, tsc current emit the following compilation: ```ts class Foo extends Bar { public foo = 1; } ``` ```js class Foo extends Bar { constructor(…args) { super(…args); this.foo = 1; } } ``` This introduces an unneeded local variable and might force a reification of the `arguments` object (or otherwise reify the arguments into an array). This is particularly bad when that output is fed into another transpiler like Babel. In Babel, you get something like this today: ```js var Foo = (function (_Bar) { _inherits(Foo, _Bar); function Foo() { _classCallCheck(this, Foo); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _Bar.call.apply(_Bar, [this].concat(args)); this.foo = 1; } return Foo; })(Bar); ``` This causes a lot of needless work/allocations and some very strange code (`.call.apply` o_0). Admittedly, this is not strictly tsc’s problem; it could have done a deeper analysis of the code and optimized out the extra dance. However, tsc could also have emitted this simpler, more concise and semantically equivalent code in the first place: ```js class Foo extends Bar { constructor() { super(…arguments); this.foo = 1; } } ``` Which compiles into the following in Babel: ```js var Foo = (function (_Bar) { _inherits(Foo, _Bar); function Foo() { _classCallCheck(this, Foo); _Bar.apply(this, arguments); this.foo = 1; } return Foo; })(Bar); ``` Which is well-optimized (today) in most engines and much less confusing to read. As far as I can tell, the proposed compilation has exactly the same semantics as before. Fixes #10175 * Fix instanceof operator narrowing issues * Accept new baselines * Add regression test * Improve naming and documentation from PR * Update comment * Add more tests * Accept new baselines * Reduce worker count to 3 (#10210) Since we saw a starvation issue on one of @sandersn's PRs. * Speed up fourslash tests * Duh * Make baselines faster by not writing out unneeded files * Fix non-strict-compliant test * Fix 10076: Fix Tuple Destructing with "this" (#10208) * Call checkExpression eventhough there is no appropriate type from destructuring of array * Add tests and baselines * use transpileModule * Remove use strict * Improve instanceof for structurally identical types * Introduce isTypeInstanceOf function * Add test * Accept new baselines * Fix loop over array to use for-of instead of for-in * Use correct this in tuple type parameter constraints Instantiate this in tuple types used as type parameter constraints * Add explanatory comment to resolveTupleTypeMembers * Ignore null, undefined, void when checking for discriminant property * Add regression test * Delay tuple type constraint resolution Create a new tuple that stores the this-type. * Always use thisType when generating tuple id * Optimize format of type list id strings used in maps * Make ReadonlyArray iterable. * Allow OSX to fail while we investigate (#10255) The random test timeouts are an issue. * avoid using the global name * Fix single-quote lint * Optimize performance of maps * Update API sample * Fix processDiagnosticMessages script * Have travis take shallow clones of the repo (#10275) Just cloning TS on travis takes 23 seconds on linux (68 seconds on mac), hopefully having it do a shallow clone will help. We don't rely on any tagging/artifacts from the travis servers which clone depth could impact, so this shouldn't impact anything other than build speed. * Add folds to travis log (#10269) * Optimize filterType to only call getUnionType if necessary * Add shorthand types declaration for travis-fold (#10293) * Optimize getTypeWithFacts * Filter out nullable and primitive types in isDiscriminantProperty * Fix typo * Add regression tests * Optimize core filter function to only allocate when necessary * Address CR comments + more optimizations * Faster path for creating union types from filterType * Allow an @types direcotry to have a package.json which specifies `"typings": null` to disclude it from automatically included typings. * Lint * Collect timing information for commands running on travis (#10308) * Simplifies performance API * Use 'MapLike' instead of 'Map' in 'preferConstRule.ts'. * narrow from 'any' in most situations instanceof and user-defined typeguards narrow from 'any' unless the narrowed-to type is exactly 'Object' or 'Function'. This is a breaking change. * Update instanceof conformance tests * accept new baselines * add tests * accept new baselines * Use lowercase names for type reference directives * Use proper response codes in web tests * Treat ambient shorthand declarations as explicit uses of the `any` type * Parallel linting (#10313) * A perilous thing, a parallel lint * Use work queue rather than scheduling work * Dont read files for lint on main thread * Fix style * Fix the style fix (#10344) * Aligned mark names with values used by ts-perf. * Use an enum in checkClassForDuplicateDeclarations to aid readability * Rename to Accessor * Correctly update package.json version * Migrated more MapLikes to Maps * Add ES2015 Date constructor signature that accepts another Date (#10353) * Parameters with no assignments implicitly considered const * Add tests * Migrate additional MapLikes to Maps. * Fix 10625: JSX Not validating when index signature is present (#10352) * Check for type of property declaration before using index signature * Add tests and baselines * fix linting error * Adding more comments * Clean up/move some Map helper functions. * Revert some formatting changes. * Improve ReadonlyArray<T>.concat to match Array<T> The Array-based signature was incorrect and also out-of-date. * Fix link to blog * Remove old assertion about when we're allowed to use fileExists * Set isNewIdentifierLocation to true for JavaScript files * Update error message for conflicting type definitions Fixes #10370 * Explain why we lower-case type reference directives * Correctly merge bindThisPropertyAssignment Also simply it considerably after noticing that it's *only* called for Javascript files, so there was a lot of dead code for TS cases that never happened. * Fix comment * Property handle imcomplete control flow types in nested loops * Update due to CR suggestion * Add regression test * Fix 10289: correctly generate tsconfig.json with --lib (#10355) * Separate generate tsconfig into its own function and implement init with --lib # Conflicts: # src/compiler/tsc.ts * Add tests and baselines; Update function name Add unittests and baselines Add unittests and baselines for generating tsconfig Move unittest into harness folder Update harness tsconfig.json USe correct function name * Use new MapLike interstead. Update unittest # Conflicts: # src/compiler/commandLineParser.ts * Update JakeFile * Add tests for incorrect cases * Address PR : remove explicity write node_modules * Add more tests for `export = foo.bar`. * Output test baselines to tests/baselines/local instead of root
2016-08-18 23:49:09 +02:00
const bundlePath = path.resolve("built/local/bundle.js");
gulp.task(
"browserify",
"Runs browserify on run.js to produce a file suitable for running tests in the browser",
[runJs],
() => gulp.src([runJs], { base: "built/local" })
.pipe(newer(bundlePath))
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(browserify())
.pipe(rename("bundle.js"))
.pipe(sourcemaps.write(".", /**@type {*}*/({ includeContent: false, destPath: "built/local" })))
.pipe(gulp.dest("built/local")));
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], --browser=[chrome|IE]",
["browserify", webTestServerJs],
() => cleanTestDirs().then(() => {
const tests = cmdLineOptions.tests;
const runners = cmdLineOptions.runners;
const light = cmdLineOptions.light;
const testConfigFile = "test.config";
if (fs.existsSync(testConfigFile)) {
fs.unlinkSync(testConfigFile);
}
if (tests || runners || light) {
writeTestConfigFile(tests, runners, light);
}
const args = [webTestServerJs];
if (cmdLineOptions.browser) {
args.push(cmdLineOptions.browser);
}
if (tests) {
args.push(JSON.stringify(tests));
}
2018-06-19 08:00:30 +02:00
return exec("node", args);
}));
gulp.task(
"generate-code-coverage",
"Generates code coverage data via istanbul",
["tests"],
2018-06-19 08:00:30 +02:00
() => exec("istanbul", ["cover", "node_modules/mocha/bin/_mocha", "--", "-R", "min", "-t", "" + cmdLineOptions.testTimeout, runJs]));
gulp.task(
"diff",
"Diffs the compiler baselines using the diff tool specified by the 'DIFF' environment variable",
2018-06-19 08:00:30 +02:00
() => exec(getDiffTool(), [refBaseline, localBaseline], { ignoreExitCode: true }));
gulp.task(
"diff-rwc",
"Diffs the RWC baselines using the diff tool specified by the 'DIFF' environment variable",
2018-06-19 08:00:30 +02:00
() => exec(getDiffTool(), [refRwcBaseline, localRwcBaseline], { ignoreExitCode: true }));
[Release-2.0] Merge master into Release-2.0 (#10347) * Change getUnionType to default to no subtype reduction * Remove unnecessary subtype reduction operations * Use binary searching in union types to improve performance * Optimize type inference * Fixed broken singleAsteriskRegex. Fixes #9918 (#9920) * Lock ts-node to 1.1.0 while perf issue is investigated (#9933) * Fix typo in comment for MAX_SAFE_INTEGER * In ts.performance.now, bind window.performance.now Using an arrow function. Previously, it was set directly to window.performance.now, which fails when used on Chrome. * Add lint enforcing line endings (#9942) * Add servicesSources to the list of prerequisites for running tests * Support emitting static properties for classes with no name * Add assertion whitespace lint rule (#9931) * Add assertion whitespace lint rule * Fix typo * Add the word `Rule` to Jakefile * Limit travis build matrix (#9968) * Convert getErrorBaseline to use canonical diagnostic formatting (#9708) * Convert getErrorBaseline to use canonical diagnostic formatting * Fix lint * Found another clone of format diagnostic - consolidate * Fully declone * Unify nodeKind implementations for navigationBar and navigateTo * Fix test and rename a function * Fix lint errors * Remove hardcoded port, use the custom port * Unlock ts-node version (#9960) * Allow an abstract class to appear in a local scope * JSDoc understands string literal types Unfortunately, I didn't find a way to reuse the normal string literal type, so I had to extend the existing JSDoc type hierarchy. Otherwise, this feature is very simple. * Update baselines to be current * Add find and findIndex to ReadonlyArray * The optional this should be readonly too. * Update baseline source location * Re-add concat overload to support inferring tuples * Update baselines with new concat overload * Update LastJSDoc[Tag]Node * Display enum member types using qualified names * Accept new baselines * Fix lint error * null/undefined are allowed as index expressions `null` and `undefined` are not allowed with `--strictNullChecks` turned on. Previously, they were disallowed whether or not it was on. * Use correct nullable terminology * Get rid of port parameter * Remove [port] in usage message * Properly reset type guards in loops * Add regression test * Introduce the `EntityNameExpression` type * Allow `export =` and `export default` to alias any EntityNameExpression, not just identifiers. * Lint tests helper files * recreate program if baseUrl or paths changed in tsconfig * Simplify some code * Have travis use a newer image for the OSX build (#10034) Suggested by travis support for stopping the randomly-halting-builds issue. * Correctly check for ambient class flag * Use "best choice type" for || and ?: operators * jsx opening element formatting * change error message for unused parameter property fix * Fix issue related to this and #8383 * Add additional tests * Accept new baselines * Provide `realpath` for module resolution in LSHost * Add test * Add test baselines * Accept new baselines * CR feedback * Remove `SupportedExpressionWithTypeArguments` type; just check that the expression of each `ExpressionWithTypeArguments` is an `EntityNameExpression`. * Fix bug * Fix #10083 - allowSyntheticDefaultImports alters getExternalModuleMember (#10096) * Use recursion, and fix error for undefined node * Rename function * Fix lint error * Narrowing type parameter intersects w/narrowed types This makes sure that a union type that includes a type parameter is still usable as the actual type that the type guard narrows to. * Add a helper function `getOrUpdateProperty` to prevent unprotected access to Maps. * Limit type guards as assertions to incomplete types in loops * Accept new baselines * Fix linting error * Allow JS multiple declarations of ctor properties When a property is declared in the constructor and on the prototype of an ES6 class, the property's symbol is discarded in favour of the method's symbol. That because the usual use for this pattern is to bind an instance function: `this.m = this.m.bind(this)`. In this case the type you want really is the method's type. * Use {} type facts for unconstrained type params Previously it was using TypeFacts.All. But the constraint of an unconstrained type parameter is actually {}. * Fix newline lint * Test that declares conflicting method first * [Release-2.0] Fix 9662: Visual Studio 2015 with TS2.0 gives incorrect @types path resolution errors (#9867) * Change the shape of the shim layer to support getAutomaticTypeDirectives * Change the key for looking up automatic type-directives * Update baselines from change look-up name of type-directives * Add @currentDirectory into the test * Update baselines * Fix linting error * Address PR: fix spelling mistake * Instead of return path of the type directive names just return type directive names * Remove unused reference files: these tests produce erros so they will not produce these files (#9233) * Add string-literal completion test for jsdoc * Support other (new) literal types in jsdoc * Don't allow properties inherited from Object to be automatically included in TSX attributes * Add new test baseline and delete else in binder The extra `else` caused a ton of test failures! * Fix lint * Port PR #10016 to Master (#10100) * Treat namespaceExportDeclaration as declaration * Update baselines * wip - add tests * Add tests * Show "export namespace" for quick-info * Fix more lint * Try using runtests-parallel for CI (#9970) * Try using runtests-parallel for CI * Put worker count setting into .travis.yml * Reduce worker count to 4 - 8 wasnt much different from 4-6 but had contention issues causing timeouts * Fix lssl task (#9967) * Surface noErrorTruncation option * Stricter check for discriminant properties in type guards * Add tests * Emit more efficient/concise "empty" ES6 ctor When there are property assignments in a the class body of an inheriting class, tsc current emit the following compilation: ```ts class Foo extends Bar { public foo = 1; } ``` ```js class Foo extends Bar { constructor(…args) { super(…args); this.foo = 1; } } ``` This introduces an unneeded local variable and might force a reification of the `arguments` object (or otherwise reify the arguments into an array). This is particularly bad when that output is fed into another transpiler like Babel. In Babel, you get something like this today: ```js var Foo = (function (_Bar) { _inherits(Foo, _Bar); function Foo() { _classCallCheck(this, Foo); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _Bar.call.apply(_Bar, [this].concat(args)); this.foo = 1; } return Foo; })(Bar); ``` This causes a lot of needless work/allocations and some very strange code (`.call.apply` o_0). Admittedly, this is not strictly tsc’s problem; it could have done a deeper analysis of the code and optimized out the extra dance. However, tsc could also have emitted this simpler, more concise and semantically equivalent code in the first place: ```js class Foo extends Bar { constructor() { super(…arguments); this.foo = 1; } } ``` Which compiles into the following in Babel: ```js var Foo = (function (_Bar) { _inherits(Foo, _Bar); function Foo() { _classCallCheck(this, Foo); _Bar.apply(this, arguments); this.foo = 1; } return Foo; })(Bar); ``` Which is well-optimized (today) in most engines and much less confusing to read. As far as I can tell, the proposed compilation has exactly the same semantics as before. Fixes #10175 * Fix instanceof operator narrowing issues * Accept new baselines * Add regression test * Improve naming and documentation from PR * Update comment * Add more tests * Accept new baselines * Reduce worker count to 3 (#10210) Since we saw a starvation issue on one of @sandersn's PRs. * Speed up fourslash tests * Duh * Make baselines faster by not writing out unneeded files * Fix non-strict-compliant test * Fix 10076: Fix Tuple Destructing with "this" (#10208) * Call checkExpression eventhough there is no appropriate type from destructuring of array * Add tests and baselines * use transpileModule * Remove use strict * Improve instanceof for structurally identical types * Introduce isTypeInstanceOf function * Add test * Accept new baselines * Fix loop over array to use for-of instead of for-in * Use correct this in tuple type parameter constraints Instantiate this in tuple types used as type parameter constraints * Add explanatory comment to resolveTupleTypeMembers * Ignore null, undefined, void when checking for discriminant property * Add regression test * Delay tuple type constraint resolution Create a new tuple that stores the this-type. * Always use thisType when generating tuple id * Optimize format of type list id strings used in maps * Make ReadonlyArray iterable. * Allow OSX to fail while we investigate (#10255) The random test timeouts are an issue. * avoid using the global name * Fix single-quote lint * Optimize performance of maps * Update API sample * Fix processDiagnosticMessages script * Have travis take shallow clones of the repo (#10275) Just cloning TS on travis takes 23 seconds on linux (68 seconds on mac), hopefully having it do a shallow clone will help. We don't rely on any tagging/artifacts from the travis servers which clone depth could impact, so this shouldn't impact anything other than build speed. * Add folds to travis log (#10269) * Optimize filterType to only call getUnionType if necessary * Add shorthand types declaration for travis-fold (#10293) * Optimize getTypeWithFacts * Filter out nullable and primitive types in isDiscriminantProperty * Fix typo * Add regression tests * Optimize core filter function to only allocate when necessary * Address CR comments + more optimizations * Faster path for creating union types from filterType * Allow an @types direcotry to have a package.json which specifies `"typings": null` to disclude it from automatically included typings. * Lint * Collect timing information for commands running on travis (#10308) * Simplifies performance API * Use 'MapLike' instead of 'Map' in 'preferConstRule.ts'. * narrow from 'any' in most situations instanceof and user-defined typeguards narrow from 'any' unless the narrowed-to type is exactly 'Object' or 'Function'. This is a breaking change. * Update instanceof conformance tests * accept new baselines * add tests * accept new baselines * Use lowercase names for type reference directives * Use proper response codes in web tests * Treat ambient shorthand declarations as explicit uses of the `any` type * Parallel linting (#10313) * A perilous thing, a parallel lint * Use work queue rather than scheduling work * Dont read files for lint on main thread * Fix style * Fix the style fix (#10344) * Aligned mark names with values used by ts-perf. * Use an enum in checkClassForDuplicateDeclarations to aid readability * Rename to Accessor * Correctly update package.json version * Migrated more MapLikes to Maps * Add ES2015 Date constructor signature that accepts another Date (#10353) * Parameters with no assignments implicitly considered const * Add tests * Migrate additional MapLikes to Maps. * Fix 10625: JSX Not validating when index signature is present (#10352) * Check for type of property declaration before using index signature * Add tests and baselines * fix linting error * Adding more comments * Clean up/move some Map helper functions. * Revert some formatting changes. * Improve ReadonlyArray<T>.concat to match Array<T> The Array-based signature was incorrect and also out-of-date. * Fix link to blog * Remove old assertion about when we're allowed to use fileExists * Set isNewIdentifierLocation to true for JavaScript files * Update error message for conflicting type definitions Fixes #10370 * Explain why we lower-case type reference directives * Correctly merge bindThisPropertyAssignment Also simply it considerably after noticing that it's *only* called for Javascript files, so there was a lot of dead code for TS cases that never happened. * Fix comment * Property handle imcomplete control flow types in nested loops * Update due to CR suggestion * Add regression test * Fix 10289: correctly generate tsconfig.json with --lib (#10355) * Separate generate tsconfig into its own function and implement init with --lib # Conflicts: # src/compiler/tsc.ts * Add tests and baselines; Update function name Add unittests and baselines Add unittests and baselines for generating tsconfig Move unittest into harness folder Update harness tsconfig.json USe correct function name * Use new MapLike interstead. Update unittest # Conflicts: # src/compiler/commandLineParser.ts * Update JakeFile * Add tests for incorrect cases * Address PR : remove explicity write node_modules * Add more tests for `export = foo.bar`. * Output test baselines to tests/baselines/local instead of root
2016-08-18 23:49:09 +02:00
gulp.task(
"baseline-accept",
"Makes the most recent test results the new baseline, overwriting the old baseline",
() => baselineAccept());
[Release-2.0] Merge master into Release-2.0 (#10347) * Change getUnionType to default to no subtype reduction * Remove unnecessary subtype reduction operations * Use binary searching in union types to improve performance * Optimize type inference * Fixed broken singleAsteriskRegex. Fixes #9918 (#9920) * Lock ts-node to 1.1.0 while perf issue is investigated (#9933) * Fix typo in comment for MAX_SAFE_INTEGER * In ts.performance.now, bind window.performance.now Using an arrow function. Previously, it was set directly to window.performance.now, which fails when used on Chrome. * Add lint enforcing line endings (#9942) * Add servicesSources to the list of prerequisites for running tests * Support emitting static properties for classes with no name * Add assertion whitespace lint rule (#9931) * Add assertion whitespace lint rule * Fix typo * Add the word `Rule` to Jakefile * Limit travis build matrix (#9968) * Convert getErrorBaseline to use canonical diagnostic formatting (#9708) * Convert getErrorBaseline to use canonical diagnostic formatting * Fix lint * Found another clone of format diagnostic - consolidate * Fully declone * Unify nodeKind implementations for navigationBar and navigateTo * Fix test and rename a function * Fix lint errors * Remove hardcoded port, use the custom port * Unlock ts-node version (#9960) * Allow an abstract class to appear in a local scope * JSDoc understands string literal types Unfortunately, I didn't find a way to reuse the normal string literal type, so I had to extend the existing JSDoc type hierarchy. Otherwise, this feature is very simple. * Update baselines to be current * Add find and findIndex to ReadonlyArray * The optional this should be readonly too. * Update baseline source location * Re-add concat overload to support inferring tuples * Update baselines with new concat overload * Update LastJSDoc[Tag]Node * Display enum member types using qualified names * Accept new baselines * Fix lint error * null/undefined are allowed as index expressions `null` and `undefined` are not allowed with `--strictNullChecks` turned on. Previously, they were disallowed whether or not it was on. * Use correct nullable terminology * Get rid of port parameter * Remove [port] in usage message * Properly reset type guards in loops * Add regression test * Introduce the `EntityNameExpression` type * Allow `export =` and `export default` to alias any EntityNameExpression, not just identifiers. * Lint tests helper files * recreate program if baseUrl or paths changed in tsconfig * Simplify some code * Have travis use a newer image for the OSX build (#10034) Suggested by travis support for stopping the randomly-halting-builds issue. * Correctly check for ambient class flag * Use "best choice type" for || and ?: operators * jsx opening element formatting * change error message for unused parameter property fix * Fix issue related to this and #8383 * Add additional tests * Accept new baselines * Provide `realpath` for module resolution in LSHost * Add test * Add test baselines * Accept new baselines * CR feedback * Remove `SupportedExpressionWithTypeArguments` type; just check that the expression of each `ExpressionWithTypeArguments` is an `EntityNameExpression`. * Fix bug * Fix #10083 - allowSyntheticDefaultImports alters getExternalModuleMember (#10096) * Use recursion, and fix error for undefined node * Rename function * Fix lint error * Narrowing type parameter intersects w/narrowed types This makes sure that a union type that includes a type parameter is still usable as the actual type that the type guard narrows to. * Add a helper function `getOrUpdateProperty` to prevent unprotected access to Maps. * Limit type guards as assertions to incomplete types in loops * Accept new baselines * Fix linting error * Allow JS multiple declarations of ctor properties When a property is declared in the constructor and on the prototype of an ES6 class, the property's symbol is discarded in favour of the method's symbol. That because the usual use for this pattern is to bind an instance function: `this.m = this.m.bind(this)`. In this case the type you want really is the method's type. * Use {} type facts for unconstrained type params Previously it was using TypeFacts.All. But the constraint of an unconstrained type parameter is actually {}. * Fix newline lint * Test that declares conflicting method first * [Release-2.0] Fix 9662: Visual Studio 2015 with TS2.0 gives incorrect @types path resolution errors (#9867) * Change the shape of the shim layer to support getAutomaticTypeDirectives * Change the key for looking up automatic type-directives * Update baselines from change look-up name of type-directives * Add @currentDirectory into the test * Update baselines * Fix linting error * Address PR: fix spelling mistake * Instead of return path of the type directive names just return type directive names * Remove unused reference files: these tests produce erros so they will not produce these files (#9233) * Add string-literal completion test for jsdoc * Support other (new) literal types in jsdoc * Don't allow properties inherited from Object to be automatically included in TSX attributes * Add new test baseline and delete else in binder The extra `else` caused a ton of test failures! * Fix lint * Port PR #10016 to Master (#10100) * Treat namespaceExportDeclaration as declaration * Update baselines * wip - add tests * Add tests * Show "export namespace" for quick-info * Fix more lint * Try using runtests-parallel for CI (#9970) * Try using runtests-parallel for CI * Put worker count setting into .travis.yml * Reduce worker count to 4 - 8 wasnt much different from 4-6 but had contention issues causing timeouts * Fix lssl task (#9967) * Surface noErrorTruncation option * Stricter check for discriminant properties in type guards * Add tests * Emit more efficient/concise "empty" ES6 ctor When there are property assignments in a the class body of an inheriting class, tsc current emit the following compilation: ```ts class Foo extends Bar { public foo = 1; } ``` ```js class Foo extends Bar { constructor(…args) { super(…args); this.foo = 1; } } ``` This introduces an unneeded local variable and might force a reification of the `arguments` object (or otherwise reify the arguments into an array). This is particularly bad when that output is fed into another transpiler like Babel. In Babel, you get something like this today: ```js var Foo = (function (_Bar) { _inherits(Foo, _Bar); function Foo() { _classCallCheck(this, Foo); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _Bar.call.apply(_Bar, [this].concat(args)); this.foo = 1; } return Foo; })(Bar); ``` This causes a lot of needless work/allocations and some very strange code (`.call.apply` o_0). Admittedly, this is not strictly tsc’s problem; it could have done a deeper analysis of the code and optimized out the extra dance. However, tsc could also have emitted this simpler, more concise and semantically equivalent code in the first place: ```js class Foo extends Bar { constructor() { super(…arguments); this.foo = 1; } } ``` Which compiles into the following in Babel: ```js var Foo = (function (_Bar) { _inherits(Foo, _Bar); function Foo() { _classCallCheck(this, Foo); _Bar.apply(this, arguments); this.foo = 1; } return Foo; })(Bar); ``` Which is well-optimized (today) in most engines and much less confusing to read. As far as I can tell, the proposed compilation has exactly the same semantics as before. Fixes #10175 * Fix instanceof operator narrowing issues * Accept new baselines * Add regression test * Improve naming and documentation from PR * Update comment * Add more tests * Accept new baselines * Reduce worker count to 3 (#10210) Since we saw a starvation issue on one of @sandersn's PRs. * Speed up fourslash tests * Duh * Make baselines faster by not writing out unneeded files * Fix non-strict-compliant test * Fix 10076: Fix Tuple Destructing with "this" (#10208) * Call checkExpression eventhough there is no appropriate type from destructuring of array * Add tests and baselines * use transpileModule * Remove use strict * Improve instanceof for structurally identical types * Introduce isTypeInstanceOf function * Add test * Accept new baselines * Fix loop over array to use for-of instead of for-in * Use correct this in tuple type parameter constraints Instantiate this in tuple types used as type parameter constraints * Add explanatory comment to resolveTupleTypeMembers * Ignore null, undefined, void when checking for discriminant property * Add regression test * Delay tuple type constraint resolution Create a new tuple that stores the this-type. * Always use thisType when generating tuple id * Optimize format of type list id strings used in maps * Make ReadonlyArray iterable. * Allow OSX to fail while we investigate (#10255) The random test timeouts are an issue. * avoid using the global name * Fix single-quote lint * Optimize performance of maps * Update API sample * Fix processDiagnosticMessages script * Have travis take shallow clones of the repo (#10275) Just cloning TS on travis takes 23 seconds on linux (68 seconds on mac), hopefully having it do a shallow clone will help. We don't rely on any tagging/artifacts from the travis servers which clone depth could impact, so this shouldn't impact anything other than build speed. * Add folds to travis log (#10269) * Optimize filterType to only call getUnionType if necessary * Add shorthand types declaration for travis-fold (#10293) * Optimize getTypeWithFacts * Filter out nullable and primitive types in isDiscriminantProperty * Fix typo * Add regression tests * Optimize core filter function to only allocate when necessary * Address CR comments + more optimizations * Faster path for creating union types from filterType * Allow an @types direcotry to have a package.json which specifies `"typings": null` to disclude it from automatically included typings. * Lint * Collect timing information for commands running on travis (#10308) * Simplifies performance API * Use 'MapLike' instead of 'Map' in 'preferConstRule.ts'. * narrow from 'any' in most situations instanceof and user-defined typeguards narrow from 'any' unless the narrowed-to type is exactly 'Object' or 'Function'. This is a breaking change. * Update instanceof conformance tests * accept new baselines * add tests * accept new baselines * Use lowercase names for type reference directives * Use proper response codes in web tests * Treat ambient shorthand declarations as explicit uses of the `any` type * Parallel linting (#10313) * A perilous thing, a parallel lint * Use work queue rather than scheduling work * Dont read files for lint on main thread * Fix style * Fix the style fix (#10344) * Aligned mark names with values used by ts-perf. * Use an enum in checkClassForDuplicateDeclarations to aid readability * Rename to Accessor * Correctly update package.json version * Migrated more MapLikes to Maps * Add ES2015 Date constructor signature that accepts another Date (#10353) * Parameters with no assignments implicitly considered const * Add tests * Migrate additional MapLikes to Maps. * Fix 10625: JSX Not validating when index signature is present (#10352) * Check for type of property declaration before using index signature * Add tests and baselines * fix linting error * Adding more comments * Clean up/move some Map helper functions. * Revert some formatting changes. * Improve ReadonlyArray<T>.concat to match Array<T> The Array-based signature was incorrect and also out-of-date. * Fix link to blog * Remove old assertion about when we're allowed to use fileExists * Set isNewIdentifierLocation to true for JavaScript files * Update error message for conflicting type definitions Fixes #10370 * Explain why we lower-case type reference directives * Correctly merge bindThisPropertyAssignment Also simply it considerably after noticing that it's *only* called for Javascript files, so there was a lot of dead code for TS cases that never happened. * Fix comment * Property handle imcomplete control flow types in nested loops * Update due to CR suggestion * Add regression test * Fix 10289: correctly generate tsconfig.json with --lib (#10355) * Separate generate tsconfig into its own function and implement init with --lib # Conflicts: # src/compiler/tsc.ts * Add tests and baselines; Update function name Add unittests and baselines Add unittests and baselines for generating tsconfig Move unittest into harness folder Update harness tsconfig.json USe correct function name * Use new MapLike interstead. Update unittest # Conflicts: # src/compiler/commandLineParser.ts * Update JakeFile * Add tests for incorrect cases * Address PR : remove explicity write node_modules * Add more tests for `export = foo.bar`. * Output test baselines to tests/baselines/local instead of root
2016-08-18 23:49:09 +02:00
gulp.task(
"baseline-accept-rwc",
"Makes the most recent rwc test results the new baseline, overwriting the old baseline",
() => baselineAccept("rwc"));
gulp.task(
"baseline-accept-test262",
"Makes the most recent test262 test results the new baseline, overwriting the old baseline",
() => baselineAccept("test262"));
// Webhost
const webtscProject = "tests/webhost/webtsc.tsconfig.json";
const webtscJs = "tests/webhost/webtsc.js";
2018-07-10 21:00:30 +02:00
gulp.task(webtscJs, /*help*/ false, useCompilerDeps, () => project.compile(webtscProject, { typescript: useCompiler }));
gulp.task(`clean:${webtscJs}`, /*help*/ false, () => project.clean(webtscProject));
gulp.task("webhost", "Builds the tsc web host", [webtscJs], () =>
gulp.src("built/local/lib.d.ts")
.pipe(gulp.dest("tests/webhost/")));
// Perf compiler
const perftscProject = "tests/perftsc.tsconfig.json";
const perftscJs = "built/local/perftsc.js";
2018-07-10 21:00:30 +02:00
gulp.task(perftscJs, /*help*/ false, useCompilerDeps, () => project.compile(perftscProject, { typescript: useCompiler }));
gulp.task(`clean:${perftscJs}`, /*help*/ false, () => project.clean(perftscProject));
gulp.task(
"perftsc",
"Builds augmented version of the compiler for perf tests",
[perftscJs]);
// Instrumented compiler
const loggedIOTs = "src/harness/loggedIO.ts";
const loggedIOJs = "built/local/loggedIO.js";
gulp.task(loggedIOJs, /*help*/ false, [], (done) => {
return mkdirp("built/local/temp")
2018-06-19 08:00:30 +02:00
.then(() => exec(host, ["lib/tsc.js", "--types", "--target es5", "--lib es5", "--outdir", "built/local/temp", loggedIOTs]))
.then(() => { fs.renameSync(path.join("built/local/temp", "/harness/loggedIO.js"), loggedIOJs); })
.then(() => del("built/local/temp"));
});
const instrumenterProject = "src/instrumenter/tsconfig.json";
const instrumenterJs = "built/local/instrumenter.js";
gulp.task(instrumenterJs, /*help*/ false, () => project.compile(instrumenterProject));
2018-07-10 21:00:30 +02:00
gulp.task(`clean:${instrumenterJs}`, /*help*/ false, () => project.clean(instrumenterProject));
gulp.task(
"tsc-instrumented",
"Builds an instrumented tsc.js - run with --test=[testname]",
["local", loggedIOJs, instrumenterJs, typescriptServicesJs],
2018-06-19 08:00:30 +02:00
() => exec(host, [instrumenterJs, "record", cmdLineOptions.tests || "iocapture", "built/local"]));
gulp.task(
"update-sublime",
"Updates the sublime plugin's tsserver",
["local", tsserverJs],
() =>
gulp.src([tsserverJs, tsserverJs + ".map"])
.pipe(gulp.dest("../TypeScript-Sublime-Plugin/tsserver/")));
gulp.task(
"build-rules",
"Compiles tslint rules to js",
() => project.compile("scripts/tslint/tsconfig.json"));
gulp.task("clean-rules", /*help*/ false, () => project.clean("scripts/tslint/tsconfig.json"));
gulp.task(
"lint",
"Runs tslint on the compiler sources. Optional arguments are: --f[iles]=regex",
["build-rules"],
() => {
if (fold.isTravis()) console.log(fold.start("lint"));
for (const project of ["scripts/tslint/tsconfig.json", "src/tsconfig-base.json"]) {
const cmd = `node node_modules/tslint/bin/tslint --project ${project} --formatters-dir ./built/local/tslint/formatters --format autolinkableStylish${cmdLineOptions.fix ? " --fix" : ""}`;
log("Linting: " + cmd);
child_process.execSync(cmd, { stdio: [0, 1, 2] });
}
if (fold.isTravis()) console.log(fold.end("lint"));
});
gulp.task(
"default",
"Runs 'local'",
["local"]);
gulp.task(
"watch-lib",
/*help*/ false,
() => gulp.watch(["src/lib/**/*"], ["lib"]));
const watchTscPatterns = [
"src/tsconfig-base.json",
"src/lib/**/*",
"src/compiler/**/*",
"src/tsc/**/*",
];
2018-06-22 09:09:21 +02:00
gulp.task(
"watch-tsc",
/*help*/ false,
useCompilerDeps,
() => gulp.watch(watchTscPatterns, ["tsc"]));
2018-07-10 21:00:30 +02:00
const watchServicesPatterns = [
"src/compiler/**/*",
"src/jsTypings/**/*",
"src/services/**/*"
];
gulp.task(
"watch-services",
/*help*/ false,
2018-07-10 21:00:30 +02:00
["watch-diagnostics", "watch-lib"],
() => gulp.watch(watchServicesPatterns, ["services"]));
const watchLsslPatterns = [
...watchServicesPatterns,
"src/server/**/*",
"src/tsserver/tsconfig.json"
];
gulp.task(
"watch-lssl",
/*help*/ false,
() => gulp.watch(watchLsslPatterns, ["lssl"]));
const watchLocalPatterns = [
"src/tsconfig-base.json",
"src/lib/**/*",
"src/compiler/**/*",
"src/tsc/**/*",
"src/services/**/*",
"src/jsTyping/**/*",
"src/server/**/*",
"src/tsserver/**/*",
"src/typingsInstallerCore/**/*",
"src/harness/**/*",
"src/testRunner/**/*",
];
gulp.task(
"watch-local",
"Watches for changes to projects in src/ (but does not execute tests).",
2019-01-25 19:55:24 +01:00
() => gulp.watch(watchLocalPatterns, ["local"]));
2018-07-10 21:00:30 +02:00
const watchPatterns = [
"src/tsconfig-base.json",
"src/lib/**/*",
"src/compiler/**/*",
"src/services/**/*",
"src/jsTyping/**/*",
"src/server/**/*",
"src/tsserver/**/*",
"src/typingsInstallerCore/**/*",
"src/harness/**/*",
"src/testRunner/**/*",
];
2018-06-22 09:09:21 +02:00
gulp.task(
"watch",
"Watches for changes to the build inputs for built/local/run.js, then runs tests.",
["build-rules"],
2018-07-10 21:00:30 +02:00
() => {
const sem = new Semaphore(1);
2018-07-10 21:00:30 +02:00
gulp.watch(watchPatterns, () => { runTests(); });
2018-07-10 21:00:30 +02:00
// NOTE: gulp.watch is far too slow when watching tests/cases/**/* as it first enumerates *every* file
const testFilePattern = /(\.ts|[\\/]tsconfig\.json)$/;
fs.watch("tests/cases", { recursive: true }, (_, file) => {
if (testFilePattern.test(file)) runTests();
2018-07-10 21:00:30 +02:00
});
async function runTests() {
try {
// Ensure only one instance of the test runner is running at any given time.
if (sem.count > 0) {
await sem.wait();
try {
// Wait for any concurrent recompilations to complete...
try {
await delay(100);
while (project.hasRemainingWork()) {
await project.waitForWorkToComplete();
await delay(500);
}
}
catch (e) {
if (e instanceof CancelError) return;
throw e;
}
// cancel any pending or active test run if a new recompilation is triggered
const source = new CancellationTokenSource();
project.waitForWorkToStart().then(() => {
source.cancel();
});
if (cmdLineOptions.tests || cmdLineOptions.failed) {
await runConsoleTests(runJs, "mocha-fivemat-progress-reporter", /*runInParallel*/ false, /*watchMode*/ true, source.token);
}
else {
await runConsoleTests(runJs, "min", /*runInParallel*/ true, /*watchMode*/ true, source.token);
}
}
finally {
sem.release();
}
}
}
catch (e) {
if (e instanceof CancelError) {
log.warn("Operation was canceled");
}
else {
log.error(e);
}
}
};
2018-07-10 21:00:30 +02:00
});
2018-07-10 21:00:30 +02:00
gulp.task("clean-built", /*help*/ false, [`clean:${diagnosticInformationMapTs}`], () => del(["built"]));
gulp.task(
"clean",
"Cleans the compiler output, declare files, and tests",
[
2018-07-10 21:00:30 +02:00
`clean:${importDefinitelyTypedTestsJs}`,
`clean:${webtscJs}`,
`clean:${perftscJs}`,
`clean:${instrumenterJs}`,
`clean:${webTestServerJs}`,
"clean:scripts",
"clean-rules",
"clean-built"
2019-01-25 19:55:24 +01:00
]);