Merge branch 'master' into referencesPrototypeSourceFile

This commit is contained in:
Sheetal Nandi
2019-09-11 12:27:58 -07:00
368 changed files with 33753 additions and 7149 deletions
+3 -3
View File
@@ -168,7 +168,7 @@ class CompilerTest {
assert.equal(testCaseContent.tsConfig.raw.exclude, undefined, `exclude in tsconfig is not currently supported`);
tsConfigOptions = ts.cloneCompilerOptions(testCaseContent.tsConfig.options);
this.tsConfigFiles.push(this.createHarnessTestFile(testCaseContent.tsConfigFileUnitData!, rootDir, ts.combinePaths(rootDir, tsConfigOptions.configFilePath!)));
this.tsConfigFiles.push(this.createHarnessTestFile(testCaseContent.tsConfigFileUnitData!, rootDir, ts.combinePaths(rootDir, tsConfigOptions.configFilePath)));
}
else {
const baseUrl = this.harnessSettings.baseUrl;
@@ -245,7 +245,7 @@ class CompilerTest {
const record = utils.removeTestPathPrefixes(this.result.getSourceMapRecord()!);
const baseline = (this.options.noEmitOnError && this.result.diagnostics.length !== 0) || record === undefined
// Because of the noEmitOnError option no files are created. We need to return null because baselining isn't required.
? null // tslint:disable-line no-null-keyword
? null // eslint-disable-line no-null/no-null
: record;
Harness.Baseline.runBaseline(this.configuredName.replace(/\.tsx?$/, ".sourcemap.txt"), baseline);
}
@@ -306,4 +306,4 @@ class CompilerTest {
private createHarnessTestFile(lastUnit: Harness.TestCaseParser.TestUnitData, rootDir: string, unitName?: string): Harness.Compiler.TestFile {
return { unitName: unitName || this.makeUnitName(lastUnit.name, rootDir), content: lastUnit.content, fileOptions: lastUnit.fileOptions };
}
}
}
+7 -6
View File
@@ -26,7 +26,7 @@ abstract class ExternalCompileRunnerBase extends RunnerBase {
// Read in and evaluate the test list
const testList = this.tests && this.tests.length ? this.tests : this.getTestFiles();
// tslint:disable-next-line:no-this-assignment
// eslint-disable-next-line @typescript-eslint/no-this-alias
const cls = this;
describe(`${this.kind()} code samples`, function(this: Mocha.ISuiteCallbackContext) {
this.timeout(600_000); // 10 minutes
@@ -36,7 +36,7 @@ abstract class ExternalCompileRunnerBase extends RunnerBase {
});
}
private runTest(directoryName: string) {
// tslint:disable-next-line:no-this-assignment
// eslint-disable-next-line @typescript-eslint/no-this-alias
const cls = this;
const timeout = 600_000; // 10 minutes
describe(directoryName, function(this: Mocha.ISuiteCallbackContext) {
@@ -95,7 +95,7 @@ class UserCodeRunner extends ExternalCompileRunnerBase {
return "user";
}
report(result: ExecResult) {
// tslint:disable-next-line:no-null-keyword
// eslint-disable-next-line no-null/no-null
return result.status === 0 && !result.stdout.length && !result.stderr.length ? null : `Exit Code: ${result.status}
Standard output:
${sortErrors(stripAbsoluteImportPaths(result.stdout.toString().replace(/\r\n/g, "\n")))}
@@ -115,7 +115,7 @@ class DockerfileRunner extends ExternalCompileRunnerBase {
// Read in and evaluate the test list
const testList = this.tests && this.tests.length ? this.tests : this.getTestFiles();
// tslint:disable-next-line:no-this-assignment
// eslint-disable-next-line @typescript-eslint/no-this-alias
const cls = this;
describe(`${this.kind()} code samples`, function(this: Mocha.ISuiteCallbackContext) {
this.timeout(cls.timeout); // 20 minutes
@@ -145,7 +145,7 @@ class DockerfileRunner extends ExternalCompileRunnerBase {
}
}
report(result: ExecResult) {
// tslint:disable-next-line:no-null-keyword
// eslint-disable-next-line no-null/no-null
return result.status === 0 && !result.stdout.length && !result.stderr.length ? null : `Exit Code: ${result.status}
Standard output:
${sanitizeDockerfileOutput(result.stdout.toString())}
@@ -254,7 +254,8 @@ class DefinitelyTypedRunner extends ExternalCompileRunnerBase {
report(result: ExecResult, cwd: string) {
const stdout = removeExpectedErrors(result.stdout.toString(), cwd);
const stderr = result.stderr.toString();
// tslint:disable-next-line:no-null-keyword
// eslint-disable-next-line no-null/no-null
return !stdout.length && !stderr.length ? null : `Exit Code: ${result.status}
Standard output:
${stdout.replace(/\r\n/g, "\n")}
+10 -10
View File
@@ -1,8 +1,5 @@
// tslint:disable no-unnecessary-type-assertion (TODO: tslint can't find node types)
namespace Harness.Parallel.Host {
export function start() {
// tslint:disable-next-line:variable-name
const Mocha = require("mocha") as typeof import("mocha");
const Base = Mocha.reporters.Base;
const color = Base.color;
@@ -17,7 +14,6 @@ namespace Harness.Parallel.Host {
const { statSync, readFileSync } = require("fs") as typeof import("fs");
// NOTE: paths for module and types for FailedTestReporter _do not_ line up due to our use of --outFile for run.js
// tslint:disable-next-line:variable-name
const FailedTestReporter = require(path.resolve(__dirname, "../../scripts/failed-tests")) as typeof import("../../../scripts/failed-tests");
const perfdataFileNameFragment = ".parallelperf";
@@ -51,7 +47,7 @@ namespace Harness.Parallel.Host {
constructor(info: ErrorInfo | TestInfo) {
super(info.name[info.name.length - 1]);
this.info = info;
this.state = "error" in info ? "failed" : "passed";
this.state = "error" in info ? "failed" : "passed"; // eslint-disable-line no-in-operator
this.pending = false;
}
}
@@ -323,12 +319,15 @@ namespace Harness.Parallel.Host {
return process.exit(2);
}
case "timeout": {
if (worker.timer) clearTimeout(worker.timer);
if (worker.timer) {
// eslint-disable-next-line no-restricted-globals
clearTimeout(worker.timer);
}
if (data.payload.duration === "reset") {
worker.timer = undefined;
}
else {
// tslint:disable-next-line:ban
// eslint-disable-next-line no-restricted-globals
worker.timer = setTimeout(killChild, data.payload.duration, data.payload);
}
break;
@@ -541,7 +540,7 @@ namespace Harness.Parallel.Host {
function replayTest(runner: Mocha.Runner, test: RemoteTest) {
runner.emit("test", test);
if (test.isFailed()) {
runner.emit("fail", test, "error" in test.info ? rebuildError(test.info) : new Error("Unknown error"));
runner.emit("fail", test, "error" in test.info ? rebuildError(test.info) : new Error("Unknown error")); // eslint-disable-line no-in-operator
}
else {
runner.emit("pass", test);
@@ -592,7 +591,8 @@ namespace Harness.Parallel.Host {
consoleReporter.epilogue();
if (noColors) Base.useColors = savedUseColors;
IO.writeFile(perfdataFileName(configOption), JSON.stringify(newPerfData, null, 4)); // tslint:disable-line:no-null-keyword
// eslint-disable-next-line no-null/no-null
IO.writeFile(perfdataFileName(configOption), JSON.stringify(newPerfData, null, 4));
if (xunitReporter) {
xunitReporter.done(errorResults.length, failures => process.exit(failures));
@@ -651,7 +651,7 @@ namespace Harness.Parallel.Host {
shimNoopTestInterface(global);
}
// tslint:disable-next-line:ban
// eslint-disable-next-line no-restricted-globals
setTimeout(() => startDelayed(perfData, totalCost), 0); // Do real startup on next tick, so all unit tests have been collected
}
}
+1 -3
View File
@@ -1,5 +1,3 @@
/// <reference path="./host.ts" />
/// <reference path="./worker.ts" />
namespace Harness.Parallel {
export interface RunnerTask {
runner: TestRunnerKind;
@@ -87,4 +85,4 @@ namespace Harness.Parallel {
global.it.skip = global.xit = global.xspecify = ts.noop as Mocha.PendingTestFunction;
global.it.only = ts.noop as Mocha.ExclusiveTestFunction;
}
}
}
+6 -6
View File
@@ -1,5 +1,3 @@
// tslint:disable no-unnecessary-type-assertion (TODO: tslint can't find node types)
namespace Harness.Parallel.Worker {
export function start() {
function hookUncaughtExceptions() {
@@ -21,7 +19,7 @@ namespace Harness.Parallel.Worker {
let exceptionsHooked = false;
hookUncaughtExceptions();
// tslint:disable-next-line:variable-name - Capitalization is aligned with the global `Mocha` namespace for typespace/namespace references.
// Capitalization is aligned with the global `Mocha` namespace for typespace/namespace references.
const Mocha = require("mocha") as typeof import("mocha");
/**
@@ -99,7 +97,6 @@ namespace Harness.Parallel.Worker {
* @param context The test context (usually the NodeJS `global` object).
*/
function shimTestInterface(rootSuite: Mocha.Suite, context: Mocha.MochaGlobals) {
// tslint:disable-next-line:variable-name
const suites = [rootSuite];
context.before = (title: string | Mocha.Func | Mocha.AsyncFunc, fn?: Mocha.Func | Mocha.AsyncFunc) => { suites[0].beforeAll(title as string, fn); };
context.after = (title: string | Mocha.Func | Mocha.AsyncFunc, fn?: Mocha.Func | Mocha.AsyncFunc) => { suites[0].afterAll(title as string, fn); };
@@ -125,7 +122,10 @@ namespace Harness.Parallel.Worker {
}
function addTest(title: string | Mocha.Func | Mocha.AsyncFunc, fn: Mocha.Func | Mocha.AsyncFunc | undefined): Mocha.Test {
if (typeof title === "function") fn = title, title = fn.name;
if (typeof title === "function") {
fn = title;
title = fn.name;
}
const test = new Test(title, suites[0].pending ? undefined : fn);
suites[0].addTest(test);
return test;
@@ -317,4 +317,4 @@ namespace Harness.Parallel.Worker {
process.on("message", processHostMessage);
}
}
}
+14 -16
View File
@@ -3,7 +3,7 @@ namespace project {
interface ProjectRunnerTestCase {
scenario: string;
projectRoot: string; // project where it lives - this also is the current directory when compiling
inputFiles: ReadonlyArray<string>; // list of input files to be given to program
inputFiles: readonly string[]; // list of input files to be given to program
resolveMapRoot?: boolean; // should we resolve this map root and give compiler the absolute disk path as map root?
resolveSourceRoot?: boolean; // should we resolve this source root and give compiler the absolute disk path as map root?
baselineCheck?: boolean; // Verify the baselines of output files, if this is false, we will write to output to the disk but there is no verification of baselines
@@ -13,21 +13,21 @@ namespace project {
interface ProjectRunnerTestCaseResolutionInfo extends ProjectRunnerTestCase {
// Apart from actual test case the results of the resolution
resolvedInputFiles: ReadonlyArray<string>; // List of files that were asked to read by compiler
emittedFiles: ReadonlyArray<string>; // List of files that were emitted by the compiler
resolvedInputFiles: readonly string[]; // List of files that were asked to read by compiler
emittedFiles: readonly string[]; // List of files that were emitted by the compiler
}
interface CompileProjectFilesResult {
configFileSourceFiles: ReadonlyArray<ts.SourceFile>;
configFileSourceFiles: readonly ts.SourceFile[];
moduleKind: ts.ModuleKind;
program?: ts.Program;
compilerOptions?: ts.CompilerOptions;
errors: ReadonlyArray<ts.Diagnostic>;
sourceMapData?: ReadonlyArray<ts.SourceMapEmitResult>;
errors: readonly ts.Diagnostic[];
sourceMapData?: readonly ts.SourceMapEmitResult[];
}
interface BatchCompileProjectTestCaseResult extends CompileProjectFilesResult {
outputFiles?: ReadonlyArray<documents.TextDocument>;
outputFiles?: readonly documents.TextDocument[];
}
export class ProjectRunner extends RunnerBase {
@@ -206,7 +206,8 @@ namespace project {
const ignoreCase = this.vfs.ignoreCase;
const resolutionInfo: ProjectRunnerTestCaseResolutionInfo & ts.CompilerOptions = JSON.parse(JSON.stringify(this.testCase));
resolutionInfo.resolvedInputFiles = this.compilerResult.program!.getSourceFiles()
.map(({ fileName: input }) => vpath.beneath(vfs.builtFolder, input, this.vfs.ignoreCase) || vpath.beneath(vfs.testLibFolder, input, this.vfs.ignoreCase) ? utils.removeTestPathPrefixes(input) :
.map(({ fileName: input }) =>
vpath.beneath(vfs.builtFolder, input, this.vfs.ignoreCase) || vpath.beneath(vfs.testLibFolder, input, this.vfs.ignoreCase) ? utils.removeTestPathPrefixes(input) :
vpath.isAbsolute(input) ? vpath.relative(cwd, input, ignoreCase) :
input);
@@ -306,8 +307,8 @@ namespace project {
return url;
}
private compileProjectFiles(moduleKind: ts.ModuleKind, configFileSourceFiles: ReadonlyArray<ts.SourceFile>,
getInputFiles: () => ReadonlyArray<string>,
private compileProjectFiles(moduleKind: ts.ModuleKind, configFileSourceFiles: readonly ts.SourceFile[],
getInputFiles: () => readonly string[],
compilerHost: ts.CompilerHost,
compilerOptions: ts.CompilerOptions): CompileProjectFilesResult {
@@ -395,11 +396,8 @@ namespace project {
}
function moduleNameToString(moduleKind: ts.ModuleKind) {
return moduleKind === ts.ModuleKind.AMD
? "amd"
: moduleKind === ts.ModuleKind.CommonJS
? "node"
: "none";
return moduleKind === ts.ModuleKind.AMD ? "amd" :
moduleKind === ts.ModuleKind.CommonJS ? "node" : "none";
}
function getErrorsBaseline(compilerResult: CompileProjectFilesResult) {
@@ -461,4 +459,4 @@ namespace project {
return compilerOptions;
}
}
}
+3 -1
View File
@@ -1,5 +1,7 @@
/* eslint-disable prefer-const */
let runners: RunnerBase[] = [];
let iterations = 1;
/* eslint-enable prefer-const */
function runTests(runners: RunnerBase[]) {
for (let i = iterations; i > 0; i--) {
@@ -52,7 +54,7 @@ const mytestconfigFileName = "mytest.config";
const testconfigFileName = "test.config";
const customConfig = tryGetConfig(Harness.IO.args());
let testConfigContent =
const testConfigContent =
customConfig && Harness.IO.fileExists(customConfig)
? Harness.IO.readFile(customConfig)!
: Harness.IO.fileExists(mytestconfigFileName)
+6 -7
View File
@@ -1,6 +1,4 @@
// In harness baselines, null is different than undefined. See `generateActual` in `harness.ts`.
/* tslint:disable:no-null-keyword */
namespace RWC {
function runWithIOLog(ioLog: IoLog, fn: (oldIO: Harness.IO) => void) {
const oldIO = Harness.IO;
@@ -11,7 +9,8 @@ namespace RWC {
try {
fn(oldIO);
} finally {
}
finally {
wrappedIO.endReplay();
Harness.IO = oldIO;
}
@@ -156,7 +155,7 @@ namespace RWC {
it("has the expected declaration file content", () => {
Harness.Baseline.runMultifileBaseline(baseName, "", () => {
if (!compilerResult.dts.size) {
return null;
return null; // eslint-disable-line no-null/no-null
}
return Harness.Compiler.iterateOutputs(compilerResult.dts.values());
@@ -166,7 +165,7 @@ namespace RWC {
it("has the expected source maps", () => {
Harness.Baseline.runMultifileBaseline(baseName, "", () => {
if (!compilerResult.maps.size) {
return null;
return null; // eslint-disable-line no-null/no-null
}
return Harness.Compiler.iterateOutputs(compilerResult.maps.values());
@@ -176,7 +175,7 @@ namespace RWC {
it("has the expected errors", () => {
Harness.Baseline.runMultifileBaseline(baseName, ".errors.txt", () => {
if (compilerResult.diagnostics.length === 0) {
return null;
return null; // eslint-disable-line no-null/no-null
}
// Do not include the library in the baselines to avoid noise
const baselineFiles = tsconfigFiles.concat(inputFiles, otherFiles).filter(f => !Harness.isDefaultLibraryFile(f.unitName));
@@ -191,7 +190,7 @@ namespace RWC {
if (compilerOptions.declaration && !compilerResult.diagnostics.length) {
Harness.Baseline.runMultifileBaseline(baseName, ".dts.errors.txt", () => {
if (compilerResult.diagnostics.length === 0) {
return null;
return null; // eslint-disable-line no-null/no-null
}
const declContext = Harness.Compiler.prepareDeclarationCompilationContext(
+1 -2
View File
@@ -1,6 +1,4 @@
// In harness baselines, null is different than undefined. See `generateActual` in `harness.ts`.
/* tslint:disable:no-null-keyword */
class Test262BaselineRunner extends RunnerBase {
private static readonly basePath = "internal/cases/test262";
private static readonly helpersFilePath = "tests/cases/test262-harness/helpers.d.ts";
@@ -69,6 +67,7 @@ class Test262BaselineRunner extends RunnerBase {
it("has the expected errors", () => {
const errors = testState.compilerResult.diagnostics;
// eslint-disable-next-line no-null/no-null
const baseline = errors.length === 0 ? null : Harness.Compiler.getErrorBaseline(testState.inputFiles, errors);
Harness.Baseline.runBaseline(testState.filename + ".errors.txt", baseline, Test262BaselineRunner.baselineOptions);
});
+3 -4
View File
@@ -71,21 +71,21 @@ namespace ts {
});
});
function makeAssertChanges(getProgram: () => Program): (fileNames: ReadonlyArray<string>) => void {
function makeAssertChanges(getProgram: () => Program): (fileNames: readonly string[]) => void {
const host: BuilderProgramHost = { useCaseSensitiveFileNames: returnTrue };
let builderProgram: EmitAndSemanticDiagnosticsBuilderProgram | undefined;
return fileNames => {
const program = getProgram();
builderProgram = createEmitAndSemanticDiagnosticsBuilderProgram(program, host, builderProgram);
const outputFileNames: string[] = [];
// tslint:disable-next-line no-empty
// eslint-disable-next-line no-empty
while (builderProgram.emitNextAffectedFile(fileName => outputFileNames.push(fileName))) {
}
assert.deepEqual(outputFileNames, fileNames);
};
}
function makeAssertChangesWithCancellationToken(getProgram: () => Program): (fileNames: ReadonlyArray<string>, cancelAfterEmitLength?: number) => void {
function makeAssertChangesWithCancellationToken(getProgram: () => Program): (fileNames: readonly string[], cancelAfterEmitLength?: number) => void {
const host: BuilderProgramHost = { useCaseSensitiveFileNames: returnTrue };
let builderProgram: EmitAndSemanticDiagnosticsBuilderProgram | undefined;
let cancel = false;
@@ -104,7 +104,6 @@ namespace ts {
builderProgram = createEmitAndSemanticDiagnosticsBuilderProgram(program, host, builderProgram);
const outputFileNames: string[] = [];
try {
// tslint:disable-next-line no-empty
do {
assert.isFalse(cancel);
if (outputFileNames.length === cancelAfterEmitLength) {
@@ -83,14 +83,14 @@ namespace ts {
start: undefined,
length: undefined,
}, {
messageText: "Argument for '--jsx' option must be: 'preserve', 'react-native', 'react'.",
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
messageText: "Argument for '--jsx' option must be: 'preserve', 'react-native', 'react'.",
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
file: undefined,
start: undefined,
length: undefined,
}],
file: undefined,
start: undefined,
length: undefined,
}],
fileNames: ["0.ts"],
options: {}
});
@@ -109,14 +109,14 @@ namespace ts {
start: undefined,
length: undefined,
}, {
messageText: "Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015', 'esnext'.",
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
messageText: "Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015', 'esnext'.",
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
file: undefined,
start: undefined,
length: undefined,
}],
file: undefined,
start: undefined,
length: undefined,
}],
fileNames: ["0.ts"],
options: {}
});
@@ -135,14 +135,14 @@ namespace ts {
start: undefined,
length: undefined,
}, {
messageText: "Argument for '--newLine' option must be: 'crlf', 'lf'.",
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
messageText: "Argument for '--newLine' option must be: 'crlf', 'lf'.",
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
file: undefined,
start: undefined,
length: undefined,
}],
file: undefined,
start: undefined,
length: undefined,
}],
fileNames: ["0.ts"],
options: {}
});
@@ -161,14 +161,14 @@ namespace ts {
start: undefined,
length: undefined,
}, {
messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'esnext'.",
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'esnext'.",
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
file: undefined,
start: undefined,
length: undefined,
}],
file: undefined,
start: undefined,
length: undefined,
}],
fileNames: ["0.ts"],
options: {}
});
@@ -187,14 +187,14 @@ namespace ts {
start: undefined,
length: undefined,
}, {
messageText: "Argument for '--moduleResolution' option must be: 'node', 'classic'.",
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
messageText: "Argument for '--moduleResolution' option must be: 'node', 'classic'.",
category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category,
code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code,
file: undefined,
start: undefined,
length: undefined,
}],
file: undefined,
start: undefined,
length: undefined,
}],
fileNames: ["0.ts"],
options: {}
});
@@ -159,8 +159,7 @@ namespace ts {
"dev/configs/third.json": JSON.stringify({
extends: "./second",
compilerOptions: {
// tslint:disable-next-line:no-null-keyword
module: null
module: null // eslint-disable-line no-null/no-null
},
include: ["../supplemental.*"]
}),
@@ -169,8 +168,7 @@ namespace ts {
compilerOptions: {
module: "system"
},
// tslint:disable-next-line:no-null-keyword
include: null,
include: null, // eslint-disable-line no-null/no-null
files: ["../main.ts"]
}),
"dev/configs/fifth.json": JSON.stringify({
@@ -8,7 +8,7 @@ namespace ts {
interface ExpectedResultWithParsingSuccess {
compilerOptions: CompilerOptions;
errors: ReadonlyArray<Diagnostic>;
errors: readonly Diagnostic[];
}
interface ExpectedResultWithParsingFailure {
@@ -59,7 +59,7 @@ namespace ts {
}
}
function verifyErrors(actualErrors: Diagnostic[], expectedErrors: ReadonlyArray<Diagnostic>, ignoreLocation?: boolean) {
function verifyErrors(actualErrors: Diagnostic[], expectedErrors: readonly Diagnostic[], ignoreLocation?: boolean) {
assert.isTrue(expectedErrors.length === actualErrors.length, `Expected error: ${JSON.stringify(expectedErrors.map(getDiagnosticString), undefined, " ")}. Actual error: ${JSON.stringify(actualErrors.map(getDiagnosticString), undefined, " ")}.`);
for (let i = 0; i < actualErrors.length; i++) {
const actualError = actualErrors[i];
@@ -592,16 +592,16 @@ namespace ts {
]
}
}
`, "tsconfig.json",
{
compilerOptions: {
target: undefined,
module: ModuleKind.ESNext,
experimentalDecorators: true,
},
hasParseErrors: true
}
);
`,
"tsconfig.json",
{
compilerOptions: {
target: undefined,
module: ModuleKind.ESNext,
experimentalDecorators: true,
},
hasParseErrors: true
});
});
});
}
@@ -68,7 +68,8 @@ namespace ts {
exclude: ["0.js", "1.js"]
},
errors: <Diagnostic[]>[]
});
}
);
});
it("Convert correctly format tsconfig.json to typeAcquisition ", () => {
@@ -90,7 +91,7 @@ namespace ts {
exclude: ["0.js", "1.js"]
},
errors: <Diagnostic[]>[]
});
});
});
it("Convert incorrect format tsconfig.json to typeAcquisition ", () => {
@@ -135,7 +135,7 @@ namespace ts {
function createDiagnosticForConfigFile(json: any, start: number, length: number, diagnosticMessage: DiagnosticMessage, arg0: string) {
const text = JSON.stringify(json);
const file = <SourceFile>{ // tslint:disable-line no-object-literal-type-assertion
const file = <SourceFile>{
fileName: caseInsensitiveTsconfigPath,
kind: SyntaxKind.SourceFile,
text
@@ -1,7 +1,7 @@
namespace ts {
interface TestProjectSpecification {
configFileName?: string;
references?: ReadonlyArray<string | ProjectReference>;
references?: readonly (string | ProjectReference)[];
files: { [fileName: string]: string };
outputFiles?: { [fileName: string]: string };
config?: object;
@@ -11,14 +11,14 @@ namespace ts {
[path: string]: TestProjectSpecification;
}
function assertHasError(message: string, errors: ReadonlyArray<Diagnostic>, diag: DiagnosticMessage) {
function assertHasError(message: string, errors: readonly Diagnostic[], diag: DiagnosticMessage) {
if (!errors.some(e => e.code === diag.code)) {
const errorString = errors.map(e => ` ${e.file ? e.file.fileName : "[global]"}: ${e.messageText}`).join("\r\n");
assert(false, `${message}: Did not find any diagnostic for ${diag.message} in:\r\n${errorString}`);
}
}
function assertNoErrors(message: string, errors: ReadonlyArray<Diagnostic>) {
function assertNoErrors(message: string, errors: readonly Diagnostic[]) {
if (errors && errors.length > 0) {
assert(false, `${message}: Expected no errors, but found:\r\n${errors.map(e => ` ${e.messageText}`).join("\r\n")}`);
}
+26 -26
View File
@@ -29,7 +29,7 @@ namespace ts {
}
const initResult = convertToTSConfig(commandLine, configPath, configParseHost);
// tslint:disable-next-line:no-null-keyword
// eslint-disable-next-line no-null/no-null
Harness.Baseline.runBaseline(outputFileName, JSON.stringify(initResult, null, 4) + "\n");
});
});
@@ -75,32 +75,32 @@ namespace ts {
// Regression test for https://github.com/Microsoft/TypeScript/issues/28836
showTSConfigCorrectly("Show TSConfig with paths and more", ["-p", "tsconfig.json"], {
compilerOptions: {
allowJs: true,
outDir: "./lib",
esModuleInterop: true,
module: "commonjs",
moduleResolution: "node",
target: "ES2017",
sourceMap: true,
baseUrl: ".",
paths: {
"@root/*": ["./*"],
"@configs/*": ["src/configs/*"],
"@common/*": ["src/common/*"],
"*": [
"node_modules/*",
"src/types/*"
compilerOptions: {
allowJs: true,
outDir: "./lib",
esModuleInterop: true,
module: "commonjs",
moduleResolution: "node",
target: "ES2017",
sourceMap: true,
baseUrl: ".",
paths: {
"@root/*": ["./*"],
"@configs/*": ["src/configs/*"],
"@common/*": ["src/common/*"],
"*": [
"node_modules/*",
"src/types/*"
]
},
experimentalDecorators: true,
emitDecoratorMetadata: true,
resolveJsonModule: true
},
include: [
"./src/**/*"
]
},
experimentalDecorators: true,
emitDecoratorMetadata: true,
resolveJsonModule: true
},
include: [
"./src/**/*"
]
});
});
// Bulk validation of all option declarations
for (const option of optionDeclarations) {
@@ -137,7 +137,7 @@ namespace ts {
"xx\\\\" // end of line comment
]
}`, { config: { exclude: ["xx\\"] } });
});
});
it("returns object with error when json is invalid", () => {
const parsed = parseConfigFileTextToJson("/apath/tsconfig.json", "invalid");
@@ -1,5 +1,7 @@
namespace ts {
ts.disableIncrementalParsing = false; // tslint:disable-line no-unnecessary-qualifier (make clear this is a global mutation!)
// make clear this is a global mutation!
// eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
ts.disableIncrementalParsing = false;
function withChange(text: IScriptSnapshot, start: number, length: number, newText: string): { text: IScriptSnapshot; textChangeRange: TextChangeRange; } {
const contents = getSnapshotText(text);
+38 -38
View File
@@ -67,7 +67,7 @@ namespace ts {
parsesCorrectly("tsFunctionType", "{() => string}");
parsesCorrectly("typeArgumentsNotFollowingDot", "{a<>}");
parsesCorrectly("functionTypeWithTrailingComma", "{function(a,)}");
});
});
describe("parsesIncorrectly", () => {
parsesIncorrectly("emptyType", "{}");
@@ -111,39 +111,39 @@ namespace ts {
describe("parsesIncorrectly", () => {
parsesIncorrectly("multipleTypes",
`/**
`/**
* @type {number}
* @type {string}
*/`);
parsesIncorrectly("multipleReturnTypes",
`/**
`/**
* @return {number}
* @return {string}
*/`);
parsesIncorrectly("noTypeParameters",
`/**
`/**
* @template
*/`);
parsesIncorrectly("trailingTypeParameterComma",
`/**
`/**
* @template T,
*/`);
parsesIncorrectly("paramWithoutName",
`/**
`/**
* @param {number}
*/`);
parsesIncorrectly("paramWithoutTypeOrName",
`/**
`/**
* @param
*/`);
parsesIncorrectly("noType",
`/**
`/**
* @type
*/`);
parsesIncorrectly("@augments with no type",
`/**
`/**
* @augments
*/`);
});
@@ -152,172 +152,172 @@ namespace ts {
parsesCorrectly("threeAsterisks", "/*** */");
parsesCorrectly("emptyComment", "/***/");
parsesCorrectly("noLeadingAsterisk",
`/**
`/**
@type {number}
*/`);
parsesCorrectly("noReturnType",
`/**
`/**
* @return
*/`);
parsesCorrectly("leadingAsterisk",
`/**
`/**
* @type {number}
*/`);
parsesCorrectly("asteriskAfterPreamble", "/** * @type {number} */");
parsesCorrectly("typeTag",
`/**
`/**
* @type {number}
*/`);
parsesCorrectly("returnTag1",
`/**
`/**
* @return {number}
*/`);
parsesCorrectly("returnTag2",
`/**
`/**
* @return {number} Description text follows
*/`);
parsesCorrectly("returnsTag1",
`/**
`/**
* @returns {number}
*/`);
parsesCorrectly("oneParamTag",
`/**
`/**
* @param {number} name1
*/`);
parsesCorrectly("twoParamTag2",
`/**
`/**
* @param {number} name1
* @param {number} name2
*/`);
parsesCorrectly("paramTag1",
`/**
`/**
* @param {number} name1 Description text follows
*/`);
parsesCorrectly("paramTagBracketedName1",
`/**
`/**
* @param {number} [name1] Description text follows
*/`);
parsesCorrectly("paramTagBracketedName2",
`/**
`/**
* @param {number} [ name1 = 1] Description text follows
*/`);
parsesCorrectly("twoParamTagOnSameLine",
`/**
`/**
* @param {number} name1 @param {number} name2
*/`);
parsesCorrectly("paramTagNameThenType1",
`/**
`/**
* @param name1 {number}
*/`);
parsesCorrectly("paramTagNameThenType2",
`/**
`/**
* @param name1 {number} Description
*/`);
parsesCorrectly("argSynonymForParamTag",
`/**
`/**
* @arg {number} name1 Description
*/`);
parsesCorrectly("argumentSynonymForParamTag",
`/**
`/**
* @argument {number} name1 Description
*/`);
parsesCorrectly("templateTag",
`/**
`/**
* @template T
*/`);
parsesCorrectly("templateTag2",
`/**
`/**
* @template K,V
*/`);
parsesCorrectly("templateTag3",
`/**
`/**
* @template K ,V
*/`);
parsesCorrectly("templateTag4",
`/**
`/**
* @template K, V
*/`);
parsesCorrectly("templateTag5",
`/**
`/**
* @template K , V
*/`);
parsesCorrectly("templateTag6",
`/**
`/**
* @template K , V Description of type parameters.
*/`);
parsesCorrectly("paramWithoutType",
`/**
`/**
* @param foo
*/`);
parsesCorrectly("typedefTagWithChildrenTags",
`/**
`/**
* @typedef People
* @type {Object}
* @property {number} age
* @property {string} name
*/`);
parsesCorrectly("less-than and greater-than characters",
`/**
`/**
* @param x hi
< > still part of the previous comment
*/`);
parsesCorrectly("Nested @param tags",
`/**
`/**
* @param {object} o Doc doc
* @param {string} o.f Doc for f
*/`);
parsesCorrectly("@link tags",
`/**
`/**
* {@link first link}
* Inside {@link link text} thing
* @see {@link second link text} and {@link Foo|a foo} as well.
*/`);
parsesCorrectly("authorTag",
`/**
`/**
* @author John Doe <john.doe@example.com>
* @author John Doe <john.doe@example.com> unexpected comment
*/`);
+3 -3
View File
@@ -170,7 +170,7 @@ namespace ts {
testTypingsIgnored(["a", "b"]);
testTypingsIgnored({ a: "b" });
testTypingsIgnored(/*typings*/ true);
testTypingsIgnored(/*typings*/ null); // tslint:disable-line no-null-keyword
testTypingsIgnored(/*typings*/ null); // eslint-disable-line no-null/no-null
testTypingsIgnored(/*typings*/ undefined);
});
it("module name as directory - load index.d.ts", () => {
@@ -966,7 +966,7 @@ import b = require("./moduleB");
function test(hasDirectoryExists: boolean) {
const file1: File = { name: "/root/folder1/file1.ts" };
const file1_1: File = { name: "/root/folder1/file1_1/index.d.ts" }; // tslint:disable-line variable-name
const file1_1: File = { name: "/root/folder1/file1_1/index.d.ts" }; // eslint-disable-line @typescript-eslint/camelcase
const file2: File = { name: "/root/generated/folder1/file2.ts" };
const file3: File = { name: "/root/generated/folder2/file3.ts" };
const host = createModuleResolutionHost(hasDirectoryExists, file1, file1_1, file2, file3);
@@ -1102,7 +1102,7 @@ import b = require("./moduleB");
paths: {
"libs/guid": [ "src/libs/guid" ]
}
};
};
const result = resolveModuleName("libs/guid", app.name, options, host);
checkResolvedModuleWithFailedLookupLocations(result, createResolvedModule(libsTypings.name), [
// first try to load module as file
+3 -4
View File
@@ -54,7 +54,7 @@ namespace ts {
printsCorrectly("removeComments", { removeComments: true }, printer => printer.printFile(sourceFile));
// github #14948
// tslint:disable-next-line no-invalid-template-strings
// eslint-disable-next-line no-template-curly-in-string
printsCorrectly("templateLiteral", {}, printer => printer.printFile(createSourceFile("source.ts", "let greeting = `Hi ${name}, how are you?`;", ScriptTarget.ES2017)));
// github #18071
@@ -124,9 +124,8 @@ namespace ts {
EmitHint.Unspecified,
createNew(
createPropertyAccess(
createCall(
createIdentifier("f"), /*typeArguments*/ undefined, /*argumentsArray*/ undefined),
"x"),
createCall(createIdentifier("f"), /*typeArguments*/ undefined, /*argumentsArray*/ undefined),
"x"),
/*typeArguments*/ undefined,
/*argumentsArray*/ undefined
),
+2 -2
View File
@@ -1,5 +1,5 @@
namespace ts {
function verifyMissingFilePaths(missingPaths: ReadonlyArray<Path>, expected: ReadonlyArray<string>) {
function verifyMissingFilePaths(missingPaths: readonly Path[], expected: readonly string[]) {
assert.isDefined(missingPaths);
const map = arrayToSet(expected) as Map<boolean>;
for (const missing of missingPaths) {
@@ -152,7 +152,7 @@ namespace ts {
assertIsExternal(program, [a, fooIndex], f => f !== a);
});
function assertIsExternal(program: Program, files: ReadonlyArray<documents.TextDocument>, isExternalExpected: (file: documents.TextDocument) => boolean): void {
function assertIsExternal(program: Program, files: readonly documents.TextDocument[], isExternalExpected: (file: documents.TextDocument) => boolean): void {
for (const file of files) {
const actual = program.isSourceFileFromExternalLibrary(program.getSourceFile(file.file)!);
const expected = isExternalExpected(file);
@@ -18,7 +18,7 @@ namespace ts {
}
export interface ProgramWithSourceTexts extends Program {
sourceTexts?: ReadonlyArray<NamedSourceText>;
sourceTexts?: readonly NamedSourceText[];
host: TestCompilerHost;
}
@@ -104,7 +104,7 @@ namespace ts {
return file;
}
export function createTestCompilerHost(texts: ReadonlyArray<NamedSourceText>, target: ScriptTarget, oldProgram?: ProgramWithSourceTexts, useGetSourceFileByPath?: boolean) {
export function createTestCompilerHost(texts: readonly NamedSourceText[], target: ScriptTarget, oldProgram?: ProgramWithSourceTexts, useGetSourceFileByPath?: boolean) {
const files = arrayToMap(texts, t => t.name, t => {
if (oldProgram) {
let oldFile = <SourceFileWithText>oldProgram.getSourceFile(t.name);
@@ -152,7 +152,7 @@ namespace ts {
return program;
}
export function updateProgram(oldProgram: ProgramWithSourceTexts, rootNames: ReadonlyArray<string>, options: CompilerOptions, updater: (files: NamedSourceText[]) => void, newTexts?: NamedSourceText[], useGetSourceFileByPath?: boolean) {
export function updateProgram(oldProgram: ProgramWithSourceTexts, rootNames: readonly string[], options: CompilerOptions, updater: (files: NamedSourceText[]) => void, newTexts?: NamedSourceText[], useGetSourceFileByPath?: boolean) {
if (!newTexts) {
newTexts = oldProgram.sourceTexts!.slice(0);
}
@@ -164,7 +164,7 @@ namespace ts {
return program;
}
export function updateProgramText(files: ReadonlyArray<NamedSourceText>, fileName: string, newProgramText: string) {
export function updateProgramText(files: readonly NamedSourceText[], fileName: string, newProgramText: string) {
const file = find(files, f => f.name === fileName)!;
file.text = file.text.updateProgram(newProgramText);
}
@@ -8,22 +8,19 @@ namespace ts {
`;
it("can cancel signature help mid-request", () => {
verifyOperationCancelledAfter(file, 4, service => // Two calls are top-level in services, one is the root type, and the second should be for the parameter type
service.getSignatureHelpItems("file.ts", file.lastIndexOf("f"), emptyOptions)!,
r => assert.exists(r.items[0])
service.getSignatureHelpItems("file.ts", file.lastIndexOf("f"), emptyOptions)!, r => assert.exists(r.items[0])
);
});
it("can cancel find all references mid-request", () => {
verifyOperationCancelledAfter(file, 3, service => // Two calls are top-level in services, one is the root type
service.findReferences("file.ts", file.lastIndexOf("o"))!,
r => assert.exists(r[0].definition)
service.findReferences("file.ts", file.lastIndexOf("o"))!, r => assert.exists(r[0].definition)
);
});
it("can cancel quick info mid-request", () => {
verifyOperationCancelledAfter(file, 1, service => // The LS doesn't do any top-level checks on the token for quickinfo, so the first check is within the checker
service.getQuickInfoAtPosition("file.ts", file.lastIndexOf("o"))!,
r => assert.exists(r.displayParts)
service.getQuickInfoAtPosition("file.ts", file.lastIndexOf("o"))!, r => assert.exists(r.displayParts)
);
});
@@ -50,18 +47,13 @@ namespace ts {
placeOpenBraceOnNewLineForControlBlocks: false,
};
verifyOperationCancelledAfter(file, 1, service => // The LS doesn't do any top-level checks on the token for completion entry details, so the first check is within the checker
service.getCompletionEntryDetails("file.ts", file.lastIndexOf("f"), "foo", options, /*content*/ undefined, {})!,
r => assert.exists(r.displayParts)
service.getCompletionEntryDetails("file.ts", file.lastIndexOf("f"), "foo", options, /*content*/ undefined, {})!, r => assert.exists(r.displayParts)
);
});
it("can cancel suggestion diagnostics mid-request", () => {
verifyOperationCancelledAfter(file, 1, service => // The LS doesn't do any top-level checks on the token for suggestion diagnostics, so the first check is within the checker
service.getSuggestionDiagnostics("file.js"),
r => assert.notEqual(r.length, 0),
"file.js",
"function foo() { let a = 10; }",
{ allowJs: true }
service.getSuggestionDiagnostics("file.js"), r => assert.notEqual(r.length, 0), "file.js", "function foo() { let a = 10; }", { allowJs: true }
);
});
});
@@ -1,4 +1,5 @@
// tslint:disable no-invalid-template-strings (lots of tests use quoted code)
// lots of tests use quoted code
/* eslint-disable no-template-curly-in-string */
interface ClassificationEntry {
value: any;
@@ -384,7 +385,7 @@ describe("unittests:: services:: Colorization", () => {
it("LexicallyClassifiesConflictTokens", () => {
// Test conflict markers.
testLexicalClassification(
"class C {\r\n\
"class C {\r\n\
<<<<<<< HEAD\r\n\
v = 1;\r\n\
=======\r\n\
@@ -406,7 +407,7 @@ describe("unittests:: services:: Colorization", () => {
finalEndOfLineState(ts.EndOfLineState.None));
testLexicalClassification(
"<<<<<<< HEAD\r\n\
"<<<<<<< HEAD\r\n\
class C { }\r\n\
=======\r\n\
class D { }\r\n\
@@ -422,7 +423,7 @@ class D { }\r\n\
finalEndOfLineState(ts.EndOfLineState.None));
testLexicalClassification(
"class C {\r\n\
"class C {\r\n\
<<<<<<< HEAD\r\n\
v = 1;\r\n\
||||||| merged common ancestors\r\n\
@@ -447,7 +448,7 @@ class D { }\r\n\
finalEndOfLineState(ts.EndOfLineState.None));
testLexicalClassification(
"<<<<<<< HEAD\r\n\
"<<<<<<< HEAD\r\n\
class C { }\r\n\
||||||| merged common ancestors\r\n\
class E { }\r\n\
@@ -366,11 +366,11 @@ function [#|f|](): Promise<void>{
const result = getResult();
return fetch('https://typescriptlang.org').then(({ result }) => { console.log(result) });
}`);
_testConvertToAsyncFunction("convertToAsyncFunction_basicNoReturnTypeAnnotation", `
_testConvertToAsyncFunction("convertToAsyncFunction_basicNoReturnTypeAnnotation", `
function [#|f|]() {
return fetch('https://typescriptlang.org').then(result => { console.log(result) });
}`);
_testConvertToAsyncFunction("convertToAsyncFunction_basicWithComments", `
_testConvertToAsyncFunction("convertToAsyncFunction_basicWithComments", `
function [#|f|](): Promise<void>{
/* Note - some of these comments are removed during the refactor. This is not ideal. */
@@ -383,7 +383,7 @@ function [#|f|](): Promise<void>{
[#|():Promise<void> => {|]
return fetch('https://typescriptlang.org').then(result => console.log(result));
}`);
_testConvertToAsyncFunction("convertToAsyncFunction_ArrowFunctionNoAnnotation", `
_testConvertToAsyncFunction("convertToAsyncFunction_ArrowFunctionNoAnnotation", `
[#|() => {|]
return fetch('https://typescriptlang.org').then(result => console.log(result));
}`);
@@ -797,7 +797,7 @@ function my_print (resp) {
`
);
_testConvertToAsyncFunction("convertToAsyncFunction_Param2", `
_testConvertToAsyncFunction("convertToAsyncFunction_Param2", `
function [#|f|]() {
return my_print(fetch("https://typescriptlang.org").then(res => console.log(res))).catch(err => console.log("Error!", err));
}
@@ -948,7 +948,7 @@ function rej(reject){
`
);
_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMatchingTypes01", `
_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMatchingTypes01", `
function [#|f|](){
return fetch("https://typescriptlang.org").then(res).catch(rej).then(res);
}
@@ -979,7 +979,7 @@ function rej(reject){
);
_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMatchingTypes02", `
_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMatchingTypes02", `
function [#|f|](){
return fetch("https://typescriptlang.org").then(res => 0).catch(rej => 1).then(res);
}
@@ -990,7 +990,7 @@ function res(result): number {
`
);
_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMatchingTypes02NoAnnotations", `
_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMatchingTypes02NoAnnotations", `
function [#|f|](){
return fetch("https://typescriptlang.org").then(res => 0).catch(rej => 1).then(res);
}
@@ -999,7 +999,7 @@ function res(result){
return 5;
}
`
);
);
_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes01", `
function [#|f|](){
@@ -1016,7 +1016,7 @@ function rej(reject){
`
);
_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes02", `
_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes02", `
function [#|f|](){
return fetch("https://typescriptlang.org").then(res).catch(rej).then(res);
}
@@ -1031,7 +1031,7 @@ function rej(reject): Response{
`
);
_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes02NoAnnotations", `
_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes02NoAnnotations", `
function [#|f|](){
return fetch("https://typescriptlang.org").then(res).catch(rej).then(res);
}
@@ -1047,7 +1047,7 @@ function rej(reject){
);
_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes03", `
_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes03", `
function [#|f|](){
return fetch("https://typescriptlang.org").then(res).catch(rej).then(res);
}
@@ -1062,7 +1062,7 @@ function rej(reject){
`
);
_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes04", `
_testConvertToAsyncFunction("convertToAsyncFunction_CatchFollowedByThenMismatchTypes04", `
interface a {
name: string;
age: number;
@@ -1097,13 +1097,13 @@ function [#|f|]() {
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_PromiseCallInner", `
_testConvertToAsyncFunction("convertToAsyncFunction_PromiseCallInner", `
function [#|f|]() {
return fetch(Promise.resolve(1).then(res => "https://typescriptlang.org")).catch(err => console.log(err));
}
`);
_testConvertToAsyncFunctionFailed("convertToAsyncFunction_CatchFollowedByCall", `
_testConvertToAsyncFunctionFailed("convertToAsyncFunction_CatchFollowedByCall", `
function [#|f|](){
return fetch("https://typescriptlang.org").then(res).catch(rej).toString();
}
@@ -1118,7 +1118,6 @@ function rej(reject){
`
);
_testConvertToAsyncFunction("convertToAsyncFunction_Scope2", `
function [#|f|](){
var i:number;
@@ -1179,7 +1178,7 @@ function [#|f|]() {
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_NestedFunctionRightLocation", `
_testConvertToAsyncFunction("convertToAsyncFunction_NestedFunctionRightLocation", `
function f() {
function fn2(){
function [#|fn3|](){
@@ -1204,43 +1203,43 @@ function [#|f|]() {
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_ResRejNoArgsArrow", `
_testConvertToAsyncFunction("convertToAsyncFunction_ResRejNoArgsArrow", `
function [#|f|]() {
return Promise.resolve().then(() => 1, () => "a");
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_simpleFunctionExpression", `
_testConvertToAsyncFunction("convertToAsyncFunction_simpleFunctionExpression", `
const [#|foo|] = function () {
return fetch('https://typescriptlang.org').then(result => { console.log(result) });
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_simpleFunctionExpressionWithName", `
_testConvertToAsyncFunction("convertToAsyncFunction_simpleFunctionExpressionWithName", `
const foo = function [#|f|]() {
return fetch('https://typescriptlang.org').then(result => { console.log(result) });
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_simpleFunctionExpressionAssignedToBindingPattern", `
_testConvertToAsyncFunction("convertToAsyncFunction_simpleFunctionExpressionAssignedToBindingPattern", `
const { length } = [#|function|] () {
return fetch('https://typescriptlang.org').then(result => { console.log(result) });
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_catchBlockUniqueParams", `
_testConvertToAsyncFunction("convertToAsyncFunction_catchBlockUniqueParams", `
function [#|f|]() {
return Promise.resolve().then(x => 1).catch(x => "a").then(x => !!x);
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_catchBlockUniqueParamsBindingPattern", `
_testConvertToAsyncFunction("convertToAsyncFunction_catchBlockUniqueParamsBindingPattern", `
function [#|f|]() {
return Promise.resolve().then(() => ({ x: 3 })).catch(() => ({ x: "a" })).then(({ x }) => !!x);
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_bindingPattern", `
_testConvertToAsyncFunction("convertToAsyncFunction_bindingPattern", `
function [#|f|]() {
return fetch('https://typescriptlang.org').then(res);
}
@@ -1249,7 +1248,7 @@ function res({ status, trailer }){
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_bindingPatternNameCollision", `
_testConvertToAsyncFunction("convertToAsyncFunction_bindingPatternNameCollision", `
function [#|f|]() {
const result = 'https://typescriptlang.org';
return fetch(result).then(res);
@@ -1259,19 +1258,19 @@ function res({ status, trailer }){
}
`);
_testConvertToAsyncFunctionFailed("convertToAsyncFunction_thenArgumentNotFunction", `
_testConvertToAsyncFunctionFailed("convertToAsyncFunction_thenArgumentNotFunction", `
function [#|f|]() {
return Promise.resolve().then(f ? (x => x) : (y => y));
}
`);
_testConvertToAsyncFunctionFailed("convertToAsyncFunction_thenArgumentNotFunctionNotLastInChain", `
_testConvertToAsyncFunctionFailed("convertToAsyncFunction_thenArgumentNotFunctionNotLastInChain", `
function [#|f|]() {
return Promise.resolve().then(f ? (x => x) : (y => y)).then(q => q);
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_runEffectfulContinuation", `
_testConvertToAsyncFunction("convertToAsyncFunction_runEffectfulContinuation", `
function [#|f|]() {
return fetch('https://typescriptlang.org').then(res).then(_ => console.log("done"));
}
@@ -1280,31 +1279,31 @@ function res(result) {
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsPromise", `
_testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsPromise", `
function [#|f|]() {
return fetch('https://typescriptlang.org').then(s => Promise.resolve(s.statusText.length)).then(x => console.log(x + 5));
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsPromiseInBlock", `
_testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsPromiseInBlock", `
function [#|f|]() {
return fetch('https://typescriptlang.org').then(s => { return Promise.resolve(s.statusText.length) }).then(x => x + 5);
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsFixablePromise", `
_testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsFixablePromise", `
function [#|f|]() {
return fetch('https://typescriptlang.org').then(s => Promise.resolve(s.statusText).then(st => st.length)).then(x => console.log(x + 5));
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsPromiseLastInChain", `
_testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsPromiseLastInChain", `
function [#|f|]() {
return fetch('https://typescriptlang.org').then(s => Promise.resolve(s.statusText.length));
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsRejectedPromiseInTryBlock", `
_testConvertToAsyncFunction("convertToAsyncFunction_callbackReturnsRejectedPromiseInTryBlock", `
function [#|f|]() {
return Promise.resolve(1)
.then(x => Promise.reject(x))
@@ -1312,12 +1311,13 @@ function [#|f|]() {
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_nestedPromises", `
_testConvertToAsyncFunction("convertToAsyncFunction_nestedPromises", `
function [#|f|]() {
return fetch('https://typescriptlang.org').then(x => Promise.resolve(3).then(y => Promise.resolve(x.statusText.length + y)));
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_noArgs", `
_testConvertToAsyncFunction("convertToAsyncFunction_noArgs", `
function delay(millis: number): Promise<void> {
throw "no"
}
@@ -1330,13 +1330,14 @@ function [#|main2|]() {
.then(() => { console.log("."); return delay(500); })
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_exportModifier", `
_testConvertToAsyncFunction("convertToAsyncFunction_exportModifier", `
export function [#|foo|]() {
return fetch('https://typescriptlang.org').then(s => console.log(s));
}
`);
_testConvertToAsyncFunction("convertToAsyncFunction_OutermostOnlySuccess", `
_testConvertToAsyncFunction("convertToAsyncFunction_OutermostOnlySuccess", `
function [#|foo|]() {
return fetch('a').then(() => {
return fetch('b').then(() => 'c');
@@ -1344,7 +1345,7 @@ function [#|foo|]() {
}
`);
_testConvertToAsyncFunctionFailedSuggestion("convertToAsyncFunction_OutermostOnlyFailure", `
_testConvertToAsyncFunctionFailedSuggestion("convertToAsyncFunction_OutermostOnlyFailure", `
function foo() {
return fetch('a').then([#|() => {|]
return fetch('b').then(() => 'c');
@@ -220,7 +220,7 @@ namespace ts {
}`, /*includeLib*/ true);
testExtractFunction("extractFunction20",
`const _ = class {
`const _ = class {
a() {
[#|let a1 = { x: 1 };
return a1.x + 10;|]
@@ -545,14 +545,14 @@ var q = /*b*/ //c
/*j*/ 2|] /*k*/ //l
/*m*/; /*n*/ //o`);
testExtractFunction("extractFunction_NamelessClass", `
testExtractFunction("extractFunction_NamelessClass", `
export default class {
M() {
[#|1 + 1|];
}
}`);
testExtractFunction("extractFunction_NoDeclarations", `
testExtractFunction("extractFunction_NoDeclarations", `
function F() {
[#|arguments.length|]; // arguments has no declaration
}`);
@@ -43,7 +43,7 @@ namespace ts {
text += source.substring(lastPos, pos);
activeRanges[activeRanges.length - 1].end = text.length;
const range = activeRanges.pop()!;
if (range.name in ranges) {
if (hasProperty(ranges, range.name)) {
throw new Error(`Duplicate name of range ${range.name}`);
}
ranges.set(range.name, range);
@@ -173,4 +173,4 @@ namespace ts {
assert.isUndefined(find(infos, info => info.description === description.message));
});
}
}
}
@@ -177,7 +177,7 @@ namespace ts {
});
testExtractRangeFailed("extractRangeFailed1",
`
`
namespace A {
function f() {
[#|
@@ -188,13 +188,11 @@ function f() {
|]
}
}
`,
[
refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message
]);
`,
[refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message]);
testExtractRangeFailed("extractRangeFailed2",
`
`
namespace A {
function f() {
while (true) {
@@ -207,13 +205,11 @@ function f() {
}
}
}
`,
[
refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message
]);
`,
[refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message]);
testExtractRangeFailed("extractRangeFailed3",
`
`
namespace A {
function f() {
while (true) {
@@ -226,13 +222,11 @@ function f() {
}
}
}
`,
[
refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message
]);
`,
[refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message]);
testExtractRangeFailed("extractRangeFailed4",
`
`
namespace A {
function f() {
l1: {
@@ -245,13 +239,11 @@ function f() {
}
}
}
`,
[
refactor.extractSymbol.Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange.message
]);
`,
[refactor.extractSymbol.Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange.message]);
testExtractRangeFailed("extractRangeFailed5",
`
`
namespace A {
function f() {
[#|
@@ -266,13 +258,11 @@ function f() {
function f2() {
}
}
`,
[
refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message
]);
`,
[refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message]);
testExtractRangeFailed("extractRangeFailed6",
`
`
namespace A {
function f() {
[#|
@@ -287,134 +277,108 @@ function f() {
function f2() {
}
}
`,
[
refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message
]);
`,
[refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalReturnStatement.message]);
testExtractRangeFailed("extractRangeFailed7",
`
`
function test(x: number) {
while (x) {
x--;
[#|break;|]
}
}
`,
[
refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message
]);
`,
[refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message]);
testExtractRangeFailed("extractRangeFailed8",
`
`
function test(x: number) {
switch (x) {
case 1:
[#|break;|]
}
}
`,
[
refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message
]);
`,
[refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message]);
testExtractRangeFailed("extractRangeFailed9",
`var x = ([#||]1 + 2);`,
[
refactor.extractSymbol.Messages.cannotExtractEmpty.message
]);
`var x = ([#||]1 + 2);`,
[refactor.extractSymbol.Messages.cannotExtractEmpty.message]);
testExtractRangeFailed("extractRangeFailed10",
`
function f() {
return 1 + [#|2 + 3|];
`
function f() {
return 1 + [#|2 + 3|];
}
}
}
`,
[
refactor.extractSymbol.Messages.cannotExtractRange.message
]);
`,
[refactor.extractSymbol.Messages.cannotExtractRange.message]);
testExtractRangeFailed("extractRangeFailed11",
`
function f(x: number) {
while (true) {
[#|try {
x++;
`
function f(x: number) {
while (true) {
[#|try {
x++;
}
finally {
break;
}|]
}
finally {
break;
}|]
}
}
`,
[
refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message
]);
`,
[refactor.extractSymbol.Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements.message]);
testExtractRangeFailed("extractRangeFailed12",
`let [#|x|];`,
[
refactor.extractSymbol.Messages.statementOrExpressionExpected.message
]);
`let [#|x|];`,
[refactor.extractSymbol.Messages.statementOrExpressionExpected.message]);
testExtractRangeFailed("extractRangeFailed13",
`[#|return;|]`,
[
refactor.extractSymbol.Messages.cannotExtractRange.message
]);
`[#|return;|]`,
[refactor.extractSymbol.Messages.cannotExtractRange.message]);
testExtractRangeFailed("extractRangeFailed14",
`
switch(1) {
case [#|1:
break;|]
}
`,
[
refactor.extractSymbol.Messages.cannotExtractRange.message
]);
`
switch(1) {
case [#|1:
break;|]
}
`,
[refactor.extractSymbol.Messages.cannotExtractRange.message]);
testExtractRangeFailed("extractRangeFailed15",
`
switch(1) {
case [#|1:
break|];
}
`,
[
refactor.extractSymbol.Messages.cannotExtractRange.message
]);
`
switch(1) {
case [#|1:
break|];
}
`,
[refactor.extractSymbol.Messages.cannotExtractRange.message]);
// Documentation only - it would be nice if the result were [$|1|]
testExtractRangeFailed("extractRangeFailed16",
`
switch(1) {
[#|case 1|]:
break;
}
`,
[
refactor.extractSymbol.Messages.cannotExtractRange.message
]);
`
switch(1) {
[#|case 1|]:
break;
}
`,
[refactor.extractSymbol.Messages.cannotExtractRange.message]);
// Documentation only - it would be nice if the result were [$|1|]
testExtractRangeFailed("extractRangeFailed17",
`
switch(1) {
[#|case 1:|]
break;
}
`,
[
refactor.extractSymbol.Messages.cannotExtractRange.message
]);
`
switch(1) {
[#|case 1:|]
break;
}
`,
[refactor.extractSymbol.Messages.cannotExtractRange.message]);
testExtractRangeFailed("extractRangeFailed18",
`[#|{ 1;|] }`,
[
refactor.extractSymbol.Messages.cannotExtractRange.message
]);
`[#|{ 1;|] }`,
[refactor.extractSymbol.Messages.cannotExtractRange.message]);
testExtractRangeFailed("extract-method-not-for-token-expression-statement", `[#|a|]`, [refactor.extractSymbol.Messages.cannotExtractIdentifier.message]);
});
@@ -60,12 +60,12 @@ namespace ts {
it("should respect CRLF line endings around outlining spans", () => {
verifyOutliningSpanNewLines("// comment not included\r\n// #region name\r\nlet x: string = \"x\";\r\n// #endregion name\r\n",
{ newLine: NewLineKind.CarriageReturnLineFeed });
{ newLine: NewLineKind.CarriageReturnLineFeed });
});
it("should respect LF line endings around outlining spans", () => {
verifyOutliningSpanNewLines("// comment not included\n// #region name\nlet x: string = \"x\";\n// #endregion name\n\n",
{ newLine: NewLineKind.LineFeed });
{ newLine: NewLineKind.LineFeed });
});
});
}
@@ -14,7 +14,7 @@ class Carousel<T> extends Vue {
"vue.d.ts": `export namespace Vue { export type Config = { template: string }; }`,
"vue-class-component.d.ts": `import Vue from "./vue";
export function Component(x: Config): any;`
};
};
// Regression test for GH #18245 - bug in single line comment writer caused a debug assertion when attempting
// to write an alias to a module's default export was referrenced across files and had no default export
it("should be able to create a language service which can respond to deinition requests without throwing", () => {
@@ -40,7 +40,7 @@ export function Component(x: Config): any;`
},
});
const definitions = languageService.getDefinitionAtPosition("foo.ts", 160); // 160 is the latter `vueTemplateHtml` position
expect(definitions).to.exist; // tslint:disable-line no-unused-expression
expect(definitions).to.exist; // eslint-disable-line no-unused-expressions
});
});
}
@@ -344,9 +344,9 @@ import { } from "lib";
libFile);
testOrganizeImports("Unused_false_positive_module_augmentation",
{
path: "/test.d.ts",
content: `
{
path: "/test.d.ts",
content: `
import foo from 'foo';
import { Caseless } from 'caseless';
@@ -356,12 +356,12 @@ declare module 'caseless' {
test(name: KeyType): boolean;
}
}`
});
});
testOrganizeImports("Unused_preserve_imports_for_module_augmentation_in_non_declaration_file",
{
path: "/test.ts",
content: `
{
path: "/test.ts",
content: `
import foo from 'foo';
import { Caseless } from 'caseless';
@@ -371,10 +371,10 @@ declare module 'caseless' {
test(name: KeyType): boolean;
}
}`
});
});
testOrganizeImports("Unused_false_positive_shorthand_assignment",
{
{
path: "/test.ts",
content: `
import { x } from "a";
@@ -383,7 +383,7 @@ const o = { x };
});
testOrganizeImports("Unused_false_positive_export_shorthand",
{
{
path: "/test.ts",
content: `
import { x } from "a";
@@ -406,7 +406,7 @@ D();
},
libFile);
// tslint:disable no-invalid-template-strings
/* eslint-disable no-template-curly-in-string */
testOrganizeImports("MoveToTop_Invalid",
{
path: "/test.ts",
@@ -423,7 +423,7 @@ D();
`,
},
libFile);
// tslint:enable no-invalid-template-strings
/* eslint-enable no-template-curly-in-string */
testOrganizeImports("CoalesceMultipleModules",
{
@@ -668,7 +668,7 @@ export * from "lib";
},
libFile);
// tslint:disable no-invalid-template-strings
/* eslint-disable no-template-curly-in-string */
testOrganizeExports("MoveToTop_Invalid",
{
path: "/test.ts",
@@ -684,7 +684,7 @@ export { D } from "lib";
`,
},
libFile);
// tslint:enable no-invalid-template-strings
/* eslint-enable no-template-curly-in-string */
testOrganizeExports("MoveToTop_WithImportsFirst",
{
@@ -831,14 +831,14 @@ export * from "lib";
}
});
function parseImports(...importStrings: string[]): ReadonlyArray<ImportDeclaration> {
function parseImports(...importStrings: string[]): readonly ImportDeclaration[] {
const sourceFile = createSourceFile("a.ts", importStrings.join("\n"), ScriptTarget.ES2015, /*setParentNodes*/ true, ScriptKind.TS);
const imports = filter(sourceFile.statements, isImportDeclaration);
assert.equal(imports.length, importStrings.length);
return imports;
}
function parseExports(...exportStrings: string[]): ReadonlyArray<ExportDeclaration> {
function parseExports(...exportStrings: string[]): readonly ExportDeclaration[] {
const sourceFile = createSourceFile("a.ts", exportStrings.join("\n"), ScriptTarget.ES2015, /*setParentNodes*/ true, ScriptKind.TS);
const exports = filter(sourceFile.statements, isExportDeclaration);
assert.equal(exports.length, exportStrings.length);
@@ -920,7 +920,7 @@ export * from "lib";
}
}
function assertListEqual(list1: ReadonlyArray<Node>, list2: ReadonlyArray<Node>) {
function assertListEqual(list1: readonly Node[], list2: readonly Node[]) {
if (list1 === undefined || list2 === undefined) {
assert.isUndefined(list1);
assert.isUndefined(list2);
@@ -44,7 +44,7 @@ describe("unittests:: services:: PreProcessFile:", () => {
ambientExternalModules: undefined,
isLibFile: false
});
}),
});
it("Do not return reference path because of invalid triple-slash syntax", () => {
test("///<reference path\"refFile1.ts\" />" + "\n" + "///<reference path =\"refFile2.ts\">" + "\n" + "///<referencepath=\"refFile3.ts\" />" + "\n" + "///<reference pat= \"refFile4d.ts\" />",
@@ -58,7 +58,7 @@ describe("unittests:: services:: PreProcessFile:", () => {
ambientExternalModules: undefined,
isLibFile: false
});
}),
});
it("Do not return reference path of non-imports", () => {
test("Quill.import('delta');",
@@ -72,7 +72,7 @@ describe("unittests:: services:: PreProcessFile:", () => {
ambientExternalModules: undefined,
isLibFile: false
});
}),
});
it("Do not return reference path of nested non-imports", () => {
test("a.b.import('c');",
@@ -86,7 +86,7 @@ describe("unittests:: services:: PreProcessFile:", () => {
ambientExternalModules: undefined,
isLibFile: false
});
}),
});
it("Correctly return imported files", () => {
test("import i1 = require(\"r1.ts\"); import i2 =require(\"r2.ts\"); import i3= require(\"r3.ts\"); import i4=require(\"r4.ts\"); import i5 = require (\"r5.ts\");",
@@ -101,7 +101,7 @@ describe("unittests:: services:: PreProcessFile:", () => {
ambientExternalModules: undefined,
isLibFile: false
});
}),
});
it("Do not return imported files if readImportFiles argument is false", () => {
test("import i1 = require(\"r1.ts\"); import i2 =require(\"r2.ts\"); import i3= require(\"r3.ts\"); import i4=require(\"r4.ts\"); import i5 = require (\"r5.ts\");",
@@ -115,7 +115,7 @@ describe("unittests:: services:: PreProcessFile:", () => {
ambientExternalModules: undefined,
isLibFile: false
});
}),
});
it("Do not return import path because of invalid import syntax", () => {
test("import i1 require(\"r1.ts\"); import = require(\"r2.ts\") import i3= require(\"r3.ts\"); import i5",
@@ -129,7 +129,7 @@ describe("unittests:: services:: PreProcessFile:", () => {
ambientExternalModules: undefined,
isLibFile: false
});
}),
});
it("Correctly return referenced files and import files", () => {
test("///<reference path=\"refFile1.ts\" />" + "\n" + "///<reference path =\"refFile2.ts\"/>" + "\n" + "import i1 = require(\"r1.ts\"); import i2 =require(\"r2.ts\");",
@@ -143,7 +143,7 @@ describe("unittests:: services:: PreProcessFile:", () => {
ambientExternalModules: undefined,
isLibFile: false
});
}),
});
it("Correctly return referenced files and import files even with some invalid syntax", () => {
test("///<reference path=\"refFile1.ts\" />" + "\n" + "///<reference path \"refFile2.ts\"/>" + "\n" + "import i1 = require(\"r1.ts\"); import = require(\"r2.ts\"); import i2 = require(\"r3.ts\");",
@@ -167,24 +167,24 @@ describe("unittests:: services:: PreProcessFile:", () => {
"import {a as A} from \"m5\";" + "\n" +
"import {a as A, b, c as C} from \"m6\";" + "\n" +
"import def , {a, b, c as C} from \"m7\";" + "\n",
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [],
typeReferenceDirectives: [],
libReferenceDirectives: [],
importedFiles: [
{ fileName: "m1", pos: 20, end: 22 },
{ fileName: "m2", pos: 51, end: 53 },
{ fileName: "m3", pos: 73, end: 75 },
{ fileName: "m4", pos: 95, end: 97 },
{ fileName: "m5", pos: 122, end: 124 },
{ fileName: "m6", pos: 160, end: 162 },
{ fileName: "m7", pos: 199, end: 201 }
],
ambientExternalModules: undefined,
isLibFile: false
});
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [],
typeReferenceDirectives: [],
libReferenceDirectives: [],
importedFiles: [
{ fileName: "m1", pos: 20, end: 22 },
{ fileName: "m2", pos: 51, end: 53 },
{ fileName: "m3", pos: 73, end: 75 },
{ fileName: "m4", pos: 95, end: 97 },
{ fileName: "m5", pos: 122, end: 124 },
{ fileName: "m6", pos: 160, end: 162 },
{ fileName: "m7", pos: 199, end: 201 }
],
ambientExternalModules: undefined,
isLibFile: false
});
});
it("Correctly return ES6 exports", () => {
@@ -192,41 +192,40 @@ describe("unittests:: services:: PreProcessFile:", () => {
"export {a} from \"m2\";" + "\n" +
"export {a as A} from \"m3\";" + "\n" +
"export {a as A, b, c as C} from \"m4\";" + "\n",
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [],
typeReferenceDirectives: [],
libReferenceDirectives: [],
importedFiles: [
{ fileName: "m1", pos: 14, end: 16 },
{ fileName: "m2", pos: 36, end: 38 },
{ fileName: "m3", pos: 63, end: 65 },
{ fileName: "m4", pos: 101, end: 103 },
],
ambientExternalModules: undefined,
isLibFile: false
});
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [],
typeReferenceDirectives: [],
libReferenceDirectives: [],
importedFiles: [
{ fileName: "m1", pos: 14, end: 16 },
{ fileName: "m2", pos: 36, end: 38 },
{ fileName: "m3", pos: 63, end: 65 },
{ fileName: "m4", pos: 101, end: 103 },
],
ambientExternalModules: undefined,
isLibFile: false
});
});
it("Correctly return ambient external modules", () => {
test(`
test(`
declare module A {}
declare module "B" {}
function foo() {
}
`,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [],
typeReferenceDirectives: [],
libReferenceDirectives: [],
importedFiles: [],
ambientExternalModules: ["B"],
isLibFile: false
});
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [],
typeReferenceDirectives: [],
libReferenceDirectives: [],
importedFiles: [],
ambientExternalModules: ["B"],
isLibFile: false
});
});
it("Correctly handles export import declarations", () => {
@@ -251,60 +250,62 @@ describe("unittests:: services:: PreProcessFile:", () => {
foo(require('m3'));
var z = { f: require('m4') }
`,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ true,
{
referencedFiles: [],
typeReferenceDirectives: [],
libReferenceDirectives: [],
importedFiles: [
{ fileName: "m1", pos: 39, end: 41 },
{ fileName: "m2", pos: 74, end: 76 },
{ fileName: "m3", pos: 105, end: 107 },
{ fileName: "m4", pos: 146, end: 148 },
],
ambientExternalModules: undefined,
isLibFile: false
});
/*readImportFile*/ true,
/*detectJavaScriptImports*/ true,
{
referencedFiles: [],
typeReferenceDirectives: [],
libReferenceDirectives: [],
importedFiles: [
{ fileName: "m1", pos: 39, end: 41 },
{ fileName: "m2", pos: 74, end: 76 },
{ fileName: "m3", pos: 105, end: 107 },
{ fileName: "m4", pos: 146, end: 148 },
],
ambientExternalModules: undefined,
isLibFile: false
});
});
it("Correctly handles dependency lists in define([deplist]) calls in JavaScript files", () => {
test(`
define(["mod1", "mod2"], (m1, m2) => {
});
`,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ true,
{
referencedFiles: [],
typeReferenceDirectives: [],
libReferenceDirectives: [],
importedFiles: [
{ fileName: "mod1", pos: 21, end: 25 },
{ fileName: "mod2", pos: 29, end: 33 },
],
ambientExternalModules: undefined,
isLibFile: false
});
/*readImportFile*/ true,
/*detectJavaScriptImports*/ true,
{
referencedFiles: [],
typeReferenceDirectives: [],
libReferenceDirectives: [],
importedFiles: [
{ fileName: "mod1", pos: 21, end: 25 },
{ fileName: "mod2", pos: 29, end: 33 },
],
ambientExternalModules: undefined,
isLibFile: false
});
});
it("Correctly handles dependency lists in define(modName, [deplist]) calls in JavaScript files", () => {
test(`
define("mod", ["mod1", "mod2"], (m1, m2) => {
});
`,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ true,
{
referencedFiles: [],
typeReferenceDirectives: [],
libReferenceDirectives: [],
importedFiles: [
{ fileName: "mod1", pos: 28, end: 32 },
{ fileName: "mod2", pos: 36, end: 40 },
],
ambientExternalModules: undefined,
isLibFile: false
});
/*readImportFile*/ true,
/*detectJavaScriptImports*/ true,
{
referencedFiles: [],
typeReferenceDirectives: [],
libReferenceDirectives: [],
importedFiles: [
{ fileName: "mod1", pos: 28, end: 32 },
{ fileName: "mod2", pos: 36, end: 40 },
],
ambientExternalModules: undefined,
isLibFile: false
});
});
it("correctly handles augmentations in external modules - 1", () => {
test(`
declare module "../Observable" {
@@ -1,5 +1,4 @@
// Some tests have trailing whitespace
// tslint:disable trim-trailing-whitespace
namespace ts {
describe("unittests:: services:: textChanges", () => {
@@ -84,14 +83,14 @@ namespace M
runSingleFileTest("extractMethodLike", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => {
const statements = (<FunctionDeclaration>findChild("foo", sourceFile)).body!.statements.slice(1);
const newFunction = createFunctionDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ "bar",
/*typeParameters*/ undefined,
/*parameters*/ emptyArray,
/*type*/ createKeywordTypeNode(SyntaxKind.AnyKeyword),
/*body */ createBlock(statements)
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ "bar",
/*typeParameters*/ undefined,
/*parameters*/ emptyArray,
/*type*/ createKeywordTypeNode(SyntaxKind.AnyKeyword),
/*body */ createBlock(statements)
);
changeTracker.insertNodeBefore(sourceFile, /*before*/findChild("M2", sourceFile), newFunction);
@@ -183,12 +182,12 @@ var a = 4; // comment 7
}
function createTestClass() {
return createClassDeclaration(
/*decorators*/ undefined,
/*decorators*/ undefined,
[
createToken(SyntaxKind.PublicKeyword)
],
"class1",
/*typeParameters*/ undefined,
/*typeParameters*/ undefined,
[
createHeritageClause(
SyntaxKind.ImplementsKeyword,
@@ -199,12 +198,12 @@ var a = 4; // comment 7
],
[
createProperty(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*decorators*/ undefined,
/*modifiers*/ undefined,
"property1",
/*questionToken*/ undefined,
/*questionToken*/ undefined,
createKeywordTypeNode(SyntaxKind.BooleanKeyword),
/*initializer*/ undefined
/*initializer*/ undefined
)
]
);
@@ -336,8 +335,8 @@ namespace M {
function createTestSuperCall() {
const superCall = createCall(
createSuper(),
/*typeArguments*/ undefined,
/*argumentsArray*/ emptyArray
/*typeArguments*/ undefined,
/*argumentsArray*/ emptyArray
);
return createStatement(superCall);
}
+28 -31
View File
@@ -8,15 +8,11 @@ namespace ts {
function transpilesCorrectly(name: string, input: string, testSettings: TranspileTestSettings) {
describe(name, () => {
let justName: string;
let transpileOptions: TranspileOptions;
let canUseOldTranspile: boolean;
let toBeCompiled: Harness.Compiler.TestFile[];
let transpileResult: TranspileOutput;
let oldTranspileResult: string;
let oldTranspileDiagnostics: Diagnostic[];
transpileOptions = testSettings.options || {};
const transpileOptions: TranspileOptions = testSettings.options || {};
if (!transpileOptions.compilerOptions) {
transpileOptions.compilerOptions = { };
}
@@ -41,13 +37,12 @@ namespace ts {
transpileOptions.reportDiagnostics = true;
justName = "transpile/" + name.replace(/[^a-z0-9\-. ]/ig, "") + (transpileOptions.compilerOptions.jsx ? Extension.Tsx : Extension.Ts);
toBeCompiled = [{
const justName = "transpile/" + name.replace(/[^a-z0-9\-. ]/ig, "") + (transpileOptions.compilerOptions.jsx ? Extension.Tsx : Extension.Ts);
const toBeCompiled = [{
unitName,
content: input
}];
canUseOldTranspile = !transpileOptions.renamedDependencies;
const canUseOldTranspile = !transpileOptions.renamedDependencies;
before(() => {
transpileResult = transpileModule(input, transpileOptions);
@@ -64,19 +59,19 @@ namespace ts {
oldTranspileDiagnostics = undefined!;
});
/* eslint-disable no-null/no-null */
it("Correct errors for " + justName, () => {
Harness.Baseline.runBaseline(justName.replace(/\.tsx?$/, ".errors.txt"),
// tslint:disable-next-line no-null-keyword
transpileResult.diagnostics!.length === 0 ? null : Harness.Compiler.getErrorBaseline(toBeCompiled, transpileResult.diagnostics!));
});
if (canUseOldTranspile) {
it("Correct errors (old transpile) for " + justName, () => {
Harness.Baseline.runBaseline(justName.replace(/\.tsx?$/, ".oldTranspile.errors.txt"),
// tslint:disable-next-line no-null-keyword
oldTranspileDiagnostics.length === 0 ? null : Harness.Compiler.getErrorBaseline(toBeCompiled, oldTranspileDiagnostics));
});
}
/* eslint-enable no-null/no-null */
it("Correct output for " + justName, () => {
Harness.Baseline.runBaseline(justName.replace(/\.tsx?$/, Extension.Js), transpileResult.outputText);
@@ -96,8 +91,8 @@ namespace ts {
transpilesCorrectly("Generates no diagnostics for missing file references", `/// <reference path="file2.ts" />
var x = 0;`, {
options: { compilerOptions: { module: ModuleKind.CommonJS } }
});
options: { compilerOptions: { module: ModuleKind.CommonJS } }
});
transpilesCorrectly("Generates no diagnostics for missing module imports", `import {a} from "module2";`, {
options: { compilerOptions: { module: ModuleKind.CommonJS } }
@@ -435,17 +430,18 @@ var x = 0;`, {
`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,
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";` +
@@ -454,17 +450,18 @@ var x = 0;`, {
`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,
options: {
compilerOptions: {
target: ScriptTarget.ES5,
module: ModuleKind.System,
moduleResolution: ModuleResolutionKind.NodeJs,
emitDecoratorMetadata: true,
experimentalDecorators: true,
isolatedModules: true,
}
}
}
});
);
transpilesCorrectly("Supports readonly keyword for arrays", "let x: readonly string[];", {
options: { compilerOptions: { module: ModuleKind.CommonJS } }
+62 -62
View File
@@ -137,28 +137,28 @@ namespace ts {
class C { foo = 10; static bar = 20 }
namespace C { export let x = 10; }
`, {
transformers: {
before: [forceNamespaceRewrite],
},
compilerOptions: {
target: ScriptTarget.ESNext,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
transformers: {
before: [forceNamespaceRewrite],
},
compilerOptions: {
target: ScriptTarget.ESNext,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
});
testBaseline("transformTypesInExportDefault", () => {
return transpileModule(`
export default (foo: string) => { return 1; }
`, {
transformers: {
before: [replaceNumberWith2],
},
compilerOptions: {
target: ScriptTarget.ESNext,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
transformers: {
before: [replaceNumberWith2],
},
compilerOptions: {
target: ScriptTarget.ESNext,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
});
testBaseline("synthesizedClassAndNamespaceCombination", () => {
@@ -344,14 +344,14 @@ namespace ts {
const exportedSeparately = 2;
export {exportedSeparately};
`, {
transformers: {
before: [addSyntheticComment(isVariableStatement)],
},
compilerOptions: {
target: ScriptTarget.ES5,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
transformers: {
before: [addSyntheticComment(isVariableStatement)],
},
compilerOptions: {
target: ScriptTarget.ES5,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
});
// https://github.com/Microsoft/TypeScript/issues/17594
@@ -365,14 +365,14 @@ export { /* specifier comment */ X, Y} from 'somewhere';
export * from 'somewhere';
export {Value};
`, {
transformers: {
before: [addSyntheticComment(n => isImportDeclaration(n) || isExportDeclaration(n) || isImportSpecifier(n) || isExportSpecifier(n))],
},
compilerOptions: {
target: ScriptTarget.ES5,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
transformers: {
before: [addSyntheticComment(n => isImportDeclaration(n) || isExportDeclaration(n) || isImportSpecifier(n) || isExportSpecifier(n))],
},
compilerOptions: {
target: ScriptTarget.ES5,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
});
// https://github.com/Microsoft/TypeScript/issues/17594
@@ -388,14 +388,14 @@ class Clazz {
constructor(readonly field = 1) {}
}
`, {
transformers: {
before: [addSyntheticComment(n => isPropertyDeclaration(n) || isParameterPropertyDeclaration(n) || isClassDeclaration(n) || isConstructorDeclaration(n))],
},
compilerOptions: {
target: ScriptTarget.ES2015,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
transformers: {
before: [addSyntheticComment(n => isPropertyDeclaration(n) || isParameterPropertyDeclaration(n) || isClassDeclaration(n) || isConstructorDeclaration(n))],
},
compilerOptions: {
target: ScriptTarget.ES2015,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
});
testBaseline("transformAddCommentToNamespace", () => {
@@ -409,14 +409,14 @@ namespace Foo {
export const y = 1;
}
`, {
transformers: {
before: [addSyntheticComment(n => isModuleDeclaration(n))],
},
compilerOptions: {
target: ScriptTarget.ES2015,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
transformers: {
before: [addSyntheticComment(n => isModuleDeclaration(n))],
},
compilerOptions: {
target: ScriptTarget.ES2015,
newLine: NewLineKind.CarriageReturnLineFeed,
}
}).outputText;
});
// https://github.com/Microsoft/TypeScript/issues/24709
@@ -428,9 +428,9 @@ namespace Foo {
const host = new fakes.CompilerHost(fs);
host.getSourceFile = () => transformedSourceFile;
const program = createProgram(["source.ts"], {
target: ScriptTarget.ES3,
module: ModuleKind.None,
noLib: true
target: ScriptTarget.ES3,
module: ModuleKind.None,
noLib: true
}, host);
program.emit(transformedSourceFile, (_p, s, b) => host.writeFile("source.js", s, b));
return host.readFile("source.js")!.toString();
@@ -439,18 +439,18 @@ namespace Foo {
const visitor: Visitor = (node) => {
if (isMethodDeclaration(node)) {
return updateMethod(
node,
node.decorators,
node.modifiers,
node.asteriskToken,
createIdentifier("foobar"),
node.questionToken,
node.typeParameters,
node.parameters,
node.type,
node.body,
node,
node.decorators,
node.modifiers,
node.asteriskToken,
createIdentifier("foobar"),
node.questionToken,
node.typeParameters,
node.parameters,
node.type,
node.body,
);
}
}
return visitEachChild(node, visitor, context);
};
return (node: SourceFile) => visitNode(node, visitor);
@@ -22,7 +22,7 @@ namespace ts {
"/src/app/module.tsbuildinfo"
]
];
type Sources = [string, ReadonlyArray<string>];
type Sources = [string, readonly string[]];
const enum source { config, ts }
const sources: [Sources, Sources] = [
[
+14 -15
View File
@@ -164,7 +164,7 @@ interface Symbol {
}
}
function generateSourceMapBaselineFiles(fs: vfs.FileSystem, mapFileNames: ReadonlyArray<string>) {
function generateSourceMapBaselineFiles(fs: vfs.FileSystem, mapFileNames: readonly string[]) {
for (const mapFile of mapFileNames) {
if (!fs.existsSync(mapFile)) continue;
const text = Harness.SourceMapRecorder.getSourceMapRecordWithVFS(fs, mapFile);
@@ -174,7 +174,7 @@ interface Symbol {
// [tsbuildinfo, js, dts]
export type BuildInfoSectionBaselineFiles = [string, string | undefined, string | undefined];
function generateBuildInfoSectionBaselineFiles(fs: vfs.FileSystem, buildInfoFileNames: ReadonlyArray<BuildInfoSectionBaselineFiles>) {
function generateBuildInfoSectionBaselineFiles(fs: vfs.FileSystem, buildInfoFileNames: readonly BuildInfoSectionBaselineFiles[]) {
for (const [file, jsFile, dtsFile] of buildInfoFileNames) {
if (!fs.existsSync(file)) continue;
@@ -232,9 +232,9 @@ interface Symbol {
interface BuildInput {
fs: vfs.FileSystem;
tick: () => void;
rootNames: ReadonlyArray<string>;
expectedMapFileNames?: ReadonlyArray<string>;
expectedBuildInfoFilesForSectionBaselines?: ReadonlyArray<BuildInfoSectionBaselineFiles>;
rootNames: readonly string[];
expectedMapFileNames?: readonly string[];
expectedBuildInfoFilesForSectionBaselines?: readonly BuildInfoSectionBaselineFiles[];
modifyFs: (fs: vfs.FileSystem) => void;
}
@@ -263,7 +263,7 @@ interface Symbol {
function generateBaseline(fs: vfs.FileSystem, proj: string, scenario: string, subScenario: string, baseFs: vfs.FileSystem) {
const patch = fs.diff(baseFs);
// tslint:disable-next-line:no-null-keyword
// eslint-disable-next-line no-null/no-null
Harness.Baseline.runBaseline(`tsbuild/${proj}/${subScenario.split(" ").join("-")}/${scenario.split(" ").join("-")}.js`, patch ? vfs.formatPatch(patch) : null);
}
@@ -273,12 +273,11 @@ interface Symbol {
const actual = actualReadFileMap.get(expectedFile);
assert.equal(actual, expected, `Mismatch in read file call number for: ${expectedFile}
Not in Actual: ${JSON.stringify(arrayFrom(mapDefinedIterator(expectedReadFiles.keys(), f => actualReadFileMap.has(f) ? undefined : f)))}
Mismatch Actual(path, actual, expected): ${JSON.stringify(arrayFrom(mapDefinedIterator(actualReadFileMap.entries(),
([p, v]) => expectedReadFiles.get(p) !== v ? [p, v, expectedReadFiles.get(p) || 0] : undefined)))}`);
Mismatch Actual(path, actual, expected): ${JSON.stringify(arrayFrom(mapDefinedIterator(actualReadFileMap.entries(), ([p, v]) => expectedReadFiles.get(p) !== v ? [p, v, expectedReadFiles.get(p) || 0] : undefined)))}`);
});
}
export function getReadFilesMap(filesReadOnce: ReadonlyArray<string>, ...filesWithTwoReadCalls: string[]) {
export function getReadFilesMap(filesReadOnce: readonly string[], ...filesWithTwoReadCalls: string[]) {
const map = arrayToMap(filesReadOnce, identity, () => 1);
for (const fileWithTwoReadCalls of filesWithTwoReadCalls) {
map.set(fileWithTwoReadCalls, 2);
@@ -287,7 +286,7 @@ Mismatch Actual(path, actual, expected): ${JSON.stringify(arrayFrom(mapDefinedIt
}
export interface ExpectedBuildOutput {
expectedDiagnostics?: ReadonlyArray<fakes.ExpectedDiagnostic>;
expectedDiagnostics?: readonly fakes.ExpectedDiagnostic[];
expectedReadFiles?: ReadonlyMap<number>;
}
@@ -301,13 +300,13 @@ Mismatch Actual(path, actual, expected): ${JSON.stringify(arrayFrom(mapDefinedIt
time: () => number;
tick: () => void;
proj: string;
rootNames: ReadonlyArray<string>;
rootNames: readonly string[];
/** map file names to generate baseline of */
expectedMapFileNames?: ReadonlyArray<string>;
expectedBuildInfoFilesForSectionBaselines?: ReadonlyArray<BuildInfoSectionBaselineFiles>;
expectedMapFileNames?: readonly string[];
expectedBuildInfoFilesForSectionBaselines?: readonly BuildInfoSectionBaselineFiles[];
lastProjectOutput: string;
initialBuild: BuildState;
outputFiles?: ReadonlyArray<string>;
outputFiles?: readonly string[];
incrementalDtsChangedBuild?: BuildState;
incrementalDtsUnchangedBuild?: BuildState;
incrementalHeaderChangedBuild?: BuildState;
@@ -358,7 +357,7 @@ Mismatch Actual(path, actual, expected): ${JSON.stringify(arrayFrom(mapDefinedIt
}
});
function incrementalBuild(subScenario: string, incrementalModifyFs: (fs: vfs.FileSystem) => void, incrementalExpectedDiagnostics: ReadonlyArray<fakes.ExpectedDiagnostic> | undefined, incrementalExpectedReadFiles: ReadonlyMap<number> | undefined) {
function incrementalBuild(subScenario: string, incrementalModifyFs: (fs: vfs.FileSystem) => void, incrementalExpectedDiagnostics: readonly fakes.ExpectedDiagnostic[] | undefined, incrementalExpectedReadFiles: ReadonlyMap<number> | undefined) {
describe(subScenario, () => {
let newFs: vfs.FileSystem;
let actualReadFileMap: Map<number>;
+12 -12
View File
@@ -29,7 +29,7 @@ namespace ts {
]
];
const relOutputFiles = outputFiles.map(v => v.map(relName)) as [OutputFile, OutputFile, OutputFile];
type Sources = [string, ReadonlyArray<string>];
type Sources = [string, readonly string[]];
const enum source { config, ts }
const enum part { one, two, three }
const sources: [Sources, Sources, Sources] = [
@@ -63,7 +63,7 @@ namespace ts {
outputFiles[project.third][ext.jsmap],
outputFiles[project.third][ext.dtsmap]
];
const expectedTsbuildInfoFileNames: ReadonlyArray<BuildInfoSectionBaselineFiles> = [
const expectedTsbuildInfoFileNames: readonly BuildInfoSectionBaselineFiles[] = [
[outputFiles[project.first][ext.buildinfo], outputFiles[project.first][ext.js], outputFiles[project.first][ext.dts]],
[outputFiles[project.second][ext.buildinfo], outputFiles[project.second][ext.js], outputFiles[project.second][ext.dts]],
[outputFiles[project.third][ext.buildinfo], outputFiles[project.third][ext.js], outputFiles[project.third][ext.dts]]
@@ -75,7 +75,7 @@ namespace ts {
...outputFiles[project.second],
...outputFiles[project.third]
];
let initialExpectedDiagnostics: ReadonlyArray<fakes.ExpectedDiagnostic> = [
let initialExpectedDiagnostics: readonly fakes.ExpectedDiagnostic[] = [
getExpectedDiagnosticForProjectsInBuild(relSources[project.first][source.config], relSources[project.second][source.config], relSources[project.third][source.config]),
[Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relSources[project.first][source.config], relOutputFiles[project.first][ext.js]],
[Diagnostics.Building_project_0, sources[project.first][source.config]],
@@ -102,7 +102,7 @@ namespace ts {
]
);
let dtsChangedExpectedDiagnostics: ReadonlyArray<fakes.ExpectedDiagnostic> = [
let dtsChangedExpectedDiagnostics: readonly fakes.ExpectedDiagnostic[] = [
getExpectedDiagnosticForProjectsInBuild(relSources[project.first][source.config], relSources[project.second][source.config], relSources[project.third][source.config]),
[Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relSources[project.first][source.config], relOutputFiles[project.first][ext.js], relSources[project.first][source.ts][part.one]],
[Diagnostics.Building_project_0, sources[project.first][source.config]],
@@ -129,7 +129,7 @@ namespace ts {
outputFiles[project.first][ext.dts], // dts changes so once read old content, and once new (to emit third)
);
let dtsChangedExpectedDiagnosticsDependOrdered: ReadonlyArray<fakes.ExpectedDiagnostic> = [
let dtsChangedExpectedDiagnosticsDependOrdered: readonly fakes.ExpectedDiagnostic[] = [
getExpectedDiagnosticForProjectsInBuild(relSources[project.first][source.config], relSources[project.second][source.config], relSources[project.third][source.config]),
[Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relSources[project.first][source.config], relOutputFiles[project.first][ext.js], relSources[project.first][source.ts][part.one]],
[Diagnostics.Building_project_0, sources[project.first][source.config]],
@@ -140,7 +140,7 @@ namespace ts {
];
let dtsChangedExpectedReadFilesDependOrdered: ReadonlyMap<number> = getDtsChangedReadFilesDependOrdered();
let dtsUnchangedExpectedDiagnostics: ReadonlyArray<fakes.ExpectedDiagnostic> = [
let dtsUnchangedExpectedDiagnostics: readonly fakes.ExpectedDiagnostic[] = [
getExpectedDiagnosticForProjectsInBuild(relSources[project.first][source.config], relSources[project.second][source.config], relSources[project.third][source.config]),
[Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relSources[project.first][source.config], relOutputFiles[project.first][ext.js], relSources[project.first][source.ts][part.one]],
[Diagnostics.Building_project_0, sources[project.first][source.config]],
@@ -166,7 +166,7 @@ namespace ts {
]
);
let dtsUnchangedExpectedDiagnosticsDependOrdered: ReadonlyArray<fakes.ExpectedDiagnostic> = [
let dtsUnchangedExpectedDiagnosticsDependOrdered: readonly fakes.ExpectedDiagnostic[] = [
getExpectedDiagnosticForProjectsInBuild(relSources[project.first][source.config], relSources[project.second][source.config], relSources[project.third][source.config]),
[Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relSources[project.first][source.config], relOutputFiles[project.first][ext.js], relSources[project.first][source.ts][part.one]],
[Diagnostics.Building_project_0, sources[project.first][source.config]],
@@ -201,7 +201,7 @@ namespace ts {
return ts.createSolutionBuilder(host, ["/src/third"], { dry: false, force: false, verbose: true, ...(baseOptions || {}) });
}
function getInitialExpectedReadFiles(additionalSourceFiles?: ReadonlyArray<string>) {
function getInitialExpectedReadFiles(additionalSourceFiles?: readonly string[]) {
if (!additionalSourceFiles) return initialExpectedReadFiles;
const expectedReadFiles = cloneMap(initialExpectedReadFiles);
for (const path of additionalSourceFiles) {
@@ -219,7 +219,7 @@ namespace ts {
return value;
}
function getDtsChangedReadFiles(dependOrdered?: boolean, additionalSourceFiles?: ReadonlyArray<string>) {
function getDtsChangedReadFiles(dependOrdered?: boolean, additionalSourceFiles?: readonly string[]) {
const value = dependOrdered ? dtsChangedExpectedReadFilesDependOrdered : dtsChangedExpectedReadFiles;
if (!additionalSourceFiles) return value;
const expectedReadFiles = cloneMap(value);
@@ -238,7 +238,7 @@ namespace ts {
return value;
}
function getDtsUnchangedReadFiles(dependOrdered?: boolean, additionalSourceFiles?: ReadonlyArray<string>) {
function getDtsUnchangedReadFiles(dependOrdered?: boolean, additionalSourceFiles?: readonly string[]) {
const value = dependOrdered ? dtsUnchangedExpectedReadFilesDependOrdered : dtsUnchangedExpectedReadFiles;
if (!additionalSourceFiles || additionalSourceFiles.length !== 3) return value;
const expectedReadFiles = cloneMap(value);
@@ -251,8 +251,8 @@ namespace ts {
scenario: string;
modifyFs: (fs: vfs.FileSystem) => void;
modifyAgainFs?: (fs: vfs.FileSystem) => void;
additionalSourceFiles?: ReadonlyArray<string>;
expectedBuildInfoFilesForSectionBaselines?: ReadonlyArray<BuildInfoSectionBaselineFiles>;
additionalSourceFiles?: readonly string[];
expectedBuildInfoFilesForSectionBaselines?: readonly BuildInfoSectionBaselineFiles[];
dependOrdered?: true;
ignoreDtsChanged?: true;
ignoreDtsUnchanged?: true;
@@ -16,7 +16,7 @@ namespace ts {
verifyProjectWithResolveJsonModuleWithFs(fs, configFile, allExpectedOutputs, ...expectedDiagnosticMessages);
}
function verifyProjectWithResolveJsonModuleWithFs(fs: vfs.FileSystem, configFile: string, allExpectedOutputs: ReadonlyArray<string>, ...expectedDiagnosticMessages: fakes.ExpectedDiagnostic[]) {
function verifyProjectWithResolveJsonModuleWithFs(fs: vfs.FileSystem, configFile: string, allExpectedOutputs: readonly string[], ...expectedDiagnosticMessages: fakes.ExpectedDiagnostic[]) {
const host = new fakes.SolutionBuilderHost(fs);
const builder = createSolutionBuilder(host, [configFile], { dry: false, force: false, verbose: false });
builder.build();
@@ -25,7 +25,7 @@ namespace ts {
projFs = undefined!; // Release the contents
});
function verifyBuild(modifyDiskLayout: (fs: vfs.FileSystem) => void, allExpectedOutputs: ReadonlyArray<string>, expectedFileTraces: ReadonlyArray<string>, ...expectedDiagnostics: fakes.ExpectedDiagnostic[]) {
function verifyBuild(modifyDiskLayout: (fs: vfs.FileSystem) => void, allExpectedOutputs: readonly string[], expectedFileTraces: readonly string[], ...expectedDiagnostics: fakes.ExpectedDiagnostic[]) {
const fs = projFs.shadow();
const host = new fakes.SolutionBuilderHost(fs);
modifyDiskLayout(fs);
@@ -29,10 +29,10 @@ namespace ts.tscWatch {
solutionBuilder.build();
checkOutputErrorsInitial(system, emptyArray, /*disableConsoleClears*/ undefined, [
`Projects in this build: \r\n${
concatenate(
pkgs(index => ` * pkg${index}/tsconfig.json`),
[" * tsconfig.json"]
).join("\r\n")}\n\n`,
concatenate(
pkgs(index => ` * pkg${index}/tsconfig.json`),
[" * tsconfig.json"]
).join("\r\n")}\n\n`,
...flatArray(pkgs(index => [
`Project 'pkg${index}/tsconfig.json' is out of date because output file 'pkg${index}/index.js' does not exist\n\n`,
`Building project '${project}/pkg${index}/tsconfig.json'...\n\n`
+49 -49
View File
@@ -4,13 +4,13 @@ namespace ts.tscWatch {
import getFileFromProject = TestFSWithWatch.getTsBuildProjectFile;
type TsBuildWatchSystem = TestFSWithWatch.TestServerHostTrackingWrittenFiles;
function createTsBuildWatchSystem(fileOrFolderList: ReadonlyArray<TestFSWithWatch.FileOrFolderOrSymLink>, params?: TestFSWithWatch.TestServerHostCreationParameters) {
function createTsBuildWatchSystem(fileOrFolderList: readonly TestFSWithWatch.FileOrFolderOrSymLink[], params?: TestFSWithWatch.TestServerHostCreationParameters) {
return TestFSWithWatch.changeToHostTrackingWrittenFiles(
createWatchedSystem(fileOrFolderList, params)
);
}
export function createSolutionBuilder(system: WatchedSystem, rootNames: ReadonlyArray<string>, defaultOptions?: BuildOptions) {
export function createSolutionBuilder(system: WatchedSystem, rootNames: readonly string[], defaultOptions?: BuildOptions) {
const host = createSolutionBuilderHost(system);
host.now = system.now.bind(system);
return ts.createSolutionBuilder(host, rootNames, defaultOptions || {});
@@ -22,7 +22,7 @@ namespace ts.tscWatch {
return host;
}
function createSolutionBuilderWithWatch(system: TsBuildWatchSystem, rootNames: ReadonlyArray<string>, defaultOptions?: BuildOptions) {
function createSolutionBuilderWithWatch(system: TsBuildWatchSystem, rootNames: readonly string[], defaultOptions?: BuildOptions) {
const host = createSolutionBuilderWithWatchHost(system);
const solutionBuilder = ts.createSolutionBuilderWithWatch(host, rootNames, defaultOptions || { watch: true });
solutionBuilder.build();
@@ -85,7 +85,7 @@ namespace ts.tscWatch {
return getOutputFileNames(subProject, baseFileNameWithoutExtension).map(f => transformOutputToOutputFileStamp(f, host));
}
function getOutputFileStamps(host: TsBuildWatchSystem, additionalFiles?: ReadonlyArray<[SubProject, string]>): OutputFileStamp[] {
function getOutputFileStamps(host: TsBuildWatchSystem, additionalFiles?: readonly [SubProject, string][]): OutputFileStamp[] {
const result = [
...getOutputStamps(host, SubProject.core, "anotherModule"),
...getOutputStamps(host, SubProject.core, "index"),
@@ -99,7 +99,7 @@ namespace ts.tscWatch {
return result;
}
function verifyChangedFiles(actualStamps: OutputFileStamp[], oldTimeStamps: OutputFileStamp[], changedFiles: ReadonlyArray<string>, modifiedTimeStampFiles: ReadonlyArray<string>) {
function verifyChangedFiles(actualStamps: OutputFileStamp[], oldTimeStamps: OutputFileStamp[], changedFiles: readonly string[], modifiedTimeStampFiles: readonly string[]) {
for (let i = 0; i < oldTimeStamps.length; i++) {
const actual = actualStamps[i];
const old = oldTimeStamps[i];
@@ -118,7 +118,7 @@ namespace ts.tscWatch {
let logic: SubProjectFiles;
let tests: SubProjectFiles;
let ui: SubProjectFiles;
let allFiles: ReadonlyArray<File>;
let allFiles: readonly File[];
let testProjectExpectedWatchedFiles: string[];
let testProjectExpectedWatchedDirectoriesRecursive: string[];
@@ -128,7 +128,7 @@ namespace ts.tscWatch {
tests = subProjectFiles(SubProject.tests);
ui = subProjectFiles(SubProject.ui);
allFiles = [libFile, ...core, ...logic, ...tests, ...ui];
testProjectExpectedWatchedFiles = [core[0], core[1], core[2]!, ...logic, ...tests].map(f => f.path.toLowerCase()); // tslint:disable-line no-unnecessary-type-assertion (TODO: type assertion should be necessary)
testProjectExpectedWatchedFiles = [core[0], core[1], core[2]!, ...logic, ...tests].map(f => f.path.toLowerCase());
testProjectExpectedWatchedDirectoriesRecursive = [projectPath(SubProject.core), projectPath(SubProject.logic)];
});
@@ -142,7 +142,7 @@ namespace ts.tscWatch {
testProjectExpectedWatchedDirectoriesRecursive = undefined!;
});
function createSolutionInWatchMode(allFiles: ReadonlyArray<File>, defaultOptions?: BuildOptions, disableConsoleClears?: boolean) {
function createSolutionInWatchMode(allFiles: readonly File[], defaultOptions?: BuildOptions, disableConsoleClears?: boolean) {
const host = createTsBuildWatchSystem(allFiles, { currentDirectory: projectsLocation });
createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`], defaultOptions);
verifyWatches(host);
@@ -193,8 +193,8 @@ namespace ts.tscWatch {
content: `export const newFileConst = 30;`
};
function verifyProjectChanges(allFilesGetter: () => ReadonlyArray<File>) {
function createSolutionInWatchModeToVerifyChanges(additionalFiles?: ReadonlyArray<[SubProject, string]>) {
function verifyProjectChanges(allFilesGetter: () => readonly File[]) {
function createSolutionInWatchModeToVerifyChanges(additionalFiles?: readonly [SubProject, string][]) {
const host = createSolutionInWatchMode(allFilesGetter());
return { host, verifyChangeWithFile, verifyChangeAfterTimeout, verifyWatches };
@@ -283,7 +283,7 @@ function foo() { }`, /*local*/ true);
});
it("builds when new file is added, and its subsequent updates", () => {
const additinalFiles: ReadonlyArray<[SubProject, string]> = [[SubProject.core, newFileWithoutExtension]];
const additinalFiles: readonly [SubProject, string][] = [[SubProject.core, newFileWithoutExtension]];
const { verifyChangeWithFile } = createSolutionInWatchModeToVerifyChanges(additinalFiles);
verifyChange(newFile.content);
@@ -320,7 +320,7 @@ export class someClass2 { }`);
const allFiles = [libFile, ...core, logic[1], ...tests];
const host = createTsBuildWatchSystem(allFiles, { currentDirectory: projectsLocation });
createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`]);
checkWatchedFiles(host, [core[0], core[1], core[2]!, logic[0], ...tests].map(f => f.path.toLowerCase())); // tslint:disable-line no-unnecessary-type-assertion (TODO: type assertion should be necessary)
checkWatchedFiles(host, [core[0], core[1], core[2]!, logic[0], ...tests].map(f => f.path.toLowerCase()));
checkWatchedDirectories(host, emptyArray, /*recursive*/ false);
checkWatchedDirectories(host, [projectPath(SubProject.core)], /*recursive*/ true);
checkOutputErrorsInitial(host, [
@@ -445,14 +445,14 @@ function myFunc() { return 100; }`, /*isLocal*/ true);
content: `
interface SomeObject
{
message: string;
message: string;
}
export function createSomeObject(): SomeObject
{
return {
message: "new Object"
};
return {
message: "new Object"
};
}`
};
const libraryTsconfig: File = {
@@ -561,7 +561,7 @@ let x: string = 10;`);
`${subProjectLocation}/tsconfig${Extension.TsBuildInfo}`
];
function verifyDtsErrors(host: TsBuildWatchSystem, isIncremental: boolean, expectedErrors: ReadonlyArray<string>) {
function verifyDtsErrors(host: TsBuildWatchSystem, isIncremental: boolean, expectedErrors: readonly string[]) {
(isIncremental ? checkOutputErrorsIncremental : checkOutputErrorsInitial)(host, expectedErrors);
outputs.forEach(f => assert.equal(host.fileExists(f), !expectedErrors.length, `Expected file ${f} to ${!expectedErrors.length ? "exist" : "not exist"}`));
}
@@ -639,16 +639,16 @@ let x: string = 10;`);
describe("tsc-watch and tsserver works with project references", () => {
describe("invoking when references are already built", () => {
function verifyWatchesOfProject(host: TsBuildWatchSystem, expectedWatchedFiles: ReadonlyArray<string>, expectedWatchedDirectoriesRecursive: ReadonlyArray<string>, expectedWatchedDirectories?: ReadonlyArray<string>) {
function verifyWatchesOfProject(host: TsBuildWatchSystem, expectedWatchedFiles: readonly string[], expectedWatchedDirectoriesRecursive: readonly string[], expectedWatchedDirectories?: readonly string[]) {
checkWatchedFilesDetailed(host, expectedWatchedFiles, 1);
checkWatchedDirectoriesDetailed(host, expectedWatchedDirectories || emptyArray, 1, /*recursive*/ false);
checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesRecursive, 1, /*recursive*/ true);
}
function createSolutionOfProject(allFiles: ReadonlyArray<File>,
function createSolutionOfProject(allFiles: readonly File[],
currentDirectory: string,
solutionBuilderconfig: string,
getOutputFileStamps: (host: TsBuildWatchSystem) => ReadonlyArray<OutputFileStamp>) {
getOutputFileStamps: (host: TsBuildWatchSystem) => readonly OutputFileStamp[]) {
// Build the composite project
const host = createTsBuildWatchSystem(allFiles, { currentDirectory });
const solutionBuilder = createSolutionBuilder(host, [solutionBuilderconfig], {});
@@ -661,11 +661,11 @@ let x: string = 10;`);
}
function createSolutionAndWatchModeOfProject(
allFiles: ReadonlyArray<File>,
allFiles: readonly File[],
currentDirectory: string,
solutionBuilderconfig: string,
watchConfig: string,
getOutputFileStamps: (host: TsBuildWatchSystem) => ReadonlyArray<OutputFileStamp>) {
getOutputFileStamps: (host: TsBuildWatchSystem) => readonly OutputFileStamp[]) {
// Build the composite project
const { host, solutionBuilder } = createSolutionOfProject(allFiles, currentDirectory, solutionBuilderconfig, getOutputFileStamps);
@@ -676,11 +676,11 @@ let x: string = 10;`);
return { host, solutionBuilder, watch };
}
function createSolutionAndServiceOfProject(allFiles: ReadonlyArray<File>,
function createSolutionAndServiceOfProject(allFiles: readonly File[],
currentDirectory: string,
solutionBuilderconfig: string,
openFileName: string,
getOutputFileStamps: (host: TsBuildWatchSystem) => ReadonlyArray<OutputFileStamp>) {
getOutputFileStamps: (host: TsBuildWatchSystem) => readonly OutputFileStamp[]) {
// Build the composite project
const { host, solutionBuilder } = createSolutionOfProject(allFiles, currentDirectory, solutionBuilderconfig, getOutputFileStamps);
@@ -691,12 +691,12 @@ let x: string = 10;`);
return { host, solutionBuilder, service };
}
function checkProjectActualFiles(service: projectSystem.TestProjectService, configFile: string, expectedFiles: ReadonlyArray<string>) {
function checkProjectActualFiles(service: projectSystem.TestProjectService, configFile: string, expectedFiles: readonly string[]) {
projectSystem.checkNumberOfProjects(service, { configuredProjects: 1 });
projectSystem.checkProjectActualFiles(service.configuredProjects.get(configFile.toLowerCase())!, expectedFiles);
}
function verifyDependencies(watch: Watch, filePath: string, expected: ReadonlyArray<string>) {
function verifyDependencies(watch: Watch, filePath: string, expected: readonly string[]) {
checkArray(`${filePath} dependencies`, watch.getBuilderProgram().getAllDependencies(watch().getSourceFile(filePath)!), expected);
}
@@ -728,8 +728,8 @@ let x: string = 10;`);
function verifyScenario(
edit: (host: TsBuildWatchSystem, solutionBuilder: SolutionBuilder<EmitAndSemanticDiagnosticsBuilderProgram>) => void,
expectedProgramFilesAfterEdit: () => ReadonlyArray<string>,
expectedProjectFilesAfterEdit: () => ReadonlyArray<string>
expectedProgramFilesAfterEdit: () => readonly string[],
expectedProjectFilesAfterEdit: () => readonly string[]
) {
it("with tsc-watch", () => {
const { host, solutionBuilder, watch } = createSolutionAndWatchMode();
@@ -833,11 +833,11 @@ export function gfoo() {
function verifyWatchState(
host: TsBuildWatchSystem,
watch: Watch,
expectedProgramFiles: ReadonlyArray<string>,
expectedWatchedFiles: ReadonlyArray<string>,
expectedWatchedDirectoriesRecursive: ReadonlyArray<string>,
dependencies: ReadonlyArray<[string, ReadonlyArray<string>]>,
expectedWatchedDirectories?: ReadonlyArray<string>) {
expectedProgramFiles: readonly string[],
expectedWatchedFiles: readonly string[],
expectedWatchedDirectoriesRecursive: readonly string[],
dependencies: readonly [string, readonly string[]][],
expectedWatchedDirectories?: readonly string[]) {
checkProgramActualFiles(watch(), expectedProgramFiles);
verifyWatchesOfProject(host, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, expectedWatchedDirectories);
for (const [file, deps] of dependencies) {
@@ -905,7 +905,7 @@ export function gfoo() {
...projectSystem.getTypeRootsFromLocation(multiFolder ? getFilePathInProject(project, "c") : getProjectPath(project))
].map(s => s.toLowerCase());
const defaultDependencies: ReadonlyArray<[string, ReadonlyArray<string>]> = [
const defaultDependencies: readonly [string, readonly string[]][] = [
[aDts, [aDts]],
[bDts, [bDts, aDts]],
[refs.path, [refs.path]],
@@ -928,17 +928,17 @@ export function gfoo() {
verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, defaultDependencies, expectedWatchedDirectories);
}
function verifyProject(host: TsBuildWatchSystem, service: projectSystem.TestProjectService, orphanInfos?: ReadonlyArray<string>) {
function verifyProject(host: TsBuildWatchSystem, service: projectSystem.TestProjectService, orphanInfos?: readonly string[]) {
verifyServerState({ host, service, expectedProjectFiles, expectedProjectWatchedFiles, expectedWatchedDirectoriesRecursive, orphanInfos });
}
interface VerifyServerState {
host: TsBuildWatchSystem;
service: projectSystem.TestProjectService;
expectedProjectFiles: ReadonlyArray<string>;
expectedProjectWatchedFiles: ReadonlyArray<string>;
expectedWatchedDirectoriesRecursive: ReadonlyArray<string>;
orphanInfos?: ReadonlyArray<string>;
expectedProjectFiles: readonly string[];
expectedProjectWatchedFiles: readonly string[];
expectedWatchedDirectoriesRecursive: readonly string[];
orphanInfos?: readonly string[];
}
function verifyServerState({ host, service, expectedProjectFiles, expectedProjectWatchedFiles, expectedWatchedDirectoriesRecursive, orphanInfos }: VerifyServerState) {
checkProjectActualFiles(service, cTsconfig.path, expectedProjectFiles.concat(cTsconfig.path));
@@ -961,16 +961,16 @@ export function gfoo() {
interface VerifyScenario {
edit: (host: TsBuildWatchSystem, solutionBuilder: SolutionBuilder<EmitAndSemanticDiagnosticsBuilderProgram>) => void;
expectedEditErrors: ReadonlyArray<string>;
expectedProgramFiles: ReadonlyArray<string>;
expectedProjectFiles: ReadonlyArray<string>;
expectedWatchedFiles: ReadonlyArray<string>;
expectedProjectWatchedFiles: ReadonlyArray<string>;
expectedWatchedDirectoriesRecursive: ReadonlyArray<string>;
dependencies: ReadonlyArray<[string, ReadonlyArray<string>]>;
expectedEditErrors: readonly string[];
expectedProgramFiles: readonly string[];
expectedProjectFiles: readonly string[];
expectedWatchedFiles: readonly string[];
expectedProjectWatchedFiles: readonly string[];
expectedWatchedDirectoriesRecursive: readonly string[];
dependencies: readonly [string, readonly string[]][];
revert?: (host: TsBuildWatchSystem) => void;
orphanInfosAfterEdit?: ReadonlyArray<string>;
orphanInfosAfterRevert?: ReadonlyArray<string>;
orphanInfosAfterEdit?: readonly string[];
orphanInfosAfterRevert?: readonly string[];
}
function verifyScenario({ edit, expectedEditErrors, expectedProgramFiles, expectedProjectFiles, expectedWatchedFiles, expectedProjectWatchedFiles, expectedWatchedDirectoriesRecursive, dependencies, revert, orphanInfosAfterEdit, orphanInfosAfterRevert }: VerifyScenario) {
it("with tsc-watch", () => {
@@ -1188,7 +1188,7 @@ export function gfoo() {
...projectSystem.getTypeRootsFromLocation(getProjectPath(project))
].map(s => s.toLowerCase());
const defaultDependencies: ReadonlyArray<[string, ReadonlyArray<string>]> = [
const defaultDependencies: readonly [string, readonly string[]][] = [
[aDts, [aDts]],
[bDts, [bDts, aDts]],
[refs.path, [refs.path]],
+17 -17
View File
@@ -383,9 +383,9 @@ namespace ts.tscWatch {
const {
moduleFile1, verifyAffectedFiles
} = getInitialState({
configObj: { compilerOptions: { module: "system", outFile: outFilePath } },
getEmitLine: (_, host) => getEmittedLineForSingleFileOutput(outFilePath, host)
});
configObj: { compilerOptions: { module: "system", outFile: outFilePath } },
getEmitLine: (_, host) => getEmittedLineForSingleFileOutput(outFilePath, host)
});
moduleFile1.content = `export var T: number;export function Foo() { };`;
verifyAffectedFiles([moduleFile1]);
@@ -399,8 +399,8 @@ namespace ts.tscWatch {
const {
moduleFile1, file1Consumer1, file1Consumer2, verifyAffectedFiles, getFile
} = getInitialState({
getAdditionalFileOrFolder: () => [file1Consumer1Consumer1]
});
getAdditionalFileOrFolder: () => [file1Consumer1Consumer1]
});
const file1Consumer1Consumer1Emit = getFile(file1Consumer1Consumer1.path);
file1Consumer1.content += "export var T: number;";
@@ -436,10 +436,10 @@ namespace ts.tscWatch {
getFile,
verifyAffectedFiles
} = getInitialState({
firstCompilationEmitFiles: [file1.path, file2.path],
getAdditionalFileOrFolder: () => [file1, file2],
firstReloadFileList: [libFile.path, file1.path, file2.path, configFilePath]
});
firstCompilationEmitFiles: [file1.path, file2.path],
getAdditionalFileOrFolder: () => [file1, file2],
firstReloadFileList: [libFile.path, file1.path, file2.path, configFilePath]
});
const file1Emit = getFile(file1.path), file2Emit = getFile(file2.path);
file1Emit.content += "export var t3 = 10;";
@@ -459,10 +459,10 @@ namespace ts.tscWatch {
getFile,
verifyAffectedFiles
} = getInitialState({
firstCompilationEmitFiles: [referenceFile1.path, moduleFile1Path],
getAdditionalFileOrFolder: () => [referenceFile1],
firstReloadFileList: [libFile.path, referenceFile1.path, moduleFile1Path, configFilePath]
});
firstCompilationEmitFiles: [referenceFile1.path, moduleFile1Path],
getAdditionalFileOrFolder: () => [referenceFile1],
firstReloadFileList: [libFile.path, referenceFile1.path, moduleFile1Path, configFilePath]
});
const referenceFile1Emit = getFile(referenceFile1.path);
verifyAffectedFiles([referenceFile1Emit], [libFile, referenceFile1Emit, configFile]);
@@ -481,10 +481,10 @@ namespace ts.tscWatch {
getFile,
verifyAffectedFiles
} = getInitialState({
firstCompilationEmitFiles: [referenceFile1.path],
getAdditionalFileOrFolder: () => [referenceFile1],
firstReloadFileList: [libFile.path, referenceFile1.path, configFilePath]
});
firstCompilationEmitFiles: [referenceFile1.path],
getAdditionalFileOrFolder: () => [referenceFile1],
firstReloadFileList: [libFile.path, referenceFile1.path, configFilePath]
});
const referenceFile1Emit = getFile(referenceFile1.path);
referenceFile1Emit.content += "export var yy = Foo();";
@@ -16,11 +16,11 @@ namespace ts.tscWatch {
};
}
function getOutputFileStampsAndErrors(host: WatchedSystem, watch: Watch, directoryFiles: ReadonlyArray<File>) {
function getOutputFileStampsAndErrors(host: WatchedSystem, watch: Watch, directoryFiles: readonly File[]) {
return directoryFiles.map(d => getOutputFileStampAndError(host, watch, d));
}
function findStampAndErrors(stampsAndErrors: ReadonlyArray<ReturnType<typeof getOutputFileStampAndError>>, file: File) {
function findStampAndErrors(stampsAndErrors: readonly ReturnType<typeof getOutputFileStampAndError>[], file: File) {
return find(stampsAndErrors, info => info.file === file)!;
}
@@ -28,8 +28,8 @@ namespace ts.tscWatch {
file: File,
emitExpected: boolean,
errorRefershExpected: boolean,
beforeChangeFileStampsAndErrors: ReadonlyArray<ReturnType<typeof getOutputFileStampAndError>>,
afterChangeFileStampsAndErrors: ReadonlyArray<ReturnType<typeof getOutputFileStampAndError>>
beforeChangeFileStampsAndErrors: readonly ReturnType<typeof getOutputFileStampAndError>[],
afterChangeFileStampsAndErrors: readonly ReturnType<typeof getOutputFileStampAndError>[]
) {
const beforeChange = findStampAndErrors(beforeChangeFileStampsAndErrors, file);
const afterChange = findStampAndErrors(afterChangeFileStampsAndErrors, file);
@@ -53,11 +53,11 @@ namespace ts.tscWatch {
interface VerifyEmitAndErrorUpdates {
change: (host: WatchedSystem) => void;
getInitialErrors: (watch: Watch) => ReadonlyArray<Diagnostic> | ReadonlyArray<string>;
getIncrementalErrors: (watch: Watch) => ReadonlyArray<Diagnostic> | ReadonlyArray<string>;
filesWithNewEmit: ReadonlyArray<File>;
filesWithOnlyErrorRefresh: ReadonlyArray<File>;
filesNotTouched: ReadonlyArray<File>;
getInitialErrors: (watch: Watch) => readonly Diagnostic[] | readonly string[];
getIncrementalErrors: (watch: Watch) => readonly Diagnostic[] | readonly string[];
filesWithNewEmit: readonly File[];
filesWithOnlyErrorRefresh: readonly File[];
filesNotTouched: readonly File[];
configFile?: File;
}
+7 -7
View File
@@ -21,11 +21,11 @@ namespace ts.tscWatch {
content: "let y = 1"
};
export function checkProgramActualFiles(program: Program, expectedFiles: ReadonlyArray<string>) {
export function checkProgramActualFiles(program: Program, expectedFiles: readonly string[]) {
checkArray(`Program actual files`, program.getSourceFiles().map(file => file.fileName), expectedFiles);
}
export function checkProgramRootFiles(program: Program, expectedFiles: ReadonlyArray<string>) {
export function checkProgramRootFiles(program: Program, expectedFiles: readonly string[]) {
checkArray(`Program rootFileNames`, program.getRootFileNames(), expectedFiles);
}
@@ -172,7 +172,7 @@ namespace ts.tscWatch {
return hostOutputWatchDiagnostic(createCompilerDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation));
}
export function checkOutputErrorsInitial(host: WatchedSystem, errors: ReadonlyArray<Diagnostic> | ReadonlyArray<string>, disableConsoleClears?: boolean, logsBeforeErrors?: string[]) {
export function checkOutputErrorsInitial(host: WatchedSystem, errors: readonly Diagnostic[] | readonly string[], disableConsoleClears?: boolean, logsBeforeErrors?: string[]) {
checkOutputErrors(
host,
[
@@ -185,7 +185,7 @@ namespace ts.tscWatch {
);
}
export function checkOutputErrorsIncremental(host: WatchedSystem, errors: ReadonlyArray<Diagnostic> | ReadonlyArray<string>, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) {
export function checkOutputErrorsIncremental(host: WatchedSystem, errors: readonly Diagnostic[] | readonly string[], disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) {
checkOutputErrors(
host,
[
@@ -199,7 +199,7 @@ namespace ts.tscWatch {
);
}
export function checkOutputErrorsIncrementalWithExit(host: WatchedSystem, errors: ReadonlyArray<Diagnostic> | ReadonlyArray<string>, expectedExitCode: ExitStatus, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) {
export function checkOutputErrorsIncrementalWithExit(host: WatchedSystem, errors: readonly Diagnostic[] | readonly string[], expectedExitCode: ExitStatus, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) {
checkOutputErrors(
host,
[
@@ -213,7 +213,7 @@ namespace ts.tscWatch {
assert.equal(host.exitCode, expectedExitCode);
}
export function checkNormalBuildErrors(host: WatchedSystem, errors: ReadonlyArray<Diagnostic> | ReadonlyArray<string>, reportErrorSummary?: boolean) {
export function checkNormalBuildErrors(host: WatchedSystem, errors: readonly Diagnostic[] | readonly string[], reportErrorSummary?: boolean) {
checkOutputErrors(
host,
[
@@ -260,7 +260,7 @@ namespace ts.tscWatch {
}
export function getDiagnosticOfFileFromProgram(program: Program, filePath: string, start: number, length: number, message: DiagnosticMessage | DiagnosticMessageChain, ...args: (string | number)[]): Diagnostic {
return getDiagnosticOfFileFrom(program.getSourceFileByPath(toPath(filePath, program.getCurrentDirectory(), s => s.toLowerCase()))!,
return getDiagnosticOfFileFrom(program.getSourceFileByPath(toPath(filePath, program.getCurrentDirectory(), s => s.toLowerCase())),
start, length, message, ...args);
}
@@ -8,13 +8,13 @@ namespace ts.tscWatch {
};
interface VerifyIncrementalWatchEmitInput {
files: ReadonlyArray<File>;
files: readonly File[];
optionsToExtend?: CompilerOptions;
expectedInitialEmit: ReadonlyArray<File>;
expectedInitialErrors: ReadonlyArray<string>;
expectedInitialEmit: readonly File[];
expectedInitialErrors: readonly string[];
modifyFs?: (host: WatchedSystem) => void;
expectedIncrementalEmit?: ReadonlyArray<File>;
expectedIncrementalErrors?: ReadonlyArray<string>;
expectedIncrementalEmit?: readonly File[];
expectedIncrementalErrors?: readonly string[];
}
function verifyIncrementalWatchEmit(input: () => VerifyIncrementalWatchEmitInput) {
it("with tsc --w", () => {
@@ -52,7 +52,7 @@ namespace ts.tscWatch {
interface VerifyIncrementalWatchEmitWorkerInput {
input: VerifyIncrementalWatchEmitInput;
emitAndReportErrors: (configFile: string, host: WatchedSystem, optionsToExtend?: CompilerOptions) => { close(): void; };
verifyErrors: (host: WatchedSystem, errors: ReadonlyArray<string>) => void;
verifyErrors: (host: WatchedSystem, errors: readonly string[]) => void;
}
function verifyIncrementalWatchEmitWorker({
input: {
@@ -100,8 +100,8 @@ namespace ts.tscWatch {
writtenFiles: Map<string>;
emitAndReportErrors: VerifyIncrementalWatchEmitWorkerInput["emitAndReportErrors"];
verifyErrors: VerifyIncrementalWatchEmitWorkerInput["verifyErrors"];
expectedEmit: ReadonlyArray<File>;
expectedErrors: ReadonlyArray<string>;
expectedEmit: readonly File[];
expectedErrors: readonly string[];
}
function verifyBuild({
host, optionsToExtend, writtenFiles, emitAndReportErrors,
@@ -120,7 +120,7 @@ namespace ts.tscWatch {
return getBuildInfoText(buildInfo);
}
function checkFileEmit(actual: Map<string>, expected: ReadonlyArray<File>) {
function checkFileEmit(actual: Map<string>, expected: readonly File[]) {
assert.equal(actual.size, expected.length, `Actual: ${JSON.stringify(arrayFrom(actual.entries()), /*replacer*/ undefined, " ")}\nExpected: ${JSON.stringify(expected, /*replacer*/ undefined, " ")}`);
for (const file of expected) {
let expectedContent = file.content;
@@ -916,7 +916,7 @@ namespace ts.tscWatch {
});
describe("should not trigger should not trigger recompilation because of program emit", () => {
function verifyWithOptions(options: CompilerOptions, outputFiles: ReadonlyArray<string>) {
function verifyWithOptions(options: CompilerOptions, outputFiles: readonly string[]) {
const proj = "/user/username/projects/myproject";
const file1: File = {
path: `${proj}/file1.ts`,
@@ -1056,14 +1056,14 @@ export default test;`;
getDiagnosticOfFileFromProgram(watch(), bFile.path, bFile.content.indexOf("y /"), 1, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type)
]);
function changeParameterType(parameterName: string, toType: string, expectedErrors: ReadonlyArray<Diagnostic>) {
function changeParameterType(parameterName: string, toType: string, expectedErrors: readonly Diagnostic[]) {
const newContent = bFileContent.replace(new RegExp(`${parameterName}\: [a-z]*`), `${parameterName}: ${toType}`);
verifyErrorsWithBFileContents(newContent, expectedErrors);
verifyErrorsWithBFileContents(bFileContent, emptyArray);
}
function verifyErrorsWithBFileContents(content: string, expectedErrors: ReadonlyArray<Diagnostic>) {
function verifyErrorsWithBFileContents(content: string, expectedErrors: readonly Diagnostic[]) {
host.writeFile(bFile.path, content);
host.runQueuedTimeoutCallbacks();
checkOutputErrorsIncremental(host, expectedErrors);
@@ -1146,7 +1146,7 @@ foo().hello`
const currentDirectory = "/user/username/projects/myproject";
const field = "fullscreen";
const fieldWithoutReadonly = `interface Document {
${field}: boolean;
${field}: boolean;
}`;
const libFileWithDocument: File = {
@@ -1227,13 +1227,13 @@ var y: number;
const aFile: File = {
path: `${currentDirectory}/a.ts`,
content: `interface Document {
${field}: boolean;
${field}: boolean;
}`
};
const bFile: File = {
path: `${currentDirectory}/b.d.ts`,
content: `interface Document {
${field}: boolean;
${field}: boolean;
}`
};
const libFileWithDocument: File = {
@@ -1266,7 +1266,7 @@ interface Document {
verifyConfigChange({ skipLibCheck: true }, [aFile]);
verifyConfigChange({}, [libFileWithDocument, aFile, bFile]);
function verifyConfigChange(compilerOptions: CompilerOptions, errorInFiles: ReadonlyArray<File>) {
function verifyConfigChange(compilerOptions: CompilerOptions, errorInFiles: readonly File[]) {
host.writeFile(configFile.path, JSON.stringify({ compilerOptions }));
host.runQueuedTimeoutCallbacks();
verifyProgramFiles();
@@ -102,7 +102,7 @@ namespace ts.tscWatch {
host.runQueuedTimeoutCallbacks();
verifyProgram(checkOutputErrorsIncremental);
function verifyProgram(checkOutputErrors: (host: WatchedSystem, errors: ReadonlyArray<Diagnostic>) => void) {
function verifyProgram(checkOutputErrors: (host: WatchedSystem, errors: readonly Diagnostic[]) => void) {
checkProgramActualFiles(watch(), programFiles.map(f => f.path));
checkOutputErrors(host, emptyArray);
File diff suppressed because one or more lines are too long
@@ -565,46 +565,46 @@ namespace ts.projectSystem {
it("should return empty array if change is made in a global declaration file", () => {
testDTS(
/*dtsFileContents*/ "declare const x: string;",
/*tsFileContents*/ "var y = 1;",
/*opts*/ {},
/*expectDTSEmit*/ false
/*dtsFileContents*/ "declare const x: string;",
/*tsFileContents*/ "var y = 1;",
/*opts*/ {},
/*expectDTSEmit*/ false
);
});
it("should return empty array if change is made in a module declaration file", () => {
testDTS(
/*dtsFileContents*/ "export const x: string;",
/*tsFileContents*/ "import { x } from './runtime/a;",
/*opts*/ {},
/*expectDTSEmit*/ false
/*dtsFileContents*/ "export const x: string;",
/*tsFileContents*/ "import { x } from './runtime/a;",
/*opts*/ {},
/*expectDTSEmit*/ false
);
});
it("should return results if change is made in a global declaration file with declaration emit", () => {
testDTS(
/*dtsFileContents*/ "declare const x: string;",
/*tsFileContents*/ "var y = 1;",
/*opts*/ { declaration: true },
/*expectDTSEmit*/ true
/*dtsFileContents*/ "declare const x: string;",
/*tsFileContents*/ "var y = 1;",
/*opts*/ { declaration: true },
/*expectDTSEmit*/ true
);
});
it("should return results if change is made in a global declaration file with composite enabled", () => {
testDTS(
/*dtsFileContents*/ "declare const x: string;",
/*tsFileContents*/ "var y = 1;",
/*opts*/ { composite: true },
/*expectDTSEmit*/ true
/*dtsFileContents*/ "declare const x: string;",
/*tsFileContents*/ "var y = 1;",
/*opts*/ { composite: true },
/*expectDTSEmit*/ true
);
});
it("should return results if change is made in a global declaration file with decorator emit enabled", () => {
testDTS(
/*dtsFileContents*/ "declare const x: string;",
/*tsFileContents*/ "var y = 1;",
/*opts*/ { experimentalDecorators: true, emitDecoratorMetadata: true },
/*expectDTSEmit*/ true
/*dtsFileContents*/ "declare const x: string;",
/*tsFileContents*/ "var y = 1;",
/*opts*/ { experimentalDecorators: true, emitDecoratorMetadata: true },
/*expectDTSEmit*/ true
);
});
});
@@ -68,7 +68,7 @@ namespace ts.projectSystem {
source: [{ text: "./a", kind: "text" }],
tags: undefined,
};
assert.deepEqual<ReadonlyArray<protocol.CompletionEntryDetails> | undefined>(detailsResponse, [
assert.deepEqual<readonly protocol.CompletionEntryDetails[] | undefined>(detailsResponse, [
{
codeActions: [
{
@@ -97,10 +97,10 @@ namespace ts.projectSystem {
readonly arguments: protocol.CompletionDetailsRequestArgs;
}
interface CompletionDetailsFullResponse extends protocol.Response {
readonly body?: ReadonlyArray<CompletionEntryDetails>;
readonly body?: readonly CompletionEntryDetails[];
}
const detailsFullResponse = executeSessionRequest<CompletionDetailsFullRequest, CompletionDetailsFullResponse>(session, protocol.CommandTypes.CompletionDetailsFull, detailsRequestArgs);
assert.deepEqual<ReadonlyArray<CompletionEntryDetails> | undefined>(detailsFullResponse, [
assert.deepEqual<readonly CompletionEntryDetails[] | undefined>(detailsFullResponse, [
{
codeActions: [
{
@@ -24,7 +24,7 @@ namespace ts.projectSystem {
};
}
function checkDeclarationFiles(file: File, session: TestSession, expectedFiles: ReadonlyArray<File>): void {
function checkDeclarationFiles(file: File, session: TestSession, expectedFiles: readonly File[]): void {
openFilesForSession([file], session);
const project = Debug.assertDefined(session.getProjectService().getDefaultProjectForFile(file.path as server.NormalizedPath, /*ensureProject*/ false));
const program = project.getCurrentProgram()!;
@@ -282,7 +282,7 @@ namespace ts.projectSystem {
it("navigateTo", () => {
const session = makeSampleProjects();
const response = executeSessionRequest<protocol.NavtoRequest, protocol.NavtoResponse>(session, CommandNames.Navto, { file: userTs.path, searchValue: "fn" });
assert.deepEqual<ReadonlyArray<protocol.NavtoItem> | undefined>(response, [
assert.deepEqual<readonly protocol.NavtoItem[] | undefined>(response, [
{
...protocolFileSpanFromSubstring({
file: bDts,
@@ -328,7 +328,7 @@ namespace ts.projectSystem {
contextText: "export function fnA() {}",
lineText: "export function fnA() {}"
});
const referencesUserTs = (userTs: File): ReadonlyArray<protocol.ReferencesResponseItem> => [
const referencesUserTs = (userTs: File): readonly protocol.ReferencesResponseItem[] => [
makeReferenceItem({
file: userTs,
isDefinition: false,
@@ -365,14 +365,14 @@ namespace ts.projectSystem {
});
interface ReferencesFullRequest extends protocol.FileLocationRequest { readonly command: protocol.CommandTypes.ReferencesFull; }
interface ReferencesFullResponse extends protocol.Response { readonly body: ReadonlyArray<ReferencedSymbol>; }
interface ReferencesFullResponse extends protocol.Response { readonly body: readonly ReferencedSymbol[]; }
it("findAllReferencesFull", () => {
const session = makeSampleProjects();
const responseFull = executeSessionRequest<ReferencesFullRequest, ReferencesFullResponse>(session, protocol.CommandTypes.ReferencesFull, protocolFileLocationFromSubstring(userTs, "fnA()"));
assert.deepEqual<ReadonlyArray<ReferencedSymbol>>(responseFull, [
assert.deepEqual<readonly ReferencedSymbol[]>(responseFull, [
{
definition: {
...documentSpanFromSubstring({
@@ -425,7 +425,7 @@ namespace ts.projectSystem {
const responseFull = executeSessionRequest<ReferencesFullRequest, ReferencesFullResponse>(session, protocol.CommandTypes.ReferencesFull, protocolFileLocationFromSubstring(bTs, "f()"));
assert.deepEqual<ReadonlyArray<ReferencedSymbol>>(responseFull, [
assert.deepEqual<readonly ReferencedSymbol[]>(responseFull, [
{
definition: {
...documentSpanFromSubstring({
@@ -556,7 +556,7 @@ namespace ts.projectSystem {
it("renameLocationsFull", () => {
const session = makeSampleProjects();
const response = executeSessionRequest<protocol.RenameFullRequest, protocol.RenameFullResponse>(session, protocol.CommandTypes.RenameLocationsFull, protocolFileLocationFromSubstring(userTs, "fnA()"));
assert.deepEqual<ReadonlyArray<RenameLocation>>(response, [
assert.deepEqual<readonly RenameLocation[]>(response, [
renameLocation({ file: userTs, text: "fnA" }),
renameLocation({ file: aTs, text: "fnA", contextText: "export function fnA() {}" }),
]);
@@ -607,7 +607,7 @@ namespace ts.projectSystem {
oldFilePath: aTs.path,
newFilePath: "/a/aNew.ts",
});
assert.deepEqual<ReadonlyArray<protocol.FileCodeEdits>>(response, [
assert.deepEqual<readonly protocol.FileCodeEdits[]>(response, [
{
fileName: userTs.path,
textChanges: [
@@ -651,7 +651,7 @@ namespace ts.projectSystem {
oldFilePath: aTs.path,
newFilePath: "/a/src/a1.ts",
});
assert.deepEqual<ReadonlyArray<protocol.FileCodeEdits>>(response, []); // Should not change anything
assert.deepEqual<readonly protocol.FileCodeEdits[]>(response, []); // Should not change anything
});
});
}
@@ -31,7 +31,7 @@ namespace ts.projectSystem {
endOffset: 4,
errorCodes: [Diagnostics.Cannot_find_name_0.code],
});
assert.deepEqual<ReadonlyArray<protocol.CodeFixAction> | undefined>(response, [
assert.deepEqual<readonly protocol.CodeFixAction[] | undefined>(response, [
{
description: `Import 'foo' from module "foo"`,
fixName: "import",
@@ -19,7 +19,7 @@ namespace ts.projectSystem {
clearEvents: () => void;
verifyProjectLoadEvents: (expected: [server.ProjectLoadingStartEvent, server.ProjectLoadingFinishEvent]) => void;
}) {
function createSessionToVerifyEvent(files: ReadonlyArray<File>) {
function createSessionToVerifyEvent(files: readonly File[]) {
const host = createServerHost(files);
const originalReadFile = host.readFile;
const { session, getNumberOfEvents, clearEvents, verifyProjectLoadEvents } = createSession(host);
@@ -1,6 +1,6 @@
namespace ts.projectSystem {
describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => {
function verifyFiles(caption: string, actual: ReadonlyArray<string>, expected: ReadonlyArray<string>) {
function verifyFiles(caption: string, actual: readonly string[], expected: readonly string[]) {
assert.equal(actual.length, expected.length, `Incorrect number of ${caption}. Actual: ${actual} Expected: ${expected}`);
const seen = createMap<true>();
forEach(actual, f => {
@@ -528,11 +528,11 @@ namespace ts.projectSystem {
return JSON.stringify(event && { eventName: event.eventName, data: event.data });
}
function eventsToString(events: ReadonlyArray<server.ProjectsUpdatedInBackgroundEvent>) {
function eventsToString(events: readonly server.ProjectsUpdatedInBackgroundEvent[]) {
return "[" + map(events, eventToString).join(",") + "]";
}
function verifyProjectsUpdatedInBackgroundEventHandler(expectedEvents: ReadonlyArray<server.ProjectsUpdatedInBackgroundEvent>) {
function verifyProjectsUpdatedInBackgroundEventHandler(expectedEvents: readonly server.ProjectsUpdatedInBackgroundEvent[]) {
assert.equal(projectChangedEvents.length, expectedEvents.length, `Incorrect number of events Actual: ${eventsToString(projectChangedEvents)} Expected: ${eventsToString(expectedEvents)}`);
forEach(projectChangedEvents, (actualEvent, i) => {
const expectedEvent = expectedEvents[i];
@@ -565,7 +565,7 @@ namespace ts.projectSystem {
verifyInitialOpen: createVerifyInitialOpen(session, verifyProjectsUpdatedInBackgroundEventHandler)
};
function verifyProjectsUpdatedInBackgroundEventHandler(expected: ReadonlyArray<server.ProjectsUpdatedInBackgroundEvent>) {
function verifyProjectsUpdatedInBackgroundEventHandler(expected: readonly server.ProjectsUpdatedInBackgroundEvent[]) {
const expectedEvents: protocol.ProjectsUpdatedInBackgroundEventBody[] = map(expected, e => {
return {
openFiles: e.data.openFiles
@@ -6,7 +6,7 @@ namespace ts.projectSystem {
openFilesForSession([aTs], session);
const response = executeSessionRequest<protocol.GetApplicableRefactorsRequest, protocol.GetApplicableRefactorsResponse>(
session, protocol.CommandTypes.GetApplicableRefactors, { file: aTs.path, line: 1, offset: 1 });
assert.deepEqual<ReadonlyArray<protocol.ApplicableRefactorInfo> | undefined>(response, []);
assert.deepEqual<readonly protocol.ApplicableRefactorInfo[] | undefined>(response, []);
});
});
}
@@ -22,7 +22,7 @@ namespace ts.projectSystem {
Debug.assert(!!project.resolveModuleNames);
const edits = project.getLanguageService().getEditsForFileRename("/old.ts", "/new.ts", testFormatSettings, emptyOptions);
assert.deepEqual<ReadonlyArray<FileTextChanges>>(edits, [{
assert.deepEqual<readonly FileTextChanges[]>(edits, [{
fileName: "/user.ts",
textChanges: [{
span: textSpanFromSubstring(userTs.content, "./old"),
@@ -61,7 +61,7 @@ namespace ts.projectSystem {
oldFilePath: aOldTs.path,
newFilePath: "/a/new.ts",
});
assert.deepEqual<ReadonlyArray<protocol.FileCodeEdits>>(response, [
assert.deepEqual<readonly protocol.FileCodeEdits[]>(response, [
{
fileName: aTsconfig.path,
textChanges: [{ ...protocolTextSpanFromSubstring(aTsconfig.content, "./old.ts"), newText: "new.ts" }],
@@ -90,7 +90,7 @@ namespace ts.projectSystem {
oldFilePath: "/b.ts",
newFilePath: cTs.path,
});
assert.deepEqual<ReadonlyArray<protocol.FileCodeEdits>>(response, [
assert.deepEqual<readonly protocol.FileCodeEdits[]>(response, [
{
fileName: "/tsconfig.json",
textChanges: [{ ...protocolTextSpanFromSubstring(tsconfig.content, "./b.ts"), newText: "c.ts" }],
+10 -10
View File
@@ -223,7 +223,7 @@ namespace ts.projectSystem {
this.service = this.session.getProjectService();
}
getEvents(): ReadonlyArray<server.ProjectServiceEvent> {
getEvents(): readonly server.ProjectServiceEvent[] {
const events = this.events;
this.events = [];
return events;
@@ -248,7 +248,7 @@ namespace ts.projectSystem {
this.events.forEach(event => assert.notEqual(event.eventName, eventName));
}
checkSingleConfigFileDiagEvent(configFileName: string, triggerFile: string, errors: ReadonlyArray<ConfigFileDiagnostic>) {
checkSingleConfigFileDiagEvent(configFileName: string, triggerFile: string, errors: readonly ConfigFileDiagnostic[]) {
const eventData = this.getEvent<server.ConfigFileDiagEvent>(server.ConfigFileDiagEvent);
assert.equal(eventData.configFileName, configFileName);
assert.equal(eventData.triggerFile, triggerFile);
@@ -447,11 +447,11 @@ namespace ts.projectSystem {
return iterResult.value;
}
export function checkProjectActualFiles(project: server.Project, expectedFiles: ReadonlyArray<string>) {
export function checkProjectActualFiles(project: server.Project, expectedFiles: readonly string[]) {
checkArray(`${server.ProjectKind[project.projectKind]} project, actual files`, project.getFileNames(), expectedFiles);
}
export function checkProjectRootFiles(project: server.Project, expectedFiles: ReadonlyArray<string>) {
export function checkProjectRootFiles(project: server.Project, expectedFiles: readonly string[]) {
checkArray(`${server.ProjectKind[project.projectKind]} project, rootFileNames`, project.getRootFiles(), expectedFiles);
}
@@ -491,7 +491,7 @@ namespace ts.projectSystem {
checkArray("Open files", arrayFrom(projectService.openFiles.keys(), path => projectService.getScriptInfoForPath(path as Path)!.fileName), expectedFiles.map(file => file.path));
}
export function checkScriptInfos(projectService: server.ProjectService, expectedFiles: ReadonlyArray<string>, additionInfo?: string) {
export function checkScriptInfos(projectService: server.ProjectService, expectedFiles: readonly string[], additionInfo?: string) {
checkArray(`ScriptInfos files: ${additionInfo || ""}`, arrayFrom(projectService.filenameToScriptInfo.values(), info => info.fileName), expectedFiles);
}
@@ -664,14 +664,14 @@ namespace ts.projectSystem {
session.executeCommand(makeSessionRequest(command, args));
}
export function openFilesForSession(files: ReadonlyArray<File | { readonly file: File | string, readonly projectRootPath: string }>, session: server.Session): void {
export function openFilesForSession(files: readonly (File | { readonly file: File | string, readonly projectRootPath: string })[], session: server.Session): void {
for (const file of files) {
session.executeCommand(makeSessionRequest<protocol.OpenRequestArgs>(CommandNames.Open,
"projectRootPath" in file ? { file: typeof file.file === "string" ? file.file : file.file.path, projectRootPath: file.projectRootPath } : { file: file.path }));
"projectRootPath" in file ? { file: typeof file.file === "string" ? file.file : file.file.path, projectRootPath: file.projectRootPath } : { file: file.path })); // eslint-disable-line no-in-operator
}
}
export function closeFilesForSession(files: ReadonlyArray<File>, session: server.Session): void {
export function closeFilesForSession(files: readonly File[], session: server.Session): void {
for (const file of files) {
session.executeCommand(makeSessionRequest<protocol.FileRequestArgs>(CommandNames.Close, { file: file.path }));
}
@@ -686,7 +686,7 @@ namespace ts.projectSystem {
return formatStringFromArgs(diagnosticMessage.message, errorTextArguments);
}
export function verifyDiagnostics(actual: ReadonlyArray<server.protocol.Diagnostic>, expected: ReadonlyArray<ErrorInformation>) {
export function verifyDiagnostics(actual: readonly server.protocol.Diagnostic[], expected: readonly ErrorInformation[]) {
const expectedErrors = expected.map(getProtocolDiagnosticMessage);
assert.deepEqual(actual.map(diag => flattenDiagnosticMessageText(diag.text, "\n")), expectedErrors);
}
@@ -699,7 +699,7 @@ namespace ts.projectSystem {
checkNthEvent(session, server.toEvent(eventName, diagnostics), 0, isMostRecent);
}
export function createDiagnostic(start: protocol.Location, end: protocol.Location, message: DiagnosticMessage, args: ReadonlyArray<string> = [], category = diagnosticCategoryName(message), reportsUnnecessary?: {}, relatedInformation?: protocol.DiagnosticRelatedInformation[]): protocol.Diagnostic {
export function createDiagnostic(start: protocol.Location, end: protocol.Location, message: DiagnosticMessage, args: readonly string[] = [], category = diagnosticCategoryName(message), reportsUnnecessary?: {}, relatedInformation?: protocol.DiagnosticRelatedInformation[]): protocol.Diagnostic {
return { start, end, text: formatStringFromArgs(message.message, args), code: message.code, category, reportsUnnecessary, relatedInformation, source: undefined };
}
@@ -24,7 +24,7 @@ namespace ts.projectSystem {
compilerOptions: { plugins: [{ name: "myplugin" }] }
})
};
function createHostWithPlugin(files: ReadonlyArray<File>) {
function createHostWithPlugin(files: readonly File[]) {
const host = createServerHost(files);
host.require = (_initialPath, moduleName) => {
assert.equal(moduleName, "myplugin");
@@ -54,7 +54,7 @@ namespace ts.projectSystem {
line: 1,
offset: aTs.content.indexOf("this.") + 1 + "this.".length
};
const expectedCompletionEntries: ReadonlyArray<protocol.CompletionEntry> = [
const expectedCompletionEntries: readonly protocol.CompletionEntry[] = [
{ name: "foo", kind: ScriptElementKind.memberFunctionElement, kindModifiers: "", sortText: "0" },
{ name: "prop", kind: ScriptElementKind.memberVariableElement, kindModifiers: "", sortText: "0" }
];
@@ -63,7 +63,7 @@ namespace ts.projectSystem {
const host = createHostWithPlugin([aTs, tsconfig]);
const session = createSession(host);
openFilesForSession([aTs], session);
verifyCommandWithMetadata<protocol.CompletionsRequest, ReadonlyArray<protocol.CompletionEntry>>(session, host, {
verifyCommandWithMetadata<protocol.CompletionsRequest, readonly protocol.CompletionEntry[]>(session, host, {
command: protocol.CommandTypes.Completions,
arguments: completionRequestArgs
}, expectedCompletionEntries);
@@ -77,11 +77,11 @@ namespace ts.projectSystem {
command: protocol.CommandTypes.CompletionInfo,
arguments: completionRequestArgs
}, {
isGlobalCompletion: false,
isMemberCompletion: true,
isNewIdentifierLocation: false,
entries: expectedCompletionEntries
});
isGlobalCompletion: false,
isMemberCompletion: true,
isNewIdentifierLocation: false,
entries: expectedCompletionEntries
});
});
it("returns undefined correctly", () => {
@@ -1,11 +1,11 @@
namespace ts.projectSystem {
describe("unittests:: tsserver:: Project Errors", () => {
function checkProjectErrors(projectFiles: server.ProjectFilesWithTSDiagnostics, expectedErrors: ReadonlyArray<string>): void {
function checkProjectErrors(projectFiles: server.ProjectFilesWithTSDiagnostics, expectedErrors: readonly string[]): void {
assert.isTrue(projectFiles !== undefined, "missing project files");
checkProjectErrorsWorker(projectFiles.projectErrors, expectedErrors);
}
function checkProjectErrorsWorker(errors: ReadonlyArray<Diagnostic>, expectedErrors: ReadonlyArray<string>): void {
function checkProjectErrorsWorker(errors: readonly Diagnostic[], expectedErrors: readonly string[]): void {
assert.equal(errors ? errors.length : 0, expectedErrors.length, `expected ${expectedErrors.length} error in the list`);
if (expectedErrors.length) {
for (let i = 0; i < errors.length; i++) {
@@ -774,7 +774,7 @@ declare module '@custom/plugin' {
command: server.CommandNames.CompilerOptionsDiagnosticsFull,
seq: 2,
arguments: { projectFileName: projectName }
}).response as ReadonlyArray<protocol.DiagnosticWithLinePosition>;
}).response as readonly protocol.DiagnosticWithLinePosition[];
assert.isTrue(diags.length === 0);
session.executeCommand(<server.protocol.SetCompilerOptionsForInferredProjectsRequest>{
@@ -788,7 +788,7 @@ declare module '@custom/plugin' {
command: server.CommandNames.CompilerOptionsDiagnosticsFull,
seq: 4,
arguments: { projectFileName: projectName }
}).response as ReadonlyArray<protocol.DiagnosticWithLinePosition>;
}).response as readonly protocol.DiagnosticWithLinePosition[];
assert.isTrue(diagsAfterUpdate.length === 0);
});
@@ -815,7 +815,7 @@ declare module '@custom/plugin' {
command: server.CommandNames.CompilerOptionsDiagnosticsFull,
seq: 2,
arguments: { projectFileName }
}).response as ReadonlyArray<server.protocol.DiagnosticWithLinePosition>;
}).response as readonly server.protocol.DiagnosticWithLinePosition[];
assert.isTrue(diags.length === 0);
session.executeCommand(<server.protocol.OpenExternalProjectRequest>{
@@ -833,7 +833,7 @@ declare module '@custom/plugin' {
command: server.CommandNames.CompilerOptionsDiagnosticsFull,
seq: 4,
arguments: { projectFileName }
}).response as ReadonlyArray<server.protocol.DiagnosticWithLinePosition>;
}).response as readonly server.protocol.DiagnosticWithLinePosition[];
assert.isTrue(diagsAfterUpdate.length === 0);
});
});
@@ -873,7 +873,7 @@ declare module '@custom/plugin' {
command: server.CommandNames.SemanticDiagnosticsSync,
seq: 2,
arguments: { file: configFile.path, projectFileName: projectName, includeLinePosition: true }
}).response as ReadonlyArray<server.protocol.DiagnosticWithLinePosition>;
}).response as readonly server.protocol.DiagnosticWithLinePosition[];
assert.isTrue(diags.length === 2);
configFile.content = configFileContentWithoutCommentLine;
@@ -884,7 +884,7 @@ declare module '@custom/plugin' {
command: server.CommandNames.SemanticDiagnosticsSync,
seq: 2,
arguments: { file: configFile.path, projectFileName: projectName, includeLinePosition: true }
}).response as ReadonlyArray<server.protocol.DiagnosticWithLinePosition>;
}).response as readonly server.protocol.DiagnosticWithLinePosition[];
assert.isTrue(diagsAfterEdit.length === 2);
verifyDiagnostic(diags[0], diagsAfterEdit[0]);
@@ -1,6 +1,6 @@
namespace ts.projectSystem {
describe("unittests:: tsserver:: with project references and tsbuild", () => {
function createHost(files: ReadonlyArray<File>, rootNames: ReadonlyArray<string>) {
function createHost(files: readonly File[], rootNames: readonly string[]) {
const host = createServerHost(files);
// ts build should succeed
@@ -151,12 +151,12 @@ fn5();
const files = [dependencyTs, dependencyConfig, mainTs, mainConfig, libFile, randomFile, randomConfig];
function verifyScriptInfos(session: TestSession, host: TestServerHost, openInfos: ReadonlyArray<string>, closedInfos: ReadonlyArray<string>, otherWatchedFiles: ReadonlyArray<string>, additionalInfo: string) {
function verifyScriptInfos(session: TestSession, host: TestServerHost, openInfos: readonly string[], closedInfos: readonly string[], otherWatchedFiles: readonly string[], additionalInfo: string) {
checkScriptInfos(session.getProjectService(), openInfos.concat(closedInfos), additionalInfo);
checkWatchedFiles(host, closedInfos.concat(otherWatchedFiles).map(f => f.toLowerCase()), additionalInfo);
}
function verifyInfosWithRandom(session: TestSession, host: TestServerHost, openInfos: ReadonlyArray<string>, closedInfos: ReadonlyArray<string>, otherWatchedFiles: ReadonlyArray<string>, reqName: string) {
function verifyInfosWithRandom(session: TestSession, host: TestServerHost, openInfos: readonly string[], closedInfos: readonly string[], otherWatchedFiles: readonly string[], reqName: string) {
verifyScriptInfos(session, host, openInfos.concat(randomFile.path), closedInfos, otherWatchedFiles.concat(randomConfig.path), reqName);
}
@@ -366,7 +366,8 @@ namespace ts.projectSystem {
const proj = projectService.externalProjects[0];
assert.deepEqual(proj.getFileNames(/*excludeFilesFromExternalLibraries*/ true), [file1.path]);
assert.deepEqual(proj.getTypeAcquisition().include, ["duck-types"]);
} finally {
}
finally {
projectService.resetSafeList();
}
});
@@ -464,7 +465,8 @@ namespace ts.projectSystem {
const proj = projectService.externalProjects[0];
assert.deepEqual(proj.getFileNames(/*excludeFilesFromExternalLibraries*/ true), [file1.path]);
assert.deepEqual(proj.getTypeAcquisition().include, ["kendo-ui", "office"]);
} finally {
}
finally {
projectService.resetSafeList();
}
});
@@ -504,7 +506,8 @@ namespace ts.projectSystem {
projectService.openExternalProject({ projectFileName: "project", options: {}, rootFiles: toExternalFiles([file1.path, file2.path]), typeAcquisition: { enable: true } });
const proj = projectService.externalProjects[0];
assert.deepEqual(proj.getFileNames(), [file2.path]);
} finally {
}
finally {
projectService.resetSafeList();
}
});
@@ -602,7 +602,7 @@ namespace ts.projectSystem {
return `Reusing resolution of module '${moduleName}' to file '${file.path}' from old program.`;
}
function verifyWatchesWithConfigFile(host: TestServerHost, files: File[], openFile: File, extraExpectedDirectories?: ReadonlyArray<string>) {
function verifyWatchesWithConfigFile(host: TestServerHost, files: File[], openFile: File, extraExpectedDirectories?: readonly string[]) {
const expectedRecursiveDirectories = arrayToSet([projectLocation, `${projectLocation}/${nodeModulesAtTypes}`, ...(extraExpectedDirectories || emptyArray)]);
checkWatchedFiles(host, mapDefined(files, f => {
if (f === openFile) {
+2 -5
View File
@@ -283,9 +283,7 @@ namespace ts.server {
session.onMessage(JSON.stringify(req));
req.seq = i;
i++;
/* tslint:disable no-null-keyword */
req.arguments = null;
/* tslint:enable no-null-keyword */
req.arguments = null; // eslint-disable-line no-null/no-null
session.onMessage(JSON.stringify(req));
req.seq = i;
i++;
@@ -337,7 +335,7 @@ namespace ts.server {
session.send = Session.prototype.send;
assert(session.send);
expect(session.send(msg)).to.not.exist; // tslint:disable-line no-unused-expression
expect(session.send(msg)).to.not.exist; // eslint-disable-line no-unused-expressions
expect(lastWrittenToHost).to.equal(resultMsg);
});
});
@@ -548,7 +546,6 @@ namespace ts.server {
});
});
it("has access to the project service", () => {
// tslint:disable-next-line no-unused-expression
new class extends TestSession {
constructor() {
super();
@@ -1005,7 +1005,7 @@ namespace ts.projectSystem {
content: "module.exports = 0",
};
const typeNames: ReadonlyArray<string> = ["commander"];
const typeNames: readonly string[] = ["commander"];
const typePath = (name: string): string => `${cachePath}/node_modules/@types/${name}/index.d.ts`;
const host = createServerHost([file, commanderJS]);
const installer = new (class extends Installer {
@@ -23,7 +23,7 @@ namespace ts.projectSystem {
endOffset: 5,
errorCodes: [Diagnostics.Cannot_find_name_0_Did_you_mean_1.code],
});
assert.deepEqual<ReadonlyArray<protocol.CodeFixAction> | undefined>(response, [
assert.deepEqual<readonly protocol.CodeFixAction[] | undefined>(response, [
{
description: "Change spelling to 'foo'",
fixAllDescription: "Fix all detected spelling errors",