diff --git a/Gulpfile.js b/Gulpfile.js
index f3f1d7ae7a662..6e379ff41d2a6 100644
--- a/Gulpfile.js
+++ b/Gulpfile.js
@@ -13,7 +13,7 @@ const mkdirp = require("mkdirp");
const { src, dest, task, parallel, series, watch } = require("gulp");
const { append, transform } = require("gulp-insert");
const { prependFile } = require("./scripts/build/prepend");
-const { exec, readJson, needsUpdate, getDiffTool, getDirSize, flatten, rm } = require("./scripts/build/utils");
+const { exec, readJson, needsUpdate, getDiffTool, getDirSize, rm } = require("./scripts/build/utils");
const { runConsoleTests, refBaseline, localBaseline, refRwcBaseline, localRwcBaseline } = require("./scripts/build/tests");
const { buildProject, cleanProject, watchProject } = require("./scripts/build/projects");
const cmdLineOptions = require("./scripts/build/options");
@@ -113,18 +113,8 @@ const localPreBuild = parallel(generateLibs, series(buildScripts, generateDiagno
const preBuild = cmdLineOptions.lkg ? lkgPreBuild : localPreBuild;
const buildServices = (() => {
- // flatten the services project
- const flattenServicesConfig = async () => flatten("src/services/tsconfig.json", "built/local/typescriptServices.tsconfig.json", {
- compilerOptions: {
- "removeComments": false,
- "stripInternal": true,
- "declarationMap": false,
- "outFile": "typescriptServices.out.js"
- }
- });
-
// build typescriptServices.out.js
- const buildTypescriptServicesOut = () => buildProject("built/local/typescriptServices.tsconfig.json", cmdLineOptions);
+ const buildTypescriptServicesOut = () => buildProject("src/typescriptServices/tsconfig.json", cmdLineOptions);
// create typescriptServices.js
const createTypescriptServicesJs = () => src("built/local/typescriptServices.out.js")
@@ -166,13 +156,13 @@ const buildServices = (() => {
.pipe(dest("built/local"));
return series(
- flattenServicesConfig,
buildTypescriptServicesOut,
createTypescriptServicesJs,
createTypescriptServicesDts,
createTypescriptJs,
createTypescriptDts,
- createTypescriptStandaloneDts);
+ createTypescriptStandaloneDts,
+ );
})();
task("services", series(preBuild, buildServices));
task("services").description = "Builds the language service";
@@ -185,13 +175,13 @@ const cleanServices = async () => {
await cleanProject("built/local/typescriptServices.tsconfig.json");
}
await del([
- "built/local/typescriptServices.tsconfig.json",
"built/local/typescriptServices.out.js",
"built/local/typescriptServices.out.d.ts",
+ "built/local/typescriptServices.out.tsbuildinfo",
"built/local/typescriptServices.js",
"built/local/typescript.js",
"built/local/typescript.d.ts",
- "built/local/typescript_standalone.d.ts",
+ "built/local/typescript_standalone.d.ts"
]);
};
cleanTasks.push(cleanServices);
@@ -247,20 +237,8 @@ task("watch-min").flags = {
}
const buildLssl = (() => {
- // flatten the server project
- const flattenTsServerProject = async () => flatten("src/tsserver/tsconfig.json", "built/local/tsserverlibrary.tsconfig.json", {
- exclude: ["src/tsserver/server.ts"],
- compilerOptions: {
- "removeComments": false,
- "stripInternal": true,
- "declaration": true,
- "declarationMap": false,
- "outFile": "tsserverlibrary.out.js"
- }
- });
-
// build tsserverlibrary.out.js
- const buildServerLibraryOut = () => buildProject("built/local/tsserverlibrary.tsconfig.json", cmdLineOptions);
+ const buildServerLibraryOut = () => buildProject("src/tsserverlibrary/tsconfig.json", cmdLineOptions);
// create tsserverlibrary.js
const createServerLibraryJs = () => src("built/local/tsserverlibrary.out.js")
@@ -281,10 +259,10 @@ const buildLssl = (() => {
.pipe(dest("built/local"));
return series(
- flattenTsServerProject,
buildServerLibraryOut,
createServerLibraryJs,
- createServerLibraryDts);
+ createServerLibraryDts,
+ );
})();
task("lssl", series(preBuild, buildLssl));
task("lssl").description = "Builds language service server library";
@@ -297,9 +275,9 @@ const cleanLssl = async () => {
await cleanProject("built/local/tsserverlibrary.tsconfig.json");
}
await del([
- "built/local/tsserverlibrary.tsconfig.json",
"built/local/tsserverlibrary.out.js",
"built/local/tsserverlibrary.out.d.ts",
+ "built/local/tsserverlibrary.out.tsbuildinfo",
"built/local/tsserverlibrary.js",
"built/local/tsserverlibrary.d.ts",
]);
diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg
index 17f927a74f3b6..0b66fd7760cc0 100644
--- a/lib/enu/diagnosticMessages.generated.json.lcg
+++ b/lib/enu/diagnosticMessages.generated.json.lcg
@@ -339,6 +339,18 @@
+ -
+
+
+
+
+
+ -
+
+
+
+
+
-
@@ -1641,6 +1653,12 @@
+ -
+
+
+
+
+
-
@@ -1671,6 +1689,12 @@
+ -
+
+
+
+
+
-
@@ -1869,6 +1893,12 @@
+ -
+
+
+
+
+
-
@@ -2031,6 +2061,12 @@
+ -
+
+
+
+
+
-
@@ -2421,6 +2457,12 @@
+ -
+
+
+
+
+
-
@@ -4485,6 +4527,18 @@
+ -
+
+
+
+
+
+ -
+
+
+
+
+
-
@@ -5343,6 +5397,12 @@
+ -
+
+
+
+
+
-
@@ -6237,6 +6297,12 @@
+ -
+
+
+
+
+
-
@@ -6465,6 +6531,12 @@
+ -
+
+
+
+
+
-
diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts
index 68651b804a5c2..38c0989c362d7 100644
--- a/lib/protocol.d.ts
+++ b/lib/protocol.d.ts
@@ -49,6 +49,7 @@ declare namespace ts.server.protocol {
OpenExternalProject = "openExternalProject",
OpenExternalProjects = "openExternalProjects",
CloseExternalProject = "closeExternalProject",
+ UpdateOpen = "updateOpen",
GetOutliningSpans = "getOutliningSpans",
TodoComments = "todoComments",
Indentation = "indentation",
@@ -1117,6 +1118,30 @@ declare namespace ts.server.protocol {
*/
interface CloseExternalProjectResponse extends Response {
}
+ /**
+ * Request to synchronize list of open files with the client
+ */
+ interface UpdateOpenRequest extends Request {
+ command: CommandTypes.UpdateOpen;
+ arguments: UpdateOpenRequestArgs;
+ }
+ /**
+ * Arguments to UpdateOpenRequest
+ */
+ interface UpdateOpenRequestArgs {
+ /**
+ * List of newly open files
+ */
+ openFiles?: OpenRequestArgs[];
+ /**
+ * List of open files files that were changes
+ */
+ changedFiles?: FileCodeEdits[];
+ /**
+ * List of files that were closed
+ */
+ closedFiles?: string[];
+ }
/**
* Request to set compiler options for inferred projects.
* External projects are opened / closed explicitly.
diff --git a/lib/tsc.js b/lib/tsc.js
index e75a1ea50badc..a32addec337f8 100644
--- a/lib/tsc.js
+++ b/lib/tsc.js
@@ -14,7 +14,6 @@ and limitations under the License.
***************************************************************************** */
-"use strict";
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
@@ -903,6 +902,21 @@ var ts;
} };
}
ts.arrayIterator = arrayIterator;
+ function arrayReverseIterator(array) {
+ var i = array.length;
+ return {
+ next: function () {
+ if (i === 0) {
+ return { value: undefined, done: true };
+ }
+ else {
+ i--;
+ return { value: array[i], done: false };
+ }
+ }
+ };
+ }
+ ts.arrayReverseIterator = arrayReverseIterator;
function stableSort(array, comparer) {
var indices = array.map(function (_, i) { return i; });
stableSortIndices(array, indices, comparer);
@@ -2458,6 +2472,7 @@ var ts;
: FileWatcherEventKind.Changed;
}
ts.getFileWatcherEventKind = getFileWatcherEventKind;
+ ts.ignoredPaths = ["/node_modules/.", "/.git"];
function createRecursiveDirectoryWatcher(host) {
var cache = ts.createMap();
var callbackCache = ts.createMultiMap();
@@ -2473,6 +2488,8 @@ var ts;
else {
directoryWatcher = {
watcher: host.watchDirectory(dirName, function (fileName) {
+ if (isIgnoredPath(fileName))
+ return;
callbackCache.forEach(function (callbacks, rootDirName) {
if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
callbacks.forEach(function (callback) { return callback(fileName); });
@@ -2514,7 +2531,7 @@ var ts;
var newChildWatches;
ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) {
var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
- return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 ? childFullName : undefined;
+ return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 ? childFullName : undefined;
}) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
return newChildWatches || ts.emptyArray;
function createAndAddChildDirectoryWatcher(childName) {
@@ -2525,6 +2542,16 @@ var ts;
(newChildWatches || (newChildWatches = [])).push(childWatcher);
}
}
+ function isIgnoredPath(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
+ }
+ function isInPath(path, searchPath) {
+ if (ts.stringContains(path, searchPath))
+ return true;
+ if (host.useCaseSensitiveFileNames)
+ return false;
+ return ts.stringContains(toCanonicalFilePath(path), searchPath);
+ }
}
ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher;
function getNodeMajorVersion() {
@@ -3805,6 +3832,7 @@ var ts;
Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."),
Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."),
+ Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."),
The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."),
Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."),
File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),
@@ -4072,6 +4100,16 @@ var ts;
Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."),
Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."),
Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."),
+ Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"),
+ Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
+ A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"),
+ A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"),
+ Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"),
+ Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"),
+ Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
+ Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."),
+ Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"),
+ Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"),
The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"),
The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."),
The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."),
@@ -4288,6 +4326,7 @@ var ts;
Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"),
+ Convert_to_named_parameters: diag(95075, ts.DiagnosticCategory.Message, "Convert_to_named_parameters_95075", "Convert to named parameters"),
};
})(ts || (ts = {}));
var ts;
@@ -4686,11 +4725,13 @@ var ts;
ts.Debug.assert(pos === 0);
return shebangTriviaRegex.test(text);
}
+ ts.isShebangTrivia = isShebangTrivia;
function scanShebangTrivia(text, pos) {
var shebang = shebangTriviaRegex.exec(text)[0];
pos = pos + shebang.length;
return pos;
}
+ ts.scanShebangTrivia = scanShebangTrivia;
function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) {
var pendingPos;
var pendingEnd;
@@ -6287,7 +6328,7 @@ var ts;
}
}
function getSourceFileOfNode(node) {
- while (node && node.kind !== 279) {
+ while (node && node.kind !== 284) {
node = node.parent;
}
return node;
@@ -6392,7 +6433,7 @@ var ts;
if (includeJsDoc && ts.hasJSDocNodes(node)) {
return getTokenPosOfNode(node.jsDoc[0]);
}
- if (node.kind === 306 && node._children.length > 0) {
+ if (node.kind === 311 && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -6411,7 +6452,7 @@ var ts;
}
ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
function isJSDocTypeExpressionOrChild(node) {
- return node.kind === 283 || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
+ return node.kind === 288 || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
}
function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
if (includeTrivia === void 0) { includeTrivia = false; }
@@ -6514,7 +6555,7 @@ var ts;
return node && node.kind === 244 && (!node.body);
}
function isBlockScopedContainerTopLevel(node) {
- return node.kind === 279 ||
+ return node.kind === 284 ||
node.kind === 244 ||
ts.isFunctionLike(node);
}
@@ -6529,7 +6570,7 @@ var ts;
ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
function isModuleAugmentationExternal(node) {
switch (node.parent.kind) {
- case 279:
+ case 284:
return ts.isExternalModule(node.parent);
case 245:
return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
@@ -6547,7 +6588,7 @@ var ts;
ts.isEffectiveExternalModule = isEffectiveExternalModule;
function isBlockScope(node, parentNode) {
switch (node.kind) {
- case 279:
+ case 284:
case 246:
case 274:
case 244:
@@ -6570,9 +6611,9 @@ var ts;
ts.isBlockScope = isBlockScope;
function isDeclarationWithTypeParameters(node) {
switch (node.kind) {
- case 297:
- case 304:
- case 293:
+ case 302:
+ case 309:
+ case 298:
return true;
default:
ts.assertType(node);
@@ -6588,12 +6629,12 @@ var ts;
case 162:
case 165:
case 166:
- case 289:
+ case 294:
case 240:
case 209:
case 241:
case 242:
- case 303:
+ case 308:
case 239:
case 156:
case 157:
@@ -6731,7 +6772,7 @@ var ts;
function getErrorSpanForNode(sourceFile, node) {
var errorNode = node;
switch (node.kind) {
- case 279:
+ case 284:
var pos_1 = ts.skipTrivia(sourceFile.text, 0, false);
if (pos_1 === sourceFile.text.length) {
return ts.createTextSpan(0, 0);
@@ -6888,7 +6929,7 @@ var ts;
return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
case 150:
return node === parent.constraint;
- case 303:
+ case 308:
return node === parent.constraint;
case 154:
case 153:
@@ -7132,7 +7173,7 @@ var ts;
}
ts.getContainingClass = getContainingClass;
function getThisContainer(node, includeArrowFunctions) {
- ts.Debug.assert(node.kind !== 279);
+ ts.Debug.assert(node.kind !== 284);
while (true) {
node = node.parent;
if (!node) {
@@ -7171,7 +7212,7 @@ var ts;
case 161:
case 162:
case 243:
- case 279:
+ case 284:
return node;
}
}
@@ -7813,7 +7854,7 @@ var ts;
}
ts.isJSDocConstructSignature = isJSDocConstructSignature;
function isJSDocTypeAlias(node) {
- return node.kind === 304 || node.kind === 297;
+ return node.kind === 309 || node.kind === 302;
}
ts.isJSDocTypeAlias = isJSDocTypeAlias;
function isTypeAlias(node) {
@@ -7949,7 +7990,7 @@ var ts;
ts.hasRestParameter = hasRestParameter;
function isRestParameter(node) {
var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
- return node.dotDotDotToken !== undefined || !!type && type.kind === 290;
+ return node.dotDotDotToken !== undefined || !!type && type.kind === 295;
}
ts.isRestParameter = isRestParameter;
function getAssignmentTargetKind(node) {
@@ -8376,7 +8417,7 @@ var ts;
|| kind === 158
|| kind === 159
|| kind === 244
- || kind === 279;
+ || kind === 284;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(range) {
@@ -8448,7 +8489,7 @@ var ts;
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 309:
+ case 314:
return 0;
case 208:
return 1;
@@ -8749,6 +8790,9 @@ var ts;
lineStart = true;
}
}
+ function getTextPosWithWriteLine() {
+ return lineStart ? output.length : (output.length + newLine.length);
+ }
reset();
return {
write: write,
@@ -8777,7 +8821,8 @@ var ts;
writeStringLiteral: write,
writeSymbol: function (s, _) { return write(s); },
writeTrailingSemicolon: write,
- writeComment: write
+ writeComment: write,
+ getTextPosWithWriteLine: getTextPosWithWriteLine
};
}
ts.createTextWriter = createTextWriter;
@@ -9042,7 +9087,7 @@ var ts;
}
ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
function isNonTypeAliasTemplate(tag) {
- return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 && tag.parent.tags.some(isJSDocTypeAlias));
+ return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 296 && tag.parent.tags.some(isJSDocTypeAlias));
}
function getEffectiveSetAccessorTypeAnnotationNode(node) {
var parameter = getSetAccessorValueParameter(node);
@@ -9873,19 +9918,29 @@ var ts;
|| kind === 96
|| kind === 132
|| kind === 211
- || kind === 284
- || kind === 285
- || kind === 286
- || kind === 287
- || kind === 288
|| kind === 289
- || kind === 290;
+ || kind === 290
+ || kind === 291
+ || kind === 292
+ || kind === 293
+ || kind === 294
+ || kind === 295;
}
ts.isTypeNodeKind = isTypeNodeKind;
function isAccessExpression(node) {
return node.kind === 189 || node.kind === 190;
}
ts.isAccessExpression = isAccessExpression;
+ function isBundleFileTextLike(section) {
+ switch (section.kind) {
+ case "text":
+ case "internal":
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isBundleFileTextLike = isBundleFileTextLike;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
@@ -10219,8 +10274,8 @@ var ts;
switch (declaration.kind) {
case 72:
return declaration;
- case 305:
- case 299: {
+ case 310:
+ case 304: {
var name = declaration.name;
if (name.kind === 148) {
return name.right;
@@ -10244,7 +10299,7 @@ var ts;
return undefined;
}
}
- case 304:
+ case 309:
return getNameOfJSDocTypedef(declaration);
case 254: {
var expression = declaration.expression;
@@ -10386,7 +10441,7 @@ var ts;
return ts.emptyArray;
}
if (ts.isJSDocTypeAlias(node)) {
- ts.Debug.assert(node.parent.kind === 291);
+ ts.Debug.assert(node.parent.kind === 296);
return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
}
if (node.typeParameters) {
@@ -10648,7 +10703,7 @@ var ts;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 308) {
+ while (node.kind === 313) {
node = node.expression;
}
return node;
@@ -10987,113 +11042,133 @@ var ts;
}
ts.isEnumMember = isEnumMember;
function isSourceFile(node) {
- return node.kind === 279;
+ return node.kind === 284;
}
ts.isSourceFile = isSourceFile;
function isBundle(node) {
- return node.kind === 280;
+ return node.kind === 285;
}
ts.isBundle = isBundle;
function isUnparsedSource(node) {
- return node.kind === 281;
+ return node.kind === 286;
}
ts.isUnparsedSource = isUnparsedSource;
+ function isUnparsedPrepend(node) {
+ return node.kind === 280;
+ }
+ ts.isUnparsedPrepend = isUnparsedPrepend;
+ function isUnparsedTextLike(node) {
+ switch (node.kind) {
+ case 281:
+ case 282:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isUnparsedTextLike = isUnparsedTextLike;
+ function isUnparsedNode(node) {
+ return isUnparsedTextLike(node) ||
+ node.kind === 279 ||
+ node.kind === 283;
+ }
+ ts.isUnparsedNode = isUnparsedNode;
function isJSDocTypeExpression(node) {
- return node.kind === 283;
+ return node.kind === 288;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 284;
+ return node.kind === 289;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 285;
+ return node.kind === 290;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 286;
+ return node.kind === 291;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 287;
+ return node.kind === 292;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 288;
+ return node.kind === 293;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 289;
+ return node.kind === 294;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 290;
+ return node.kind === 295;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 291;
+ return node.kind === 296;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 295;
+ return node.kind === 300;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 296;
+ return node.kind === 301;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocEnumTag(node) {
- return node.kind === 298;
+ return node.kind === 303;
}
ts.isJSDocEnumTag = isJSDocEnumTag;
function isJSDocThisTag(node) {
- return node.kind === 301;
+ return node.kind === 306;
}
ts.isJSDocThisTag = isJSDocThisTag;
function isJSDocParameterTag(node) {
- return node.kind === 299;
+ return node.kind === 304;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 300;
+ return node.kind === 305;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 302;
+ return node.kind === 307;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 303;
+ return node.kind === 308;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 304;
+ return node.kind === 309;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 305;
+ return node.kind === 310;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 305 || node.kind === 299;
+ return node.kind === 310 || node.kind === 304;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 292;
+ return node.kind === 297;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
function isJSDocCallbackTag(node) {
- return node.kind === 297;
+ return node.kind === 302;
}
ts.isJSDocCallbackTag = isJSDocCallbackTag;
function isJSDocSignature(node) {
- return node.kind === 293;
+ return node.kind === 298;
}
ts.isJSDocSignature = isJSDocSignature;
})(ts || (ts = {}));
(function (ts) {
function isSyntaxList(n) {
- return n.kind === 306;
+ return n.kind === 311;
}
ts.isSyntaxList = isSyntaxList;
function isNode(node) {
@@ -11223,11 +11298,11 @@ var ts;
switch (kind) {
case 155:
case 160:
- case 293:
+ case 298:
case 161:
case 162:
case 165:
- case 289:
+ case 294:
case 166:
return true;
default:
@@ -11478,8 +11553,8 @@ var ts;
case 208:
case 212:
case 210:
- case 309:
- case 308:
+ case 314:
+ case 313:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -11492,11 +11567,11 @@ var ts;
}
ts.isAssertionExpression = isAssertionExpression;
function isPartiallyEmittedExpression(node) {
- return node.kind === 308;
+ return node.kind === 313;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
function isNotEmittedStatement(node) {
- return node.kind === 307;
+ return node.kind === 312;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
function isNotEmittedOrPartiallyEmittedNode(node) {
@@ -11596,9 +11671,9 @@ var ts;
|| kind === 242
|| kind === 150
|| kind === 237
- || kind === 304
- || kind === 297
- || kind === 305;
+ || kind === 309
+ || kind === 302
+ || kind === 310;
}
function isDeclarationStatementKind(kind) {
return kind === 239
@@ -11633,13 +11708,13 @@ var ts;
|| kind === 219
|| kind === 224
|| kind === 231
- || kind === 307
- || kind === 311
- || kind === 310;
+ || kind === 312
+ || kind === 316
+ || kind === 315;
}
function isDeclaration(node) {
if (node.kind === 150) {
- return node.parent.kind !== 303 || ts.isInJSFile(node);
+ return (node.parent && node.parent.kind !== 308) || ts.isInJSFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -11717,15 +11792,15 @@ var ts;
}
ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
function isJSDocNode(node) {
- return node.kind >= 283 && node.kind <= 305;
+ return node.kind >= 288 && node.kind <= 310;
}
ts.isJSDocNode = isJSDocNode;
function isJSDocCommentContainingNode(node) {
- return node.kind === 291 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
+ return node.kind === 296 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
}
ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
function isJSDocTag(node) {
- return node.kind >= 294 && node.kind <= 305;
+ return node.kind >= 299 && node.kind <= 310;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -12027,6 +12102,10 @@ var ts;
return !!(compilerOptions.declaration || compilerOptions.composite);
}
ts.getEmitDeclarations = getEmitDeclarations;
+ function isIncrementalCompilation(options) {
+ return !!(options.incremental || options.composite);
+ }
+ ts.isIncrementalCompilation = isIncrementalCompilation;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
}
@@ -13080,7 +13159,7 @@ var ts;
var IdentifierConstructor;
var SourceFileConstructor;
function createNode(kind, pos, end) {
- if (kind === 279) {
+ if (kind === 284) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 72) {
@@ -13317,7 +13396,7 @@ var ts;
case 218:
case 245:
return visitNodes(cbNode, cbNodes, node.statements);
- case 279:
+ case 284:
return visitNodes(cbNode, cbNodes, node.statements) ||
visitNode(cbNode, node.endOfFileToken);
case 219:
@@ -13466,7 +13545,7 @@ var ts;
return visitNode(cbNode, node.expression);
case 258:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 309:
+ case 314:
return visitNodes(cbNode, cbNodes, node.elements);
case 260:
return visitNode(cbNode, node.openingElement) ||
@@ -13495,60 +13574,60 @@ var ts;
return visitNode(cbNode, node.tagName);
case 171:
case 172:
- case 283:
- case 287:
- case 286:
case 288:
- case 290:
+ case 292:
+ case 291:
+ case 293:
+ case 295:
return visitNode(cbNode, node.type);
- case 289:
+ case 294:
return visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 291:
+ case 296:
return visitNodes(cbNode, cbNodes, node.tags);
- case 299:
- case 305:
+ case 304:
+ case 310:
return visitNode(cbNode, node.tagName) ||
(node.isNameFirst
? visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression)
: visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name));
- case 295:
+ case 300:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.class);
- case 303:
+ case 308:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.constraint) ||
visitNodes(cbNode, cbNodes, node.typeParameters);
- case 304:
+ case 309:
return visitNode(cbNode, node.tagName) ||
(node.typeExpression &&
- node.typeExpression.kind === 283
+ node.typeExpression.kind === 288
? visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName)
: visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression));
- case 297:
+ case 302:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
- case 300:
- case 302:
- case 301:
- case 298:
+ case 305:
+ case 307:
+ case 306:
+ case 303:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.typeExpression);
- case 293:
+ case 298:
return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
- case 292:
+ case 297:
return ts.forEach(node.jsDocPropertyTags, cbNode);
- case 294:
- case 296:
+ case 299:
+ case 301:
return visitNode(cbNode, node.tagName);
- case 308:
+ case 313:
return visitNode(cbNode, node.expression);
}
}
@@ -13799,7 +13878,7 @@ var ts;
}
Parser.fixupParentReferences = fixupParentReferences;
function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
- var sourceFile = new SourceFileConstructor(279, 0, sourceText.length);
+ var sourceFile = new SourceFileConstructor(284, 0, sourceText.length);
nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
@@ -14746,9 +14825,9 @@ var ts;
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(284);
+ var result = createNode(289);
if (postFixEquals) {
- return createPostfixType(288, result);
+ return createPostfixType(293, result);
}
else {
nextToken();
@@ -14756,7 +14835,7 @@ var ts;
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(287);
+ var result = createNode(292);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -14770,18 +14849,18 @@ var ts;
token() === 30 ||
token() === 59 ||
token() === 50) {
- var result = createNode(285, pos);
+ var result = createNode(290, pos);
return finishNode(result);
}
else {
- var result = createNode(286, pos);
+ var result = createNode(291, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(289);
+ var result = createNodeWithJSDoc(294);
nextToken();
fillSignature(57, 4 | 32, result);
return finishNode(result);
@@ -14805,12 +14884,12 @@ var ts;
var type = parseTypeOrTypePredicate();
scanner.setInJSDocType(false);
if (dotdotdot) {
- var variadic = createNode(290, dotdotdot.pos);
+ var variadic = createNode(295, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 59) {
- return createPostfixType(288, type);
+ return createPostfixType(293, type);
}
return type;
}
@@ -15104,7 +15183,7 @@ var ts;
return finishNode(node);
}
var type = parseType();
- if (!(contextFlags & 2097152) && type.kind === 286 && type.pos === type.type.pos) {
+ if (!(contextFlags & 2097152) && type.kind === 291 && type.pos === type.type.pos) {
type.kind = 171;
}
return type;
@@ -15288,13 +15367,13 @@ var ts;
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 52:
- type = createPostfixType(287, type);
+ type = createPostfixType(292, type);
break;
case 56:
if (!(contextFlags & 2097152) && lookAhead(nextTokenIsStartOfType)) {
return type;
}
- type = createPostfixType(286, type);
+ type = createPostfixType(291, type);
break;
case 22:
parseExpected(22);
@@ -17622,7 +17701,7 @@ var ts;
}
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(283);
+ var result = createNode(288);
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18);
result.type = doInsideOfContext(2097152, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -17759,7 +17838,7 @@ var ts;
}
}
function createJSDocComment() {
- var result = createNode(291, start);
+ var result = createNode(296, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
@@ -17918,7 +17997,7 @@ var ts;
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(start, tagName) {
- var result = createNode(294, start);
+ var result = createNode(299, start);
result.tagName = tagName;
return finishNode(result);
}
@@ -17974,8 +18053,8 @@ var ts;
typeExpression = tryParseTypeExpression();
}
var result = target === 1 ?
- createNode(305, start) :
- createNode(299, start);
+ createNode(310, start) :
+ createNode(304, start);
var comment = parseTagComments(indent + scanner.getStartPos() - start);
var nestedTypeLiteral = target !== 4 && parseNestedTypeLiteral(typeExpression, name, target, indent);
if (nestedTypeLiteral) {
@@ -17992,18 +18071,18 @@ var ts;
}
function parseNestedTypeLiteral(typeExpression, name, target, indent) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(283, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(288, scanner.getTokenPos());
var child = void 0;
var jsdocTypeLiteral = void 0;
var start_2 = scanner.getStartPos();
var children = void 0;
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
- if (child.kind === 299 || child.kind === 305) {
+ if (child.kind === 304 || child.kind === 310) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(292, start_2);
+ jsdocTypeLiteral = createNode(297, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 169) {
jsdocTypeLiteral.isArrayType = true;
@@ -18014,25 +18093,25 @@ var ts;
}
}
function parseReturnTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 300; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 305; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(300, start);
+ var result = createNode(305, start);
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 302; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 307; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(302, start);
+ var result = createNode(307, start);
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(true);
return finishNode(result);
}
function parseAugmentsTag(start, tagName) {
- var result = createNode(295, start);
+ var result = createNode(300, start);
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
return finishNode(result);
@@ -18059,19 +18138,19 @@ var ts;
return node;
}
function parseClassTag(start, tagName) {
- var tag = createNode(296, start);
+ var tag = createNode(301, start);
tag.tagName = tagName;
return finishNode(tag);
}
function parseThisTag(start, tagName) {
- var tag = createNode(301, start);
+ var tag = createNode(306, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(true);
skipWhitespace();
return finishNode(tag);
}
function parseEnumTag(start, tagName) {
- var tag = createNode(298, start);
+ var tag = createNode(303, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(true);
skipWhitespace();
@@ -18080,7 +18159,7 @@ var ts;
function parseTypedefTag(start, tagName, indent) {
var typeExpression = tryParseTypeExpression();
skipWhitespaceOrAsterisk();
- var typedefTag = createNode(304, start);
+ var typedefTag = createNode(309, start);
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace();
typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
@@ -18094,9 +18173,9 @@ var ts;
var childTypeTag = void 0;
while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(292, start);
+ jsdocTypeLiteral = createNode(297, start);
}
- if (child.kind === 302) {
+ if (child.kind === 307) {
if (childTypeTag) {
break;
}
@@ -18141,14 +18220,14 @@ var ts;
return typeNameOrNamespaceName;
}
function parseCallbackTag(start, tagName, indent) {
- var callbackTag = createNode(297, start);
+ var callbackTag = createNode(302, start);
callbackTag.tagName = tagName;
callbackTag.fullName = parseJSDocTypeNameWithNamespace();
callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
skipWhitespace();
callbackTag.comment = parseTagComments(indent);
var child;
- var jsdocSignature = createNode(293, start);
+ var jsdocSignature = createNode(298, start);
jsdocSignature.parameters = [];
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4, indent); })) {
jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
@@ -18156,7 +18235,7 @@ var ts;
var returnTag = tryParse(function () {
if (parseOptionalJsdoc(58)) {
var tag = parseTag(indent);
- if (tag && tag.kind === 300) {
+ if (tag && tag.kind === 305) {
return tag;
}
}
@@ -18201,7 +18280,7 @@ var ts;
case 58:
if (canParseTag) {
var child = tryParseChildTag(target, indent);
- if (child && (child.kind === 299 || child.kind === 305) &&
+ if (child && (child.kind === 304 || child.kind === 310) &&
target !== 4 &&
name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
@@ -18270,7 +18349,7 @@ var ts;
skipWhitespace();
typeParameters.push(typeParameter);
} while (parseOptionalJsdoc(27));
- var result = createNode(303, start);
+ var result = createNode(308, start);
result.tagName = tagName;
result.constraint = constraint;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -19126,6 +19205,22 @@ var ts;
category: ts.Diagnostics.Basic_Options,
description: ts.Diagnostics.Enable_project_compilation,
},
+ {
+ name: "incremental",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_incremental_compilation,
+ },
+ {
+ name: "tsBuildInfoFile",
+ type: "string",
+ isFilePath: true,
+ paramType: ts.Diagnostics.FILE,
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
+ },
{
name: "removeComments",
type: "boolean",
@@ -22309,7 +22404,7 @@ var ts;
return "__constructor";
case 165:
case 160:
- case 293:
+ case 298:
return "__call";
case 166:
case 161:
@@ -22318,7 +22413,7 @@ var ts;
return "__index";
case 255:
return "__export";
- case 279:
+ case 284:
return "export=";
case 204:
if (ts.getAssignmentDeclarationKind(node) === 2) {
@@ -22326,10 +22421,10 @@ var ts;
}
ts.Debug.fail("Unknown binary declaration kind");
break;
- case 289:
+ case 294:
return (ts.isJSDocConstructSignature(node) ? "__new" : "__call");
case 151:
- ts.Debug.assert(node.parent.kind === 289, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
+ ts.Debug.assert(node.parent.kind === 294, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
var functionType = node.parent;
var index = functionType.parameters.indexOf(node);
return "arg" + index;
@@ -22481,7 +22576,7 @@ var ts;
if (hasExplicitReturn)
node.flags |= 256;
}
- if (node.kind === 279) {
+ if (node.kind === 284) {
node.flags |= emitFlags;
}
if (currentReturnTarget) {
@@ -22625,11 +22720,11 @@ var ts;
case 191:
bindCallExpressionFlow(node);
break;
- case 304:
- case 297:
+ case 309:
+ case 302:
bindJSDocTypeAlias(node);
break;
- case 279: {
+ case 284: {
bindEachFunctionsFirst(node.statements);
bind(node.endOfFileToken);
break;
@@ -23269,7 +23364,7 @@ var ts;
case 243:
case 188:
case 168:
- case 292:
+ case 297:
case 268:
return 1;
case 241:
@@ -23278,7 +23373,7 @@ var ts;
case 242:
case 181:
return 1 | 32;
- case 279:
+ case 284:
return 1 | 4 | 32;
case 156:
if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
@@ -23290,8 +23385,8 @@ var ts;
case 158:
case 159:
case 160:
- case 293:
- case 289:
+ case 298:
+ case 294:
case 165:
case 161:
case 162:
@@ -23325,7 +23420,7 @@ var ts;
switch (container.kind) {
case 244:
return declareModuleMember(node, symbolFlags, symbolExcludes);
- case 279:
+ case 284:
return declareSourceFileMember(node, symbolFlags, symbolExcludes);
case 209:
case 240:
@@ -23333,7 +23428,7 @@ var ts;
case 243:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
case 168:
- case 292:
+ case 297:
case 188:
case 241:
case 268:
@@ -23342,7 +23437,7 @@ var ts;
case 166:
case 160:
case 161:
- case 293:
+ case 298:
case 162:
case 156:
case 155:
@@ -23352,9 +23447,9 @@ var ts;
case 239:
case 196:
case 197:
- case 289:
- case 304:
- case 297:
+ case 294:
+ case 309:
+ case 302:
case 242:
case 181:
return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
@@ -23371,8 +23466,8 @@ var ts;
: declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes);
}
function hasExportDeclarations(node) {
- var body = node.kind === 279 ? node : node.body;
- if (body && (body.kind === 279 || body.kind === 245)) {
+ var body = node.kind === 284 ? node : node.body;
+ if (body && (body.kind === 284 || body.kind === 245)) {
for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
var stat = _a[_i];
if (stat.kind === 255 || stat.kind === 254) {
@@ -23482,7 +23577,7 @@ var ts;
case 244:
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
- case 279:
+ case 284:
if (ts.isExternalOrCommonJsModule(container)) {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
@@ -23599,7 +23694,7 @@ var ts;
}
function checkStrictModeFunctionDeclaration(node) {
if (languageVersion < 2) {
- if (blockScopeContainer.kind !== 279 &&
+ if (blockScopeContainer.kind !== 284 &&
blockScopeContainer.kind !== 244 &&
!ts.isFunctionLike(blockScopeContainer)) {
var errorSpan = ts.getErrorSpanForNode(file, node);
@@ -23828,12 +23923,12 @@ var ts;
case 159:
return bindPropertyOrMethodOrAccessor(node, 65536, 67187647);
case 165:
- case 289:
- case 293:
+ case 294:
+ case 298:
case 166:
return bindFunctionOrConstructorType(node);
case 168:
- case 292:
+ case 297:
case 181:
return bindAnonymousTypeWorker(node);
case 188:
@@ -23888,7 +23983,7 @@ var ts;
return bindExportDeclaration(node);
case 254:
return bindExportAssignment(node);
- case 279:
+ case 284:
updateStrictModeStatementList(node.statements);
return bindSourceFileIfExternalModule();
case 218:
@@ -23897,21 +23992,21 @@ var ts;
}
case 245:
return updateStrictModeStatementList(node.statements);
- case 299:
- if (node.parent.kind === 293) {
+ case 304:
+ if (node.parent.kind === 298) {
return bindParameter(node);
}
- if (node.parent.kind !== 292) {
+ if (node.parent.kind !== 297) {
break;
}
- case 305:
+ case 310:
var propTag = node;
- var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 ?
+ var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 293 ?
4 | 16777216 :
4;
return declareSymbolAndAddToSymbolTable(propTag, flags, 0);
- case 304:
- case 297:
+ case 309:
+ case 302:
return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
}
}
@@ -24062,7 +24157,7 @@ var ts;
var symbolTable = ts.hasModifier(thisContainer, 32) ? containingClass.symbol.exports : containingClass.symbol.members;
declareSymbol(symbolTable, containingClass.symbol, node, 4, 0, true);
break;
- case 279:
+ case 284:
if (thisContainer.commonJsModuleIndicator) {
declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 | 1048576, 0);
}
@@ -24078,7 +24173,7 @@ var ts;
if (node.expression.kind === 100) {
bindThisPropertyAssignment(node);
}
- else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279) {
+ else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 284) {
if (ts.isPrototypeAccess(node.expression)) {
bindPrototypePropertyAssignment(node, node.parent);
}
@@ -24107,7 +24202,7 @@ var ts;
}
function bindObjectDefinePropertyAssignment(node) {
var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
- var isToplevel = node.parent.parent.kind === 279;
+ var isToplevel = node.parent.parent.kind === 284;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, false);
bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, false);
}
@@ -24163,8 +24258,8 @@ var ts;
function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) {
var namespaceSymbol = lookupSymbolForPropertyAccess(name);
var isToplevel = ts.isBinaryExpression(propertyAccess.parent)
- ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279
- : propertyAccess.parent.parent.kind === 279;
+ ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 284
+ : propertyAccess.parent.parent.kind === 284;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty);
bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
}
@@ -24271,7 +24366,7 @@ var ts;
}
}
function bindParameter(node) {
- if (node.kind === 299 && container.kind !== 293) {
+ if (node.kind === 304 && container.kind !== 298) {
return;
}
if (inStrictMode && !(node.flags & 4194304)) {
@@ -24883,7 +24978,7 @@ var ts;
break;
case 194:
case 212:
- case 308:
+ case 313:
transformFlags |= 3;
excludeFlags = 536872257;
break;
@@ -25053,7 +25148,7 @@ var ts;
transformFlags |= 192;
}
break;
- case 279:
+ case 284:
if (subtreeFlags & 16384) {
transformFlags |= 192;
}
@@ -25125,7 +25220,7 @@ var ts;
return 637666625;
case 194:
case 212:
- case 308:
+ case 313:
case 195:
case 98:
return 536872257;
@@ -25505,10 +25600,10 @@ var ts;
isContextSensitive: isContextSensitive,
getFullyQualifiedName: getFullyQualifiedName,
getResolvedSignature: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, false);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 0);
},
getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, true);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16);
},
getConstantValue: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
@@ -25629,10 +25724,10 @@ var ts;
},
getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
};
- function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) {
+ function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
apparentArgumentCount = argumentCount;
- var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined;
+ var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
apparentArgumentCount = undefined;
return res;
}
@@ -26112,7 +26207,7 @@ var ts;
return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 });
}
function isGlobalSourceFile(node) {
- return node.kind === 279 && !ts.isExternalOrCommonJsModule(node);
+ return node.kind === 284 && !ts.isExternalOrCommonJsModule(node);
}
function getSymbol(symbols, name, meaning) {
if (meaning) {
@@ -26242,7 +26337,7 @@ var ts;
if (result = lookup(location.locals, name, meaning)) {
var useResult = true;
if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
- if (meaning & result.flags & 67897832 && lastLocation.kind !== 291) {
+ if (meaning & result.flags & 67897832 && lastLocation.kind !== 296) {
useResult = result.flags & 262144
? lastLocation === location.type ||
lastLocation.kind === 151 ||
@@ -26275,13 +26370,13 @@ var ts;
}
}
switch (location.kind) {
- case 279:
+ case 284:
if (!ts.isExternalOrCommonJsModule(location))
break;
isInExternalModule = true;
case 244:
var moduleExports = getSymbolOfNode(location).exports;
- if (location.kind === 279 || ts.isAmbientModule(location)) {
+ if (location.kind === 284 || ts.isAmbientModule(location)) {
if (result = moduleExports.get("default")) {
var localSymbol = ts.getLocalSymbolForExportDefault(result);
if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) {
@@ -26398,8 +26493,8 @@ var ts;
location = location.parent;
}
break;
- case 304:
- case 297:
+ case 309:
+ case 302:
location = ts.getJSDocHost(location);
break;
}
@@ -26414,7 +26509,7 @@ var ts;
}
if (!result) {
if (lastLocation) {
- ts.Debug.assert(lastLocation.kind === 279);
+ ts.Debug.assert(lastLocation.kind === 284);
if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
return lastLocation.symbol;
}
@@ -27168,7 +27263,7 @@ var ts;
function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) {
var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
if (!dontResolveAlias && symbol) {
- if (!(symbol.flags & (1536 | 3)) && !ts.getDeclarationOfKind(symbol, 279)) {
+ if (!(symbol.flags & (1536 | 3)) && !ts.getDeclarationOfKind(symbol, 284)) {
var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
? "allowSyntheticDefaultImports"
: "esModuleInterop";
@@ -27497,7 +27592,7 @@ var ts;
}
}
switch (location.kind) {
- case 279:
+ case 284:
if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
@@ -27685,10 +27780,10 @@ var ts;
return node && getSymbolOfNode(node);
}
function hasExternalModuleSymbol(declaration) {
- return ts.isAmbientModule(declaration) || (declaration.kind === 279 && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isAmbientModule(declaration) || (declaration.kind === 284 && ts.isExternalOrCommonJsModule(declaration));
}
function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
- return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 284 && ts.isExternalOrCommonJsModule(declaration));
}
function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
var aliasesToMakeVisible;
@@ -28121,7 +28216,7 @@ var ts;
var isNonLocalFunctionSymbol = !!(symbol.flags & 16) &&
(symbol.parent ||
ts.forEach(symbol.declarations, function (declaration) {
- return declaration.parent.kind === 279 || declaration.parent.kind === 245;
+ return declaration.parent.kind === 284 || declaration.parent.kind === 245;
}));
if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
return (!!(context.flags & 4096) || (context.visitedTypes && context.visitedTypes.has(typeId))) &&
@@ -28470,7 +28565,7 @@ var ts;
var savedContextFlags = context.flags;
context.flags &= ~512;
var shouldUseGeneratedName = context.flags & 4 &&
- type.symbol.declarations[0] &&
+ type.symbol.declarations && type.symbol.declarations[0] &&
ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
typeParameterShadowsNameInScope(type, context);
var name = shouldUseGeneratedName
@@ -28489,7 +28584,7 @@ var ts;
function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151);
if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) {
- parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299);
+ parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 304);
}
var parameterType = getTypeOfSymbol(parameterSymbol);
if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
@@ -28631,7 +28726,7 @@ var ts;
return top;
}
function getSpecifierForModuleSymbol(symbol, context) {
- var file = ts.getDeclarationOfKind(symbol, 279);
+ var file = ts.getDeclarationOfKind(symbol, 284);
if (file && file.moduleName !== undefined) {
return file.moduleName;
}
@@ -28874,7 +28969,7 @@ var ts;
ts.isExternalModuleAugmentation(node.parent.parent);
}
function isDefaultBindingContext(location) {
- return location.kind === 279 || ts.isAmbientModule(location);
+ return location.kind === 284 || ts.isAmbientModule(location);
}
function getNameOfSymbolFromNameType(symbol, context) {
var nameType = symbol.nameType;
@@ -28940,8 +29035,8 @@ var ts;
return false;
function determineIfDeclarationIsVisible() {
switch (node.kind) {
- case 297:
- case 304:
+ case 302:
+ case 309:
return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
case 186:
return isDeclarationVisible(node.parent.parent);
@@ -28962,7 +29057,7 @@ var ts;
}
var parent = getDeclarationContainer(node);
if (!(ts.getCombinedModifierFlags(node) & 1) &&
- !(node.kind !== 248 && parent.kind !== 279 && parent.flags & 4194304)) {
+ !(node.kind !== 248 && parent.kind !== 284 && parent.flags & 4194304)) {
return isGlobalSourceFile(parent);
}
return isDeclarationVisible(parent);
@@ -28996,7 +29091,7 @@ var ts;
case 253:
return false;
case 150:
- case 279:
+ case 284:
case 247:
return true;
case 254:
@@ -29975,15 +30070,15 @@ var ts;
case 155:
case 165:
case 166:
- case 289:
+ case 294:
case 239:
case 156:
case 196:
case 197:
case 242:
- case 303:
- case 304:
- case 297:
+ case 308:
+ case 309:
+ case 302:
case 181:
case 175:
var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
@@ -31683,10 +31778,10 @@ var ts;
return result;
}
function isJSDocOptionalParameter(node) {
- return ts.isInJSFile(node) && (node.type && node.type.kind === 288
+ return ts.isInJSFile(node) && (node.type && node.type.kind === 293
|| ts.getJSDocParameterTags(node).some(function (_a) {
var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293;
}));
}
function tryFindAmbientModule(moduleName, withAugmentations) {
@@ -31719,7 +31814,7 @@ var ts;
return false;
}
var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293;
}
function createIdentifierTypePredicate(parameterName, parameterIndex, type) {
return { kind: 1, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
@@ -32028,8 +32123,21 @@ var ts;
}
return undefined;
}
- function getSignatureInstantiation(signature, typeArguments, isJavascript) {
- return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ if (inferredTypeParameters) {
+ var returnSignature = getSingleCallSignature(getReturnTypeOfSignature(instantiatedSignature));
+ if (returnSignature) {
+ var newReturnSignature = cloneSignature(returnSignature);
+ newReturnSignature.typeParameters = inferredTypeParameters;
+ newReturnSignature.target = returnSignature.target;
+ newReturnSignature.mapper = returnSignature.mapper;
+ var newInstantiatedSignature = cloneSignature(instantiatedSignature);
+ newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
+ return newInstantiatedSignature;
+ }
+ }
+ return instantiatedSignature;
}
function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
@@ -32346,7 +32454,7 @@ var ts;
}
function getTypeReferenceTypeWorker(node, symbol, typeArguments) {
if (symbol.flags & (32 | 64)) {
- if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
+ if (symbol.valueDeclaration && symbol.valueDeclaration.parent && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
var jsdocType = getJSDocTypeReference(node, symbol, typeArguments);
if (jsdocType) {
return jsdocType;
@@ -32382,7 +32490,7 @@ var ts;
}
function getConstrainedTypeVariable(typeVariable, node) {
var constraints;
- while (node && !ts.isStatement(node) && node.kind !== 291) {
+ while (node && !ts.isStatement(node) && node.kind !== 296) {
var parent = node.parent;
if (parent.kind === 175 && node === parent.trueType) {
var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType);
@@ -33804,8 +33912,8 @@ var ts;
function getTypeFromTypeNode(node) {
switch (node.kind) {
case 120:
- case 284:
- case 285:
+ case 289:
+ case 290:
return anyType;
case 143:
return unknownType;
@@ -33852,23 +33960,23 @@ var ts;
return getTypeFromUnionTypeNode(node);
case 174:
return getTypeFromIntersectionTypeNode(node);
- case 286:
+ case 291:
return getTypeFromJSDocNullableTypeNode(node);
- case 288:
+ case 293:
return addOptionality(getTypeFromTypeNode(node.type));
case 177:
case 172:
- case 287:
- case 283:
+ case 292:
+ case 288:
return getTypeFromTypeNode(node.type);
- case 290:
+ case 295:
return getTypeFromJSDocVariadicType(node);
case 165:
case 166:
case 168:
- case 292:
- case 289:
- case 293:
+ case 297:
+ case 294:
+ case 298:
return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
case 179:
return getTypeFromTypeOperatorNode(node);
@@ -34701,7 +34809,7 @@ var ts;
if (isTupleLikeType(source)) {
return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation);
}
- var tupleizedType = checkArrayLiteral(node, 3, true);
+ var tupleizedType = checkArrayLiteral(node, 1, true);
if (isTupleLikeType(tupleizedType)) {
return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation);
}
@@ -36798,7 +36906,7 @@ var ts;
return;
}
break;
- case 289:
+ case 294:
error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
return;
case 239:
@@ -38788,7 +38896,7 @@ var ts;
return ts.findAncestor(node.parent, function (node) {
return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
node.kind === 245 ||
- node.kind === 279 ||
+ node.kind === 284 ||
node.kind === 154;
});
}
@@ -38889,7 +38997,7 @@ var ts;
}
else if (declaration.kind === 209) {
var container = ts.getThisContainer(node, false);
- while (container.kind !== 279) {
+ while (container.kind !== 284) {
if (container.parent === declaration) {
if (container.kind === 154 && ts.hasModifier(container, 32)) {
getNodeLinks(declaration).flags |= 16777216;
@@ -39237,7 +39345,7 @@ var ts;
}
function getTypeForThisExpressionFromJSDoc(node) {
var jsdocType = ts.getJSDocType(node);
- if (jsdocType && jsdocType.kind === 289) {
+ if (jsdocType && jsdocType.kind === 294) {
var jsDocFunctionType = jsdocType;
if (jsDocFunctionType.parameters.length > 0 &&
jsDocFunctionType.parameters[0].name &&
@@ -41382,22 +41490,30 @@ var ts;
}
function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) {
var context = createInferenceContext(signature.typeParameters, signature, 0, compareTypes);
- var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature;
+ var restType = getEffectiveRestType(contextualSignature);
+ var mapper = contextualMapper && restType && restType.flags & 262144 ? cloneTypeMapper(contextualMapper) : contextualMapper;
+ var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
forEachMatchingParameterType(sourceSignature, signature, function (source, target) {
inferTypes(context.inferences, source, target);
});
if (!contextualMapper) {
inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8);
+ var signaturePredicate = getTypePredicateOfSignature(signature);
+ var contextualPredicate = getTypePredicateOfSignature(sourceSignature);
+ if (signaturePredicate && contextualPredicate && signaturePredicate.kind === contextualPredicate.kind &&
+ (signaturePredicate.kind === 0 || signaturePredicate.parameterIndex === contextualPredicate.parameterIndex)) {
+ inferTypes(context.inferences, contextualPredicate.type, signaturePredicate.type, 8);
+ }
}
return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
}
- function inferJsxTypeArguments(node, signature, excludeArgument, context) {
+ function inferJsxTypeArguments(node, signature, checkMode, context) {
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context);
+ var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
inferTypes(context.inferences, checkAttrType, paramType);
return getInferredTypes(context);
}
- function inferTypeArguments(node, signature, args, excludeArgument, context) {
+ function inferTypeArguments(node, signature, args, checkMode, context) {
for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) {
var inference = _a[_i];
if (!inference.isFixed) {
@@ -41405,7 +41521,7 @@ var ts;
}
}
if (ts.isJsxOpeningLikeElement(node)) {
- return inferJsxTypeArguments(node, signature, excludeArgument, context);
+ return inferJsxTypeArguments(node, signature, checkMode, context);
}
if (node.kind !== 152) {
var contextualType = getContextualType(node);
@@ -41432,8 +41548,7 @@ var ts;
var arg = args[i];
if (arg.kind !== 210) {
var paramType = getTypeAtPosition(signature, i);
- var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context;
- var argType = checkExpressionWithContextualType(arg, paramType, mapper);
+ var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
inferTypes(context.inferences, argType, paramType);
}
}
@@ -41455,7 +41570,7 @@ var ts;
if (isSpreadArgument(arg)) {
return arg.kind === 215 ?
createArrayType(arg.type) :
- getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context));
+ getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0));
}
}
var contextualType = getIndexTypeOfType(restType, 1) || anyType;
@@ -41463,7 +41578,7 @@ var ts;
var types = [];
var spreadIndex = -1;
for (var i = index; i < argCount; i++) {
- var argType = checkExpressionWithContextualType(args[i], contextualType, context);
+ var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0);
if (spreadIndex < 0 && isSpreadArgument(args[i])) {
spreadIndex = i - index;
}
@@ -41508,14 +41623,14 @@ var ts;
}
return 2;
}
- function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors) {
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined);
+ var attributesType = checkExpressionWithContextualType(node.attributes, paramType, undefined, checkMode);
return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes);
}
- function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignature(node, args, signature, relation, checkMode, reportErrors) {
if (ts.isJsxOpeningLikeElement(node)) {
- return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors);
+ return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors);
}
var thisType = getThisTypeOfSignature(signature);
if (thisType && thisType !== voidType && node.kind !== 192) {
@@ -41534,8 +41649,8 @@ var ts;
var arg = args[i];
if (arg.kind !== 210) {
var paramType = getTypeAtPosition(signature, i);
- var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined);
- var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType;
+ var argType = checkExpressionWithContextualType(arg, paramType, undefined, checkMode);
+ var checkArgType = checkMode & 4 ? getRegularTypeOfObjectLiteral(argType) : argType;
if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) {
return false;
}
@@ -41715,7 +41830,7 @@ var ts;
}
return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
}
- function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) {
+ function resolveCall(node, signatures, candidatesOutArray, checkMode, fallbackError) {
var isTaggedTemplate = node.kind === 193;
var isDecorator = node.kind === 152;
var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
@@ -41737,12 +41852,12 @@ var ts;
}
var args = getEffectiveCallArguments(node);
var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
- var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined;
+ var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 : 0;
var candidateForArgumentError;
var candidateForArgumentArityError;
var candidateForTypeArgumentError;
var result;
- var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 && node.arguments.hasTrailingComma;
+ var signatureHelpTrailingComma = !!(checkMode & 16) && node.kind === 191 && node.arguments.hasTrailingComma;
if (candidates.length > 1) {
result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma);
}
@@ -41754,7 +41869,7 @@ var ts;
}
if (reportErrors) {
if (candidateForArgumentError) {
- checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true);
+ checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, 0, true);
}
else if (candidateForArgumentArityError) {
diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
@@ -41786,7 +41901,7 @@ var ts;
if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
return undefined;
}
- if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) {
+ if (!checkApplicableSignature(node, args, candidate, relation, 0, false)) {
candidateForArgumentError = candidate;
return undefined;
}
@@ -41810,9 +41925,10 @@ var ts;
}
else {
inferenceContext = createInferenceContext(candidate.typeParameters, candidate, ts.isInJSFile(node) ? 2 : 0);
- typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
+ typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8, inferenceContext);
+ argCheckMode |= inferenceContext.flags & 8 ? 8 : 0;
}
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
candidateForArgumentArityError = checkCandidate;
continue;
@@ -41821,23 +41937,23 @@ var ts;
else {
checkCandidate = candidate;
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, false)) {
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
}
continue;
}
- if (excludeArgument) {
- excludeArgument = undefined;
+ if (argCheckMode) {
+ argCheckMode = 0;
if (inferenceContext) {
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
candidateForArgumentArityError = checkCandidate;
continue;
}
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, false)) {
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
}
@@ -41850,18 +41966,6 @@ var ts;
return undefined;
}
}
- function getExcludeArgument(args) {
- var excludeArgument;
- for (var i = 0; i < args.length; i++) {
- if (isContextSensitive(args[i])) {
- if (!excludeArgument) {
- excludeArgument = new Array(args.length);
- }
- excludeArgument[i] = true;
- }
- }
- return excludeArgument;
- }
function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
ts.Debug.assert(candidates.length > 0);
return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; })
@@ -41933,7 +42037,7 @@ var ts;
}
function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
var inferenceContext = createInferenceContext(typeParameters, candidate, ts.isInJSFile(node) ? 2 : 0);
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext);
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 | 8, inferenceContext);
return createSignatureInstantiation(candidate, typeArgumentTypes);
}
function getLongestCandidateIndex(candidates, argsCount) {
@@ -41952,7 +42056,7 @@ var ts;
}
return maxParamsIndex;
}
- function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveCallExpression(node, candidatesOutArray, checkMode) {
if (node.expression.kind === 98) {
var superType = checkSuperExpression(node.expression);
if (isTypeAny(superType)) {
@@ -41966,7 +42070,7 @@ var ts;
var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
if (baseTypeNode) {
var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
- return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, baseConstructors, candidatesOutArray, checkMode);
}
}
return resolveUntypedCall(node);
@@ -42003,17 +42107,24 @@ var ts;
}
return resolveErrorCall(node);
}
+ if (checkMode & 8 && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
+ skippedGenericFunction(node, checkMode);
+ return resolvingSignature;
+ }
if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
+ }
+ function isGenericFunctionReturningFunction(signature) {
+ return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
}
function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) {
return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144) ||
!numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 | 131072)) && isTypeAssignableTo(funcType, globalFunctionType);
}
- function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveNewExpression(node, candidatesOutArray, checkMode) {
if (node.arguments && languageVersion < 1) {
var spreadIndex = getSpreadArgumentIndex(node.arguments);
if (spreadIndex >= 0) {
@@ -42044,11 +42155,11 @@ var ts;
error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
return resolveErrorCall(node);
}
- return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, constructSignatures, candidatesOutArray, checkMode);
}
var callSignatures = getSignaturesOfType(expressionType, 0);
if (callSignatures.length) {
- var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode);
if (!noImplicitAny) {
if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
@@ -42140,7 +42251,7 @@ var ts;
addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead));
}
}
- function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
var tagType = checkExpression(node.tag);
var apparentType = getApparentType(tagType);
if (apparentType === errorType) {
@@ -42155,7 +42266,7 @@ var ts;
invocationError(node, apparentType, 0);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
}
function getDiagnosticHeadMessageForDecoratorResolution(node) {
switch (node.parent.kind) {
@@ -42174,7 +42285,7 @@ var ts;
return ts.Debug.fail();
}
}
- function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveDecorator(node, candidatesOutArray, checkMode) {
var funcType = checkExpression(node.expression);
var apparentType = getApparentType(funcType);
if (apparentType === errorType) {
@@ -42199,7 +42310,7 @@ var ts;
invocationErrorRecovery(apparentType, 0, diag);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode, headMessage);
}
function createSignatureForJSXIntrinsic(node, result) {
var namespace = getJsxNamespaceAt(node);
@@ -42211,11 +42322,11 @@ var ts;
parameterSymbol.type = result;
return createSignature(declaration, undefined, undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, undefined, 1, false, false);
}
- function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
if (isJsxIntrinsicIdentifier(node.tagName)) {
var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
var fakeSignature = createSignatureForJSXIntrinsic(node, result);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), undefined), result, node.tagName, node.attributes);
+ checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), undefined, 0), result, node.tagName, node.attributes);
return fakeSignature;
}
var exprTypes = checkExpression(node.tagName);
@@ -42231,7 +42342,7 @@ var ts;
error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
return resolveErrorCall(node);
}
- return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, signatures, candidatesOutArray, checkMode);
}
function isPotentiallyUncalledDecorator(decorator, signatures) {
return signatures.length && ts.every(signatures, function (signature) {
@@ -42240,32 +42351,33 @@ var ts;
signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
});
}
- function resolveSignature(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveSignature(node, candidatesOutArray, checkMode) {
switch (node.kind) {
case 191:
- return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveCallExpression(node, candidatesOutArray, checkMode);
case 192:
- return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveNewExpression(node, candidatesOutArray, checkMode);
case 193:
- return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
case 152:
- return resolveDecorator(node, candidatesOutArray, isForSignatureHelp);
+ return resolveDecorator(node, candidatesOutArray, checkMode);
case 262:
case 261:
- return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp);
+ return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
}
throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
}
- function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) {
- if (isForSignatureHelp === void 0) { isForSignatureHelp = false; }
+ function getResolvedSignature(node, candidatesOutArray, checkMode) {
var links = getNodeLinks(node);
var cached = links.resolvedSignature;
if (cached && cached !== resolvingSignature && !candidatesOutArray) {
return cached;
}
links.resolvedSignature = resolvingSignature;
- var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp);
- links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ var result = resolveSignature(node, candidatesOutArray, checkMode || 0);
+ if (result !== resolvingSignature) {
+ links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ }
return result;
}
function isJSConstructor(node) {
@@ -42330,10 +42442,13 @@ var ts;
}
return links.inferredClassType;
}
- function checkCallExpression(node) {
+ function checkCallExpression(node, checkMode) {
if (!checkGrammarTypeArguments(node, node.typeArguments))
checkGrammarArguments(node.arguments);
- var signature = getResolvedSignature(node);
+ var signature = getResolvedSignature(node, undefined, checkMode);
+ if (signature === resolvingSignature) {
+ return silentNeverType;
+ }
if (node.expression.kind === 98) {
return voidType;
}
@@ -42566,7 +42681,7 @@ var ts;
if (isTupleType(restType)) {
var associatedNames = restType.target.associatedNames;
var index = pos - paramCount;
- return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index;
+ return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
}
return restParameter.escapedName;
}
@@ -42762,7 +42877,7 @@ var ts;
var functionFlags = ts.getFunctionFlags(func);
var type;
if (func.body.kind !== 218) {
- type = checkExpressionCached(func.body, checkMode);
+ type = checkExpressionCached(func.body, checkMode && checkMode & ~8);
if (functionFlags & 2) {
type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
}
@@ -42907,7 +43022,7 @@ var ts;
ts.forEachReturnStatement(func.body, function (returnStatement) {
var expr = returnStatement.expression;
if (expr) {
- var type = checkExpressionCached(expr, checkMode);
+ var type = checkExpressionCached(expr, checkMode && checkMode & ~8);
if (functionFlags & 2) {
type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
}
@@ -42976,7 +43091,7 @@ var ts;
function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
ts.Debug.assert(node.kind !== 156 || ts.isObjectLiteralMethod(node));
checkNodeDeferred(node);
- if (checkMode === 1 && isContextSensitive(node)) {
+ if (checkMode && checkMode & 4 && isContextSensitive(node)) {
if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) {
var links_1 = getNodeLinks(node);
if (links_1.contextFreeType) {
@@ -43007,7 +43122,7 @@ var ts;
var signature = getSignaturesOfType(type, 0)[0];
if (isContextSensitive(node)) {
var contextualMapper = getContextualMapper(node);
- if (checkMode === 2) {
+ if (checkMode && checkMode & 2) {
inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper);
}
var instantiatedContextualSignature = contextualMapper === identityMapper ?
@@ -43831,15 +43946,13 @@ var ts;
}
return node;
}
- function checkExpressionWithContextualType(node, contextualType, contextualMapper) {
+ function checkExpressionWithContextualType(node, contextualType, contextualMapper, checkMode) {
var context = getContextNode(node);
var saveContextualType = context.contextualType;
var saveContextualMapper = context.contextualMapper;
context.contextualType = contextualType;
context.contextualMapper = contextualMapper;
- var checkMode = contextualMapper === identityMapper ? 1 :
- contextualMapper ? 2 : 3;
- var type = checkExpression(node, checkMode);
+ var type = checkExpression(node, checkMode | 1 | (contextualMapper ? 2 : 0));
var result = maybeTypeOfKind(type, 2944) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
getRegularTypeOfLiteralType(type) : type;
context.contextualType = saveContextualType;
@@ -43849,7 +43962,7 @@ var ts;
function checkExpressionCached(node, checkMode) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- if (checkMode) {
+ if (checkMode && checkMode !== 0) {
return checkExpression(node, checkMode);
}
var saveFlowLoopStart = flowLoopStart;
@@ -43931,20 +44044,105 @@ var ts;
return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
}
function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
- if (checkMode === 2) {
+ if (checkMode && checkMode & (2 | 8)) {
var signature = getSingleCallSignature(type);
if (signature && signature.typeParameters) {
+ if (checkMode & 8) {
+ skippedGenericFunction(node, checkMode);
+ return anyFunctionType;
+ }
var contextualType = getApparentTypeOfContextualType(node);
if (contextualType) {
var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType));
if (contextualSignature && !contextualSignature.typeParameters) {
- return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node)));
+ var context = getContextualMapper(node);
+ var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature));
+ if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
+ var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
+ var strippedType = getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters));
+ var inferences = ts.map(context.typeParameters, createInferenceInfo);
+ inferTypes(inferences, strippedType, contextualType);
+ if (ts.some(inferences, hasInferenceCandidates) && !hasOverlappingInferences(context.inferences, inferences)) {
+ mergeInferences(context.inferences, inferences);
+ context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
+ return strippedType;
+ }
+ }
+ return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
}
}
}
}
return type;
}
+ function skippedGenericFunction(node, checkMode) {
+ if (checkMode & 2) {
+ var context = getContextualMapper(node);
+ context.flags |= 8;
+ }
+ }
+ function hasInferenceCandidates(info) {
+ return !!(info.candidates || info.contraCandidates);
+ }
+ function hasOverlappingInferences(a, b) {
+ for (var i = 0; i < a.length; i++) {
+ if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
+ return true;
+ }
+ }
+ return false;
+ }
+ function mergeInferences(target, source) {
+ for (var i = 0; i < target.length; i++) {
+ if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
+ target[i] = source[i];
+ }
+ }
+ }
+ function getUniqueTypeParameters(context, typeParameters) {
+ var result = [];
+ var oldTypeParameters;
+ var newTypeParameters;
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var tp = typeParameters_2[_i];
+ var name = tp.symbol.escapedName;
+ if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
+ var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
+ var symbol = createSymbol(262144, newName);
+ var newTypeParameter = createTypeParameter(symbol);
+ newTypeParameter.target = tp;
+ oldTypeParameters = ts.append(oldTypeParameters, tp);
+ newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
+ result.push(newTypeParameter);
+ }
+ else {
+ result.push(tp);
+ }
+ }
+ if (newTypeParameters) {
+ var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
+ for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
+ var tp = newTypeParameters_1[_a];
+ tp.mapper = mapper;
+ }
+ }
+ return result;
+ }
+ function hasTypeParameterByName(typeParameters, name) {
+ return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
+ }
+ function getUniqueTypeParameterName(typeParameters, baseName) {
+ var len = baseName.length;
+ while (len > 1 && baseName.charCodeAt(len - 1) >= 48 && baseName.charCodeAt(len - 1) <= 57)
+ len--;
+ var s = baseName.slice(0, len);
+ for (var index = 1; true; index++) {
+ var augmentedName = (s + index);
+ if (!hasTypeParameterByName(typeParameters, augmentedName)) {
+ return augmentedName;
+ }
+ }
+ }
function getTypeOfExpression(node, cache) {
var expr = ts.skipParentheses(node);
if (expr.kind === 191 && expr.expression.kind !== 98 && !ts.isRequireCall(expr, true) && !isSymbolOrSymbolForCall(expr)) {
@@ -43966,7 +44164,7 @@ var ts;
}
var saveContextualType = node.contextualType;
node.contextualType = anyType;
- var type = links.contextFreeType = checkExpression(node, 1);
+ var type = links.contextFreeType = checkExpression(node, 4);
node.contextualType = saveContextualType;
return type;
}
@@ -44046,7 +44244,7 @@ var ts;
return checkImportCallExpression(node);
}
case 192:
- return checkCallExpression(node);
+ return checkCallExpression(node, checkMode);
case 193:
return checkTaggedTemplateExpression(node);
case 195:
@@ -44281,7 +44479,7 @@ var ts;
checkAsyncFunctionReturnType(node, returnTypeNode);
}
}
- if (node.kind !== 162 && node.kind !== 289) {
+ if (node.kind !== 162 && node.kind !== 294) {
registerForUnusedIdentifiersCheck(node);
}
}
@@ -44940,8 +45138,8 @@ var ts;
switch (d.kind) {
case 241:
case 242:
- case 304:
- case 297:
+ case 309:
+ case 302:
return 2;
case 244:
return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0
@@ -44950,7 +45148,7 @@ var ts;
case 240:
case 243:
return 2 | 1;
- case 279:
+ case 284:
return 2 | 1 | 4;
case 254:
if (!ts.isEntityNameExpression(d.expression)) {
@@ -45422,7 +45620,7 @@ var ts;
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 279:
+ case 284:
case 244:
case 218:
case 246:
@@ -45511,8 +45709,8 @@ var ts;
return;
var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
var seenParentsWithEveryUnused = new ts.NodeSet();
- for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
- var typeParameter = typeParameters_2[_i];
+ for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
+ var typeParameter = typeParameters_3[_i];
if (!isTypeParameterUnused(typeParameter))
continue;
var name = ts.idText(typeParameter.name);
@@ -45750,7 +45948,7 @@ var ts;
return;
}
var parent = getDeclarationContainer(node);
- if (parent.kind === 279 && ts.isExternalOrCommonJsModule(parent)) {
+ if (parent.kind === 284 && ts.isExternalOrCommonJsModule(parent)) {
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
}
@@ -45762,7 +45960,7 @@ var ts;
return;
}
var parent = getDeclarationContainer(node);
- if (parent.kind === 279 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) {
+ if (parent.kind === 284 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) {
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
}
@@ -45790,7 +45988,7 @@ var ts;
(container.kind === 218 && ts.isFunctionLike(container.parent) ||
container.kind === 245 ||
container.kind === 244 ||
- container.kind === 279);
+ container.kind === 284);
if (!namesShareScope) {
var name = symbolToString(localDeclarationSymbol);
error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
@@ -47338,7 +47536,7 @@ var ts;
return false;
}
var inAmbientExternalModule = node.parent.kind === 245 && ts.isAmbientModule(node.parent.parent);
- if (node.parent.kind !== 279 && !inAmbientExternalModule) {
+ if (node.parent.kind !== 284 && !inAmbientExternalModule) {
error(moduleName, node.kind === 255 ?
ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
@@ -47449,7 +47647,7 @@ var ts;
var inAmbientExternalModule = node.parent.kind === 245 && ts.isAmbientModule(node.parent.parent);
var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 &&
!node.moduleSpecifier && node.flags & 4194304;
- if (node.parent.kind !== 279 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
+ if (node.parent.kind !== 284 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
}
}
@@ -47465,7 +47663,7 @@ var ts;
}
}
function checkGrammarModuleElementContext(node, errorMessage) {
- var isInAppropriateContext = node.parent.kind === 279 || node.parent.kind === 245 || node.parent.kind === 244;
+ var isInAppropriateContext = node.parent.kind === 284 || node.parent.kind === 245 || node.parent.kind === 244;
if (!isInAppropriateContext) {
grammarErrorOnFirstToken(node, errorMessage);
}
@@ -47491,7 +47689,7 @@ var ts;
if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) {
return;
}
- var container = node.parent.kind === 279 ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 ? node.parent : node.parent.parent;
if (container.kind === 244 && !ts.isAmbientModule(container)) {
if (node.isExportEquals) {
error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
@@ -47650,31 +47848,31 @@ var ts;
return checkInferType(node);
case 183:
return checkImportType(node);
- case 295:
+ case 300:
return checkJSDocAugmentsTag(node);
- case 304:
- case 297:
+ case 309:
+ case 302:
return checkJSDocTypeAliasTag(node);
- case 303:
+ case 308:
return checkJSDocTemplateTag(node);
- case 302:
+ case 307:
return checkJSDocTypeTag(node);
- case 299:
+ case 304:
return checkJSDocParameterTag(node);
- case 289:
+ case 294:
checkJSDocFunctionType(node);
- case 287:
- case 286:
- case 284:
- case 285:
case 292:
+ case 291:
+ case 289:
+ case 290:
+ case 297:
checkJSDocTypeIsInJsFile(node);
ts.forEachChild(node, checkSourceElement);
return;
- case 290:
+ case 295:
checkJSDocVariadicType(node);
return;
- case 283:
+ case 288:
return checkSourceElement(node.type);
case 180:
return checkIndexedAccessType(node);
@@ -47947,7 +48145,7 @@ var ts;
copySymbols(location.locals, meaning);
}
switch (location.kind) {
- case 279:
+ case 284:
if (!ts.isExternalOrCommonJsModule(location))
break;
case 244:
@@ -48141,10 +48339,10 @@ var ts;
return entityNameSymbol;
}
}
- if (entityName.parent.kind === 299) {
+ if (entityName.parent.kind === 304) {
return ts.getParameterSymbolFromJSDoc(entityName.parent);
}
- if (entityName.parent.kind === 150 && entityName.parent.parent.kind === 303) {
+ if (entityName.parent.kind === 150 && entityName.parent.parent.kind === 308) {
ts.Debug.assert(!ts.isInJSFile(entityName));
var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
return typeParameter && typeParameter.symbol;
@@ -48184,7 +48382,7 @@ var ts;
return undefined;
}
function getSymbolAtLocation(node) {
- if (node.kind === 279) {
+ if (node.kind === 284) {
return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
}
var parent = node.parent;
@@ -48467,7 +48665,7 @@ var ts;
}
var parentSymbol_1 = getParentOfSymbol(symbol);
if (parentSymbol_1) {
- if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 279) {
+ if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 284) {
var symbolFile = parentSymbol_1.valueDeclaration;
var referenceFile = ts.getSourceFileOfNode(node);
var symbolIsUmdExport = symbolFile !== referenceFile;
@@ -48556,7 +48754,7 @@ var ts;
}
function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
- if (node === undefined || node.parent.kind !== 279 || !ts.isInternalModuleImportEqualsDeclaration(node)) {
+ if (node === undefined || node.parent.kind !== 284 || !ts.isInternalModuleImportEqualsDeclaration(node)) {
return false;
}
var isValue = isAliasResolvedToValue(getSymbolOfNode(node));
@@ -48942,7 +49140,7 @@ var ts;
break;
}
}
- if (current.valueDeclaration && current.valueDeclaration.kind === 279 && current.flags & 512) {
+ if (current.valueDeclaration && current.valueDeclaration.kind === 284 && current.flags & 512) {
return false;
}
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
@@ -48974,7 +49172,7 @@ var ts;
if (!moduleSymbol) {
return undefined;
}
- return ts.getDeclarationOfKind(moduleSymbol, 279);
+ return ts.getDeclarationOfKind(moduleSymbol, 284);
}
function initializeTypeChecker() {
for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
@@ -49187,7 +49385,7 @@ var ts;
else if (flags & 256) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
}
- else if (node.parent.kind === 245 || node.parent.kind === 279) {
+ else if (node.parent.kind === 245 || node.parent.kind === 284) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
}
else if (flags & 128) {
@@ -49210,7 +49408,7 @@ var ts;
else if (flags & 256) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
}
- else if (node.parent.kind === 245 || node.parent.kind === 279) {
+ else if (node.parent.kind === 245 || node.parent.kind === 284) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
}
else if (node.kind === 151) {
@@ -49254,7 +49452,7 @@ var ts;
flags |= 1;
break;
case 80:
- var container = node.parent.kind === 279 ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 ? node.parent : node.parent.parent;
if (container.kind === 244 && !ts.isAmbientModule(container)) {
return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
}
@@ -49373,7 +49571,7 @@ var ts;
case 151:
return false;
default:
- if (node.parent.kind === 245 || node.parent.kind === 279) {
+ if (node.parent.kind === 245 || node.parent.kind === 284) {
return false;
}
switch (node.kind) {
@@ -50222,7 +50420,7 @@ var ts;
if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) {
return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
}
- if (node.parent.kind === 218 || node.parent.kind === 245 || node.parent.kind === 279) {
+ if (node.parent.kind === 218 || node.parent.kind === 245 || node.parent.kind === 284) {
var links_2 = getNodeLinks(node.parent);
if (!links_2.hasReportedStatementInAmbientContext) {
return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts);
@@ -52231,27 +52429,27 @@ var ts;
}
ts.updateExternalModuleReference = updateExternalModuleReference;
function createJSDocTypeExpression(type) {
- var node = createSynthesizedNode(283);
+ var node = createSynthesizedNode(288);
node.type = type;
return node;
}
ts.createJSDocTypeExpression = createJSDocTypeExpression;
function createJSDocTypeTag(typeExpression, comment) {
- var tag = createJSDocTag(302, "type");
+ var tag = createJSDocTag(307, "type");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
}
ts.createJSDocTypeTag = createJSDocTypeTag;
function createJSDocReturnTag(typeExpression, comment) {
- var tag = createJSDocTag(300, "returns");
+ var tag = createJSDocTag(305, "returns");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
}
ts.createJSDocReturnTag = createJSDocReturnTag;
function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
- var tag = createJSDocTag(299, "param");
+ var tag = createJSDocTag(304, "param");
tag.typeExpression = typeExpression;
tag.name = name;
tag.isBracketed = isBracketed;
@@ -52260,7 +52458,7 @@ var ts;
}
ts.createJSDocParamTag = createJSDocParamTag;
function createJSDocComment(comment, tags) {
- var node = createSynthesizedNode(291);
+ var node = createSynthesizedNode(296);
node.comment = comment;
node.tags = tags;
return node;
@@ -52513,7 +52711,7 @@ var ts;
(typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
(libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
(hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
- var updated = createSynthesizedNode(279);
+ var updated = createSynthesizedNode(284);
updated.flags |= node.flags;
updated.statements = createNodeArray(statements);
updated.endOfFileToken = node.endOfFileToken;
@@ -52587,28 +52785,28 @@ var ts;
}
ts.getMutableClone = getMutableClone;
function createNotEmittedStatement(original) {
- var node = createSynthesizedNode(307);
+ var node = createSynthesizedNode(312);
node.original = original;
setTextRange(node, original);
return node;
}
ts.createNotEmittedStatement = createNotEmittedStatement;
function createEndOfDeclarationMarker(original) {
- var node = createSynthesizedNode(311);
+ var node = createSynthesizedNode(316);
node.emitNode = {};
node.original = original;
return node;
}
ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker;
function createMergeDeclarationMarker(original) {
- var node = createSynthesizedNode(310);
+ var node = createSynthesizedNode(315);
node.emitNode = {};
node.original = original;
return node;
}
ts.createMergeDeclarationMarker = createMergeDeclarationMarker;
function createPartiallyEmittedExpression(expression, original) {
- var node = createSynthesizedNode(308);
+ var node = createSynthesizedNode(313);
node.expression = expression;
node.original = original;
setTextRange(node, original);
@@ -52624,7 +52822,7 @@ var ts;
ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
function flattenCommaElements(node) {
if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
- if (node.kind === 309) {
+ if (node.kind === 314) {
return node.elements;
}
if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27) {
@@ -52634,7 +52832,7 @@ var ts;
return node;
}
function createCommaList(elements) {
- var node = createSynthesizedNode(309);
+ var node = createSynthesizedNode(314);
node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
return node;
}
@@ -52647,33 +52845,195 @@ var ts;
ts.updateCommaList = updateCommaList;
function createBundle(sourceFiles, prepends) {
if (prepends === void 0) { prepends = ts.emptyArray; }
- var node = ts.createNode(280);
+ var node = ts.createNode(285);
node.prepends = prepends;
node.sourceFiles = sourceFiles;
return node;
}
ts.createBundle = createBundle;
- function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, map) {
- var node = ts.createNode(281);
+ var allUnscopedEmitHelpers;
+ function getAllUnscopedEmitHelpers() {
+ return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
+ ts.valuesHelper,
+ ts.readHelper,
+ ts.spreadHelper,
+ ts.restHelper,
+ ts.decorateHelper,
+ ts.metadataHelper,
+ ts.paramHelper,
+ ts.awaiterHelper,
+ ts.assignHelper,
+ ts.awaitHelper,
+ ts.asyncGeneratorHelper,
+ ts.asyncDelegator,
+ ts.asyncValues,
+ ts.extendsHelper,
+ ts.templateObjectHelper,
+ ts.generatorHelper,
+ ts.importStarHelper,
+ ts.importDefaultHelper
+ ], function (helper) { return helper.name; }));
+ }
+ function createUnparsedSource() {
+ var node = ts.createNode(286);
+ node.prologues = ts.emptyArray;
+ node.referencedFiles = ts.emptyArray;
+ node.libReferenceDirectives = ts.emptyArray;
+ node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
+ return node;
+ }
+ function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
+ var node = createUnparsedSource();
+ var stripInternal;
+ var bundleFileInfo;
if (!ts.isString(textOrInputFiles)) {
ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
- node.fileName = mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath;
+ node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
Object.defineProperties(node, {
text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
});
+ if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
+ node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
+ ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
+ stripInternal = mapTextOrStripInternal;
+ bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
+ if (node.oldFileOfCurrentEmit) {
+ parseOldFileOfCurrentEmit(node, ts.Debug.assertDefined(bundleFileInfo));
+ return node;
+ }
+ }
}
else {
+ node.fileName = "";
node.text = textOrInputFiles;
node.sourceMapPath = mapPathOrType;
- node.sourceMapText = map;
+ node.sourceMapText = mapTextOrStripInternal;
}
+ ts.Debug.assert(!node.oldFileOfCurrentEmit);
+ parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
return node;
}
ts.createUnparsedSourceFile = createUnparsedSourceFile;
- function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapText) {
- var node = ts.createNode(282);
+ function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
+ var prologues;
+ var helpers;
+ var referencedFiles;
+ var typeReferenceDirectives;
+ var libReferenceDirectives;
+ var texts;
+ for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "prologue":
+ (prologues || (prologues = [])).push(createUnparsedNode(section, node));
+ break;
+ case "emitHelpers":
+ (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
+ break;
+ case "no-default-lib":
+ node.hasNoDefaultLib = true;
+ break;
+ case "reference":
+ (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "type":
+ (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
+ break;
+ case "lib":
+ (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "prepend":
+ var prependNode = createUnparsedNode(section, node);
+ var prependTexts = void 0;
+ for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
+ var text = _c[_b];
+ if (!stripInternal || text.kind !== "internal") {
+ (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
+ }
+ }
+ prependNode.texts = prependTexts || ts.emptyArray;
+ (texts || (texts = [])).push(prependNode);
+ break;
+ case "internal":
+ if (stripInternal)
+ break;
+ case "text":
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.prologues = prologues || ts.emptyArray;
+ node.helpers = helpers;
+ node.referencedFiles = referencedFiles || ts.emptyArray;
+ node.typeReferenceDirectives = typeReferenceDirectives;
+ node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
+ node.texts = texts || [createUnparsedNode({ kind: "text", pos: 0, end: node.text.length }, node)];
+ }
+ function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
+ ts.Debug.assert(!!node.oldFileOfCurrentEmit);
+ var texts;
+ var syntheticReferences;
+ for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "internal":
+ case "text":
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ case "no-default-lib":
+ case "reference":
+ case "type":
+ case "lib":
+ (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
+ break;
+ case "prologue":
+ case "emitHelpers":
+ case "prepend":
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.texts = texts || ts.emptyArray;
+ node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
+ node.syntheticReferences = syntheticReferences;
+ return node;
+ }
+ function mapBundleFileSectionKindToSyntaxKind(kind) {
+ switch (kind) {
+ case "prologue": return 279;
+ case "prepend": return 280;
+ case "internal": return 282;
+ case "text": return 281;
+ case "emitHelpers":
+ case "no-default-lib":
+ case "reference":
+ case "type":
+ case "lib":
+ return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
+ default:
+ return ts.Debug.assertNever(kind);
+ }
+ }
+ function createUnparsedNode(section, parent) {
+ var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ return node;
+ }
+ function createUnparsedSyntheticReference(section, parent) {
+ var node = ts.createNode(283, section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ node.section = section;
+ return node;
+ }
+ function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
+ var node = ts.createNode(287);
if (!ts.isString(javascriptTextOrReadFileText)) {
var cache_1 = ts.createMap();
var textGetter_1 = function (path) {
@@ -52690,15 +53050,25 @@ var ts;
var result = textGetter_1(path);
return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
};
+ var buildInfo_1;
+ var getAndCacheBuildInfo_1 = function (getText) {
+ if (buildInfo_1 === undefined) {
+ var result = getText();
+ buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
+ }
+ return buildInfo_1 || undefined;
+ };
node.javascriptPath = declarationTextOrJavascriptPath;
node.javascriptMapPath = javascriptMapPath;
node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
node.declarationMapPath = declarationMapPath;
+ node.buildInfoPath = declarationMapTextOrBuildInfoPath;
Object.defineProperties(node, {
javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
- declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } }
+ declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
+ buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
});
}
else {
@@ -52707,7 +53077,12 @@ var ts;
node.javascriptMapText = javascriptMapTextOrDeclarationPath;
node.declarationText = declarationTextOrJavascriptPath;
node.declarationMapPath = declarationMapPath;
- node.declarationMapText = declarationMapText;
+ node.declarationMapText = declarationMapTextOrBuildInfoPath;
+ node.javascriptPath = javascriptPath;
+ node.declarationPath = declarationPath,
+ node.buildInfoPath = buildInfoPath;
+ node.buildInfo = buildInfo;
+ node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
}
return node;
}
@@ -52811,7 +53186,7 @@ var ts;
function getOrCreateEmitNode(node) {
if (!node.emitNode) {
if (ts.isParseTreeNode(node)) {
- if (node.kind === 279) {
+ if (node.kind === 284) {
return node.emitNode = { annotatedNodes: [node] };
}
var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
@@ -53184,36 +53559,36 @@ var ts;
return ts.setEmitFlags(ts.createIdentifier(name), 4096 | 2);
}
ts.getHelperName = getHelperName;
- var valuesHelper = {
+ ts.valuesHelper = {
name: "typescript:values",
scoped: false,
text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };"
};
function createValuesHelper(context, expression, location) {
- context.requestEmitHelper(valuesHelper);
+ context.requestEmitHelper(ts.valuesHelper);
return ts.setTextRange(ts.createCall(getHelperName("__values"), undefined, [expression]), location);
}
ts.createValuesHelper = createValuesHelper;
- var readHelper = {
+ ts.readHelper = {
name: "typescript:read",
scoped: false,
text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };"
};
function createReadHelper(context, iteratorRecord, count, location) {
- context.requestEmitHelper(readHelper);
+ context.requestEmitHelper(ts.readHelper);
return ts.setTextRange(ts.createCall(getHelperName("__read"), undefined, count !== undefined
? [iteratorRecord, ts.createLiteral(count)]
: [iteratorRecord]), location);
}
ts.createReadHelper = createReadHelper;
- var spreadHelper = {
+ ts.spreadHelper = {
name: "typescript:spread",
scoped: false,
text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };"
};
function createSpreadHelper(context, argumentList, location) {
- context.requestEmitHelper(readHelper);
- context.requestEmitHelper(spreadHelper);
+ context.requestEmitHelper(ts.readHelper);
+ context.requestEmitHelper(ts.spreadHelper);
return ts.setTextRange(ts.createCall(getHelperName("__spread"), undefined, argumentList), location);
}
ts.createSpreadHelper = createSpreadHelper;
@@ -53817,7 +54192,7 @@ var ts;
case 190:
case 189:
case 213:
- case 308:
+ case 313:
node = node.expression;
continue;
}
@@ -53833,7 +54208,7 @@ var ts;
ts.parenthesizeConciseBody = parenthesizeConciseBody;
function isCommaSequence(node) {
return node.kind === 204 && node.operatorToken.kind === 27 ||
- node.kind === 309;
+ node.kind === 314;
}
ts.isCommaSequence = isCommaSequence;
function isOuterExpression(node, kinds) {
@@ -53845,7 +54220,7 @@ var ts;
case 212:
case 213:
return (kinds & 2) !== 0;
- case 308:
+ case 313:
return (kinds & 4) !== 0;
}
return false;
@@ -53882,7 +54257,7 @@ var ts;
case 194: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
case 212: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
case 213: return ts.updateNonNullExpression(outerExpression, expression);
- case 308: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
+ case 313: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
}
}
function isIgnorableParen(node) {
@@ -54515,11 +54890,11 @@ var ts;
return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression));
case 278:
return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
- case 279:
+ case 284:
return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
- case 308:
+ case 313:
return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- case 309:
+ case 314:
return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
default:
return node;
@@ -54557,7 +54932,7 @@ var ts;
case 220:
case 210:
case 236:
- case 307:
+ case 312:
break;
case 148:
result = reduceNode(node.left, cbNode, result);
@@ -54919,13 +55294,13 @@ var ts;
result = reduceNode(node.name, cbNode, result);
result = reduceNode(node.initializer, cbNode, result);
break;
- case 279:
+ case 284:
result = reduceNodes(node.statements, cbNodes, result);
break;
- case 308:
+ case 313:
result = reduceNode(node.expression, cbNode, result);
break;
- case 309:
+ case 314:
result = reduceNodes(node.elements, cbNodes, result);
break;
default:
@@ -55171,7 +55546,7 @@ var ts;
}
exit();
}
- function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) {
+ function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
var _a;
ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
@@ -55180,6 +55555,14 @@ var ts;
var nameIndexToNewNameIndexMap;
var mappingIterator = decodeMappings(map.mappings);
for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) {
+ if (end && (raw.generatedLine > end.line ||
+ (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
+ break;
+ }
+ if (start && (raw.generatedLine < start.line ||
+ (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
+ continue;
+ }
var newSourceIndex = void 0;
var newSourceLine = void 0;
var newSourceCharacter = void 0;
@@ -55206,8 +55589,10 @@ var ts;
}
}
}
- var newGeneratedLine = raw.generatedLine + generatedLine;
- var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter;
+ var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
+ var newGeneratedLine = rawGeneratedLine + generatedLine;
+ var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
+ var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
}
exit();
@@ -55654,7 +56039,7 @@ var ts;
function chainBundle(transformSourceFile) {
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- return node.kind === 279 ? transformSourceFile(node) : transformBundle(node);
+ return node.kind === 284 ? transformSourceFile(node) : transformBundle(node);
}
function transformBundle(node) {
return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
@@ -56168,13 +56553,13 @@ var ts;
function makeAssignmentElement(name) {
return name;
}
- var restHelper = {
+ ts.restHelper = {
name: "typescript:rest",
scoped: false,
text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };"
};
function createRestCall(context, value, elements, computedTempVariables, location) {
- context.requestEmitHelper(restHelper);
+ context.requestEmitHelper(ts.restHelper);
var propertyNames = [];
var computedTempVariableOffset = 0;
for (var i = 0; i < elements.length - 1; i++) {
@@ -56224,14 +56609,14 @@ var ts;
var pendingExpressions;
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- if (node.kind === 280) {
+ if (node.kind === 285) {
return transformBundle(node);
}
return transformSourceFile(node);
}
function transformBundle(node) {
return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
- if (prepend.kind === 282) {
+ if (prepend.kind === 287) {
return ts.createUnparsedSourceFile(prepend, "js");
}
return prepend;
@@ -56262,7 +56647,7 @@ var ts;
}
function onBeforeVisitNode(node) {
switch (node.kind) {
- case 279:
+ case 284:
case 246:
case 245:
case 218:
@@ -57546,7 +57931,7 @@ var ts;
function addVarForEnumOrModuleDeclaration(statements, node) {
var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
ts.createVariableDeclaration(ts.getLocalName(node, false, true))
- ], currentLexicalScope.kind === 279 ? 0 : 1));
+ ], currentLexicalScope.kind === 284 ? 0 : 1));
ts.setOriginalNode(statement, node);
recordEmittedDeclarationInScope(node);
if (isFirstEmittedDeclarationInScope(node)) {
@@ -57887,7 +58272,7 @@ var ts;
function trySubstituteNamespaceExportedName(node) {
if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
var container = resolver.getReferencedExportContainer(node, false);
- if (container && container.kind !== 279) {
+ if (container && container.kind !== 284) {
var substitute = (applicableSubstitutions & 2 && container.kind === 244) ||
(applicableSubstitutions & 8 && container.kind === 243);
if (substitute) {
@@ -57936,36 +58321,36 @@ var ts;
argumentsArray.push(descriptor);
}
}
- context.requestEmitHelper(decorateHelper);
+ context.requestEmitHelper(ts.decorateHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"), undefined, argumentsArray), location);
}
- var decorateHelper = {
+ ts.decorateHelper = {
name: "typescript:decorate",
scoped: false,
priority: 2,
text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };"
};
function createMetadataHelper(context, metadataKey, metadataValue) {
- context.requestEmitHelper(metadataHelper);
+ context.requestEmitHelper(ts.metadataHelper);
return ts.createCall(ts.getHelperName("__metadata"), undefined, [
ts.createLiteral(metadataKey),
metadataValue
]);
}
- var metadataHelper = {
+ ts.metadataHelper = {
name: "typescript:metadata",
scoped: false,
priority: 3,
text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };"
};
function createParamHelper(context, expression, parameterOffset, location) {
- context.requestEmitHelper(paramHelper);
+ context.requestEmitHelper(ts.paramHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__param"), undefined, [
ts.createLiteral(parameterOffset),
expression
]), location);
}
- var paramHelper = {
+ ts.paramHelper = {
name: "typescript:param",
scoped: false,
priority: 4,
@@ -58389,14 +58774,14 @@ var ts;
], 2));
}
ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
- var awaiterHelper = {
+ ts.awaiterHelper = {
name: "typescript:awaiter",
scoped: false,
priority: 5,
text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };"
};
function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) {
- context.requestEmitHelper(awaiterHelper);
+ context.requestEmitHelper(ts.awaiterHelper);
var generatorFunc = ts.createFunctionExpression(undefined, ts.createToken(40), undefined, undefined, [], undefined, body);
(generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 | 524288;
return ts.createCall(ts.getHelperName("__awaiter"), undefined, [
@@ -58928,7 +59313,7 @@ var ts;
}
}
ts.transformES2018 = transformES2018;
- var assignHelper = {
+ ts.assignHelper = {
name: "typescript:assign",
scoped: false,
priority: 1,
@@ -58938,27 +59323,27 @@ var ts;
if (context.getCompilerOptions().target >= 2) {
return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), undefined, attributesSegments);
}
- context.requestEmitHelper(assignHelper);
+ context.requestEmitHelper(ts.assignHelper);
return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments);
}
ts.createAssignHelper = createAssignHelper;
- var awaitHelper = {
+ ts.awaitHelper = {
name: "typescript:await",
scoped: false,
text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
};
function createAwaitHelper(context, expression) {
- context.requestEmitHelper(awaitHelper);
+ context.requestEmitHelper(ts.awaitHelper);
return ts.createCall(ts.getHelperName("__await"), undefined, [expression]);
}
- var asyncGeneratorHelper = {
+ ts.asyncGeneratorHelper = {
name: "typescript:asyncGenerator",
scoped: false,
text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
};
function createAsyncGeneratorHelper(context, generatorFunc) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncGeneratorHelper);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncGeneratorHelper);
(generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144;
return ts.createCall(ts.getHelperName("__asyncGenerator"), undefined, [
ts.createThis(),
@@ -58966,23 +59351,23 @@ var ts;
generatorFunc
]);
}
- var asyncDelegator = {
+ ts.asyncDelegator = {
name: "typescript:asyncDelegator",
scoped: false,
text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };"
};
function createAsyncDelegatorHelper(context, expression, location) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncDelegator);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncDelegator);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), undefined, [expression]), location);
}
- var asyncValues = {
+ ts.asyncValues = {
name: "typescript:asyncValues",
scoped: false,
text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };"
};
function createAsyncValuesHelper(context, expression, location) {
- context.requestEmitHelper(asyncValues);
+ context.requestEmitHelper(ts.asyncValues);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"), undefined, [expression]), location);
}
})(ts || (ts = {}));
@@ -61562,26 +61947,26 @@ var ts;
}
ts.transformES2015 = transformES2015;
function createExtendsHelper(context, name) {
- context.requestEmitHelper(extendsHelper);
+ context.requestEmitHelper(ts.extendsHelper);
return ts.createCall(ts.getHelperName("__extends"), undefined, [
name,
ts.createFileLevelUniqueName("_super")
]);
}
function createTemplateObjectHelper(context, cooked, raw) {
- context.requestEmitHelper(templateObjectHelper);
+ context.requestEmitHelper(ts.templateObjectHelper);
return ts.createCall(ts.getHelperName("__makeTemplateObject"), undefined, [
cooked,
raw
]);
}
- var extendsHelper = {
+ ts.extendsHelper = {
name: "typescript:extends",
scoped: false,
priority: 0,
text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();"
};
- var templateObjectHelper = {
+ ts.templateObjectHelper = {
name: "typescript:makeTemplateObject",
scoped: false,
priority: 0,
@@ -63280,10 +63665,10 @@ var ts;
}
ts.transformGenerators = transformGenerators;
function createGeneratorHelper(context, body) {
- context.requestEmitHelper(generatorHelper);
+ context.requestEmitHelper(ts.generatorHelper);
return ts.createCall(ts.getHelperName("__generator"), undefined, [ts.createThis(), body]);
}
- var generatorHelper = {
+ ts.generatorHelper = {
name: "typescript:generator",
scoped: false,
priority: 6,
@@ -63315,7 +63700,7 @@ var ts;
context.enableSubstitution(202);
context.enableSubstitution(203);
context.enableSubstitution(276);
- context.enableEmitNotification(279);
+ context.enableEmitNotification(284);
var moduleInfoMap = [];
var deferredExports = [];
var currentSourceFile;
@@ -63520,9 +63905,9 @@ var ts;
return visitFunctionDeclaration(node);
case 240:
return visitClassDeclaration(node);
- case 310:
+ case 315:
return visitMergeDeclarationMarker(node);
- case 311:
+ case 316:
return visitEndOfDeclarationMarker(node);
default:
return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
@@ -63640,7 +64025,7 @@ var ts;
}
var promise = ts.createNew(ts.createIdentifier("Promise"), undefined, [func]);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), undefined, [ts.getHelperName("__importStar")]);
}
return promise;
@@ -63649,7 +64034,7 @@ var ts;
var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []);
var requireCall = ts.createCall(ts.createIdentifier("require"), undefined, arg ? [arg] : []);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
requireCall = ts.createCall(ts.getHelperName("__importStar"), undefined, [requireCall]);
}
var func;
@@ -63669,11 +64054,11 @@ var ts;
return innerExpr;
}
if (ts.getImportNeedsImportStarHelper(node)) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.getHelperName("__importStar"), undefined, [innerExpr]);
}
if (ts.getImportNeedsImportDefaultHelper(node)) {
- context.requestEmitHelper(importDefaultHelper);
+ context.requestEmitHelper(ts.importDefaultHelper);
return ts.createCall(ts.getHelperName("__importDefault"), undefined, [innerExpr]);
}
return innerExpr;
@@ -64022,7 +64407,7 @@ var ts;
return node;
}
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279) {
+ if (node.kind === 284) {
currentSourceFile = node;
currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
noSubstitution = [];
@@ -64082,7 +64467,7 @@ var ts;
}
if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
- if (exportContainer && exportContainer.kind === 279) {
+ if (exportContainer && exportContainer.kind === 284) {
return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), node);
}
var importDeclaration = resolver.getReferencedImportDeclaration(node);
@@ -64166,12 +64551,12 @@ var ts;
scoped: true,
text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
};
- var importStarHelper = {
+ ts.importStarHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
};
- var importDefaultHelper = {
+ ts.importDefaultHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
@@ -64193,7 +64578,7 @@ var ts;
context.enableSubstitution(204);
context.enableSubstitution(202);
context.enableSubstitution(203);
- context.enableEmitNotification(279);
+ context.enableEmitNotification(284);
var moduleInfoMap = [];
var deferredExports = [];
var exportFunctionsMap = [];
@@ -64528,7 +64913,7 @@ var ts;
}
function shouldHoistVariableDeclarationList(node) {
return (ts.getEmitFlags(node) & 2097152) === 0
- && (enclosingBlockScopedContainer.kind === 279
+ && (enclosingBlockScopedContainer.kind === 284
|| (ts.getOriginalNode(node).flags & 3) === 0);
}
function transformInitializedVariable(node, isExportedDeclaration) {
@@ -64726,9 +65111,9 @@ var ts;
return visitCatchClause(node);
case 218:
return visitBlock(node);
- case 310:
+ case 315:
return visitMergeDeclarationMarker(node);
- case 311:
+ case 316:
return visitEndOfDeclarationMarker(node);
default:
return destructuringAndImportCallVisitor(node);
@@ -64865,7 +65250,7 @@ var ts;
}
else if (ts.isIdentifier(node)) {
var container = resolver.getReferencedExportContainer(node);
- return container !== undefined && container.kind === 279;
+ return container !== undefined && container.kind === 284;
}
else {
return false;
@@ -64880,7 +65265,7 @@ var ts;
return node;
}
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279) {
+ if (node.kind === 284) {
var id = ts.getOriginalNodeId(node);
currentSourceFile = node;
moduleInfo = moduleInfoMap[id];
@@ -65017,7 +65402,7 @@ var ts;
|| resolver.getReferencedValueDeclaration(name);
if (valueDeclaration) {
var exportContainer = resolver.getReferencedExportContainer(name, false);
- if (exportContainer && exportContainer.kind === 279) {
+ if (exportContainer && exportContainer.kind === 284) {
exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
}
exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
@@ -65045,7 +65430,7 @@ var ts;
var previousOnSubstituteNode = context.onSubstituteNode;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
- context.enableEmitNotification(279);
+ context.enableEmitNotification(284);
context.enableSubstitution(72);
var currentSourceFile;
return ts.chainBundle(transformSourceFile);
@@ -65436,6 +65821,9 @@ var ts;
case 241:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
break;
+ case 181:
+ diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
+ break;
case 166:
case 161:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
@@ -65515,6 +65903,15 @@ var ts;
return result.diagnostics;
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
+ function isInternalDeclaration(node, currentSourceFile) {
+ var parseTreeNode = ts.getParseTreeNode(node);
+ var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
+ return !!ts.forEach(leadingCommentRanges, function (range) {
+ var comment = currentSourceFile.text.substring(range.pos, range.end);
+ return ts.stringContains(comment, "@internal");
+ });
+ }
+ ts.isInternalDeclaration = isInternalDeclaration;
var declarationEmitNodeBuilderFlags = 1024 |
2048 |
4096 |
@@ -65632,10 +66029,10 @@ var ts;
}
}
function transformRoot(node) {
- if (node.kind === 279 && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
+ if (node.kind === 284 && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
}
- if (node.kind === 280) {
+ if (node.kind === 285) {
isBundledEmit = true;
refs = ts.createMap();
libs = ts.createMap();
@@ -65665,9 +66062,15 @@ var ts;
var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), true, [], [], false, []);
}), ts.mapDefined(node.prepends, function (prepend) {
- if (prepend.kind === 282) {
- return ts.createUnparsedSourceFile(prepend, "dts");
- }
+ if (prepend.kind === 287) {
+ var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
+ hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
+ collectReferences(sourceFile, refs);
+ recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
+ collectLibs(sourceFile, libs);
+ return sourceFile;
+ }
+ return prepend;
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
@@ -65754,7 +66157,7 @@ var ts;
}
}
function collectReferences(sourceFile, ret) {
- if (noResolve || ts.isSourceFileJS(sourceFile))
+ if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
return ret;
ts.forEach(sourceFile.referencedFiles, function (f) {
var elem = ts.tryResolveScriptReference(host, sourceFile, f);
@@ -66408,18 +66811,8 @@ var ts;
}
errorNameNode = undefined;
}
- function hasInternalAnnotation(range) {
- var comment = currentSourceFile.text.substring(range.pos, range.end);
- return ts.stringContains(comment, "@internal");
- }
function shouldStripInternal(node) {
- if (stripInternal && node) {
- var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile);
- if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) {
- return true;
- }
- }
- return false;
+ return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
}
function isScopeMarker(node) {
return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
@@ -66441,7 +66834,7 @@ var ts;
function ensureModifierFlags(node, privateDeclaration) {
var mask = 3071 ^ (4 | 256);
var additions = (needsDeclare && !isAlwaysType(node)) ? 2 : 0;
- var parentIsFile = node.parent.kind === 279;
+ var parentIsFile = node.parent.kind === 284;
if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1) | 2);
additions = 0;
@@ -66629,7 +67022,7 @@ var ts;
}
ts.noEmitNotification = noEmitNotification;
function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
- var enabledSyntaxKindFeatures = new Array(312);
+ var enabledSyntaxKindFeatures = new Array(317);
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
@@ -66830,16 +67223,20 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- var infoExtension = ".tsbundleinfo";
var brackets = createBracketsMap();
var syntheticParent = { pos: -1, end: -1 };
- function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) {
+ function isBuildInfoFile(file) {
+ return ts.fileExtensionIs(file, ".tsbuildinfo");
+ }
+ ts.isBuildInfoFile = isBuildInfoFile;
+ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles, onlyBuildInfo, includeBuildInfo) {
if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; }
var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
- if (sourceFiles.length) {
- var bundle = ts.createBundle(sourceFiles, host.getPrependNodes());
+ var prepends = host.getPrependNodes();
+ if (sourceFiles.length || prepends.length) {
+ var bundle = ts.createBundle(sourceFiles, prepends);
var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
if (result) {
return result;
@@ -66847,29 +67244,58 @@ var ts;
}
}
else {
- for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
- var sourceFile = sourceFiles_1[_a];
- var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
- if (result) {
- return result;
+ if (!onlyBuildInfo) {
+ for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
+ var sourceFile = sourceFiles_1[_a];
+ var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
+ if (result) {
+ return result;
+ }
}
}
+ if (includeBuildInfo) {
+ var buildInfoPath = getOutputPathForBuildInfo(host.getCompilerOptions());
+ if (buildInfoPath)
+ return action({ buildInfoPath: buildInfoPath }, undefined);
+ }
}
}
ts.forEachEmittedFile = forEachEmittedFile;
+ function getOutputPathForBuildInfo(options) {
+ var configFile = options.configFilePath;
+ if (!configFile || !ts.isIncrementalCompilation(options))
+ return undefined;
+ if (options.tsBuildInfoFile)
+ return options.tsBuildInfoFile;
+ var outPath = options.outFile || options.out;
+ var buildInfoExtensionLess;
+ if (outPath) {
+ buildInfoExtensionLess = ts.removeFileExtension(outPath);
+ }
+ else {
+ var configFileExtensionLess = ts.removeFileExtension(configFile);
+ buildInfoExtensionLess = options.outDir ?
+ options.rootDir ?
+ ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, true)) :
+ ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
+ configFileExtensionLess;
+ }
+ return buildInfoExtensionLess + ".tsbuildinfo";
+ }
+ ts.getOutputPathForBuildInfo = getOutputPathForBuildInfo;
function getOutputPathsForBundle(options, forceDtsPaths) {
var outPath = options.outFile || options.out;
var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath };
+ var buildInfoPath = getOutputPathForBuildInfo(options);
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
}
ts.getOutputPathsForBundle = getOutputPathsForBundle;
function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
var options = host.getCompilerOptions();
- if (sourceFile.kind === 280) {
+ if (sourceFile.kind === 285) {
return getOutputPathsForBundle(options, forceDtsPaths);
}
else {
@@ -66881,19 +67307,13 @@ var ts;
var isJs = ts.isSourceFileJS(sourceFile);
var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined };
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
}
}
ts.getOutputPathsFor = getOutputPathsFor;
function getSourceMapFilePath(jsFilePath, options) {
return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
}
- function createDefaultBundleInfo() {
- return {
- originalOffset: -1,
- totalLength: -1
- };
- }
function getOutputExtension(sourceFile, options) {
if (ts.isJsonSourceFile(sourceFile)) {
return ".json";
@@ -66911,7 +67331,7 @@ var ts;
return ".js";
}
ts.getOutputExtension = getOutputExtension;
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) {
+ function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers, onlyBuildInfo) {
var compilerOptions = host.getCompilerOptions();
var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
@@ -66919,11 +67339,11 @@ var ts;
var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
var writer = ts.createTextWriter(newLine);
var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit;
- var bundleInfo = createDefaultBundleInfo();
+ var bundleBuildInfo;
var emitSkipped = false;
var exportedModulesFromDeclarationEmit;
enter();
- forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles);
+ forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles, onlyBuildInfo, !targetSourceFile);
exit();
return {
emitSkipped: emitSkipped,
@@ -66933,9 +67353,16 @@ var ts;
exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
};
function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
- var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath;
- emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
+ var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
+ bundleBuildInfo = {
+ commonSourceDirectory: host.getCommonSourceDirectory(),
+ sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return file.fileName; })
+ };
+ }
+ emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
+ emitBuildInfo(bundleBuildInfo, buildInfoPath);
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
if (jsFilePath) {
@@ -66944,8 +67371,8 @@ var ts;
if (sourceMapFilePath) {
emittedFilesList.push(sourceMapFilePath);
}
- if (bundleInfoPath) {
- emittedFilesList.push(bundleInfoPath);
+ if (buildInfoPath) {
+ emittedFilesList.push(buildInfoPath);
}
}
if (declarationFilePath) {
@@ -66956,8 +67383,20 @@ var ts;
}
}
}
- function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) {
- if (emitOnlyDtsFiles || !jsFilePath) {
+ function emitBuildInfo(bundle, buildInfoPath) {
+ if (!buildInfoPath || targetSourceFile || emitSkipped)
+ return;
+ var program = host.getProgramBuildInfo();
+ if (!bundle && !program)
+ return;
+ if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
+ emitSkipped = true;
+ return;
+ }
+ ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: ts.version }), false);
+ }
+ function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) {
+ if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
return;
}
if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) {
@@ -66975,6 +67414,7 @@ var ts;
inlineSourceMap: compilerOptions.inlineSourceMap,
inlineSources: compilerOptions.inlineSources,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
+ writeBundleFileInfo: !!bundleBuildInfo
};
var printer = createPrinter(printerOptions, {
hasGlobalName: resolver.hasGlobalName,
@@ -66982,11 +67422,13 @@ var ts;
substituteNode: transform.substituteNode,
});
ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
- printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions);
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
transform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.js = printer.bundleFileInfo;
}
function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) {
- if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
+ if (!sourceFileOrBundle || !(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
return;
}
var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
@@ -67012,6 +67454,8 @@ var ts;
inlineSourceMap: compilerOptions.inlineSourceMap,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
onlyPrintJsDocStyle: true,
+ writeBundleFileInfo: !!bundleBuildInfo,
+ recordInternalSection: !!bundleBuildInfo
};
var declarationPrinter = createPrinter(printerOptions, {
hasGlobalName: resolver.hasGlobalName,
@@ -67022,18 +67466,20 @@ var ts;
emitSkipped = emitSkipped || declBlocked;
if (!declBlocked || emitOnlyDtsFiles) {
ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
- printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], undefined, declarationPrinter, {
+ printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
sourceMap: compilerOptions.declarationMap,
sourceRoot: compilerOptions.sourceRoot,
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
});
- if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279) {
+ if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 284) {
var sourceFile = declarationTransform.transformed[0];
exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
}
}
declarationTransform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
}
function collectLinkedAliases(node) {
if (ts.isExportAssignment(node)) {
@@ -67048,16 +67494,16 @@ var ts;
}
ts.forEachChild(node, collectLinkedAliases);
}
- function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) {
- var bundle = sourceFileOrBundle.kind === 280 ? sourceFileOrBundle : undefined;
- var sourceFile = sourceFileOrBundle.kind === 279 ? sourceFileOrBundle : undefined;
+ function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
+ var bundle = sourceFileOrBundle.kind === 285 ? sourceFileOrBundle : undefined;
+ var sourceFile = sourceFileOrBundle.kind === 284 ? sourceFileOrBundle : undefined;
var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
var sourceMapGenerator;
if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
}
if (bundle) {
- printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator);
+ printer.writeBundle(bundle, writer, sourceMapGenerator);
}
else {
printer.writeFile(sourceFile, writer, sourceMapGenerator);
@@ -67084,16 +67530,11 @@ var ts;
writer.writeLine();
}
ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
- if (bundleInfoPath) {
- bundleInfo.totalLength = writer.getTextPos();
- ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), false);
- }
writer.clear();
- bundleInfo = createDefaultBundleInfo();
}
function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
- && (sourceFileOrBundle.kind !== 279 || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json"));
+ && (sourceFileOrBundle.kind !== 284 || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json"));
}
function getSourceRoot(mapOptions) {
var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || "");
@@ -67138,6 +67579,156 @@ var ts;
}
}
ts.emitFiles = emitFiles;
+ function getBuildInfoText(buildInfo) {
+ return JSON.stringify(buildInfo, undefined, 2);
+ }
+ ts.getBuildInfoText = getBuildInfoText;
+ function getBuildInfo(buildInfoText) {
+ return JSON.parse(buildInfoText);
+ }
+ ts.getBuildInfo = getBuildInfo;
+ ts.notImplementedResolver = {
+ hasGlobalName: ts.notImplemented,
+ getReferencedExportContainer: ts.notImplemented,
+ getReferencedImportDeclaration: ts.notImplemented,
+ getReferencedDeclarationWithCollidingName: ts.notImplemented,
+ isDeclarationWithCollidingName: ts.notImplemented,
+ isValueAliasDeclaration: ts.notImplemented,
+ isReferencedAliasDeclaration: ts.notImplemented,
+ isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
+ getNodeCheckFlags: ts.notImplemented,
+ isDeclarationVisible: ts.notImplemented,
+ isLateBound: function (_node) { return false; },
+ collectLinkedAliases: ts.notImplemented,
+ isImplementationOfOverload: ts.notImplemented,
+ isRequiredInitializedParameter: ts.notImplemented,
+ isOptionalUninitializedParameterProperty: ts.notImplemented,
+ isExpandoFunctionDeclaration: ts.notImplemented,
+ getPropertiesOfContainerFunction: ts.notImplemented,
+ createTypeOfDeclaration: ts.notImplemented,
+ createReturnTypeOfSignatureDeclaration: ts.notImplemented,
+ createTypeOfExpression: ts.notImplemented,
+ createLiteralConstValue: ts.notImplemented,
+ isSymbolAccessible: ts.notImplemented,
+ isEntityNameVisible: ts.notImplemented,
+ getConstantValue: ts.notImplemented,
+ getReferencedValueDeclaration: ts.notImplemented,
+ getTypeReferenceSerializationKind: ts.notImplemented,
+ isOptionalParameter: ts.notImplemented,
+ moduleExportsSomeValue: ts.notImplemented,
+ isArgumentsLocalBinding: ts.notImplemented,
+ getExternalModuleFileFromDeclaration: ts.notImplemented,
+ getTypeReferenceDirectivesForEntityName: ts.notImplemented,
+ getTypeReferenceDirectivesForSymbol: ts.notImplemented,
+ isLiteralConstDeclaration: ts.notImplemented,
+ getJsxFactoryEntity: ts.notImplemented,
+ getAllAccessorDeclarations: ts.notImplemented,
+ getSymbolOfExternalModuleSpecifier: ts.notImplemented,
+ isBindingCapturedByNode: ts.notImplemented,
+ };
+ function createSourceFilesFromBundleBuildInfo(bundle) {
+ var sourceFiles = bundle.sourceFiles.map(function (fileName) {
+ var sourceFile = ts.createNode(284, 0, 0);
+ sourceFile.fileName = fileName;
+ sourceFile.text = "";
+ sourceFile.statements = ts.createNodeArray();
+ return sourceFile;
+ });
+ var jsBundle = ts.Debug.assertDefined(bundle.js);
+ ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
+ var sourceFile = sourceFiles[prologueInfo.file];
+ sourceFile.text = prologueInfo.text;
+ sourceFile.end = prologueInfo.text.length;
+ sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
+ var statement = ts.createNode(221, directive.pos, directive.end);
+ statement.expression = ts.createNode(10, directive.expression.pos, directive.expression.end);
+ statement.expression.text = directive.expression.text;
+ return statement;
+ }));
+ });
+ return sourceFiles;
+ }
+ function emitUsingBuildInfo(config, host, getCommandLine) {
+ var _a = getOutputPathsForBundle(config.options, false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
+ var buildInfoText = host.readFile(ts.Debug.assertDefined(buildInfoPath));
+ if (!buildInfoText)
+ return buildInfoPath;
+ var jsFileText = host.readFile(ts.Debug.assertDefined(jsFilePath));
+ if (!jsFileText)
+ return jsFilePath;
+ var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
+ if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
+ return sourceMapFilePath || "inline sourcemap decoding";
+ var declarationText = declarationFilePath && host.readFile(declarationFilePath);
+ if (declarationFilePath && !declarationText)
+ return declarationFilePath;
+ var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
+ if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
+ return declarationMapPath || "inline sourcemap decoding";
+ var buildInfo = getBuildInfo(buildInfoText);
+ if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
+ return buildInfoPath;
+ var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, true);
+ var outputFiles = [];
+ var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
+ var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle);
+ var emitHost = {
+ getPrependNodes: ts.memoize(function () { return prependNodes.concat([ownPrependInput]); }),
+ getCanonicalFileName: host.getCanonicalFileName,
+ getCommonSourceDirectory: function () { return buildInfo.bundle.commonSourceDirectory; },
+ getCompilerOptions: function () { return config.options; },
+ getCurrentDirectory: function () { return host.getCurrentDirectory(); },
+ getNewLine: function () { return host.getNewLine(); },
+ getSourceFile: function () { return undefined; },
+ getSourceFileByPath: function () { return undefined; },
+ getSourceFiles: function () { return sourceFilesForJsEmit; },
+ getLibFileFromReference: ts.notImplemented,
+ isSourceFileFromExternalLibrary: ts.returnFalse,
+ writeFile: function (name, text, writeByteOrderMark) {
+ switch (name) {
+ case jsFilePath:
+ if (jsFileText === text)
+ return;
+ break;
+ case sourceMapFilePath:
+ if (sourceMapText === text)
+ return;
+ break;
+ case buildInfoPath:
+ var newBuildInfo = getBuildInfo(text);
+ newBuildInfo.program = buildInfo.program;
+ var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
+ newBuildInfo.bundle.js.sources = js.sources;
+ if (dts) {
+ newBuildInfo.bundle.dts.sources = dts.sources;
+ }
+ newBuildInfo.bundle.sourceFiles = sourceFiles;
+ outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
+ return;
+ case declarationFilePath:
+ if (declarationText === text)
+ return;
+ break;
+ case declarationMapPath:
+ if (declarationMapText === text)
+ return;
+ break;
+ default:
+ ts.Debug.fail("Unexpected path: " + name);
+ }
+ outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
+ },
+ isEmitBlocked: ts.returnFalse,
+ readFile: function (f) { return host.readFile(f); },
+ fileExists: function (f) { return host.fileExists(f); },
+ directoryExists: host.directoryExists && (function (f) { return host.directoryExists(f); }),
+ useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
+ getProgramBuildInfo: function () { return undefined; }
+ };
+ emitFiles(ts.notImplementedResolver, emitHost, undefined, false, ts.getTransformers(config.options));
+ return outputFiles;
+ }
+ ts.emitUsingBuildInfo = emitUsingBuildInfo;
function createPrinter(printerOptions, handlers) {
if (printerOptions === void 0) { printerOptions = {}; }
if (handlers === void 0) { handlers = {}; }
@@ -67158,6 +67749,10 @@ var ts;
var ownWriter;
var write = writeBase;
var isOwnFileEmit;
+ var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
+ var recordInternalSection = printerOptions.recordInternalSection;
+ var sourceFileTextPos = 0;
+ var sourceFileTextKind = "text";
var sourceMapsDisabled = true;
var sourceMapGenerator;
var sourceMapSource;
@@ -67179,7 +67774,8 @@ var ts;
writeNode: writeNode,
writeList: writeList,
writeFile: writeFile,
- writeBundle: writeBundle
+ writeBundle: writeBundle,
+ bundleFileInfo: bundleFileInfo
};
function printNode(hint, node, sourceFile) {
switch (hint) {
@@ -67194,9 +67790,9 @@ var ts;
break;
}
switch (node.kind) {
- case 279: return printFile(node);
- case 280: return printBundle(node);
- case 281: return printUnparsedSource(node);
+ case 284: return printFile(node);
+ case 285: return printBundle(node);
+ case 286: return printUnparsedSource(node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
@@ -67206,7 +67802,7 @@ var ts;
return endPrint();
}
function printBundle(bundle) {
- writeBundle(bundle, undefined, beginPrint(), undefined);
+ writeBundle(bundle, beginPrint(), undefined);
return endPrint();
}
function printFile(sourceFile) {
@@ -67234,7 +67830,49 @@ var ts;
reset();
writer = previousWriter;
}
- function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) {
+ function getTextPosWithWriteLine() {
+ return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
+ }
+ function updateOrPushBundleFileTextLike(pos, end, kind) {
+ var last = ts.lastOrUndefined(bundleFileInfo.sections);
+ if (last && last.kind === kind) {
+ last.end = end;
+ }
+ else {
+ bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
+ }
+ }
+ function recordBundleFileInternalSectionStart(node) {
+ if (recordInternalSection &&
+ bundleFileInfo &&
+ currentSourceFile &&
+ (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
+ ts.isInternalDeclaration(node, currentSourceFile) &&
+ sourceFileTextKind !== "internal") {
+ var prevSourceFileTextKind = sourceFileTextKind;
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = "internal";
+ return prevSourceFileTextKind;
+ }
+ return undefined;
+ }
+ function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
+ if (prevSourceFileTextKind) {
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = prevSourceFileTextKind;
+ }
+ }
+ function recordBundleFileTextLikeSection(end) {
+ if (sourceFileTextPos < end) {
+ updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
+ return true;
+ }
+ return false;
+ }
+ function writeBundle(bundle, output, sourceMapGenerator) {
+ var _a;
isOwnFileEmit = false;
var previousWriter = writer;
setWriter(output, sourceMapGenerator);
@@ -67242,18 +67880,47 @@ var ts;
emitPrologueDirectivesIfNeeded(bundle);
emitHelpers(bundle);
emitSyntheticTripleSlashReferencesIfNeeded(bundle);
- for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) {
- var prepend = _b[_a];
+ for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
+ var prepend = _c[_b];
writeLine();
+ var pos = writer.getTextPos();
+ var savedSections = bundleFileInfo && bundleFileInfo.sections;
+ if (savedSections)
+ bundleFileInfo.sections = [];
print(4, prepend, undefined);
+ if (bundleFileInfo) {
+ var newSections = bundleFileInfo.sections;
+ bundleFileInfo.sections = savedSections;
+ if (prepend.oldFileOfCurrentEmit)
+ (_a = bundleFileInfo.sections).push.apply(_a, newSections);
+ else {
+ newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prepend", data: prepend.fileName, texts: newSections });
+ }
+ }
}
- if (bundleInfo) {
- bundleInfo.originalOffset = writer.getTextPos();
- }
- for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) {
- var sourceFile = _d[_c];
+ sourceFileTextPos = getTextPosWithWriteLine();
+ for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
+ var sourceFile = _e[_d];
print(0, sourceFile, sourceFile);
}
+ if (bundleFileInfo && bundle.sourceFiles.length) {
+ var end = writer.getTextPos();
+ if (recordBundleFileTextLikeSection(end)) {
+ var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
+ if (prologues) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.prologues = prologues;
+ }
+ var helpers = getHelpersFromBundledSourceFiles(bundle);
+ if (helpers) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.helpers = helpers;
+ }
+ }
+ }
reset();
writer = previousWriter;
}
@@ -67323,8 +67990,10 @@ var ts;
function emit(node) {
if (node === undefined)
return;
+ var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
var pipelinePhase = getPipelinePhase(0, node);
pipelinePhase(4, node);
+ recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
}
function emitIdentifierName(node) {
if (node === undefined)
@@ -67349,11 +68018,11 @@ var ts;
return pipelineEmitWithSubstitution;
}
case 2:
- if (!commentsDisabled && node.kind !== 279) {
+ if (!commentsDisabled && node.kind !== 284) {
return pipelineEmitWithComments;
}
case 3:
- if (!sourceMapsDisabled && node.kind !== 279 && !ts.isInJsonFile(node)) {
+ if (!sourceMapsDisabled && node.kind !== 284 && !ts.isInJsonFile(node)) {
return pipelineEmitWithSourceMap;
}
case 4:
@@ -67388,8 +68057,16 @@ var ts;
case 16:
case 17:
return emitLiteral(node);
+ case 286:
+ case 280:
+ return emitUnparsedSourceOrPrepend(node);
+ case 279:
+ return writeUnparsedNode(node);
case 281:
- return emitUnparsedSource(node);
+ case 282:
+ return emitUnparsedTextLike(node);
+ case 283:
+ return emitUnparsedSyntheticReference(node);
case 72:
return emitIdentifier(node);
case 148:
@@ -67427,7 +68104,7 @@ var ts;
return emitTypeReference(node);
case 165:
return emitFunctionType(node);
- case 289:
+ case 294:
return emitJSDocFunctionType(node);
case 166:
return emitConstructorType(node);
@@ -67465,20 +68142,20 @@ var ts;
return emitLiteralType(node);
case 183:
return emitImportTypeNode(node);
- case 284:
+ case 289:
writePunctuation("*");
return;
- case 285:
+ case 290:
writePunctuation("?");
return;
- case 286:
+ case 291:
return emitJSDocNullableType(node);
- case 287:
+ case 292:
return emitJSDocNonNullableType(node);
- case 288:
+ case 293:
return emitJSDocOptionalType(node);
case 172:
- case 290:
+ case 295:
return emitRestOrJSDocVariadicType(node);
case 184:
return emitObjectBindingPattern(node);
@@ -67606,30 +68283,30 @@ var ts;
return emitSpreadAssignment(node);
case 278:
return emitEnumMember(node);
- case 299:
- case 305:
+ case 304:
+ case 310:
return emitJSDocPropertyLikeTag(node);
- case 300:
- case 302:
- case 301:
- case 298:
+ case 305:
+ case 307:
+ case 306:
+ case 303:
return emitJSDocSimpleTypedTag(node);
- case 295:
+ case 300:
return emitJSDocAugmentsTag(node);
- case 303:
+ case 308:
return emitJSDocTemplateTag(node);
- case 304:
+ case 309:
return emitJSDocTypedefTag(node);
- case 297:
+ case 302:
return emitJSDocCallbackTag(node);
- case 293:
+ case 298:
return emitJSDocSignature(node);
- case 292:
+ case 297:
return emitJSDocTypeLiteral(node);
- case 296:
- case 294:
+ case 301:
+ case 299:
return emitJSDocSimpleTag(node);
- case 291:
+ case 296:
return emitJSDoc(node);
}
if (ts.isExpression(node)) {
@@ -67721,9 +68398,9 @@ var ts;
return emitJsxSelfClosingElement(node);
case 264:
return emitJsxFragment(node);
- case 308:
+ case 313:
return emitPartiallyEmittedExpression(node);
- case 309:
+ case 314:
return emitCommaList(node);
}
}
@@ -67739,22 +68416,45 @@ var ts;
var pipelinePhase = getNextPipelinePhase(1, node);
pipelinePhase(hint, substituteNode(hint, node));
}
+ function getHelpersFromBundledSourceFiles(bundle) {
+ var result;
+ if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
+ return undefined;
+ }
+ var bundledHelpers = ts.createMap();
+ for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
+ var sourceFile = _b[_a];
+ var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
+ var helpers = getSortedEmitHelpers(sourceFile);
+ if (!helpers)
+ continue;
+ for (var _c = 0, helpers_3 = helpers; _c < helpers_3.length; _c++) {
+ var helper = helpers_3[_c];
+ if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
+ bundledHelpers.set(helper.name, true);
+ (result || (result = [])).push(helper.name);
+ }
+ }
+ }
+ return result;
+ }
function emitHelpers(node) {
var helpersEmitted = false;
- var bundle = node.kind === 280 ? node : undefined;
+ var bundle = node.kind === 285 ? node : undefined;
if (bundle && moduleKind === ts.ModuleKind.None) {
return;
}
- var numNodes = bundle ? bundle.sourceFiles.length : 1;
+ var numPrepends = bundle ? bundle.prepends.length : 0;
+ var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
for (var i = 0; i < numNodes; i++) {
- var currentNode = bundle ? bundle.sourceFiles[i] : node;
- var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile;
- var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined;
- var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit;
- var helpers = ts.getEmitHelpers(currentNode);
+ var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
+ var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
+ var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined);
+ var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
+ var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
if (helpers) {
- for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) {
- var helper = _b[_a];
+ for (var _a = 0, helpers_4 = helpers; _a < helpers_4.length; _a++) {
+ var helper = helpers_4[_a];
if (!helper.scoped) {
if (shouldSkip)
continue;
@@ -67768,18 +68468,25 @@ var ts;
else if (bundle) {
continue;
}
+ var pos = getTextPosWithWriteLine();
if (typeof helper.text === "string") {
writeLines(helper.text);
}
else {
writeLines(helper.text(makeFileLevelOptimisticUniqueName));
}
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers", data: helper.name });
helpersEmitted = true;
}
}
}
return helpersEmitted;
}
+ function getSortedEmitHelpers(node) {
+ var helpers = ts.getEmitHelpers(node);
+ return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
+ }
function emitNumericOrBigIntLiteral(node) {
emitLiteral(node);
}
@@ -67793,8 +68500,34 @@ var ts;
writeStringLiteral(text);
}
}
- function emitUnparsedSource(unparsed) {
- writer.rawWrite(unparsed.text);
+ function emitUnparsedSourceOrPrepend(unparsed) {
+ for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
+ var text = _b[_a];
+ writeLine();
+ emit(text);
+ }
+ }
+ function writeUnparsedNode(unparsed) {
+ writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
+ }
+ function emitUnparsedTextLike(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 281 ?
+ "text" :
+ "internal");
+ }
+ }
+ function emitUnparsedSyntheticReference(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ var section = ts.clone(unparsed.section);
+ section.pos = pos;
+ section.end = writer.getTextPos();
+ bundleFileInfo.sections.push(section);
+ }
}
function emitIdentifier(node) {
var writeText = node.symbol ? writeSymbol : write;
@@ -67840,7 +68573,7 @@ var ts;
emit(node.dotDotDotToken);
emitNodeWithWriter(node.name, writeParameter);
emit(node.questionToken);
- if (node.parent && node.parent.kind === 289 && !node.name) {
+ if (node.parent && node.parent.kind === 294 && !node.name) {
emit(node.type);
}
else {
@@ -68666,7 +69399,7 @@ var ts;
emitBlockFunctionBodyWorker(body, true);
}
function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
- var statementOffset = emitPrologueDirectives(body.statements, true);
+ var statementOffset = emitPrologueDirectives(body.statements);
var pos = writer.getTextPos();
emitHelpers(body);
if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
@@ -69044,7 +69777,7 @@ var ts;
}
}
if (node.tags) {
- if (node.tags.length === 1 && node.tags[0].kind === 302 && !node.comment) {
+ if (node.tags.length === 1 && node.tags[0].kind === 307 && !node.comment) {
writeSpace();
emit(node.tags[0]);
}
@@ -69078,7 +69811,7 @@ var ts;
function emitJSDocTypedefTag(tag) {
emitJSDocTagName(tag.tagName);
if (tag.typeExpression) {
- if (tag.typeExpression.kind === 283) {
+ if (tag.typeExpression.kind === 288) {
emitJSDocTypeExpression(tag.typeExpression);
}
else {
@@ -69097,7 +69830,7 @@ var ts;
emit(tag.fullName);
}
emitJSDocComment(tag.comment);
- if (tag.typeExpression && tag.typeExpression.kind === 292) {
+ if (tag.typeExpression && tag.typeExpression.kind === 297) {
emitJSDocTypeLiteral(tag.typeExpression);
}
}
@@ -69179,6 +69912,16 @@ var ts;
}
function emitSyntheticTripleSlashReferencesIfNeeded(node) {
emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
+ for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
+ for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
+ var ref = _d[_c];
+ emit(ref);
+ writeLine();
+ }
+ }
+ }
}
function emitTripleSlashDirectivesIfNeeded(node) {
if (node.isDeclarationFile)
@@ -69186,7 +69929,10 @@ var ts;
}
function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
if (hasNoDefaultLib) {
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" });
writeLine();
}
if (currentSourceFile && currentSourceFile.moduleName) {
@@ -69207,17 +69953,26 @@ var ts;
}
for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
var directive = files_1[_c];
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference", data: directive.fileName });
writeLine();
}
for (var _d = 0, types_19 = types; _d < types_19.length; _d++) {
var directive = types_19[_d];
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type", data: directive.fileName });
writeLine();
}
for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
var directive = libs_1[_e];
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib", data: directive.fileName });
writeLine();
}
}
@@ -69237,16 +69992,22 @@ var ts;
function emitCommaList(node) {
emitExpressionList(node, node.elements, 528);
}
- function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) {
+ function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
+ var needsToSetSourceFile = !!sourceFile;
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (ts.isPrologueDirective(statement)) {
var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
if (shouldEmitPrologueDirective) {
- if (startWithNewLine || i > 0) {
- writeLine();
+ if (needsToSetSourceFile) {
+ needsToSetSourceFile = false;
+ setSourceFile(sourceFile);
}
+ writeLine();
+ var pos = writer.getTextPos();
emit(statement);
+ if (recordBundleFileSection && bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue", data: statement.expression.text });
if (seenPrologueDirectives) {
seenPrologueDirectives.set(statement.expression.text, true);
}
@@ -69258,23 +70019,70 @@ var ts;
}
return statements.length;
}
+ function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
+ for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
+ var prologue = prologues_1[_a];
+ if (!seenPrologueDirectives.has(prologue.data)) {
+ writeLine();
+ var pos = writer.getTextPos();
+ emit(prologue);
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue", data: prologue.data });
+ if (seenPrologueDirectives) {
+ seenPrologueDirectives.set(prologue.data, true);
+ }
+ }
+ }
+ }
function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
if (ts.isSourceFile(sourceFileOrBundle)) {
- setSourceFile(sourceFileOrBundle);
- emitPrologueDirectives(sourceFileOrBundle.statements);
+ emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
}
else {
var seenPrologueDirectives = ts.createMap();
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
- setSourceFile(sourceFile);
- emitPrologueDirectives(sourceFile.statements, true, seenPrologueDirectives);
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
+ emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, true);
}
setSourceFile(undefined);
}
}
+ function getPrologueDirectivesFromBundledSourceFiles(bundle) {
+ var seenPrologueDirectives = ts.createMap();
+ var prologues;
+ for (var index = 0; index < bundle.sourceFiles.length; index++) {
+ var sourceFile = bundle.sourceFiles[index];
+ var directives = void 0;
+ var end = 0;
+ for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
+ var statement = _b[_a];
+ if (!ts.isPrologueDirective(statement))
+ break;
+ if (seenPrologueDirectives.has(statement.expression.text))
+ continue;
+ seenPrologueDirectives.set(statement.expression.text, true);
+ (directives || (directives = [])).push({
+ pos: statement.pos,
+ end: statement.end,
+ expression: {
+ pos: statement.expression.pos,
+ end: statement.expression.end,
+ text: statement.expression.text
+ }
+ });
+ end = end < statement.end ? statement.end : end;
+ }
+ if (directives)
+ (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
+ }
+ return prologues;
+ }
function emitShebangIfNeeded(sourceFileOrBundle) {
- if (ts.isSourceFile(sourceFileOrBundle)) {
+ if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
var shebang = ts.getShebang(sourceFileOrBundle.text);
if (shebang) {
writeComment(shebang);
@@ -69283,10 +70091,17 @@ var ts;
}
}
else {
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ ts.Debug.assertNode(prepend, ts.isUnparsedSource);
+ if (emitShebangIfNeeded(prepend)) {
+ return true;
+ }
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
if (emitShebangIfNeeded(sourceFile)) {
- break;
+ return true;
}
}
}
@@ -69481,6 +70296,7 @@ var ts;
increaseIndent();
}
var previousSibling = void 0;
+ var previousSourceFileTextKind = void 0;
var shouldDecreaseIndentAfterEmit = false;
for (var i = 0; i < count; i++) {
var child = children[start + i];
@@ -69493,6 +70309,7 @@ var ts;
emitLeadingCommentsOfPosition(previousSibling.end);
}
writeDelimiter(format);
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) {
if ((format & (3 | 128)) === 0) {
increaseIndent();
@@ -69505,6 +70322,7 @@ var ts;
writeSpace();
}
}
+ previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
if (shouldEmitInterveningComments) {
if (emitTrailingCommentsOfPosition) {
var commentRange = ts.getCommentRange(child);
@@ -69531,6 +70349,7 @@ var ts;
if (format & 128) {
decreaseIndent();
}
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
if (shouldWriteClosingLineTerminator(parentNode, children, format)) {
writeLine();
}
@@ -69629,7 +70448,6 @@ var ts;
if (line.length) {
writeLine();
write(line);
- writer.rawWrite(newLine);
}
}
}
@@ -70074,7 +70892,7 @@ var ts;
hasWrittenComment = false;
var emitFlags = ts.getEmitFlags(node);
var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
- var isEmittedNode = node.kind !== 307;
+ var isEmittedNode = node.kind !== 312;
var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0 || node.kind === 11;
var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0 || node.kind === 11;
var savedContainerPos = containerPos;
@@ -70302,19 +71120,28 @@ var ts;
function isTripleSlashComment(commentPos, commentEnd) {
return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
}
+ function getParsedSourceMap(node) {
+ if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
+ node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
+ }
+ return node.parsedSourceMap || undefined;
+ }
function pipelineEmitWithSourceMap(hint, node) {
var pipelinePhase = getNextPipelinePhase(3, node);
- if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) {
- var parsed = ts.tryParseRawSourceMap(node.sourceMapText);
- if (parsed) {
- sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath);
+ if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
+ pipelinePhase(hint, node);
+ }
+ else if (ts.isUnparsedNode(node)) {
+ var parsed = getParsedSourceMap(node.parent);
+ if (parsed && sourceMapGenerator) {
+ sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
}
pipelinePhase(hint, node);
}
else {
var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
var emitFlags = ts.getEmitFlags(node);
- if (node.kind !== 307
+ if (node.kind !== 312
&& (emitFlags & 16) === 0
&& pos >= 0) {
emitSourcePos(source, skipSourceTrivia(source, pos));
@@ -70327,7 +71154,7 @@ var ts;
else {
pipelinePhase(hint, node);
}
- if (node.kind !== 307
+ if (node.kind !== 312
&& (emitFlags & 32) === 0
&& end >= 0) {
emitSourcePos(source, end);
@@ -70901,7 +71728,7 @@ var ts;
var value = readFileCache.get(key);
if (value !== undefined)
return value !== false ? value : undefined;
- if (!ts.fileExtensionIs(fileName, ".json")) {
+ if (!ts.fileExtensionIs(fileName, ".json") && !ts.isBuildInfoFile(fileName)) {
return originalReadFile.call(host, fileName);
}
return setReadFileCache(key, fileName);
@@ -70931,7 +71758,7 @@ var ts;
var key = toPath(fileName);
fileExistsCache.delete(key);
var value = readFileCache.get(key);
- if (value && value !== data) {
+ if (value !== undefined && value !== data) {
readFileCache.delete(key);
sourceFileCache.delete(key);
}
@@ -71414,7 +72241,8 @@ var ts;
getProjectReferenceRedirect: getProjectReferenceRedirect,
getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
- forEachResolvedProjectReference: forEachResolvedProjectReference
+ forEachResolvedProjectReference: forEachResolvedProjectReference,
+ emitBuildInfo: emitBuildInfo
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -71747,7 +72575,15 @@ var ts;
if (ts.contains(missingFilePaths, path))
return false;
return host.fileExists(f);
- } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } });
+ } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); } });
+ }
+ function emitBuildInfo(writeFileCallback) {
+ ts.Debug.assert(!options.out && !options.outFile);
+ ts.performance.mark("beforeEmit");
+ var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), undefined, false, undefined, undefined, true);
+ ts.performance.mark("afterEmit");
+ ts.performance.measure("Emit", "beforeEmit", "afterEmit");
+ return emitResult;
}
function getResolvedProjectReferences() {
return resolvedProjectReferences;
@@ -71756,27 +72592,11 @@ var ts;
return projectReferences;
}
function getPrependNodes() {
- if (!projectReferences) {
- return ts.emptyArray;
- }
- var nodes = [];
- for (var i = 0; i < projectReferences.length; i++) {
- var ref = projectReferences[i];
- var resolvedRefOpts = resolvedProjectReferences[i].commandLine;
- if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
- var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
- if (!out)
- continue;
- var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
- var node = ts.createInputFiles(function (fileName) {
- var path = toPath(fileName);
- var sourceFile = getSourceFileByPath(path);
- return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
- }, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath);
- nodes.push(node);
- }
- }
- return nodes;
+ return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
+ var path = toPath(fileName);
+ var sourceFile = getSourceFileByPath(path);
+ return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
+ });
}
function isSourceFileFromExternalLibrary(file) {
return !!sourceFilesFoundSearchingNodeModules.get(file.path);
@@ -72732,6 +73552,14 @@ var ts;
if (options.declaration === false) {
createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
}
+ if (options.incremental === false) {
+ createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
+ }
+ }
+ if (options.tsBuildInfoFile) {
+ if (!ts.isIncrementalCompilation(options)) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
+ }
}
verifyProjectReferences();
if (options.composite) {
@@ -72911,6 +73739,7 @@ var ts;
}
}
function verifyProjectReferences() {
+ var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getOutputPathForBuildInfo(options) : undefined;
forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
var parentFile = parent && parent.sourceFile;
@@ -72936,6 +73765,10 @@ var ts;
createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
}
}
+ if (!parent && buildInfoPath && buildInfoPath === ts.getOutputPathForBuildInfo(options)) {
+ createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
+ hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
+ }
});
}
function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
@@ -73079,6 +73912,25 @@ var ts;
};
}
ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
+ function createPrependNodes(projectReferences, getCommandLine, readFile) {
+ if (!projectReferences)
+ return ts.emptyArray;
+ var nodes;
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = getCommandLine(ref, i);
+ if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
+ var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
+ if (!out)
+ continue;
+ var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
+ (nodes || (nodes = [])).push(node);
+ }
+ }
+ return nodes || ts.emptyArray;
+ }
+ ts.createPrependNodes = createPrependNodes;
function resolveProjectReferencePath(hostOrRef, ref) {
var passedInRef = ref ? ref : hostOrRef;
return ts.resolveConfigFileProjectName(passedInRef.path);
@@ -73500,10 +74352,13 @@ var ts;
var affectedSignatures = oldState.currentAffectedFilesSignatures;
ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
}
+ var changedFilesSet = oldState.changedFilesSet;
if (canCopySemanticDiagnostics) {
- ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
+ ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
+ }
+ if (changedFilesSet) {
+ ts.copyEntries(changedFilesSet, state.changedFilesSet);
}
- ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet);
if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit;
state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
@@ -73533,7 +74388,7 @@ var ts;
}
var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
if (diagnostics) {
- state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics);
+ state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics);
if (!state.semanticDiagnosticsFromOldState) {
state.semanticDiagnosticsFromOldState = ts.createMap();
}
@@ -73541,8 +74396,44 @@ var ts;
}
}
});
+ if (oldCompilerOptions &&
+ (oldCompilerOptions.outDir !== compilerOptions.outDir ||
+ oldCompilerOptions.declarationDir !== compilerOptions.declarationDir ||
+ (oldCompilerOptions.outFile || oldCompilerOptions.out) !== (compilerOptions.outFile || compilerOptions.out))) {
+ state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, newProgram.getSourceFiles().map(function (f) { return f.path; }));
+ if (state.affectedFilesPendingEmitIndex === undefined) {
+ state.affectedFilesPendingEmitIndex = 0;
+ }
+ ts.Debug.assert(state.seenAffectedFiles === undefined);
+ state.seenAffectedFiles = ts.createMap();
+ }
return state;
}
+ function convertToDiagnostics(diagnostics, newProgram) {
+ if (!diagnostics.length)
+ return ts.emptyArray;
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToDiagnosticRelatedInformation(diagnostic, newProgram) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && newProgram.getSourceFileByPath(file), messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToDiagnosticMessageChain(messageText, newProgram) });
+ }
+ function convertToDiagnosticMessageChain(diagnostic, newProgram) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToDiagnosticMessageChain(diagnostic.next, newProgram) });
+ }
function releaseCache(state) {
ts.BuilderState.releaseCache(state);
state.program = undefined;
@@ -73704,8 +74595,11 @@ var ts;
state.semanticDiagnosticsPerFile.delete(path);
return !state.semanticDiagnosticsFromOldState.size;
}
- function doneWithAffectedFile(state, affected, isPendingEmit) {
- if (affected === state.program) {
+ function doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit) {
+ if (isBuildInfoEmit) {
+ state.emittedBuildInfo = true;
+ }
+ else if (affected === state.program) {
state.changedFilesSet.clear();
state.programEmitComplete = true;
}
@@ -73719,8 +74613,8 @@ var ts;
}
}
}
- function toAffectedFileResult(state, result, affected, isPendingEmit) {
- doneWithAffectedFile(state, affected, isPendingEmit);
+ function toAffectedFileResult(state, result, affected, isPendingEmit, isBuildInfoEmit) {
+ doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit);
return { result: result, affected: affected };
}
function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) {
@@ -73737,6 +74631,71 @@ var ts;
}
return diagnostics;
}
+ function getProgramBuildInfo(state) {
+ if (state.compilerOptions.outFile || state.compilerOptions.out)
+ return undefined;
+ var fileInfos = {};
+ state.fileInfos.forEach(function (value, key) {
+ var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
+ fileInfos[key] = signature === undefined ? value : { version: value.version, signature: signature };
+ });
+ var result = { fileInfos: fileInfos, options: state.compilerOptions };
+ if (state.referencedMap) {
+ var referencedMap_1 = {};
+ state.referencedMap.forEach(function (value, key) {
+ referencedMap_1[key] = ts.arrayFrom(value.keys());
+ });
+ result.referencedMap = referencedMap_1;
+ }
+ if (state.exportedModulesMap) {
+ var exportedModulesMap_1 = {};
+ state.exportedModulesMap.forEach(function (value, key) {
+ var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
+ if (newValue === undefined)
+ exportedModulesMap_1[key] = ts.arrayFrom(value.keys());
+ else if (newValue)
+ exportedModulesMap_1[key] = ts.arrayFrom(newValue.keys());
+ });
+ result.exportedModulesMap = exportedModulesMap_1;
+ }
+ if (state.semanticDiagnosticsPerFile) {
+ var semanticDiagnosticsPerFile_1 = [];
+ state.semanticDiagnosticsPerFile.forEach(function (value, key) { return semanticDiagnosticsPerFile_1.push(value.length ?
+ [
+ key,
+ state.hasReusableDiagnostic ?
+ value :
+ convertToReusableDiagnostics(value)
+ ] :
+ key); });
+ result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile_1;
+ }
+ return result;
+ }
+ function convertToReusableDiagnostics(diagnostics) {
+ ts.Debug.assert(!!diagnostics.length);
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToReusableDiagnosticRelatedInformation(diagnostic);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToReusableDiagnosticRelatedInformation(diagnostic) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && file.path, messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToReusableDiagnosticMessageChain(messageText) });
+ }
+ function convertToReusableDiagnosticMessageChain(diagnostic) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToReusableDiagnosticMessageChain(diagnostic.next) });
+ }
var BuilderProgramKind;
(function (BuilderProgramKind) {
BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
@@ -73786,6 +74745,7 @@ var ts;
var computeHash = host.createHash || ts.generateDjb2Hash;
var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
var backupState;
+ newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state); };
newProgram = undefined;
oldProgram = undefined;
oldState = undefined;
@@ -73823,7 +74783,11 @@ var ts;
if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
affected = getNextAffectedFilePendingEmit(state);
if (!affected) {
- return undefined;
+ if (state.emittedBuildInfo) {
+ return undefined;
+ }
+ var affected_1 = ts.Debug.assertDefined(state.program);
+ return toAffectedFileResult(state, affected_1.emitBuildInfo(writeFile || host.writeFile, cancellationToken), affected_1, false, true);
}
isPendingEmitFile = true;
}
@@ -73915,6 +74879,51 @@ var ts;
}
}
ts.createBuilderProgram = createBuilderProgram;
+ function getMapOfReferencedSet(mapLike) {
+ if (!mapLike)
+ return undefined;
+ var map = ts.createMap();
+ for (var key in mapLike) {
+ if (ts.hasProperty(mapLike, key)) {
+ map.set(key, ts.arrayToSet(mapLike[key]));
+ }
+ }
+ return map;
+ }
+ function createBuildProgramUsingProgramBuildInfo(program) {
+ var fileInfos = ts.createMapFromTemplate(program.fileInfos);
+ var state = {
+ fileInfos: fileInfos,
+ compilerOptions: program.options,
+ referencedMap: getMapOfReferencedSet(program.referencedMap),
+ exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap),
+ semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return ts.isString(value) ? value : value[0]; }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }),
+ hasReusableDiagnostic: true
+ };
+ return {
+ getState: function () { return state; },
+ backupState: ts.noop,
+ restoreState: ts.noop,
+ getProgram: ts.notImplemented,
+ getProgramOrUndefined: function () { return undefined; },
+ releaseProgram: ts.noop,
+ getCompilerOptions: function () { return state.compilerOptions; },
+ getSourceFile: ts.notImplemented,
+ getSourceFiles: ts.notImplemented,
+ getOptionsDiagnostics: ts.notImplemented,
+ getGlobalDiagnostics: ts.notImplemented,
+ getConfigFileParsingDiagnostics: ts.notImplemented,
+ getSyntacticDiagnostics: ts.notImplemented,
+ getDeclarationDiagnostics: ts.notImplemented,
+ getSemanticDiagnostics: ts.notImplemented,
+ emit: ts.notImplemented,
+ getAllDependencies: ts.notImplemented,
+ getCurrentDirectory: ts.notImplemented,
+ emitNextAffectedFile: ts.notImplemented,
+ getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
+ };
+ }
+ ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
return {
getState: ts.notImplemented,
@@ -73934,7 +74943,7 @@ var ts;
getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
getAllDependencies: ts.notImplemented,
- getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); }
+ getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
};
function getProgram() {
return ts.Debug.assertDefined(state.program);
@@ -73959,10 +74968,10 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- function isPathInNodeModulesStartingWithDot(path) {
- return ts.stringContains(path, "/node_modules/.");
+ function isPathIgnored(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); });
}
- ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot;
+ ts.isPathIgnored = isPathIgnored;
ts.maxNumberOfFilesToIterateForInvalidation = 256;
function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
var filesWithChangedSetOfUnresolvedImports;
@@ -74422,7 +75431,7 @@ var ts;
isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); };
}
else {
- if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (isPathIgnored(fileOrDirectoryPath))
return false;
var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath);
if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) ||
@@ -74826,6 +75835,8 @@ var ts;
case ".jsx":
case ".json":
return ext;
+ case ".tsbuildinfo":
+ return ts.Debug.fail("Extension " + ".tsbuildinfo" + " is unsupported:: FileName:: " + fileName);
default:
return ts.Debug.assertNever(ext);
}
@@ -75074,14 +76085,14 @@ var ts;
writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; },
createHash: ts.maybeBind(system, system.createHash),
- createProgram: createProgram
+ createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
};
}
ts.createProgramHost = createProgramHost;
function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
var writeFileName = function (s) { return system.write(s + system.newLine); };
- var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram);
+ var result = createProgramHost(system, createProgram);
ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
result.afterProgramCreate = function (builderProgram) {
var compilerOptions = builderProgram.getCompilerOptions();
@@ -75464,7 +76475,7 @@ var ts;
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
nextSourceFileVersion(fileOrDirectoryPath);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) {
writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory);
@@ -75500,13 +76511,15 @@ var ts;
UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable";
UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate";
UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
- UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream";
- UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate";
- UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked";
- UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream";
- UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
+ UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
+ UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
+ UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
+ UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
+ UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
+ UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
})(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
function createFileMap(toPath) {
var lookup = ts.createMap();
@@ -75585,24 +76598,18 @@ var ts;
}
return outputs;
}
- function getOutFileOutputs(project) {
- var out = project.options.outFile || project.options.out;
- if (!out) {
- return ts.Debug.fail("outFile must be set");
- }
+ function getOutFileOutputs(project, ignoreBuildInfo) {
+ ts.Debug.assert(!!project.options.outFile || !!project.options.out, "outFile must be set");
+ var _a = ts.getOutputPathsForBundle(project.options, false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
var outputs = [];
- outputs.push(out);
- if (project.options.sourceMap) {
- outputs.push(out + ".map");
- }
- if (ts.getEmitDeclarations(project.options)) {
- var dts = ts.changeExtension(out, ".d.ts");
- outputs.push(dts);
- if (project.options.declarationMap) {
- outputs.push(dts + ".map");
- }
- }
- return outputs;
+ var addOutput = function (path) { return path && (outputs || (outputs = [])).push(path); };
+ addOutput(jsFilePath);
+ addOutput(sourceMapFilePath);
+ addOutput(declarationFilePath);
+ addOutput(declarationMapPath);
+ if (!ignoreBuildInfo)
+ addOutput(buildInfoPath);
+ return outputs || ts.emptyArray;
}
function rootDirOfOptions(opts, configFileName) {
return opts.rootDir || ts.getDirectoryPath(configFileName);
@@ -75632,14 +76639,14 @@ var ts;
}
function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
host.reportErrorSummary = reportErrorSummary;
return host;
}
ts.createSolutionBuilderHost = createSolutionBuilderHost;
function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
var watchHost = ts.createWatchHost(system, reportWatchStatus);
ts.copyProperties(host, watchHost);
return host;
@@ -75670,7 +76677,18 @@ var ts;
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; });
var originalGetSourceFile = compilerHost.getSourceFile;
var computeHash = host.createHash || ts.generateDjb2Hash;
- updateGetSourceFile();
+ compilerHost.getSourceFile = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
+ if (result) {
+ result.version = computeHash.call(host, result.text);
+ }
+ return result;
+ };
+ var buildInfoChecked = createFileMap(toPath);
var builderPrograms = createFileMap(toPath);
var diagnostics = createFileMap(toPath);
var projectPendingBuild = createFileMap(toPath);
@@ -75706,6 +76724,7 @@ var ts;
projectStatus.clear();
missingRoots.clear();
globalDependencyGraph = undefined;
+ buildInfoChecked.clear();
diagnostics.clear();
projectPendingBuild.clear();
projectErrorsReported.clear();
@@ -75720,29 +76739,6 @@ var ts;
ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); });
ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher);
builderPrograms.clear();
- updateGetSourceFile();
- }
- function updateGetSourceFile() {
- if (options.watch) {
- if (compilerHost.getSourceFile === originalGetSourceFile) {
- compilerHost.getSourceFile = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
- if (result && options.watch) {
- result.version = computeHash.call(host, result.text);
- }
- return result;
- };
- }
- }
- else {
- if (compilerHost.getSourceFile !== originalGetSourceFile) {
- compilerHost.getSourceFile = originalGetSourceFile;
- }
- }
}
function isParsedCommandLine(entry) {
return !!entry.options;
@@ -75953,20 +76949,22 @@ var ts;
upstreamProjectName: ref.path
};
}
- if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
- continue;
- }
- if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
- pseudoUpToDate = true;
- upstreamChangedProject = ref.path;
- continue;
+ if (!missingOutputFileName) {
+ if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
+ continue;
+ }
+ if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
+ pseudoUpToDate = true;
+ upstreamChangedProject = ref.path;
+ continue;
+ }
+ ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
+ return {
+ type: UpToDateStatusType.OutOfDateWithUpstream,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerProjectName: ref.path
+ };
}
- ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
- return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: oldestOutputFileName,
- newerProjectName: ref.path
- };
}
}
if (missingOutputFileName !== undefined) {
@@ -75982,9 +76980,23 @@ var ts;
newerInputFileName: newestInputFileName
};
}
+ if (!buildInfoChecked.hasKey(project.options.configFilePath)) {
+ buildInfoChecked.setValue(project.options.configFilePath, true);
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath) {
+ var value = readFileWithCache(buildInfoPath);
+ var buildInfo = value && ts.getBuildInfo(value);
+ if (buildInfo && buildInfo.version !== ts.version) {
+ return {
+ type: UpToDateStatusType.TsVersionOutputOfDate,
+ version: buildInfo.version
+ };
+ }
+ }
+ }
if (usesPrepend && pseudoUpToDate) {
return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
+ type: UpToDateStatusType.OutOfDateWithPrepend,
outOfDateOutputFileName: oldestOutputFileName,
newerProjectName: upstreamChangedProject
};
@@ -76111,7 +77123,9 @@ var ts;
updateOutputTimestamps(proj);
return;
}
- var buildResult = buildSingleProject(resolved);
+ var buildResult = status.type === UpToDateStatusType.OutOfDateWithPrepend ?
+ updateBundle(resolved) :
+ buildSingleProject(resolved);
if (buildResult & BuildResultFlags.AnyErrors)
return;
var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue;
@@ -76123,17 +77137,26 @@ var ts;
var prepend = referencingProjects.getValue(project);
if (prepend !== undefined) {
var status_1 = projectStatus.getValue(project);
- if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
- if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) {
+ if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
+ if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes || status_1.type === UpToDateStatusType.OutOfDateWithPrepend)) {
projectStatus.setValue(project, {
type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: status_1.oldestOutputFileName,
+ outOfDateOutputFileName: status_1.type === UpToDateStatusType.OutOfDateWithPrepend ? status_1.outOfDateOutputFileName : status_1.oldestOutputFileName,
newerProjectName: resolved
});
}
}
else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) {
- status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
+ if (prepend) {
+ projectStatus.setValue(project, {
+ type: UpToDateStatusType.OutOfDateWithPrepend,
+ outOfDateOutputFileName: status_1.oldestOutputFileName,
+ newerProjectName: resolved
+ });
+ }
+ else {
+ status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
+ }
}
addProjToQueue(project);
}
@@ -76186,8 +77209,7 @@ var ts;
}
if (options.verbose)
reportStatus(ts.Diagnostics.Building_project_0, proj);
- var resultFlags = BuildResultFlags.None;
- resultFlags |= BuildResultFlags.DeclarationOutputUnchanged;
+ var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
var configFile = parseConfigFile(proj);
if (!configFile) {
resultFlags |= BuildResultFlags.ConfigFileErrors;
@@ -76200,8 +77222,7 @@ var ts;
return BuildResultFlags.None;
}
projectCompilerOptions = configFile.options;
- var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences);
- projectCompilerOptions = baseCompilerOptions;
+ var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, getOldProgram(proj, configFile), configFile.errors, configFile.projectReferences);
var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic");
@@ -76255,12 +77276,14 @@ var ts;
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
}
}
@@ -76273,9 +77296,64 @@ var ts;
builderPrograms.setValue(proj, program);
}
}
+ function getOldProgram(proj, parsed) {
+ var value = builderPrograms.getValue(proj);
+ if (value)
+ return value;
+ var buildInfoPath = ts.getOutputPathForBuildInfo(parsed.options);
+ if (!buildInfoPath)
+ return undefined;
+ var content = readFileWithCache(buildInfoPath);
+ if (!content)
+ return undefined;
+ var buildInfo = ts.getBuildInfo(content);
+ if (buildInfo.version !== ts.version)
+ return undefined;
+ return buildInfo.program && ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program);
+ }
+ function updateBundle(proj) {
+ if (options.dry) {
+ reportStatus(ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, proj);
+ return BuildResultFlags.Success;
+ }
+ if (options.verbose)
+ reportStatus(ts.Diagnostics.Updating_output_of_project_0, proj);
+ var config = ts.Debug.assertDefined(parseConfigFile(proj));
+ projectCompilerOptions = config.options;
+ var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) { return parseConfigFile(resolveProjectName(ref.path)); });
+ if (ts.isString(outputFiles)) {
+ reportStatus(ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, proj, relName(outputFiles));
+ return buildSingleProject(proj);
+ }
+ ts.Debug.assert(!!outputFiles.length);
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ var emittedOutputs = createFileMap(toPath);
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
+ emittedOutputs.setValue(name, true);
+ ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
+ });
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
+ reportAndStoreErrors(proj, emitDiagnostics);
+ projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Emit errors" });
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged | BuildResultFlags.EmitErrors;
+ }
+ var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(config, minimumDate, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
+ oldestOutputFileName: outputFiles[0].name
+ };
+ diagnostics.removeKey(proj);
+ projectStatus.setValue(proj, status);
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged;
+ }
function updateOutputTimestamps(proj) {
if (options.dry) {
- return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath);
+ return reportStatus(ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
}
var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime });
@@ -76393,7 +77471,9 @@ var ts;
reportAndStoreErrors(next, errors);
continue;
}
- var buildResult = buildSingleProject(next);
+ var buildResult = status.type === UpToDateStatusType.OutOfDateWithPrepend && !options.force ?
+ updateBundle(next) :
+ buildSingleProject(next);
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
@@ -76449,6 +77529,9 @@ var ts;
var inputFile = _a[_i];
outputs.push.apply(outputs, getOutputFileNames(inputFile, project));
}
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath)
+ outputs.push(buildInfoPath);
return outputs;
}
}
@@ -76479,6 +77562,8 @@ var ts;
return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(configFileName), relName(status.newestInputFileName || ""), relName(status.oldestOutputFileName || ""));
}
break;
+ case UpToDateStatusType.OutOfDateWithPrepend:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(configFileName), relName(status.newerProjectName));
case UpToDateStatusType.UpToDateWithUpstreamTypes:
return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName));
case UpToDateStatusType.UpstreamOutOfDate:
@@ -76487,6 +77572,8 @@ var ts;
return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName));
case UpToDateStatusType.Unbuildable:
return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason);
+ case UpToDateStatusType.TsVersionOutputOfDate:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(configFileName), status.version, ts.version);
case UpToDateStatusType.ContainerOnly:
case UpToDateStatusType.ComputingUpstream:
break;
@@ -76623,7 +77710,6 @@ var ts;
}
}
})(ts || (ts = {}));
-//# sourceMappingURL=compiler.release.js.map
var ts;
(function (ts) {
function countLines(program) {
diff --git a/lib/tsserver.js b/lib/tsserver.js
index d1c60ba72d52f..ed05481b9abde 100644
--- a/lib/tsserver.js
+++ b/lib/tsserver.js
@@ -14,31 +14,6 @@ and limitations under the License.
***************************************************************************** */
-"use strict";
-var __extends = (this && this.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
-})();
-var __assign = (this && this.__assign) || function () {
- __assign = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
@@ -82,6 +57,28 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
+var __extends = (this && this.__extends) || (function () {
+ var extendStatics = function (d, b) {
+ extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
+ return extendStatics(d, b);
+ };
+ return function (d, b) {
+ extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+ };
+})();
+var __rest = (this && this.__rest) || function (s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
+ t[p[i]] = s[p[i]];
+ return t;
+};
var ts;
(function (ts) {
// WARNING: The script `configureNightly.ts` uses a regexp to parse out these values.
@@ -825,7 +822,7 @@ var ts;
}
/**
* Deduplicates an unsorted array.
- * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates.
+ * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates.
* @param comparer An optional `Comparer` used to sort entries before comparison, though the
* result will remain in the original order in `array`.
*/
@@ -1041,6 +1038,21 @@ var ts;
} };
}
ts.arrayIterator = arrayIterator;
+ function arrayReverseIterator(array) {
+ var i = array.length;
+ return {
+ next: function () {
+ if (i === 0) {
+ return { value: undefined, done: true };
+ }
+ else {
+ i--;
+ return { value: array[i], done: false };
+ }
+ }
+ };
+ }
+ ts.arrayReverseIterator = arrayReverseIterator;
/**
* Stable sort of an array. Elements equal to each other maintain their relative position in the array.
*/
@@ -2880,47 +2892,53 @@ var ts;
SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment";
// Enum
SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember";
+ // Unparsed
+ SyntaxKind[SyntaxKind["UnparsedPrologue"] = 279] = "UnparsedPrologue";
+ SyntaxKind[SyntaxKind["UnparsedPrepend"] = 280] = "UnparsedPrepend";
+ SyntaxKind[SyntaxKind["UnparsedText"] = 281] = "UnparsedText";
+ SyntaxKind[SyntaxKind["UnparsedInternalText"] = 282] = "UnparsedInternalText";
+ SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 283] = "UnparsedSyntheticReference";
// Top-level nodes
- SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile";
- SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle";
- SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource";
- SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles";
+ SyntaxKind[SyntaxKind["SourceFile"] = 284] = "SourceFile";
+ SyntaxKind[SyntaxKind["Bundle"] = 285] = "Bundle";
+ SyntaxKind[SyntaxKind["UnparsedSource"] = 286] = "UnparsedSource";
+ SyntaxKind[SyntaxKind["InputFiles"] = 287] = "InputFiles";
// JSDoc nodes
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression";
+ SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 288] = "JSDocTypeExpression";
// The * type
- SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType";
+ SyntaxKind[SyntaxKind["JSDocAllType"] = 289] = "JSDocAllType";
// The ? type
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature";
- SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag";
- SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag";
- SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag";
+ SyntaxKind[SyntaxKind["JSDocUnknownType"] = 290] = "JSDocUnknownType";
+ SyntaxKind[SyntaxKind["JSDocNullableType"] = 291] = "JSDocNullableType";
+ SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 292] = "JSDocNonNullableType";
+ SyntaxKind[SyntaxKind["JSDocOptionalType"] = 293] = "JSDocOptionalType";
+ SyntaxKind[SyntaxKind["JSDocFunctionType"] = 294] = "JSDocFunctionType";
+ SyntaxKind[SyntaxKind["JSDocVariadicType"] = 295] = "JSDocVariadicType";
+ SyntaxKind[SyntaxKind["JSDocComment"] = 296] = "JSDocComment";
+ SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 297] = "JSDocTypeLiteral";
+ SyntaxKind[SyntaxKind["JSDocSignature"] = 298] = "JSDocSignature";
+ SyntaxKind[SyntaxKind["JSDocTag"] = 299] = "JSDocTag";
+ SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 300] = "JSDocAugmentsTag";
+ SyntaxKind[SyntaxKind["JSDocClassTag"] = 301] = "JSDocClassTag";
+ SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 302] = "JSDocCallbackTag";
+ SyntaxKind[SyntaxKind["JSDocEnumTag"] = 303] = "JSDocEnumTag";
+ SyntaxKind[SyntaxKind["JSDocParameterTag"] = 304] = "JSDocParameterTag";
+ SyntaxKind[SyntaxKind["JSDocReturnTag"] = 305] = "JSDocReturnTag";
+ SyntaxKind[SyntaxKind["JSDocThisTag"] = 306] = "JSDocThisTag";
+ SyntaxKind[SyntaxKind["JSDocTypeTag"] = 307] = "JSDocTypeTag";
+ SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 308] = "JSDocTemplateTag";
+ SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 309] = "JSDocTypedefTag";
+ SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 310] = "JSDocPropertyTag";
// Synthesized list
- SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList";
+ SyntaxKind[SyntaxKind["SyntaxList"] = 311] = "SyntaxList";
// Transformation nodes
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker";
+ SyntaxKind[SyntaxKind["NotEmittedStatement"] = 312] = "NotEmittedStatement";
+ SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 313] = "PartiallyEmittedExpression";
+ SyntaxKind[SyntaxKind["CommaListExpression"] = 314] = "CommaListExpression";
+ SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 315] = "MergeDeclarationMarker";
+ SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 316] = "EndOfDeclarationMarker";
// Enum value count
- SyntaxKind[SyntaxKind["Count"] = 312] = "Count";
+ SyntaxKind[SyntaxKind["Count"] = 317] = "Count";
// Markers
SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment";
SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment";
@@ -2947,10 +2965,10 @@ var ts;
SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator";
SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator";
SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode";
+ SyntaxKind[SyntaxKind["FirstJSDocNode"] = 288] = "FirstJSDocNode";
+ SyntaxKind[SyntaxKind["LastJSDocNode"] = 310] = "LastJSDocNode";
+ SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 299] = "FirstJSDocTagNode";
+ SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 310] = "LastJSDocTagNode";
/* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword";
/* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword";
})(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
@@ -3568,6 +3586,7 @@ var ts;
InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
InferenceFlags[InferenceFlags["NoFixing"] = 4] = "NoFixing";
+ InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 8] = "SkippedGenericFunction";
})(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
/**
* Ternary values are defined such that
@@ -3827,6 +3846,7 @@ var ts;
Extension["Js"] = ".js";
Extension["Jsx"] = ".jsx";
Extension["Json"] = ".json";
+ Extension["TsBuildInfo"] = ".tsbuildinfo";
})(Extension = ts.Extension || (ts.Extension = {}));
/* @internal */
var TransformFlags;
@@ -3984,6 +4004,20 @@ var ts;
EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
})(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
+ /*@internal*/
+ var BundleFileSectionKind;
+ (function (BundleFileSectionKind) {
+ BundleFileSectionKind["Prologue"] = "prologue";
+ BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
+ BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
+ BundleFileSectionKind["Reference"] = "reference";
+ BundleFileSectionKind["Type"] = "type";
+ BundleFileSectionKind["Lib"] = "lib";
+ BundleFileSectionKind["Prepend"] = "prepend";
+ BundleFileSectionKind["Text"] = "text";
+ BundleFileSectionKind["Internal"] = "internal";
+ // comments?
+ })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
var ListFormat;
(function (ListFormat) {
ListFormat[ListFormat["None"] = 0] = "None";
@@ -4391,6 +4425,8 @@ var ts;
: FileWatcherEventKind.Changed;
}
ts.getFileWatcherEventKind = getFileWatcherEventKind;
+ /*@internal*/
+ ts.ignoredPaths = ["/node_modules/.", "/.git"];
/**
* Watch the directory recursively using host provided method to watch child directories
* that means if this is recursive watcher, watch the children directories as well
@@ -4415,6 +4451,8 @@ var ts;
else {
directoryWatcher = {
watcher: host.watchDirectory(dirName, function (fileName) {
+ if (isIgnoredPath(fileName))
+ return;
// Call the actual callback
callbackCache.forEach(function (callbacks, rootDirName) {
if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
@@ -4464,7 +4502,7 @@ var ts;
var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
// Filter our the symbolic link directories since those arent included in recursive watch
// which is same behaviour when recursive: true is passed to fs.watch
- return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
+ return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
}) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
return newChildWatches || ts.emptyArray;
/**
@@ -4481,6 +4519,16 @@ var ts;
(newChildWatches || (newChildWatches = [])).push(childWatcher);
}
}
+ function isIgnoredPath(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
+ }
+ function isInPath(path, searchPath) {
+ if (ts.stringContains(path, searchPath))
+ return true;
+ if (host.useCaseSensitiveFileNames)
+ return false;
+ return ts.stringContains(toCanonicalFilePath(path), searchPath);
+ }
}
ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher;
function getNodeMajorVersion() {
@@ -5846,6 +5894,7 @@ var ts;
Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."),
Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."),
+ Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."),
The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."),
Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."),
File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),
@@ -6113,6 +6162,16 @@ var ts;
Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."),
Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."),
Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."),
+ Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"),
+ Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
+ A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"),
+ A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"),
+ Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"),
+ Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"),
+ Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
+ Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."),
+ Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"),
+ Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"),
The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"),
The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."),
The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."),
@@ -6329,6 +6388,7 @@ var ts;
Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"),
+ Convert_to_named_parameters: diag(95075, ts.DiagnosticCategory.Message, "Convert_to_named_parameters_95075", "Convert to named parameters"),
};
})(ts || (ts = {}));
var ts;
@@ -6816,16 +6876,20 @@ var ts;
return pos;
}
var shebangTriviaRegex = /^#!.*/;
+ /*@internal*/
function isShebangTrivia(text, pos) {
// Shebangs check must only be done at the start of the file
ts.Debug.assert(pos === 0);
return shebangTriviaRegex.test(text);
}
+ ts.isShebangTrivia = isShebangTrivia;
+ /*@internal*/
function scanShebangTrivia(text, pos) {
var shebang = shebangTriviaRegex.exec(text)[0];
pos = pos + shebang.length;
return pos;
}
+ ts.scanShebangTrivia = scanShebangTrivia;
/**
* Invokes a callback for each comment range following the provided position.
*
@@ -8535,7 +8599,7 @@ var ts;
}
}
function getSourceFileOfNode(node) {
- while (node && node.kind !== 279 /* SourceFile */) {
+ while (node && node.kind !== 284 /* SourceFile */) {
node = node.parent;
}
return node;
@@ -8681,7 +8745,7 @@ var ts;
// the syntax list itself considers them as normal trivia. Therefore if we simply skip
// trivia for the list, we may have skipped the JSDocComment as well. So we should process its
// first child to determine the actual position of its first token.
- if (node.kind === 306 /* SyntaxList */ && node._children.length > 0) {
+ if (node.kind === 311 /* SyntaxList */ && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -8700,7 +8764,7 @@ var ts;
}
ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
function isJSDocTypeExpressionOrChild(node) {
- return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
+ return node.kind === 288 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
}
function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
if (includeTrivia === void 0) { includeTrivia = false; }
@@ -8827,7 +8891,7 @@ var ts;
return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body);
}
function isBlockScopedContainerTopLevel(node) {
- return node.kind === 279 /* SourceFile */ ||
+ return node.kind === 284 /* SourceFile */ ||
node.kind === 244 /* ModuleDeclaration */ ||
ts.isFunctionLike(node);
}
@@ -8845,7 +8909,7 @@ var ts;
// - defined in the top level scope and source file is an external module
// - defined inside ambient module declaration located in the top level scope and source file not an external module
switch (node.parent.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node.parent);
case 245 /* ModuleBlock */:
return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
@@ -8863,7 +8927,7 @@ var ts;
ts.isEffectiveExternalModule = isEffectiveExternalModule;
function isBlockScope(node, parentNode) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 274 /* CatchClause */:
case 244 /* ModuleDeclaration */:
@@ -8888,9 +8952,9 @@ var ts;
ts.isBlockScope = isBlockScope;
function isDeclarationWithTypeParameters(node) {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
- case 293 /* JSDocSignature */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 298 /* JSDocSignature */:
return true;
default:
ts.assertType(node);
@@ -8906,12 +8970,12 @@ var ts;
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 240 /* ClassDeclaration */:
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
@@ -9056,7 +9120,7 @@ var ts;
function getErrorSpanForNode(sourceFile, node) {
var errorNode = node;
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
if (pos_1 === sourceFile.text.length) {
// file is empty - return span for the beginning of the file
@@ -9231,7 +9295,7 @@ var ts;
return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
case 150 /* TypeParameter */:
return node === parent.constraint;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return node === parent.constraint;
case 154 /* PropertyDeclaration */:
case 153 /* PropertySignature */:
@@ -9491,7 +9555,7 @@ var ts;
}
ts.getContainingClass = getContainingClass;
function getThisContainer(node, includeArrowFunctions) {
- ts.Debug.assert(node.kind !== 279 /* SourceFile */);
+ ts.Debug.assert(node.kind !== 284 /* SourceFile */);
while (true) {
node = node.parent;
if (!node) {
@@ -9545,7 +9609,7 @@ var ts;
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 243 /* EnumDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return node;
}
}
@@ -10253,7 +10317,7 @@ var ts;
}
ts.isJSDocConstructSignature = isJSDocConstructSignature;
function isJSDocTypeAlias(node) {
- return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 309 /* JSDocTypedefTag */ || node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocTypeAlias = isJSDocTypeAlias;
function isTypeAlias(node) {
@@ -10397,7 +10461,7 @@ var ts;
ts.hasRestParameter = hasRestParameter;
function isRestParameter(node) {
var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
- return node.dotDotDotToken !== undefined || !!type && type.kind === 290 /* JSDocVariadicType */;
+ return node.dotDotDotToken !== undefined || !!type && type.kind === 295 /* JSDocVariadicType */;
}
ts.isRestParameter = isRestParameter;
var AssignmentKind;
@@ -10882,7 +10946,7 @@ var ts;
|| kind === 158 /* GetAccessor */
|| kind === 159 /* SetAccessor */
|| kind === 244 /* ModuleDeclaration */
- || kind === 279 /* SourceFile */;
+ || kind === 284 /* SourceFile */;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(range) {
@@ -10959,7 +11023,7 @@ var ts;
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return 0;
case 208 /* SpreadElement */:
return 1;
@@ -11277,6 +11341,9 @@ var ts;
lineStart = true;
}
}
+ function getTextPosWithWriteLine() {
+ return lineStart ? output.length : (output.length + newLine.length);
+ }
reset();
return {
write: write,
@@ -11305,7 +11372,8 @@ var ts;
writeStringLiteral: write,
writeSymbol: function (s, _) { return write(s); },
writeTrailingSemicolon: write,
- writeComment: write
+ writeComment: write,
+ getTextPosWithWriteLine: getTextPosWithWriteLine
};
}
ts.createTextWriter = createTextWriter;
@@ -11596,7 +11664,7 @@ var ts;
ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
/** template tags are only available when a typedef isn't already using them */
function isNonTypeAliasTemplate(tag) {
- return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
+ return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 296 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
}
/**
* Gets the effective type annotation of the value parameter of a set accessor. If the node
@@ -12568,19 +12636,29 @@ var ts;
|| kind === 96 /* NullKeyword */
|| kind === 132 /* NeverKeyword */
|| kind === 211 /* ExpressionWithTypeArguments */
- || kind === 284 /* JSDocAllType */
- || kind === 285 /* JSDocUnknownType */
- || kind === 286 /* JSDocNullableType */
- || kind === 287 /* JSDocNonNullableType */
- || kind === 288 /* JSDocOptionalType */
- || kind === 289 /* JSDocFunctionType */
- || kind === 290 /* JSDocVariadicType */;
+ || kind === 289 /* JSDocAllType */
+ || kind === 290 /* JSDocUnknownType */
+ || kind === 291 /* JSDocNullableType */
+ || kind === 292 /* JSDocNonNullableType */
+ || kind === 293 /* JSDocOptionalType */
+ || kind === 294 /* JSDocFunctionType */
+ || kind === 295 /* JSDocVariadicType */;
}
ts.isTypeNodeKind = isTypeNodeKind;
function isAccessExpression(node) {
return node.kind === 189 /* PropertyAccessExpression */ || node.kind === 190 /* ElementAccessExpression */;
}
ts.isAccessExpression = isAccessExpression;
+ function isBundleFileTextLike(section) {
+ switch (section.kind) {
+ case "text" /* Text */:
+ case "internal" /* Internal */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isBundleFileTextLike = isBundleFileTextLike;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
@@ -13042,8 +13120,8 @@ var ts;
switch (declaration.kind) {
case 72 /* Identifier */:
return declaration;
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */: {
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */: {
var name = declaration.name;
if (name.kind === 148 /* QualifiedName */) {
return name.right;
@@ -13067,7 +13145,7 @@ var ts;
return undefined;
}
}
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return getNameOfJSDocTypedef(declaration);
case 254 /* ExportAssignment */: {
var expression = declaration.expression;
@@ -13271,7 +13349,7 @@ var ts;
return ts.emptyArray;
}
if (ts.isJSDocTypeAlias(node)) {
- ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */);
+ ts.Debug.assert(node.parent.kind === 296 /* JSDocComment */);
return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
}
if (node.typeParameters) {
@@ -13543,7 +13621,7 @@ var ts;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 308 /* PartiallyEmittedExpression */) {
+ while (node.kind === 313 /* PartiallyEmittedExpression */) {
node = node.expression;
}
return node;
@@ -13890,108 +13968,128 @@ var ts;
ts.isEnumMember = isEnumMember;
// Top-level nodes
function isSourceFile(node) {
- return node.kind === 279 /* SourceFile */;
+ return node.kind === 284 /* SourceFile */;
}
ts.isSourceFile = isSourceFile;
function isBundle(node) {
- return node.kind === 280 /* Bundle */;
+ return node.kind === 285 /* Bundle */;
}
ts.isBundle = isBundle;
function isUnparsedSource(node) {
- return node.kind === 281 /* UnparsedSource */;
+ return node.kind === 286 /* UnparsedSource */;
}
ts.isUnparsedSource = isUnparsedSource;
+ function isUnparsedPrepend(node) {
+ return node.kind === 280 /* UnparsedPrepend */;
+ }
+ ts.isUnparsedPrepend = isUnparsedPrepend;
+ function isUnparsedTextLike(node) {
+ switch (node.kind) {
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isUnparsedTextLike = isUnparsedTextLike;
+ function isUnparsedNode(node) {
+ return isUnparsedTextLike(node) ||
+ node.kind === 279 /* UnparsedPrologue */ ||
+ node.kind === 283 /* UnparsedSyntheticReference */;
+ }
+ ts.isUnparsedNode = isUnparsedNode;
// JSDoc
function isJSDocTypeExpression(node) {
- return node.kind === 283 /* JSDocTypeExpression */;
+ return node.kind === 288 /* JSDocTypeExpression */;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 284 /* JSDocAllType */;
+ return node.kind === 289 /* JSDocAllType */;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 285 /* JSDocUnknownType */;
+ return node.kind === 290 /* JSDocUnknownType */;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 286 /* JSDocNullableType */;
+ return node.kind === 291 /* JSDocNullableType */;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 287 /* JSDocNonNullableType */;
+ return node.kind === 292 /* JSDocNonNullableType */;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 288 /* JSDocOptionalType */;
+ return node.kind === 293 /* JSDocOptionalType */;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 289 /* JSDocFunctionType */;
+ return node.kind === 294 /* JSDocFunctionType */;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 290 /* JSDocVariadicType */;
+ return node.kind === 295 /* JSDocVariadicType */;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 291 /* JSDocComment */;
+ return node.kind === 296 /* JSDocComment */;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 295 /* JSDocAugmentsTag */;
+ return node.kind === 300 /* JSDocAugmentsTag */;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 296 /* JSDocClassTag */;
+ return node.kind === 301 /* JSDocClassTag */;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocEnumTag(node) {
- return node.kind === 298 /* JSDocEnumTag */;
+ return node.kind === 303 /* JSDocEnumTag */;
}
ts.isJSDocEnumTag = isJSDocEnumTag;
function isJSDocThisTag(node) {
- return node.kind === 301 /* JSDocThisTag */;
+ return node.kind === 306 /* JSDocThisTag */;
}
ts.isJSDocThisTag = isJSDocThisTag;
function isJSDocParameterTag(node) {
- return node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 300 /* JSDocReturnTag */;
+ return node.kind === 305 /* JSDocReturnTag */;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 302 /* JSDocTypeTag */;
+ return node.kind === 307 /* JSDocTypeTag */;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 303 /* JSDocTemplateTag */;
+ return node.kind === 308 /* JSDocTemplateTag */;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 304 /* JSDocTypedefTag */;
+ return node.kind === 309 /* JSDocTypedefTag */;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */;
+ return node.kind === 310 /* JSDocPropertyTag */;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 310 /* JSDocPropertyTag */ || node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 292 /* JSDocTypeLiteral */;
+ return node.kind === 297 /* JSDocTypeLiteral */;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
function isJSDocCallbackTag(node) {
- return node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocCallbackTag = isJSDocCallbackTag;
function isJSDocSignature(node) {
- return node.kind === 293 /* JSDocSignature */;
+ return node.kind === 298 /* JSDocSignature */;
}
ts.isJSDocSignature = isJSDocSignature;
})(ts || (ts = {}));
@@ -14002,7 +14100,7 @@ var ts;
(function (ts) {
/* @internal */
function isSyntaxList(n) {
- return n.kind === 306 /* SyntaxList */;
+ return n.kind === 311 /* SyntaxList */;
}
ts.isSyntaxList = isSyntaxList;
/* @internal */
@@ -14154,11 +14252,11 @@ var ts;
switch (kind) {
case 155 /* MethodSignature */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 166 /* ConstructorType */:
return true;
default:
@@ -14449,8 +14547,8 @@ var ts;
case 208 /* SpreadElement */:
case 212 /* AsExpression */:
case 210 /* OmittedExpression */:
- case 309 /* CommaListExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 314 /* CommaListExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -14464,12 +14562,12 @@ var ts;
ts.isAssertionExpression = isAssertionExpression;
/* @internal */
function isPartiallyEmittedExpression(node) {
- return node.kind === 308 /* PartiallyEmittedExpression */;
+ return node.kind === 313 /* PartiallyEmittedExpression */;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
/* @internal */
function isNotEmittedStatement(node) {
- return node.kind === 307 /* NotEmittedStatement */;
+ return node.kind === 312 /* NotEmittedStatement */;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
/* @internal */
@@ -14580,9 +14678,9 @@ var ts;
|| kind === 242 /* TypeAliasDeclaration */
|| kind === 150 /* TypeParameter */
|| kind === 237 /* VariableDeclaration */
- || kind === 304 /* JSDocTypedefTag */
- || kind === 297 /* JSDocCallbackTag */
- || kind === 305 /* JSDocPropertyTag */;
+ || kind === 309 /* JSDocTypedefTag */
+ || kind === 302 /* JSDocCallbackTag */
+ || kind === 310 /* JSDocPropertyTag */;
}
function isDeclarationStatementKind(kind) {
return kind === 239 /* FunctionDeclaration */
@@ -14617,14 +14715,14 @@ var ts;
|| kind === 219 /* VariableStatement */
|| kind === 224 /* WhileStatement */
|| kind === 231 /* WithStatement */
- || kind === 307 /* NotEmittedStatement */
- || kind === 311 /* EndOfDeclarationMarker */
- || kind === 310 /* MergeDeclarationMarker */;
+ || kind === 312 /* NotEmittedStatement */
+ || kind === 316 /* EndOfDeclarationMarker */
+ || kind === 315 /* MergeDeclarationMarker */;
}
/* @internal */
function isDeclaration(node) {
if (node.kind === 150 /* TypeParameter */) {
- return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node);
+ return (node.parent && node.parent.kind !== 308 /* JSDocTemplateTag */) || ts.isInJSFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -14719,18 +14817,18 @@ var ts;
/** True if node is of some JSDoc syntax kind. */
/* @internal */
function isJSDocNode(node) {
- return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */;
+ return node.kind >= 288 /* FirstJSDocNode */ && node.kind <= 310 /* LastJSDocNode */;
}
ts.isJSDocNode = isJSDocNode;
/** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node) {
- return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
+ return node.kind === 296 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
}
ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
// TODO: determine what this does before making it public.
/* @internal */
function isJSDocTag(node) {
- return node.kind >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */;
+ return node.kind >= 299 /* FirstJSDocTagNode */ && node.kind <= 310 /* LastJSDocTagNode */;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -15047,6 +15145,10 @@ var ts;
return !!(compilerOptions.declaration || compilerOptions.composite);
}
ts.getEmitDeclarations = getEmitDeclarations;
+ function isIncrementalCompilation(options) {
+ return !!(options.incremental || options.composite);
+ }
+ ts.isIncrementalCompilation = isIncrementalCompilation;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
}
@@ -16331,7 +16433,7 @@ var ts;
var SourceFileConstructor;
// tslint:enable variable-name
function createNode(kind, pos, end) {
- if (kind === 279 /* SourceFile */) {
+ if (kind === 284 /* SourceFile */) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 72 /* Identifier */) {
@@ -16582,7 +16684,7 @@ var ts;
case 218 /* Block */:
case 245 /* ModuleBlock */:
return visitNodes(cbNode, cbNodes, node.statements);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return visitNodes(cbNode, cbNodes, node.statements) ||
visitNode(cbNode, node.endOfFileToken);
case 219 /* VariableStatement */:
@@ -16731,7 +16833,7 @@ var ts;
return visitNode(cbNode, node.expression);
case 258 /* MissingDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return visitNodes(cbNode, cbNodes, node.elements);
case 260 /* JsxElement */:
return visitNode(cbNode, node.openingElement) ||
@@ -16760,60 +16862,60 @@ var ts;
return visitNode(cbNode, node.tagName);
case 171 /* OptionalType */:
case 172 /* RestType */:
- case 283 /* JSDocTypeExpression */:
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 288 /* JSDocOptionalType */:
- case 290 /* JSDocVariadicType */:
+ case 288 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 293 /* JSDocOptionalType */:
+ case 295 /* JSDocVariadicType */:
return visitNode(cbNode, node.type);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return visitNodes(cbNode, cbNodes, node.tags);
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return visitNode(cbNode, node.tagName) ||
(node.isNameFirst
? visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression)
: visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name));
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.constraint) ||
visitNodes(cbNode, cbNodes, node.typeParameters);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return visitNode(cbNode, node.tagName) ||
(node.typeExpression &&
- node.typeExpression.kind === 283 /* JSDocTypeExpression */
+ node.typeExpression.kind === 288 /* JSDocTypeExpression */
? visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName)
: visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression));
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.typeExpression);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return ts.forEach(node.jsDocPropertyTags, cbNode);
- case 294 /* JSDocTag */:
- case 296 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
return visitNode(cbNode, node.tagName);
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
}
@@ -17187,7 +17289,7 @@ var ts;
function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
// code from createNode is inlined here so createNode won't have to deal with special case of creating source files
// this is quite rare comparing to other nodes and createNode should be as fast as possible
- var sourceFile = new SourceFileConstructor(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
+ var sourceFile = new SourceFileConstructor(284 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
@@ -18387,9 +18489,9 @@ var ts;
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(284 /* JSDocAllType */);
+ var result = createNode(289 /* JSDocAllType */);
if (postFixEquals) {
- return createPostfixType(288 /* JSDocOptionalType */, result);
+ return createPostfixType(293 /* JSDocOptionalType */, result);
}
else {
nextToken();
@@ -18397,7 +18499,7 @@ var ts;
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(287 /* JSDocNonNullableType */);
+ var result = createNode(292 /* JSDocNonNullableType */);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -18421,18 +18523,18 @@ var ts;
token() === 30 /* GreaterThanToken */ ||
token() === 59 /* EqualsToken */ ||
token() === 50 /* BarToken */) {
- var result = createNode(285 /* JSDocUnknownType */, pos);
+ var result = createNode(290 /* JSDocUnknownType */, pos);
return finishNode(result);
}
else {
- var result = createNode(286 /* JSDocNullableType */, pos);
+ var result = createNode(291 /* JSDocNullableType */, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(289 /* JSDocFunctionType */);
+ var result = createNodeWithJSDoc(294 /* JSDocFunctionType */);
nextToken();
fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
return finishNode(result);
@@ -18456,12 +18558,12 @@ var ts;
var type = parseTypeOrTypePredicate();
scanner.setInJSDocType(false);
if (dotdotdot) {
- var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos);
+ var variadic = createNode(295 /* JSDocVariadicType */, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 59 /* EqualsToken */) {
- return createPostfixType(288 /* JSDocOptionalType */, type);
+ return createPostfixType(293 /* JSDocOptionalType */, type);
}
return type;
}
@@ -18833,7 +18935,7 @@ var ts;
return finishNode(node);
}
var type = parseType();
- if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) {
+ if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 291 /* JSDocNullableType */ && type.pos === type.type.pos) {
type.kind = 171 /* OptionalType */;
}
return type;
@@ -19020,14 +19122,14 @@ var ts;
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 52 /* ExclamationToken */:
- type = createPostfixType(287 /* JSDocNonNullableType */, type);
+ type = createPostfixType(292 /* JSDocNonNullableType */, type);
break;
case 56 /* QuestionToken */:
// If not in JSDoc and next token is start of a type we have a conditional type
if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
return type;
}
- type = createPostfixType(286 /* JSDocNullableType */, type);
+ type = createPostfixType(291 /* JSDocNullableType */, type);
break;
case 22 /* OpenBracketToken */:
parseExpected(22 /* OpenBracketToken */);
@@ -21964,7 +22066,7 @@ var ts;
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
// Parses out a JSDoc type expression.
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(283 /* JSDocTypeExpression */);
+ var result = createNode(288 /* JSDocTypeExpression */);
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -22127,7 +22229,7 @@ var ts;
}
}
function createJSDocComment() {
- var result = createNode(291 /* JSDocComment */, start);
+ var result = createNode(296 /* JSDocComment */, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
@@ -22294,7 +22396,7 @@ var ts;
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(start, tagName) {
- var result = createNode(294 /* JSDocTag */, start);
+ var result = createNode(299 /* JSDocTag */, start);
result.tagName = tagName;
return finishNode(result);
}
@@ -22353,8 +22455,8 @@ var ts;
typeExpression = tryParseTypeExpression();
}
var result = target === 1 /* Property */ ?
- createNode(305 /* JSDocPropertyTag */, start) :
- createNode(299 /* JSDocParameterTag */, start);
+ createNode(310 /* JSDocPropertyTag */, start) :
+ createNode(304 /* JSDocParameterTag */, start);
var comment = parseTagComments(indent + scanner.getStartPos() - start);
var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
if (nestedTypeLiteral) {
@@ -22371,18 +22473,18 @@ var ts;
}
function parseNestedTypeLiteral(typeExpression, name, target, indent) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(288 /* JSDocTypeExpression */, scanner.getTokenPos());
var child = void 0;
var jsdocTypeLiteral = void 0;
var start_2 = scanner.getStartPos();
var children = void 0;
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
- if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) {
+ if (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 169 /* ArrayType */) {
jsdocTypeLiteral.isArrayType = true;
@@ -22393,25 +22495,25 @@ var ts;
}
}
function parseReturnTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 305 /* JSDocReturnTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(300 /* JSDocReturnTag */, start);
+ var result = createNode(305 /* JSDocReturnTag */, start);
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 307 /* JSDocTypeTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(302 /* JSDocTypeTag */, start);
+ var result = createNode(307 /* JSDocTypeTag */, start);
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
return finishNode(result);
}
function parseAugmentsTag(start, tagName) {
- var result = createNode(295 /* JSDocAugmentsTag */, start);
+ var result = createNode(300 /* JSDocAugmentsTag */, start);
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
return finishNode(result);
@@ -22438,19 +22540,19 @@ var ts;
return node;
}
function parseClassTag(start, tagName) {
- var tag = createNode(296 /* JSDocClassTag */, start);
+ var tag = createNode(301 /* JSDocClassTag */, start);
tag.tagName = tagName;
return finishNode(tag);
}
function parseThisTag(start, tagName) {
- var tag = createNode(301 /* JSDocThisTag */, start);
+ var tag = createNode(306 /* JSDocThisTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
return finishNode(tag);
}
function parseEnumTag(start, tagName) {
- var tag = createNode(298 /* JSDocEnumTag */, start);
+ var tag = createNode(303 /* JSDocEnumTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
@@ -22459,7 +22561,7 @@ var ts;
function parseTypedefTag(start, tagName, indent) {
var typeExpression = tryParseTypeExpression();
skipWhitespaceOrAsterisk();
- var typedefTag = createNode(304 /* JSDocTypedefTag */, start);
+ var typedefTag = createNode(309 /* JSDocTypedefTag */, start);
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace();
typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
@@ -22473,9 +22575,9 @@ var ts;
var childTypeTag = void 0;
while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start);
}
- if (child.kind === 302 /* JSDocTypeTag */) {
+ if (child.kind === 307 /* JSDocTypeTag */) {
if (childTypeTag) {
break;
}
@@ -22521,14 +22623,14 @@ var ts;
return typeNameOrNamespaceName;
}
function parseCallbackTag(start, tagName, indent) {
- var callbackTag = createNode(297 /* JSDocCallbackTag */, start);
+ var callbackTag = createNode(302 /* JSDocCallbackTag */, start);
callbackTag.tagName = tagName;
callbackTag.fullName = parseJSDocTypeNameWithNamespace();
callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
skipWhitespace();
callbackTag.comment = parseTagComments(indent);
var child;
- var jsdocSignature = createNode(293 /* JSDocSignature */, start);
+ var jsdocSignature = createNode(298 /* JSDocSignature */, start);
jsdocSignature.parameters = [];
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
@@ -22536,7 +22638,7 @@ var ts;
var returnTag = tryParse(function () {
if (parseOptionalJsdoc(58 /* AtToken */)) {
var tag = parseTag(indent);
- if (tag && tag.kind === 300 /* JSDocReturnTag */) {
+ if (tag && tag.kind === 305 /* JSDocReturnTag */) {
return tag;
}
}
@@ -22581,7 +22683,7 @@ var ts;
case 58 /* AtToken */:
if (canParseTag) {
var child = tryParseChildTag(target, indent);
- if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) &&
+ if (child && (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) &&
target !== 4 /* CallbackParameter */ &&
name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
@@ -22651,7 +22753,7 @@ var ts;
skipWhitespace();
typeParameters.push(typeParameter);
} while (parseOptionalJsdoc(27 /* CommaToken */));
- var result = createNode(303 /* JSDocTemplateTag */, start);
+ var result = createNode(308 /* JSDocTemplateTag */, start);
result.tagName = tagName;
result.constraint = constraint;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -23737,6 +23839,22 @@ var ts;
category: ts.Diagnostics.Basic_Options,
description: ts.Diagnostics.Enable_project_compilation,
},
+ {
+ name: "incremental",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_incremental_compilation,
+ },
+ {
+ name: "tsBuildInfoFile",
+ type: "string",
+ isFilePath: true,
+ paramType: ts.Diagnostics.FILE,
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
+ },
{
name: "removeComments",
type: "boolean",
@@ -27455,7 +27573,7 @@ var ts;
return "__constructor" /* Constructor */;
case 165 /* FunctionType */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return "__call" /* Call */;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
@@ -27464,7 +27582,7 @@ var ts;
return "__index" /* Index */;
case 255 /* ExportDeclaration */:
return "__export" /* ExportStar */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// json file should behave as
// module.exports = ...
return "export=" /* ExportEquals */;
@@ -27475,12 +27593,12 @@ var ts;
}
ts.Debug.fail("Unknown binary declaration kind");
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
case 151 /* Parameter */:
// Parameters with names are handled at the top of this function. Parameters
// without names can only come from JSDocFunctionTypes.
- ts.Debug.assert(node.parent.kind === 289 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
+ ts.Debug.assert(node.parent.kind === 294 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
var functionType = node.parent;
var index = functionType.parameters.indexOf(node);
return "arg" + index;
@@ -27719,7 +27837,7 @@ var ts;
if (hasExplicitReturn)
node.flags |= 256 /* HasExplicitReturn */;
}
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
node.flags |= emitFlags;
}
if (currentReturnTarget) {
@@ -27863,12 +27981,12 @@ var ts;
case 191 /* CallExpression */:
bindCallExpressionFlow(node);
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
bindJSDocTypeAlias(node);
break;
// In source files and blocks, bind functions first to match hoisting that occurs at runtime
- case 279 /* SourceFile */: {
+ case 284 /* SourceFile */: {
bindEachFunctionsFirst(node.statements);
bind(node.endOfFileToken);
break;
@@ -28555,7 +28673,7 @@ var ts;
case 243 /* EnumDeclaration */:
case 188 /* ObjectLiteralExpression */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 268 /* JsxAttributes */:
return 1 /* IsContainer */;
case 241 /* InterfaceDeclaration */:
@@ -28564,7 +28682,7 @@ var ts;
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
return 1 /* IsContainer */ | 32 /* HasLocals */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
case 156 /* MethodDeclaration */:
if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
@@ -28577,8 +28695,8 @@ var ts;
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
- case 289 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
case 165 /* FunctionType */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
@@ -28632,7 +28750,7 @@ var ts;
// handlers to take care of declaring these child members.
case 244 /* ModuleDeclaration */:
return declareModuleMember(node, symbolFlags, symbolExcludes);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return declareSourceFileMember(node, symbolFlags, symbolExcludes);
case 209 /* ClassExpression */:
case 240 /* ClassDeclaration */:
@@ -28640,7 +28758,7 @@ var ts;
case 243 /* EnumDeclaration */:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 188 /* ObjectLiteralExpression */:
case 241 /* InterfaceDeclaration */:
case 268 /* JsxAttributes */:
@@ -28654,7 +28772,7 @@ var ts;
case 166 /* ConstructorType */:
case 160 /* CallSignature */:
case 161 /* ConstructSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 162 /* IndexSignature */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
@@ -28664,9 +28782,9 @@ var ts;
case 239 /* FunctionDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
- case 289 /* JSDocFunctionType */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 294 /* JSDocFunctionType */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
// All the children of these container types are never visible through another
@@ -28689,8 +28807,8 @@ var ts;
: declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
function hasExportDeclarations(node) {
- var body = node.kind === 279 /* SourceFile */ ? node : node.body;
- if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
+ var body = node.kind === 284 /* SourceFile */ ? node : node.body;
+ if (body && (body.kind === 284 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
var stat = _a[_i];
if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) {
@@ -28824,7 +28942,7 @@ var ts;
case 244 /* ModuleDeclaration */:
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalOrCommonJsModule(container)) {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
@@ -28962,7 +29080,7 @@ var ts;
function checkStrictModeFunctionDeclaration(node) {
if (languageVersion < 2 /* ES2015 */) {
// Report error if function is not top level function declaration
- if (blockScopeContainer.kind !== 279 /* SourceFile */ &&
+ if (blockScopeContainer.kind !== 284 /* SourceFile */ &&
blockScopeContainer.kind !== 244 /* ModuleDeclaration */ &&
!ts.isFunctionLike(blockScopeContainer)) {
// We check first if the name is inside class declaration or class expression; if so give explicit message
@@ -29237,12 +29355,12 @@ var ts;
case 159 /* SetAccessor */:
return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */);
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
case 166 /* ConstructorType */:
return bindFunctionOrConstructorType(node);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 181 /* MappedType */:
return bindAnonymousTypeWorker(node);
case 188 /* ObjectLiteralExpression */:
@@ -29301,7 +29419,7 @@ var ts;
return bindExportDeclaration(node);
case 254 /* ExportAssignment */:
return bindExportAssignment(node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
updateStrictModeStatementList(node.statements);
return bindSourceFileIfExternalModule();
case 218 /* Block */:
@@ -29311,22 +29429,22 @@ var ts;
// falls through
case 245 /* ModuleBlock */:
return updateStrictModeStatementList(node.statements);
- case 299 /* JSDocParameterTag */:
- if (node.parent.kind === 293 /* JSDocSignature */) {
+ case 304 /* JSDocParameterTag */:
+ if (node.parent.kind === 298 /* JSDocSignature */) {
return bindParameter(node);
}
- if (node.parent.kind !== 292 /* JSDocTypeLiteral */) {
+ if (node.parent.kind !== 297 /* JSDocTypeLiteral */) {
break;
}
// falls through
- case 305 /* JSDocPropertyTag */:
+ case 310 /* JSDocPropertyTag */:
var propTag = node;
- var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ?
+ var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 293 /* JSDocOptionalType */ ?
4 /* Property */ | 16777216 /* Optional */ :
4 /* Property */;
return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
}
}
@@ -29498,7 +29616,7 @@ var ts;
var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
if (thisContainer.commonJsModuleIndicator) {
declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
@@ -29515,7 +29633,7 @@ var ts;
if (node.expression.kind === 100 /* ThisKeyword */) {
bindThisPropertyAssignment(node);
}
- else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) {
+ else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 284 /* SourceFile */) {
if (ts.isPrototypeAccess(node.expression)) {
bindPrototypePropertyAssignment(node, node.parent);
}
@@ -29552,7 +29670,7 @@ var ts;
}
function bindObjectDefinePropertyAssignment(node) {
var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
- var isToplevel = node.parent.parent.kind === 279 /* SourceFile */;
+ var isToplevel = node.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false);
bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
}
@@ -29619,8 +29737,8 @@ var ts;
function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) {
var namespaceSymbol = lookupSymbolForPropertyAccess(name);
var isToplevel = ts.isBinaryExpression(propertyAccess.parent)
- ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */
- : propertyAccess.parent.parent.kind === 279 /* SourceFile */;
+ ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 284 /* SourceFile */
+ : propertyAccess.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty);
bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
}
@@ -29758,7 +29876,7 @@ var ts;
}
}
function bindParameter(node) {
- if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) {
+ if (node.kind === 304 /* JSDocParameterTag */ && container.kind !== 298 /* JSDocSignature */) {
return;
}
if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) {
@@ -30501,7 +30619,7 @@ var ts;
break;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
// These nodes are TypeScript syntax.
transformFlags |= 3 /* AssertTypeScript */;
excludeFlags = 536872257 /* OuterExpressionExcludes */;
@@ -30702,7 +30820,7 @@ var ts;
transformFlags |= 192 /* AssertES2015 */;
}
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) {
transformFlags |= 192 /* AssertES2015 */;
}
@@ -30782,7 +30900,7 @@ var ts;
return 637666625 /* BindingPatternExcludes */;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
case 195 /* ParenthesizedExpression */:
case 98 /* SuperKeyword */:
return 536872257 /* OuterExpressionExcludes */;
@@ -31193,10 +31311,10 @@ var ts;
isContextSensitive: isContextSensitive,
getFullyQualifiedName: getFullyQualifiedName,
getResolvedSignature: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 0 /* Normal */);
},
getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16 /* IsForSignatureHelp */);
},
getConstantValue: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
@@ -31323,10 +31441,10 @@ var ts;
},
getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
};
- function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) {
+ function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
apparentArgumentCount = argumentCount;
- var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined;
+ var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
apparentArgumentCount = undefined;
return res;
}
@@ -31601,9 +31719,11 @@ var ts;
var CheckMode;
(function (CheckMode) {
CheckMode[CheckMode["Normal"] = 0] = "Normal";
- CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive";
+ CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
- CheckMode[CheckMode["Contextual"] = 3] = "Contextual";
+ CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
+ CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
+ CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
})(CheckMode || (CheckMode = {}));
var CallbackCheck;
(function (CallbackCheck) {
@@ -31959,7 +32079,7 @@ var ts;
return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 });
}
function isGlobalSourceFile(node) {
- return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
+ return node.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
}
function getSymbol(symbols, name, meaning) {
if (meaning) {
@@ -32133,7 +32253,7 @@ var ts;
// - parameters are only in the scope of function body
// This restriction does not apply to JSDoc comment types because they are parented
// at a higher level than type parameters would normally be
- if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) {
+ if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 296 /* JSDocComment */) {
useResult = result.flags & 262144 /* TypeParameter */
// type parameters are visible in parameter list, return type and type parameter list
? lastLocation === location.type ||
@@ -32175,14 +32295,14 @@ var ts;
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
isInExternalModule = true;
// falls through
case 244 /* ModuleDeclaration */:
var moduleExports = getSymbolOfNode(location).exports;
- if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) {
+ if (location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location)) {
// It's an external module. First see if the module has an export default and if the local
// name of that export default matches.
if (result = moduleExports.get("default" /* Default */)) {
@@ -32354,8 +32474,8 @@ var ts;
location = location.parent;
}
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
// js type aliases do not resolve names from their host, so skip past it
location = ts.getJSDocHost(location);
break;
@@ -32374,7 +32494,7 @@ var ts;
}
if (!result) {
if (lastLocation) {
- ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */);
+ ts.Debug.assert(lastLocation.kind === 284 /* SourceFile */);
if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
return lastLocation.symbol;
}
@@ -33230,7 +33350,7 @@ var ts;
function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) {
var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
if (!dontResolveAlias && symbol) {
- if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) {
+ if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 284 /* SourceFile */)) {
var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
? "allowSyntheticDefaultImports"
: "esModuleInterop";
@@ -33581,7 +33701,7 @@ var ts;
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
@@ -33821,10 +33941,10 @@ var ts;
return node && getSymbolOfNode(node);
}
function hasExternalModuleSymbol(declaration) {
- return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isAmbientModule(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
- return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
var aliasesToMakeVisible;
@@ -34281,7 +34401,7 @@ var ts;
var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
(symbol.parent || // is exported function symbol
ts.forEach(symbol.declarations, function (declaration) {
- return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
+ return declaration.parent.kind === 284 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
}));
if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
// typeof is allowed only for static/non local functions
@@ -34647,7 +34767,7 @@ var ts;
var savedContextFlags = context.flags;
context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
- type.symbol.declarations[0] &&
+ type.symbol.declarations && type.symbol.declarations[0] &&
ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
typeParameterShadowsNameInScope(type, context);
var name = shouldUseGeneratedName
@@ -34666,7 +34786,7 @@ var ts;
function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */);
if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) {
- parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */);
+ parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 304 /* JSDocParameterTag */);
}
var parameterType = getTypeOfSymbol(parameterSymbol);
if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
@@ -34824,7 +34944,7 @@ var ts;
return top;
}
function getSpecifierForModuleSymbol(symbol, context) {
- var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */);
+ var file = ts.getDeclarationOfKind(symbol, 284 /* SourceFile */);
if (file && file.moduleName !== undefined) {
// Use the amd name if it is available
return file.moduleName;
@@ -35077,7 +35197,7 @@ var ts;
ts.isExternalModuleAugmentation(node.parent.parent);
}
function isDefaultBindingContext(location) {
- return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location);
+ return location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location);
}
function getNameOfSymbolFromNameType(symbol, context) {
var nameType = symbol.nameType;
@@ -35154,8 +35274,8 @@ var ts;
return false;
function determineIfDeclarationIsVisible() {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
// Top-level jsdoc type aliases are considered exported
// First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file
return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
@@ -35182,7 +35302,7 @@ var ts;
var parent = getDeclarationContainer(node);
// If the node is not exported or it is not ambient module element (except import declaration)
if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
- !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
+ !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 284 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
return isGlobalSourceFile(parent);
}
// Exported members/ambient module elements (exception import declaration) are visible if parent is visible
@@ -35224,7 +35344,7 @@ var ts;
// Type parameters are always visible
case 150 /* TypeParameter */:
// Source file and namespace export are always visible
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 247 /* NamespaceExportDeclaration */:
return true;
// Export assignments do not create name bindings outside the module
@@ -36334,15 +36454,15 @@ var ts;
case 155 /* MethodSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 308 /* JSDocTemplateTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 181 /* MappedType */:
case 175 /* ConditionalType */:
var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
@@ -38334,10 +38454,10 @@ var ts;
function isJSDocOptionalParameter(node) {
return ts.isInJSFile(node) && (
// node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
- node.type && node.type.kind === 288 /* JSDocOptionalType */
+ node.type && node.type.kind === 293 /* JSDocOptionalType */
|| ts.getJSDocParameterTags(node).some(function (_a) {
var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}));
}
function tryFindAmbientModule(moduleName, withAugmentations) {
@@ -38371,7 +38491,7 @@ var ts;
return false;
}
var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}
function createIdentifierTypePredicate(parameterName, parameterIndex, type) {
return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
@@ -38702,8 +38822,21 @@ var ts;
}
return undefined;
}
- function getSignatureInstantiation(signature, typeArguments, isJavascript) {
- return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ if (inferredTypeParameters) {
+ var returnSignature = getSingleCallSignature(getReturnTypeOfSignature(instantiatedSignature));
+ if (returnSignature) {
+ var newReturnSignature = cloneSignature(returnSignature);
+ newReturnSignature.typeParameters = inferredTypeParameters;
+ newReturnSignature.target = returnSignature.target;
+ newReturnSignature.mapper = returnSignature.mapper;
+ var newInstantiatedSignature = cloneSignature(instantiatedSignature);
+ newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
+ return newInstantiatedSignature;
+ }
+ }
+ return instantiatedSignature;
}
function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
@@ -39075,7 +39208,7 @@ var ts;
}
function getTypeReferenceTypeWorker(node, symbol, typeArguments) {
if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
- if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
+ if (symbol.valueDeclaration && symbol.valueDeclaration.parent && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
var jsdocType = getJSDocTypeReference(node, symbol, typeArguments);
if (jsdocType) {
return jsdocType;
@@ -39111,7 +39244,7 @@ var ts;
}
function getConstrainedTypeVariable(typeVariable, node) {
var constraints;
- while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) {
+ while (node && !ts.isStatement(node) && node.kind !== 296 /* JSDocComment */) {
var parent = node.parent;
if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) {
var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType);
@@ -40684,8 +40817,8 @@ var ts;
function getTypeFromTypeNode(node) {
switch (node.kind) {
case 120 /* AnyKeyword */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return anyType;
case 143 /* UnknownKeyword */:
return unknownType;
@@ -40732,23 +40865,23 @@ var ts;
return getTypeFromUnionTypeNode(node);
case 174 /* IntersectionType */:
return getTypeFromIntersectionTypeNode(node);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return getTypeFromJSDocNullableTypeNode(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return addOptionality(getTypeFromTypeNode(node.type));
case 177 /* ParenthesizedType */:
case 172 /* RestType */:
- case 287 /* JSDocNonNullableType */:
- case 283 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 288 /* JSDocTypeExpression */:
return getTypeFromTypeNode(node.type);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return getTypeFromJSDocVariadicType(node);
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 297 /* JSDocTypeLiteral */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
case 179 /* TypeOperator */:
return getTypeFromTypeOperatorNode(node);
@@ -41686,7 +41819,7 @@ var ts;
return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation);
}
// recreate a tuple from the elements, if possible
- var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true);
+ var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
if (isTupleLikeType(tupleizedType)) {
return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation);
}
@@ -44109,7 +44242,7 @@ var ts;
return;
}
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
return;
case 239 /* FunctionDeclaration */:
@@ -46390,7 +46523,7 @@ var ts;
return ts.findAncestor(node.parent, function (node) {
return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
node.kind === 245 /* ModuleBlock */ ||
- node.kind === 279 /* SourceFile */ ||
+ node.kind === 284 /* SourceFile */ ||
node.kind === 154 /* PropertyDeclaration */;
});
}
@@ -46511,7 +46644,7 @@ var ts;
// to the constructor in the initializer, we will need to substitute that
// binding with an alias as the class name is not in scope.
var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
- while (container.kind !== 279 /* SourceFile */) {
+ while (container.kind !== 284 /* SourceFile */) {
if (container.parent === declaration) {
if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
@@ -46934,7 +47067,7 @@ var ts;
}
function getTypeForThisExpressionFromJSDoc(node) {
var jsdocType = ts.getJSDocType(node);
- if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) {
+ if (jsdocType && jsdocType.kind === 294 /* JSDocFunctionType */) {
var jsDocFunctionType = jsdocType;
if (jsDocFunctionType.parameters.length > 0 &&
jsDocFunctionType.parameters[0].name &&
@@ -49536,23 +49669,34 @@ var ts;
// Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) {
var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
- var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature;
+ // We clone the contextualMapper to avoid fixing. For example, when the source signature is (x: T) => T[] and
+ // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
+ // for T but leave it possible to later infer '[any]' back to A.
+ var restType = getEffectiveRestType(contextualSignature);
+ var mapper = contextualMapper && restType && restType.flags & 262144 /* TypeParameter */ ? cloneTypeMapper(contextualMapper) : contextualMapper;
+ var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
forEachMatchingParameterType(sourceSignature, signature, function (source, target) {
// Type parameters from outer context referenced by source type are fixed by instantiation of the source type
inferTypes(context.inferences, source, target);
});
if (!contextualMapper) {
inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */);
+ var signaturePredicate = getTypePredicateOfSignature(signature);
+ var contextualPredicate = getTypePredicateOfSignature(sourceSignature);
+ if (signaturePredicate && contextualPredicate && signaturePredicate.kind === contextualPredicate.kind &&
+ (signaturePredicate.kind === 0 /* This */ || signaturePredicate.parameterIndex === contextualPredicate.parameterIndex)) {
+ inferTypes(context.inferences, contextualPredicate.type, signaturePredicate.type, 8 /* ReturnType */);
+ }
}
return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
}
- function inferJsxTypeArguments(node, signature, excludeArgument, context) {
+ function inferJsxTypeArguments(node, signature, checkMode, context) {
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context);
+ var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
inferTypes(context.inferences, checkAttrType, paramType);
return getInferredTypes(context);
}
- function inferTypeArguments(node, signature, args, excludeArgument, context) {
+ function inferTypeArguments(node, signature, args, checkMode, context) {
// Clear out all the inference results from the last time inferTypeArguments was called on this context
for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) {
var inference = _a[_i];
@@ -49565,7 +49709,7 @@ var ts;
}
}
if (ts.isJsxOpeningLikeElement(node)) {
- return inferJsxTypeArguments(node, signature, excludeArgument, context);
+ return inferJsxTypeArguments(node, signature, checkMode, context);
}
// If a contextual type is available, infer from that type to the return type of the call expression. For
// example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression
@@ -49609,10 +49753,7 @@ var ts;
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- // For context sensitive arguments we pass the identityMapper, which is a signal to treat all
- // context sensitive function expressions as wildcards
- var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context;
- var argType = checkExpressionWithContextualType(arg, paramType, mapper);
+ var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
inferTypes(context.inferences, argType, paramType);
}
}
@@ -49636,7 +49777,7 @@ var ts;
// and the argument are ...x forms.
return arg.kind === 215 /* SyntheticExpression */ ?
createArrayType(arg.type) :
- getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context));
+ getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
}
}
var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType;
@@ -49644,7 +49785,7 @@ var ts;
var types = [];
var spreadIndex = -1;
for (var i = index; i < argCount; i++) {
- var argType = checkExpressionWithContextualType(args[i], contextualType, context);
+ var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
if (spreadIndex < 0 && isSpreadArgument(args[i])) {
spreadIndex = i - index;
}
@@ -49694,19 +49835,18 @@ var ts;
* @param node a JSX opening-like element we are trying to figure its call signature
* @param signature a candidate signature we are trying whether it is a call signature
* @param relation a relationship to check parameter and argument type
- * @param excludeArgument
*/
- function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors) {
// Stateless function components can have maximum of three arguments: "props", "context", and "updater".
// However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
// can be specified by users through attributes property.
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined);
+ var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined, checkMode);
return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes);
}
- function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignature(node, args, signature, relation, checkMode, reportErrors) {
if (ts.isJsxOpeningLikeElement(node)) {
- return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors);
+ return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors);
}
var thisType = getThisTypeOfSignature(signature);
if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) {
@@ -49728,11 +49868,11 @@ var ts;
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined);
- // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter),
+ var argType = checkExpressionWithContextualType(arg, paramType, /*contextualMapper*/ undefined, checkMode);
+ // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
// we obtain the regular type of any object literal arguments because we may not have inferred complete
// parameter types yet and therefore excess property checks may yield false positives (see #17041).
- var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType;
+ var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) {
return false;
}
@@ -49937,7 +50077,7 @@ var ts;
}
return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
}
- function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) {
+ function resolveCall(node, signatures, candidatesOutArray, checkMode, fallbackError) {
var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */;
var isDecorator = node.kind === 152 /* Decorator */;
var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
@@ -49973,7 +50113,7 @@ var ts;
// For a decorator, no arguments are susceptible to contextual typing due to the fact
// decorators are applied to a declaration by the emitter, and not to an expression.
var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
- var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined;
+ var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
// The following variables are captured and modified by calls to chooseOverload.
// If overload resolution or type argument inference fails, we want to report the
// best error possible. The best error is one which says that an argument was not
@@ -50001,7 +50141,7 @@ var ts;
var result;
// If we are in signature help, a trailing comma indicates that we intend to provide another argument,
// so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
- var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma;
+ var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma;
// Section 4.12.1:
// if the candidate list contains one or more signatures for which the type of each argument
// expression is a subtype of each corresponding parameter type, the return type of the first
@@ -50027,12 +50167,7 @@ var ts;
// skip the checkApplicableSignature check.
if (reportErrors) {
if (candidateForArgumentError) {
- // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...]
- // The importance of excludeArgument is to prevent us from typing function expression parameters
- // in arguments too early. If possible, we'd like to only type them once we know the correct
- // overload. However, this matters for the case where the call is correct. When the call is
- // an error, we don't need to exclude any arguments, although it would cause no harm to do so.
- checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true);
+ checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, 0 /* Normal */, /*reportErrors*/ true);
}
else if (candidateForArgumentArityError) {
diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
@@ -50064,7 +50199,7 @@ var ts;
if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
return undefined;
}
- if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false)) {
candidateForArgumentError = candidate;
return undefined;
}
@@ -50088,9 +50223,10 @@ var ts;
}
else {
inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
+ typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
+ argCheckMode |= inferenceContext.flags & 8 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
}
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// If the original signature has a generic rest type, instantiation may produce a
// signature with different arity and we need to perform another arity check.
if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -50101,21 +50237,21 @@ var ts;
else {
checkCandidate = candidate;
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
}
continue;
}
- if (excludeArgument) {
+ if (argCheckMode) {
// If one or more context sensitive arguments were excluded, we start including
// them now (and keeping do so for any subsequent candidates) and perform a second
// round of type inference and applicability checking for this particular candidate.
- excludeArgument = undefined;
+ argCheckMode = 0 /* Normal */;
if (inferenceContext) {
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// If the original signature has a generic rest type, instantiation may produce a
// signature with different arity and we need to perform another arity check.
if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -50123,7 +50259,7 @@ var ts;
continue;
}
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
@@ -50137,20 +50273,6 @@ var ts;
return undefined;
}
}
- function getExcludeArgument(args) {
- var excludeArgument;
- // We do not need to call `getEffectiveArgumentCount` here as it only
- // applies when calculating the number of arguments for a decorator.
- for (var i = 0; i < args.length; i++) {
- if (isContextSensitive(args[i])) {
- if (!excludeArgument) {
- excludeArgument = new Array(args.length);
- }
- excludeArgument[i] = true;
- }
- }
- return excludeArgument;
- }
// No signature was applicable. We have already reported the errors for the invalid signature.
// If this is a type resolution session, e.g. Language Service, try to get better information than anySignature.
function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
@@ -50239,7 +50361,7 @@ var ts;
}
function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext);
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
return createSignatureInstantiation(candidate, typeArgumentTypes);
}
function getLongestCandidateIndex(candidates, argsCount) {
@@ -50258,7 +50380,7 @@ var ts;
}
return maxParamsIndex;
}
- function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveCallExpression(node, candidatesOutArray, checkMode) {
if (node.expression.kind === 98 /* SuperKeyword */) {
var superType = checkSuperExpression(node.expression);
if (isTypeAny(superType)) {
@@ -50274,7 +50396,7 @@ var ts;
var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
if (baseTypeNode) {
var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
- return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, baseConstructors, candidatesOutArray, checkMode);
}
}
return resolveUntypedCall(node);
@@ -50324,12 +50446,31 @@ var ts;
}
return resolveErrorCall(node);
}
+ // When a call to a generic function is an argument to an outer call to a generic function for which
+ // inference is in process, we have a choice to make. If the inner call relies on inferences made from
+ // its contextual type to its return type, deferring the inner call processing allows the best possible
+ // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
+ // the inner call, the inner call should be processed early. There's no sure way to know which choice is
+ // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
+ // If no type arguments are specified in the inner call and at least one call signature is generic and
+ // returns a function type, we choose to defer processing. This narrowly permits function composition
+ // operators to flow inferences through return types, but otherwise processes calls right away. We
+ // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
+ // propagated out and eventually turned into silentNeverType (a type that is assignable to anything and
+ // from which we never make inferences).
+ if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
+ skippedGenericFunction(node, checkMode);
+ return resolvingSignature;
+ }
// If the function is explicitly marked with `@class`, then it must be constructed.
if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
+ }
+ function isGenericFunctionReturningFunction(signature) {
+ return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
}
/**
* TS 1.0 spec: 4.12
@@ -50341,7 +50482,7 @@ var ts;
return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
!numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
}
- function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveNewExpression(node, candidatesOutArray, checkMode) {
if (node.arguments && languageVersion < 1 /* ES5 */) {
var spreadIndex = getSpreadArgumentIndex(node.arguments);
if (spreadIndex >= 0) {
@@ -50389,7 +50530,7 @@ var ts;
error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
return resolveErrorCall(node);
}
- return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, constructSignatures, candidatesOutArray, checkMode);
}
// If expressionType's apparent type is an object type with no construct signatures but
// one or more call signatures, the expression is processed as a function call. A compile-time
@@ -50397,7 +50538,7 @@ var ts;
// operation is Any. It is an error to have a Void this type.
var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
if (callSignatures.length) {
- var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode);
if (!noImplicitAny) {
if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
@@ -50494,7 +50635,7 @@ var ts;
addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead));
}
}
- function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
var tagType = checkExpression(node.tag);
var apparentType = getApparentType(tagType);
if (apparentType === errorType) {
@@ -50510,7 +50651,7 @@ var ts;
invocationError(node, apparentType, 0 /* Call */);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
}
/**
* Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
@@ -50535,7 +50676,7 @@ var ts;
/**
* Resolves a decorator as if it were a call expression.
*/
- function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveDecorator(node, candidatesOutArray, checkMode) {
var funcType = checkExpression(node.expression);
var apparentType = getApparentType(funcType);
if (apparentType === errorType) {
@@ -50560,7 +50701,7 @@ var ts;
invocationErrorRecovery(apparentType, 0 /* Call */, diag);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode, headMessage);
}
function createSignatureForJSXIntrinsic(node, result) {
var namespace = getJsxNamespaceAt(node);
@@ -50579,11 +50720,11 @@ var ts;
/*hasRestparameter*/ false,
/*hasLiteralTypes*/ false);
}
- function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
if (isJsxIntrinsicIdentifier(node.tagName)) {
var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
var fakeSignature = createSignatureForJSXIntrinsic(node, result);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes);
+ checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
return fakeSignature;
}
var exprTypes = checkExpression(node.tagName);
@@ -50600,7 +50741,7 @@ var ts;
error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
return resolveErrorCall(node);
}
- return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, signatures, candidatesOutArray, checkMode);
}
/**
* Sometimes, we have a decorator that could accept zero arguments,
@@ -50614,19 +50755,19 @@ var ts;
signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
});
}
- function resolveSignature(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveSignature(node, candidatesOutArray, checkMode) {
switch (node.kind) {
case 191 /* CallExpression */:
- return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveCallExpression(node, candidatesOutArray, checkMode);
case 192 /* NewExpression */:
- return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveNewExpression(node, candidatesOutArray, checkMode);
case 193 /* TaggedTemplateExpression */:
- return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
case 152 /* Decorator */:
- return resolveDecorator(node, candidatesOutArray, isForSignatureHelp);
+ return resolveDecorator(node, candidatesOutArray, checkMode);
case 262 /* JsxOpeningElement */:
case 261 /* JsxSelfClosingElement */:
- return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp);
+ return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
}
throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
}
@@ -50637,8 +50778,7 @@ var ts;
* the function will fill it up with appropriate candidate signatures
* @return a signature of the call-like expression or undefined if one can't be found
*/
- function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) {
- if (isForSignatureHelp === void 0) { isForSignatureHelp = false; }
+ function getResolvedSignature(node, candidatesOutArray, checkMode) {
var links = getNodeLinks(node);
// If getResolvedSignature has already been called, we will have cached the resolvedSignature.
// However, it is possible that either candidatesOutArray was not passed in the first time,
@@ -50649,11 +50789,15 @@ var ts;
return cached;
}
links.resolvedSignature = resolvingSignature;
- var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp);
- // If signature resolution originated in control flow type analysis (for example to compute the
- // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
- // types from the control flow analysis.
- links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
+ // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
+ // resolution should be deferred.
+ if (result !== resolvingSignature) {
+ // If signature resolution originated in control flow type analysis (for example to compute the
+ // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
+ // types from the control flow analysis.
+ links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ }
return result;
}
/**
@@ -50729,10 +50873,15 @@ var ts;
* @param node The call/new expression to be checked.
* @returns On success, the expression's signature's return type. On failure, anyType.
*/
- function checkCallExpression(node) {
+ function checkCallExpression(node, checkMode) {
if (!checkGrammarTypeArguments(node, node.typeArguments))
checkGrammarArguments(node.arguments);
- var signature = getResolvedSignature(node);
+ var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
+ if (signature === resolvingSignature) {
+ // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
+ // returns a function type. We defer checking and return anyFunctionType.
+ return silentNeverType;
+ }
if (node.expression.kind === 98 /* SuperKeyword */) {
return voidType;
}
@@ -50976,7 +51125,7 @@ var ts;
if (isTupleType(restType)) {
var associatedNames = restType.target.associatedNames;
var index = pos - paramCount;
- return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index;
+ return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
}
return restParameter.escapedName;
}
@@ -51184,7 +51333,7 @@ var ts;
var functionFlags = ts.getFunctionFlags(func);
var type;
if (func.body.kind !== 218 /* Block */) {
- type = checkExpressionCached(func.body, checkMode);
+ type = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -51362,7 +51511,7 @@ var ts;
ts.forEachReturnStatement(func.body, function (returnStatement) {
var expr = returnStatement.expression;
if (expr) {
- var type = checkExpressionCached(expr, checkMode);
+ var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -51455,7 +51604,7 @@ var ts;
ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
checkNodeDeferred(node);
// The identityMapper object is used to indicate that function expressions are wildcards
- if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) {
+ if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
// Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) {
var links_1 = getNodeLinks(node);
@@ -51492,7 +51641,7 @@ var ts;
var signature = getSignaturesOfType(type, 0 /* Call */)[0];
if (isContextSensitive(node)) {
var contextualMapper = getContextualMapper(node);
- if (checkMode === 2 /* Inferential */) {
+ if (checkMode && checkMode & 2 /* Inferential */) {
inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper);
}
var instantiatedContextualSignature = contextualMapper === identityMapper ?
@@ -52414,15 +52563,13 @@ var ts;
}
return node;
}
- function checkExpressionWithContextualType(node, contextualType, contextualMapper) {
+ function checkExpressionWithContextualType(node, contextualType, contextualMapper, checkMode) {
var context = getContextNode(node);
var saveContextualType = context.contextualType;
var saveContextualMapper = context.contextualMapper;
context.contextualType = contextualType;
context.contextualMapper = contextualMapper;
- var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ :
- contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */;
- var type = checkExpression(node, checkMode);
+ var type = checkExpression(node, checkMode | 1 /* Contextual */ | (contextualMapper ? 2 /* Inferential */ : 0));
// We strip literal freshness when an appropriate contextual type is present such that contextually typed
// literals always preserve their literal types (otherwise they might widen during type inference). An alternative
// here would be to not mark contextually typed literals as fresh in the first place.
@@ -52435,7 +52582,7 @@ var ts;
function checkExpressionCached(node, checkMode) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- if (checkMode) {
+ if (checkMode && checkMode !== 0 /* Normal */) {
return checkExpression(node, checkMode);
}
// When computing a type that we're going to cache, we need to ignore any ongoing control flow
@@ -52532,20 +52679,122 @@ var ts;
return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
}
function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
- if (checkMode === 2 /* Inferential */) {
+ if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
var signature = getSingleCallSignature(type);
if (signature && signature.typeParameters) {
+ if (checkMode & 8 /* SkipGenericFunctions */) {
+ skippedGenericFunction(node, checkMode);
+ return anyFunctionType;
+ }
var contextualType = getApparentTypeOfContextualType(node);
if (contextualType) {
var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType));
if (contextualSignature && !contextualSignature.typeParameters) {
- return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node)));
+ var context = getContextualMapper(node);
+ // We have an expression that is an argument of a generic function for which we are performing
+ // type argument inference. The expression is of a function type with a single generic call
+ // signature and a contextual function type with a single non-generic call signature. Now check
+ // if the outer function returns a function type with a single non-generic call signature and
+ // if some of the outer function type parameters have no inferences so far. If so, we can
+ // potentially add inferred type parameters to the outer function return type.
+ var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature));
+ if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
+ // Instantiate the expression type with its own type parameters as type arguments. This
+ // ensures that the type parameters are not erased to type any during type inference such
+ // that they can be inferred as actual types.
+ var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
+ var strippedType = getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters));
+ // Infer from the stripped expression type to the contextual type starting with an empty
+ // set of inference candidates.
+ var inferences = ts.map(context.typeParameters, createInferenceInfo);
+ inferTypes(inferences, strippedType, contextualType);
+ // If we produced some inference candidates and if the type parameters for which we produced
+ // candidates do not already have existing inferences, we adopt the new inference candidates and
+ // add the type parameters of the expression type to the set of inferred type parameters for
+ // the outer function return type.
+ if (ts.some(inferences, hasInferenceCandidates) && !hasOverlappingInferences(context.inferences, inferences)) {
+ mergeInferences(context.inferences, inferences);
+ context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
+ return strippedType;
+ }
+ }
+ return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
}
}
}
}
return type;
}
+ function skippedGenericFunction(node, checkMode) {
+ if (checkMode & 2 /* Inferential */) {
+ // We have skipped a generic function during inferential typing. Obtain the inference context and
+ // indicate this has occurred such that we know a second pass of inference is be needed.
+ var context = getContextualMapper(node);
+ context.flags |= 8 /* SkippedGenericFunction */;
+ }
+ }
+ function hasInferenceCandidates(info) {
+ return !!(info.candidates || info.contraCandidates);
+ }
+ function hasOverlappingInferences(a, b) {
+ for (var i = 0; i < a.length; i++) {
+ if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
+ return true;
+ }
+ }
+ return false;
+ }
+ function mergeInferences(target, source) {
+ for (var i = 0; i < target.length; i++) {
+ if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
+ target[i] = source[i];
+ }
+ }
+ }
+ function getUniqueTypeParameters(context, typeParameters) {
+ var result = [];
+ var oldTypeParameters;
+ var newTypeParameters;
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var tp = typeParameters_2[_i];
+ var name = tp.symbol.escapedName;
+ if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
+ var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
+ var symbol = createSymbol(262144 /* TypeParameter */, newName);
+ var newTypeParameter = createTypeParameter(symbol);
+ newTypeParameter.target = tp;
+ oldTypeParameters = ts.append(oldTypeParameters, tp);
+ newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
+ result.push(newTypeParameter);
+ }
+ else {
+ result.push(tp);
+ }
+ }
+ if (newTypeParameters) {
+ var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
+ for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
+ var tp = newTypeParameters_1[_a];
+ tp.mapper = mapper;
+ }
+ }
+ return result;
+ }
+ function hasTypeParameterByName(typeParameters, name) {
+ return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
+ }
+ function getUniqueTypeParameterName(typeParameters, baseName) {
+ var len = baseName.length;
+ while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
+ len--;
+ var s = baseName.slice(0, len);
+ for (var index = 1; true; index++) {
+ var augmentedName = (s + index);
+ if (!hasTypeParameterByName(typeParameters, augmentedName)) {
+ return augmentedName;
+ }
+ }
+ }
/**
* Returns the type of an expression. Unlike checkExpression, this function is simply concerned
* with computing the type and may not fully check all contained sub-expressions for errors.
@@ -52585,7 +52834,7 @@ var ts;
}
var saveContextualType = node.contextualType;
node.contextualType = anyType;
- var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */);
+ var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
node.contextualType = saveContextualType;
return type;
}
@@ -52677,7 +52926,7 @@ var ts;
}
/* falls through */
case 192 /* NewExpression */:
- return checkCallExpression(node);
+ return checkCallExpression(node, checkMode);
case 193 /* TaggedTemplateExpression */:
return checkTaggedTemplateExpression(node);
case 195 /* ParenthesizedExpression */:
@@ -52936,7 +53185,7 @@ var ts;
checkAsyncFunctionReturnType(node, returnTypeNode);
}
}
- if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) {
+ if (node.kind !== 162 /* IndexSignature */ && node.kind !== 294 /* JSDocFunctionType */) {
registerForUnusedIdentifiersCheck(node);
}
}
@@ -53692,8 +53941,8 @@ var ts;
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
// A jsdoc typedef and callback are, by definition, type aliases
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return 2 /* ExportType */;
case 244 /* ModuleDeclaration */:
return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
@@ -53702,7 +53951,7 @@ var ts;
case 240 /* ClassDeclaration */:
case 243 /* EnumDeclaration */:
return 2 /* ExportType */ | 1 /* ExportValue */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
case 254 /* ExportAssignment */:
// Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
@@ -54343,7 +54592,7 @@ var ts;
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 244 /* ModuleDeclaration */:
case 218 /* Block */:
case 246 /* CaseBlock */:
@@ -54436,8 +54685,8 @@ var ts;
return;
var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
var seenParentsWithEveryUnused = new ts.NodeSet();
- for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
- var typeParameter = typeParameters_2[_i];
+ for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
+ var typeParameter = typeParameters_3[_i];
if (!isTypeParameterUnused(typeParameter))
continue;
var name = ts.idText(typeParameter.name);
@@ -54690,7 +54939,7 @@ var ts;
}
// In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
var parent = getDeclarationContainer(node);
- if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
+ if (parent.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
// If the declaration happens to be in external module, report error that require and exports are reserved keywords
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
@@ -54705,7 +54954,7 @@ var ts;
}
// In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
var parent = getDeclarationContainer(node);
- if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
+ if (parent.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
// If the declaration happens to be in external module, report error that Promise is a reserved identifier.
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
@@ -54762,7 +55011,7 @@ var ts;
(container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) ||
container.kind === 245 /* ModuleBlock */ ||
container.kind === 244 /* ModuleDeclaration */ ||
- container.kind === 279 /* SourceFile */);
+ container.kind === 284 /* SourceFile */);
// here we know that function scoped variable is shadowed by block scoped one
// if they are defined in the same scope - binder has already reported redeclaration error
// otherwise if variable has an initializer - show error that initialization will fail
@@ -56612,7 +56861,7 @@ var ts;
return false;
}
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule) {
error(moduleName, node.kind === 255 /* ExportDeclaration */ ?
ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
@@ -56743,7 +56992,7 @@ var ts;
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ &&
!node.moduleSpecifier && node.flags & 4194304 /* Ambient */;
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
}
}
@@ -56760,7 +57009,7 @@ var ts;
}
}
function checkGrammarModuleElementContext(node, errorMessage) {
- var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
+ var isInAppropriateContext = node.parent.kind === 284 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
if (!isInAppropriateContext) {
grammarErrorOnFirstToken(node, errorMessage);
}
@@ -56789,7 +57038,7 @@ var ts;
// If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
return;
}
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
if (node.isExportEquals) {
error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
@@ -56959,32 +57208,32 @@ var ts;
return checkInferType(node);
case 183 /* ImportType */:
return checkImportType(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return checkJSDocAugmentsTag(node);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return checkJSDocTypeAliasTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return checkJSDocTemplateTag(node);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return checkJSDocTypeTag(node);
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
return checkJSDocParameterTag(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
checkJSDocFunctionType(node);
// falls through
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
- case 292 /* JSDocTypeLiteral */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
+ case 297 /* JSDocTypeLiteral */:
checkJSDocTypeIsInJsFile(node);
ts.forEachChild(node, checkSourceElement);
return;
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
checkJSDocVariadicType(node);
return;
- case 283 /* JSDocTypeExpression */:
+ case 288 /* JSDocTypeExpression */:
return checkSourceElement(node.type);
case 180 /* IndexedAccessType */:
return checkIndexedAccessType(node);
@@ -57292,7 +57541,7 @@ var ts;
copySymbols(location.locals, meaning);
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
// falls through
@@ -57511,10 +57760,10 @@ var ts;
return entityNameSymbol;
}
}
- if (entityName.parent.kind === 299 /* JSDocParameterTag */) {
+ if (entityName.parent.kind === 304 /* JSDocParameterTag */) {
return ts.getParameterSymbolFromJSDoc(entityName.parent);
}
- if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) {
+ if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 308 /* JSDocTemplateTag */) {
ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true.
var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
return typeParameter && typeParameter.symbol;
@@ -57556,7 +57805,7 @@ var ts;
return undefined;
}
function getSymbolAtLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
}
var parent = node.parent;
@@ -57898,7 +58147,7 @@ var ts;
}
var parentSymbol_1 = getParentOfSymbol(symbol);
if (parentSymbol_1) {
- if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) {
+ if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 284 /* SourceFile */) {
var symbolFile = parentSymbol_1.valueDeclaration;
var referenceFile = ts.getSourceFileOfNode(node);
// If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
@@ -58013,7 +58262,7 @@ var ts;
}
function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
- if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
+ if (node === undefined || node.parent.kind !== 284 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
// parent is not source file or it is not reference to internal module
return false;
}
@@ -58442,7 +58691,7 @@ var ts;
break;
}
}
- if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
+ if (current.valueDeclaration && current.valueDeclaration.kind === 284 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
return false;
}
// check that at least one declaration of top level symbol originates from type declaration file
@@ -58475,7 +58724,7 @@ var ts;
if (!moduleSymbol) {
return undefined;
}
- return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */);
+ return ts.getDeclarationOfKind(moduleSymbol, 284 /* SourceFile */);
}
function initializeTypeChecker() {
// Bind all source files and propagate errors
@@ -58707,7 +58956,7 @@ var ts;
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
}
else if (flags & 128 /* Abstract */) {
@@ -58730,7 +58979,7 @@ var ts;
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
}
else if (node.kind === 151 /* Parameter */) {
@@ -58775,7 +59024,7 @@ var ts;
flags |= 1 /* Export */;
break;
case 80 /* DefaultKeyword */:
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
}
@@ -58898,7 +59147,7 @@ var ts;
case 151 /* Parameter */:
return false;
default:
- if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return false;
}
switch (node.kind) {
@@ -59821,7 +60070,7 @@ var ts;
// to prevent noisiness. So use a bit on the block to indicate if
// this has already been reported, and don't report if it has.
//
- if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
var links_2 = getNodeLinks(node.parent);
// Check if the containing block ever report this error
if (!links_2.hasReportedStatementInAmbientContext) {
@@ -61875,14 +62124,14 @@ var ts;
// JSDoc
/* @internal */
function createJSDocTypeExpression(type) {
- var node = createSynthesizedNode(283 /* JSDocTypeExpression */);
+ var node = createSynthesizedNode(288 /* JSDocTypeExpression */);
node.type = type;
return node;
}
ts.createJSDocTypeExpression = createJSDocTypeExpression;
/* @internal */
function createJSDocTypeTag(typeExpression, comment) {
- var tag = createJSDocTag(302 /* JSDocTypeTag */, "type");
+ var tag = createJSDocTag(307 /* JSDocTypeTag */, "type");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61890,7 +62139,7 @@ var ts;
ts.createJSDocTypeTag = createJSDocTypeTag;
/* @internal */
function createJSDocReturnTag(typeExpression, comment) {
- var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns");
+ var tag = createJSDocTag(305 /* JSDocReturnTag */, "returns");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61898,7 +62147,7 @@ var ts;
ts.createJSDocReturnTag = createJSDocReturnTag;
/* @internal */
function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
- var tag = createJSDocTag(299 /* JSDocParameterTag */, "param");
+ var tag = createJSDocTag(304 /* JSDocParameterTag */, "param");
tag.typeExpression = typeExpression;
tag.name = name;
tag.isBracketed = isBracketed;
@@ -61908,7 +62157,7 @@ var ts;
ts.createJSDocParamTag = createJSDocParamTag;
/* @internal */
function createJSDocComment(comment, tags) {
- var node = createSynthesizedNode(291 /* JSDocComment */);
+ var node = createSynthesizedNode(296 /* JSDocComment */);
node.comment = comment;
node.tags = tags;
return node;
@@ -62167,7 +62416,7 @@ var ts;
(typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
(libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
(hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
- var updated = createSynthesizedNode(279 /* SourceFile */);
+ var updated = createSynthesizedNode(284 /* SourceFile */);
updated.flags |= node.flags;
updated.statements = createNodeArray(statements);
updated.endOfFileToken = node.endOfFileToken;
@@ -62251,7 +62500,7 @@ var ts;
* @param original The original statement.
*/
function createNotEmittedStatement(original) {
- var node = createSynthesizedNode(307 /* NotEmittedStatement */);
+ var node = createSynthesizedNode(312 /* NotEmittedStatement */);
node.original = original;
setTextRange(node, original);
return node;
@@ -62263,7 +62512,7 @@ var ts;
*/
/* @internal */
function createEndOfDeclarationMarker(original) {
- var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */);
+ var node = createSynthesizedNode(316 /* EndOfDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -62275,7 +62524,7 @@ var ts;
*/
/* @internal */
function createMergeDeclarationMarker(original) {
- var node = createSynthesizedNode(310 /* MergeDeclarationMarker */);
+ var node = createSynthesizedNode(315 /* MergeDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -62290,7 +62539,7 @@ var ts;
* @param location The location for the expression. Defaults to the positions from "original" if provided.
*/
function createPartiallyEmittedExpression(expression, original) {
- var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */);
+ var node = createSynthesizedNode(313 /* PartiallyEmittedExpression */);
node.expression = expression;
node.original = original;
setTextRange(node, original);
@@ -62306,7 +62555,7 @@ var ts;
ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
function flattenCommaElements(node) {
if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
- if (node.kind === 309 /* CommaListExpression */) {
+ if (node.kind === 314 /* CommaListExpression */) {
return node.elements;
}
if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
@@ -62316,7 +62565,7 @@ var ts;
return node;
}
function createCommaList(elements) {
- var node = createSynthesizedNode(309 /* CommaListExpression */);
+ var node = createSynthesizedNode(314 /* CommaListExpression */);
node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
return node;
}
@@ -62329,33 +62578,197 @@ var ts;
ts.updateCommaList = updateCommaList;
function createBundle(sourceFiles, prepends) {
if (prepends === void 0) { prepends = ts.emptyArray; }
- var node = ts.createNode(280 /* Bundle */);
+ var node = ts.createNode(285 /* Bundle */);
node.prepends = prepends;
node.sourceFiles = sourceFiles;
return node;
}
ts.createBundle = createBundle;
- function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, map) {
- var node = ts.createNode(281 /* UnparsedSource */);
+ var allUnscopedEmitHelpers;
+ function getAllUnscopedEmitHelpers() {
+ return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
+ ts.valuesHelper,
+ ts.readHelper,
+ ts.spreadHelper,
+ ts.restHelper,
+ ts.decorateHelper,
+ ts.metadataHelper,
+ ts.paramHelper,
+ ts.awaiterHelper,
+ ts.assignHelper,
+ ts.awaitHelper,
+ ts.asyncGeneratorHelper,
+ ts.asyncDelegator,
+ ts.asyncValues,
+ ts.extendsHelper,
+ ts.templateObjectHelper,
+ ts.generatorHelper,
+ ts.importStarHelper,
+ ts.importDefaultHelper
+ ], function (helper) { return helper.name; }));
+ }
+ function createUnparsedSource() {
+ var node = ts.createNode(286 /* UnparsedSource */);
+ node.prologues = ts.emptyArray;
+ node.referencedFiles = ts.emptyArray;
+ node.libReferenceDirectives = ts.emptyArray;
+ node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
+ return node;
+ }
+ function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
+ var node = createUnparsedSource();
+ var stripInternal;
+ var bundleFileInfo;
if (!ts.isString(textOrInputFiles)) {
ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
- node.fileName = mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath;
+ node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
Object.defineProperties(node, {
text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
});
+ if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
+ node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
+ ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
+ stripInternal = mapTextOrStripInternal;
+ bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
+ if (node.oldFileOfCurrentEmit) {
+ parseOldFileOfCurrentEmit(node, ts.Debug.assertDefined(bundleFileInfo));
+ return node;
+ }
+ }
}
else {
+ node.fileName = "";
node.text = textOrInputFiles;
node.sourceMapPath = mapPathOrType;
- node.sourceMapText = map;
+ node.sourceMapText = mapTextOrStripInternal;
}
+ ts.Debug.assert(!node.oldFileOfCurrentEmit);
+ parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
return node;
}
ts.createUnparsedSourceFile = createUnparsedSourceFile;
- function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapText) {
- var node = ts.createNode(282 /* InputFiles */);
+ function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
+ var prologues;
+ var helpers;
+ var referencedFiles;
+ var typeReferenceDirectives;
+ var libReferenceDirectives;
+ var texts;
+ for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "prologue" /* Prologue */:
+ (prologues || (prologues = [])).push(createUnparsedNode(section, node));
+ break;
+ case "emitHelpers" /* EmitHelpers */:
+ (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ node.hasNoDefaultLib = true;
+ break;
+ case "reference" /* Reference */:
+ (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "type" /* Type */:
+ (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
+ break;
+ case "lib" /* Lib */:
+ (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "prepend" /* Prepend */:
+ var prependNode = createUnparsedNode(section, node);
+ var prependTexts = void 0;
+ for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
+ var text = _c[_b];
+ if (!stripInternal || text.kind !== "internal" /* Internal */) {
+ (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
+ }
+ }
+ prependNode.texts = prependTexts || ts.emptyArray;
+ (texts || (texts = [])).push(prependNode);
+ break;
+ case "internal" /* Internal */:
+ if (stripInternal)
+ break;
+ // falls through
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.prologues = prologues || ts.emptyArray;
+ node.helpers = helpers;
+ node.referencedFiles = referencedFiles || ts.emptyArray;
+ node.typeReferenceDirectives = typeReferenceDirectives;
+ node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
+ node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
+ }
+ function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
+ ts.Debug.assert(!!node.oldFileOfCurrentEmit);
+ var texts;
+ var syntheticReferences;
+ for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "internal" /* Internal */:
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
+ break;
+ // Ignore
+ case "prologue" /* Prologue */:
+ case "emitHelpers" /* EmitHelpers */:
+ case "prepend" /* Prepend */:
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.texts = texts || ts.emptyArray;
+ node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
+ node.syntheticReferences = syntheticReferences;
+ return node;
+ }
+ function mapBundleFileSectionKindToSyntaxKind(kind) {
+ switch (kind) {
+ case "prologue" /* Prologue */: return 279 /* UnparsedPrologue */;
+ case "prepend" /* Prepend */: return 280 /* UnparsedPrepend */;
+ case "internal" /* Internal */: return 282 /* UnparsedInternalText */;
+ case "text" /* Text */: return 281 /* UnparsedText */;
+ case "emitHelpers" /* EmitHelpers */:
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
+ default:
+ return ts.Debug.assertNever(kind);
+ }
+ }
+ function createUnparsedNode(section, parent) {
+ var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ return node;
+ }
+ function createUnparsedSyntheticReference(section, parent) {
+ var node = ts.createNode(283 /* UnparsedSyntheticReference */, section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ node.section = section;
+ return node;
+ }
+ function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
+ var node = ts.createNode(287 /* InputFiles */);
if (!ts.isString(javascriptTextOrReadFileText)) {
var cache_1 = ts.createMap();
var textGetter_1 = function (path) {
@@ -62372,15 +62785,25 @@ var ts;
var result = textGetter_1(path);
return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
};
+ var buildInfo_1;
+ var getAndCacheBuildInfo_1 = function (getText) {
+ if (buildInfo_1 === undefined) {
+ var result = getText();
+ buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
+ }
+ return buildInfo_1 || undefined;
+ };
node.javascriptPath = declarationTextOrJavascriptPath;
node.javascriptMapPath = javascriptMapPath;
node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
node.declarationMapPath = declarationMapPath;
+ node.buildInfoPath = declarationMapTextOrBuildInfoPath;
Object.defineProperties(node, {
javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
- declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } } // TODO:: if there is inline sourceMap in dtsFile, use that
+ declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
+ buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
});
}
else {
@@ -62389,7 +62812,12 @@ var ts;
node.javascriptMapText = javascriptMapTextOrDeclarationPath;
node.declarationText = declarationTextOrJavascriptPath;
node.declarationMapPath = declarationMapPath;
- node.declarationMapText = declarationMapText;
+ node.declarationMapText = declarationMapTextOrBuildInfoPath;
+ node.javascriptPath = javascriptPath;
+ node.declarationPath = declarationPath,
+ node.buildInfoPath = buildInfoPath;
+ node.buildInfo = buildInfo;
+ node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
}
return node;
}
@@ -62527,7 +62955,7 @@ var ts;
// To avoid holding onto transformation artifacts, we keep track of any
// parse tree node we are annotating. This allows us to clean them up after
// all transformations have completed.
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return node.emitNode = { annotatedNodes: [node] };
}
var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
@@ -62973,38 +63401,38 @@ var ts;
return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
}
ts.getHelperName = getHelperName;
- var valuesHelper = {
+ ts.valuesHelper = {
name: "typescript:values",
scoped: false,
text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };"
};
function createValuesHelper(context, expression, location) {
- context.requestEmitHelper(valuesHelper);
+ context.requestEmitHelper(ts.valuesHelper);
return ts.setTextRange(ts.createCall(getHelperName("__values"),
/*typeArguments*/ undefined, [expression]), location);
}
ts.createValuesHelper = createValuesHelper;
- var readHelper = {
+ ts.readHelper = {
name: "typescript:read",
scoped: false,
text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };"
};
function createReadHelper(context, iteratorRecord, count, location) {
- context.requestEmitHelper(readHelper);
+ context.requestEmitHelper(ts.readHelper);
return ts.setTextRange(ts.createCall(getHelperName("__read"),
/*typeArguments*/ undefined, count !== undefined
? [iteratorRecord, ts.createLiteral(count)]
: [iteratorRecord]), location);
}
ts.createReadHelper = createReadHelper;
- var spreadHelper = {
+ ts.spreadHelper = {
name: "typescript:spread",
scoped: false,
text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };"
};
function createSpreadHelper(context, argumentList, location) {
- context.requestEmitHelper(readHelper);
- context.requestEmitHelper(spreadHelper);
+ context.requestEmitHelper(ts.readHelper);
+ context.requestEmitHelper(ts.spreadHelper);
return ts.setTextRange(ts.createCall(getHelperName("__spread"),
/*typeArguments*/ undefined, argumentList), location);
}
@@ -63850,7 +64278,7 @@ var ts;
case 190 /* ElementAccessExpression */:
case 189 /* PropertyAccessExpression */:
case 213 /* NonNullExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
node = node.expression;
continue;
}
@@ -63866,7 +64294,7 @@ var ts;
ts.parenthesizeConciseBody = parenthesizeConciseBody;
function isCommaSequence(node) {
return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
- node.kind === 309 /* CommaListExpression */;
+ node.kind === 314 /* CommaListExpression */;
}
ts.isCommaSequence = isCommaSequence;
var OuterExpressionKinds;
@@ -63885,7 +64313,7 @@ var ts;
case 212 /* AsExpression */:
case 213 /* NonNullExpression */:
return (kinds & 2 /* Assertions */) !== 0;
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0;
}
return false;
@@ -63922,7 +64350,7 @@ var ts;
case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
- case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
+ case 313 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
}
}
/**
@@ -64714,12 +65142,12 @@ var ts;
case 278 /* EnumMember */:
return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
default:
// No need to visit nodes with no children.
@@ -64775,7 +65203,7 @@ var ts;
case 220 /* EmptyStatement */:
case 210 /* OmittedExpression */:
case 236 /* DebuggerStatement */:
- case 307 /* NotEmittedStatement */:
+ case 312 /* NotEmittedStatement */:
// No need to visit nodes with no children.
break;
// Names
@@ -65152,14 +65580,14 @@ var ts;
result = reduceNode(node.initializer, cbNode, result);
break;
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
result = reduceNodes(node.statements, cbNodes, result);
break;
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
result = reduceNodes(node.elements, cbNodes, result);
break;
default:
@@ -65440,7 +65868,7 @@ var ts;
}
exit();
}
- function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) {
+ function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
var _a;
ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
@@ -65450,6 +65878,14 @@ var ts;
var nameIndexToNewNameIndexMap;
var mappingIterator = decodeMappings(map.mappings);
for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) {
+ if (end && (raw.generatedLine > end.line ||
+ (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
+ break;
+ }
+ if (start && (raw.generatedLine < start.line ||
+ (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
+ continue;
+ }
// Then reencode all the updated mappings into the overall map
var newSourceIndex = void 0;
var newSourceLine = void 0;
@@ -65478,8 +65914,10 @@ var ts;
}
}
}
- var newGeneratedLine = raw.generatedLine + generatedLine;
- var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter;
+ var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
+ var newGeneratedLine = rawGeneratedLine + generatedLine;
+ var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
+ var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
}
exit();
@@ -65962,7 +66400,7 @@ var ts;
function chainBundle(transformSourceFile) {
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
+ return node.kind === 284 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
}
function transformBundle(node) {
return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
@@ -66623,7 +67061,7 @@ var ts;
function makeAssignmentElement(name) {
return name;
}
- var restHelper = {
+ ts.restHelper = {
name: "typescript:rest",
scoped: false,
text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };"
@@ -66632,7 +67070,7 @@ var ts;
* `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
*/
function createRestCall(context, value, elements, computedTempVariables, location) {
- context.requestEmitHelper(restHelper);
+ context.requestEmitHelper(ts.restHelper);
var propertyNames = [];
var computedTempVariableOffset = 0;
for (var i = 0; i < elements.length - 1; i++) {
@@ -66733,14 +67171,14 @@ var ts;
var pendingExpressions;
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* Bundle */) {
return transformBundle(node);
}
return transformSourceFile(node);
}
function transformBundle(node) {
return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
- if (prepend.kind === 282 /* InputFiles */) {
+ if (prepend.kind === 287 /* InputFiles */) {
return ts.createUnparsedSourceFile(prepend, "js");
}
return prepend;
@@ -66789,7 +67227,7 @@ var ts;
*/
function onBeforeVisitNode(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 245 /* ModuleBlock */:
case 218 /* Block */:
@@ -69020,7 +69458,7 @@ var ts;
// enums in any other scope are emitted as a `let` declaration.
var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
- ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
+ ], currentLexicalScope.kind === 284 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
ts.setOriginalNode(statement, node);
recordEmittedDeclarationInScope(node);
if (isFirstEmittedDeclarationInScope(node)) {
@@ -69585,7 +70023,7 @@ var ts;
// If we are nested within a namespace declaration, we may need to qualifiy
// an identifier that is exported from a merged namespace.
var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
- if (container && container.kind !== 279 /* SourceFile */) {
+ if (container && container.kind !== 284 /* SourceFile */) {
var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) ||
(applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */);
if (substitute) {
@@ -69636,39 +70074,39 @@ var ts;
argumentsArray.push(descriptor);
}
}
- context.requestEmitHelper(decorateHelper);
+ context.requestEmitHelper(ts.decorateHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"),
/*typeArguments*/ undefined, argumentsArray), location);
}
- var decorateHelper = {
+ ts.decorateHelper = {
name: "typescript:decorate",
scoped: false,
priority: 2,
text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };"
};
function createMetadataHelper(context, metadataKey, metadataValue) {
- context.requestEmitHelper(metadataHelper);
+ context.requestEmitHelper(ts.metadataHelper);
return ts.createCall(ts.getHelperName("__metadata"),
/*typeArguments*/ undefined, [
ts.createLiteral(metadataKey),
metadataValue
]);
}
- var metadataHelper = {
+ ts.metadataHelper = {
name: "typescript:metadata",
scoped: false,
priority: 3,
text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };"
};
function createParamHelper(context, expression, parameterOffset, location) {
- context.requestEmitHelper(paramHelper);
+ context.requestEmitHelper(ts.paramHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__param"),
/*typeArguments*/ undefined, [
ts.createLiteral(parameterOffset),
expression
]), location);
}
- var paramHelper = {
+ ts.paramHelper = {
name: "typescript:param",
scoped: false,
priority: 4,
@@ -70219,14 +70657,14 @@ var ts;
], 2 /* Const */));
}
ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
- var awaiterHelper = {
+ ts.awaiterHelper = {
name: "typescript:awaiter",
scoped: false,
priority: 5,
text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };"
};
function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) {
- context.requestEmitHelper(awaiterHelper);
+ context.requestEmitHelper(ts.awaiterHelper);
var generatorFunc = ts.createFunctionExpression(
/*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */),
/*name*/ undefined,
@@ -70858,7 +71296,7 @@ var ts;
}
}
ts.transformES2018 = transformES2018;
- var assignHelper = {
+ ts.assignHelper = {
name: "typescript:assign",
scoped: false,
priority: 1,
@@ -70869,28 +71307,28 @@ var ts;
return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"),
/*typeArguments*/ undefined, attributesSegments);
}
- context.requestEmitHelper(assignHelper);
+ context.requestEmitHelper(ts.assignHelper);
return ts.createCall(ts.getHelperName("__assign"),
/*typeArguments*/ undefined, attributesSegments);
}
ts.createAssignHelper = createAssignHelper;
- var awaitHelper = {
+ ts.awaitHelper = {
name: "typescript:await",
scoped: false,
text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
};
function createAwaitHelper(context, expression) {
- context.requestEmitHelper(awaitHelper);
+ context.requestEmitHelper(ts.awaitHelper);
return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]);
}
- var asyncGeneratorHelper = {
+ ts.asyncGeneratorHelper = {
name: "typescript:asyncGenerator",
scoped: false,
text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
};
function createAsyncGeneratorHelper(context, generatorFunc) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncGeneratorHelper);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncGeneratorHelper);
// Mark this node as originally an async function
(generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */;
return ts.createCall(ts.getHelperName("__asyncGenerator"),
@@ -70900,24 +71338,24 @@ var ts;
generatorFunc
]);
}
- var asyncDelegator = {
+ ts.asyncDelegator = {
name: "typescript:asyncDelegator",
scoped: false,
text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };"
};
function createAsyncDelegatorHelper(context, expression, location) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncDelegator);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncDelegator);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"),
/*typeArguments*/ undefined, [expression]), location);
}
- var asyncValues = {
+ ts.asyncValues = {
name: "typescript:asyncValues",
scoped: false,
text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };"
};
function createAsyncValuesHelper(context, expression, location) {
- context.requestEmitHelper(asyncValues);
+ context.requestEmitHelper(ts.asyncValues);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"),
/*typeArguments*/ undefined, [expression]), location);
}
@@ -74729,7 +75167,7 @@ var ts;
}
ts.transformES2015 = transformES2015;
function createExtendsHelper(context, name) {
- context.requestEmitHelper(extendsHelper);
+ context.requestEmitHelper(ts.extendsHelper);
return ts.createCall(ts.getHelperName("__extends"),
/*typeArguments*/ undefined, [
name,
@@ -74737,20 +75175,20 @@ var ts;
]);
}
function createTemplateObjectHelper(context, cooked, raw) {
- context.requestEmitHelper(templateObjectHelper);
+ context.requestEmitHelper(ts.templateObjectHelper);
return ts.createCall(ts.getHelperName("__makeTemplateObject"),
/*typeArguments*/ undefined, [
cooked,
raw
]);
}
- var extendsHelper = {
+ ts.extendsHelper = {
name: "typescript:extends",
scoped: false,
priority: 0,
text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();"
};
- var templateObjectHelper = {
+ ts.templateObjectHelper = {
name: "typescript:makeTemplateObject",
scoped: false,
priority: 0,
@@ -77444,7 +77882,7 @@ var ts;
}
ts.transformGenerators = transformGenerators;
function createGeneratorHelper(context, body) {
- context.requestEmitHelper(generatorHelper);
+ context.requestEmitHelper(ts.generatorHelper);
return ts.createCall(ts.getHelperName("__generator"),
/*typeArguments*/ undefined, [ts.createThis(), body]);
}
@@ -77507,7 +77945,7 @@ var ts;
// entering a finally block.
//
// For examples of how these are used, see the comments in ./transformers/generators.ts
- var generatorHelper = {
+ ts.generatorHelper = {
name: "typescript:generator",
scoped: false,
priority: 6,
@@ -77540,7 +77978,7 @@ var ts;
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* SourceFile */); // Restore state when substituting nodes in a file.
var moduleInfoMap = []; // The ExternalModuleInfo for each file.
var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
var currentSourceFile; // The current file.
@@ -77882,9 +78320,9 @@ var ts;
return visitFunctionDeclaration(node);
case 240 /* ClassDeclaration */:
return visitClassDeclaration(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
@@ -78042,7 +78480,7 @@ var ts;
}
var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]);
}
return promise;
@@ -78056,7 +78494,7 @@ var ts;
var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
}
var func;
@@ -78090,11 +78528,11 @@ var ts;
return innerExpr;
}
if (ts.getImportNeedsImportStarHelper(node)) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
}
if (ts.getImportNeedsImportDefaultHelper(node)) {
- context.requestEmitHelper(importDefaultHelper);
+ context.requestEmitHelper(ts.importDefaultHelper);
return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
}
return innerExpr;
@@ -78663,7 +79101,7 @@ var ts;
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
currentSourceFile = node;
currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
noSubstitution = [];
@@ -78751,7 +79189,7 @@ var ts;
}
if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)),
/*location*/ node);
}
@@ -78877,13 +79315,13 @@ var ts;
text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
};
// emit helper for `import * as Name from "foo"`
- var importStarHelper = {
+ ts.importStarHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
};
// emit helper for `import Name from "foo"`
- var importDefaultHelper = {
+ ts.importDefaultHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
@@ -78906,7 +79344,7 @@ var ts;
context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols.
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* SourceFile */); // Restore state when substituting nodes in a file.
var moduleInfoMap = []; // The ExternalModuleInfo for each file.
var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
var exportFunctionsMap = []; // The export function associated with a source file.
@@ -79476,7 +79914,7 @@ var ts;
function shouldHoistVariableDeclarationList(node) {
// hoist only non-block scoped declarations or block scoped declarations parented by source file
return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
- && (enclosingBlockScopedContainer.kind === 279 /* SourceFile */
+ && (enclosingBlockScopedContainer.kind === 284 /* SourceFile */
|| (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
}
/**
@@ -79819,9 +80257,9 @@ var ts;
return visitCatchClause(node);
case 218 /* Block */:
return visitBlock(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return destructuringAndImportCallVisitor(node);
@@ -80069,7 +80507,7 @@ var ts;
}
else if (ts.isIdentifier(node)) {
var container = resolver.getReferencedExportContainer(node);
- return container !== undefined && container.kind === 279 /* SourceFile */;
+ return container !== undefined && container.kind === 284 /* SourceFile */;
}
else {
return false;
@@ -80102,7 +80540,7 @@ var ts;
* @param emitCallback A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
var id = ts.getOriginalNodeId(node);
currentSourceFile = node;
moduleInfo = moduleInfoMap[id];
@@ -80311,7 +80749,7 @@ var ts;
|| resolver.getReferencedValueDeclaration(name);
if (valueDeclaration) {
var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
}
exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
@@ -80350,7 +80788,7 @@ var ts;
var previousOnSubstituteNode = context.onSubstituteNode;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
- context.enableEmitNotification(279 /* SourceFile */);
+ context.enableEmitNotification(284 /* SourceFile */);
context.enableSubstitution(72 /* Identifier */);
var currentSourceFile;
return ts.chainBundle(transformSourceFile);
@@ -80780,6 +81218,9 @@ var ts;
case 241 /* InterfaceDeclaration */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
break;
+ case 181 /* MappedType */:
+ diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
+ break;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
@@ -80863,6 +81304,15 @@ var ts;
return result.diagnostics;
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
+ function isInternalDeclaration(node, currentSourceFile) {
+ var parseTreeNode = ts.getParseTreeNode(node);
+ var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
+ return !!ts.forEach(leadingCommentRanges, function (range) {
+ var comment = currentSourceFile.text.substring(range.pos, range.end);
+ return ts.stringContains(comment, "@internal");
+ });
+ }
+ ts.isInternalDeclaration = isInternalDeclaration;
var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
2048 /* WriteClassExpressionAsTypeLiteral */ |
4096 /* UseTypeOfFunction */ |
@@ -80991,10 +81441,10 @@ var ts;
}
}
function transformRoot(node) {
- if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
+ if (node.kind === 284 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
}
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* Bundle */) {
isBundledEmit = true;
refs = ts.createMap();
libs = ts.createMap();
@@ -81024,9 +81474,15 @@ var ts;
var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
}), ts.mapDefined(node.prepends, function (prepend) {
- if (prepend.kind === 282 /* InputFiles */) {
- return ts.createUnparsedSourceFile(prepend, "dts");
+ if (prepend.kind === 287 /* InputFiles */) {
+ var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
+ hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
+ collectReferences(sourceFile, refs);
+ recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
+ collectLibs(sourceFile, libs);
+ return sourceFile;
}
+ return prepend;
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
@@ -81118,7 +81574,7 @@ var ts;
}
}
function collectReferences(sourceFile, ret) {
- if (noResolve || ts.isSourceFileJS(sourceFile))
+ if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
return ret;
ts.forEach(sourceFile.referencedFiles, function (f) {
var elem = ts.tryResolveScriptReference(host, sourceFile, f);
@@ -81846,18 +82302,8 @@ var ts;
}
errorNameNode = undefined;
}
- function hasInternalAnnotation(range) {
- var comment = currentSourceFile.text.substring(range.pos, range.end);
- return ts.stringContains(comment, "@internal");
- }
function shouldStripInternal(node) {
- if (stripInternal && node) {
- var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile);
- if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) {
- return true;
- }
- }
- return false;
+ return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
}
function isScopeMarker(node) {
return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
@@ -81879,7 +82325,7 @@ var ts;
function ensureModifierFlags(node, privateDeclaration) {
var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
- var parentIsFile = node.parent.kind === 279 /* SourceFile */;
+ var parentIsFile = node.parent.kind === 284 /* SourceFile */;
if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */);
additions = 0 /* None */;
@@ -82096,7 +82542,7 @@ var ts;
* @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
*/
function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
- var enabledSyntaxKindFeatures = new Array(312 /* Count */);
+ var enabledSyntaxKindFeatures = new Array(317 /* Count */);
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
@@ -82356,10 +82802,14 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- var infoExtension = ".tsbundleinfo";
var brackets = createBracketsMap();
var syntheticParent = { pos: -1, end: -1 };
/*@internal*/
+ function isBuildInfoFile(file) {
+ return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
+ }
+ ts.isBuildInfoFile = isBuildInfoFile;
+ /*@internal*/
/**
* Iterates over the source files that are expected to have an emit output.
*
@@ -82369,13 +82819,14 @@ var ts;
* If an array, the full list of source files to emit.
* Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
*/
- function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) {
+ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles, onlyBuildInfo, includeBuildInfo) {
if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; }
var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
- if (sourceFiles.length) {
- var bundle = ts.createBundle(sourceFiles, host.getPrependNodes());
+ var prepends = host.getPrependNodes();
+ if (sourceFiles.length || prepends.length) {
+ var bundle = ts.createBundle(sourceFiles, prepends);
var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
if (result) {
return result;
@@ -82383,31 +82834,61 @@ var ts;
}
}
else {
- for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
- var sourceFile = sourceFiles_1[_a];
- var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
- if (result) {
- return result;
+ if (!onlyBuildInfo) {
+ for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
+ var sourceFile = sourceFiles_1[_a];
+ var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
+ if (result) {
+ return result;
+ }
}
}
+ if (includeBuildInfo) {
+ var buildInfoPath = getOutputPathForBuildInfo(host.getCompilerOptions());
+ if (buildInfoPath)
+ return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
+ }
}
}
ts.forEachEmittedFile = forEachEmittedFile;
/*@internal*/
+ function getOutputPathForBuildInfo(options) {
+ var configFile = options.configFilePath;
+ if (!configFile || !ts.isIncrementalCompilation(options))
+ return undefined;
+ if (options.tsBuildInfoFile)
+ return options.tsBuildInfoFile;
+ var outPath = options.outFile || options.out;
+ var buildInfoExtensionLess;
+ if (outPath) {
+ buildInfoExtensionLess = ts.removeFileExtension(outPath);
+ }
+ else {
+ var configFileExtensionLess = ts.removeFileExtension(configFile);
+ buildInfoExtensionLess = options.outDir ?
+ options.rootDir ?
+ ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
+ ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
+ configFileExtensionLess;
+ }
+ return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
+ }
+ ts.getOutputPathForBuildInfo = getOutputPathForBuildInfo;
+ /*@internal*/
function getOutputPathsForBundle(options, forceDtsPaths) {
var outPath = options.outFile || options.out;
var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath };
+ var buildInfoPath = getOutputPathForBuildInfo(options);
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
}
ts.getOutputPathsForBundle = getOutputPathsForBundle;
/*@internal*/
function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
var options = host.getCompilerOptions();
- if (sourceFile.kind === 280 /* Bundle */) {
+ if (sourceFile.kind === 285 /* Bundle */) {
return getOutputPathsForBundle(options, forceDtsPaths);
}
else {
@@ -82421,19 +82902,13 @@ var ts;
var isJs = ts.isSourceFileJS(sourceFile);
var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined };
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
}
}
ts.getOutputPathsFor = getOutputPathsFor;
function getSourceMapFilePath(jsFilePath, options) {
return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
}
- function createDefaultBundleInfo() {
- return {
- originalOffset: -1,
- totalLength: -1
- };
- }
// JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
// So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
// For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
@@ -82458,7 +82933,7 @@ var ts;
ts.getOutputExtension = getOutputExtension;
/*@internal*/
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) {
+ function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers, onlyBuildInfo) {
var compilerOptions = host.getCompilerOptions();
var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
@@ -82466,12 +82941,12 @@ var ts;
var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
var writer = ts.createTextWriter(newLine);
var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit;
- var bundleInfo = createDefaultBundleInfo();
+ var bundleBuildInfo;
var emitSkipped = false;
var exportedModulesFromDeclarationEmit;
// Emit each output file
enter();
- forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles);
+ forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles, onlyBuildInfo, !targetSourceFile);
exit();
return {
emitSkipped: emitSkipped,
@@ -82481,9 +82956,16 @@ var ts;
exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
};
function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
- var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath;
- emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
+ var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
+ bundleBuildInfo = {
+ commonSourceDirectory: host.getCommonSourceDirectory(),
+ sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return file.fileName; })
+ };
+ }
+ emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
+ emitBuildInfo(bundleBuildInfo, buildInfoPath);
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
if (jsFilePath) {
@@ -82492,8 +82974,8 @@ var ts;
if (sourceMapFilePath) {
emittedFilesList.push(sourceMapFilePath);
}
- if (bundleInfoPath) {
- emittedFilesList.push(bundleInfoPath);
+ if (buildInfoPath) {
+ emittedFilesList.push(buildInfoPath);
}
}
if (declarationFilePath) {
@@ -82504,8 +82986,21 @@ var ts;
}
}
}
- function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) {
- if (emitOnlyDtsFiles || !jsFilePath) {
+ function emitBuildInfo(bundle, buildInfoPath) {
+ // Write build information if applicable
+ if (!buildInfoPath || targetSourceFile || emitSkipped)
+ return;
+ var program = host.getProgramBuildInfo();
+ if (!bundle && !program)
+ return;
+ if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
+ emitSkipped = true;
+ return;
+ }
+ ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: ts.version }), /*writeByteOrderMark*/ false);
+ }
+ function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) {
+ if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
return;
}
// Make sure not to write js file and source map file if any of them cannot be written
@@ -82525,6 +83020,7 @@ var ts;
inlineSourceMap: compilerOptions.inlineSourceMap,
inlineSources: compilerOptions.inlineSources,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
+ writeBundleFileInfo: !!bundleBuildInfo
};
// Create a printer to print the nodes
var printer = createPrinter(printerOptions, {
@@ -82535,12 +83031,14 @@ var ts;
substituteNode: transform.substituteNode,
});
ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
- printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions);
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
// Clean up emit nodes on parse tree
transform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.js = printer.bundleFileInfo;
}
function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) {
- if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
+ if (!sourceFileOrBundle || !(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
return;
}
var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
@@ -82569,6 +83067,8 @@ var ts;
inlineSourceMap: compilerOptions.inlineSourceMap,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
onlyPrintJsDocStyle: true,
+ writeBundleFileInfo: !!bundleBuildInfo,
+ recordInternalSection: !!bundleBuildInfo
};
var declarationPrinter = createPrinter(printerOptions, {
// resolver hooks
@@ -82581,18 +83081,20 @@ var ts;
emitSkipped = emitSkipped || declBlocked;
if (!declBlocked || emitOnlyDtsFiles) {
ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
- printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, {
+ printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
sourceMap: compilerOptions.declarationMap,
sourceRoot: compilerOptions.sourceRoot,
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
});
- if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) {
+ if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 284 /* SourceFile */) {
var sourceFile = declarationTransform.transformed[0];
exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
}
}
declarationTransform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
}
function collectLinkedAliases(node) {
if (ts.isExportAssignment(node)) {
@@ -82607,16 +83109,16 @@ var ts;
}
ts.forEachChild(node, collectLinkedAliases);
}
- function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) {
- var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined;
- var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined;
+ function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
+ var bundle = sourceFileOrBundle.kind === 285 /* Bundle */ ? sourceFileOrBundle : undefined;
+ var sourceFile = sourceFileOrBundle.kind === 284 /* SourceFile */ ? sourceFileOrBundle : undefined;
var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
var sourceMapGenerator;
if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
}
if (bundle) {
- printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator);
+ printer.writeBundle(bundle, writer, sourceMapGenerator);
}
else {
printer.writeFile(sourceFile, writer, sourceMapGenerator);
@@ -82645,18 +83147,12 @@ var ts;
}
// Write the output file
ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
- // Write bundled offset information if applicable
- if (bundleInfoPath) {
- bundleInfo.totalLength = writer.getTextPos();
- ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false);
- }
// Reset state
writer.clear();
- bundleInfo = createDefaultBundleInfo();
}
function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
- && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
+ && (sourceFileOrBundle.kind !== 284 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
}
function getSourceRoot(mapOptions) {
// Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
@@ -82713,6 +83209,166 @@ var ts;
}
}
ts.emitFiles = emitFiles;
+ /*@internal*/
+ function getBuildInfoText(buildInfo) {
+ return JSON.stringify(buildInfo, undefined, 2);
+ }
+ ts.getBuildInfoText = getBuildInfoText;
+ /*@internal*/
+ function getBuildInfo(buildInfoText) {
+ return JSON.parse(buildInfoText);
+ }
+ ts.getBuildInfo = getBuildInfo;
+ /*@internal*/
+ ts.notImplementedResolver = {
+ hasGlobalName: ts.notImplemented,
+ getReferencedExportContainer: ts.notImplemented,
+ getReferencedImportDeclaration: ts.notImplemented,
+ getReferencedDeclarationWithCollidingName: ts.notImplemented,
+ isDeclarationWithCollidingName: ts.notImplemented,
+ isValueAliasDeclaration: ts.notImplemented,
+ isReferencedAliasDeclaration: ts.notImplemented,
+ isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
+ getNodeCheckFlags: ts.notImplemented,
+ isDeclarationVisible: ts.notImplemented,
+ isLateBound: function (_node) { return false; },
+ collectLinkedAliases: ts.notImplemented,
+ isImplementationOfOverload: ts.notImplemented,
+ isRequiredInitializedParameter: ts.notImplemented,
+ isOptionalUninitializedParameterProperty: ts.notImplemented,
+ isExpandoFunctionDeclaration: ts.notImplemented,
+ getPropertiesOfContainerFunction: ts.notImplemented,
+ createTypeOfDeclaration: ts.notImplemented,
+ createReturnTypeOfSignatureDeclaration: ts.notImplemented,
+ createTypeOfExpression: ts.notImplemented,
+ createLiteralConstValue: ts.notImplemented,
+ isSymbolAccessible: ts.notImplemented,
+ isEntityNameVisible: ts.notImplemented,
+ // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
+ getConstantValue: ts.notImplemented,
+ getReferencedValueDeclaration: ts.notImplemented,
+ getTypeReferenceSerializationKind: ts.notImplemented,
+ isOptionalParameter: ts.notImplemented,
+ moduleExportsSomeValue: ts.notImplemented,
+ isArgumentsLocalBinding: ts.notImplemented,
+ getExternalModuleFileFromDeclaration: ts.notImplemented,
+ getTypeReferenceDirectivesForEntityName: ts.notImplemented,
+ getTypeReferenceDirectivesForSymbol: ts.notImplemented,
+ isLiteralConstDeclaration: ts.notImplemented,
+ getJsxFactoryEntity: ts.notImplemented,
+ getAllAccessorDeclarations: ts.notImplemented,
+ getSymbolOfExternalModuleSpecifier: ts.notImplemented,
+ isBindingCapturedByNode: ts.notImplemented,
+ };
+ function createSourceFilesFromBundleBuildInfo(bundle) {
+ var sourceFiles = bundle.sourceFiles.map(function (fileName) {
+ var sourceFile = ts.createNode(284 /* SourceFile */, 0, 0);
+ sourceFile.fileName = fileName;
+ sourceFile.text = "";
+ sourceFile.statements = ts.createNodeArray();
+ return sourceFile;
+ });
+ var jsBundle = ts.Debug.assertDefined(bundle.js);
+ ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
+ var sourceFile = sourceFiles[prologueInfo.file];
+ sourceFile.text = prologueInfo.text;
+ sourceFile.end = prologueInfo.text.length;
+ sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
+ var statement = ts.createNode(221 /* ExpressionStatement */, directive.pos, directive.end);
+ statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
+ statement.expression.text = directive.expression.text;
+ return statement;
+ }));
+ });
+ return sourceFiles;
+ }
+ /*@internal*/
+ function emitUsingBuildInfo(config, host, getCommandLine) {
+ var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
+ var buildInfoText = host.readFile(ts.Debug.assertDefined(buildInfoPath));
+ if (!buildInfoText)
+ return buildInfoPath;
+ var jsFileText = host.readFile(ts.Debug.assertDefined(jsFilePath));
+ if (!jsFileText)
+ return jsFilePath;
+ var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
+ // error if no source map or for now if inline sourcemap
+ if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
+ return sourceMapFilePath || "inline sourcemap decoding";
+ // read declaration text
+ var declarationText = declarationFilePath && host.readFile(declarationFilePath);
+ if (declarationFilePath && !declarationText)
+ return declarationFilePath;
+ var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
+ // error if no source map or for now if inline sourcemap
+ if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
+ return declarationMapPath || "inline sourcemap decoding";
+ var buildInfo = getBuildInfo(buildInfoText);
+ if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
+ return buildInfoPath;
+ var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo,
+ /*onlyOwnText*/ true);
+ var outputFiles = [];
+ var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
+ var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle);
+ var emitHost = {
+ getPrependNodes: ts.memoize(function () { return prependNodes.concat([ownPrependInput]); }),
+ getCanonicalFileName: host.getCanonicalFileName,
+ getCommonSourceDirectory: function () { return buildInfo.bundle.commonSourceDirectory; },
+ getCompilerOptions: function () { return config.options; },
+ getCurrentDirectory: function () { return host.getCurrentDirectory(); },
+ getNewLine: function () { return host.getNewLine(); },
+ getSourceFile: function () { return undefined; },
+ getSourceFileByPath: function () { return undefined; },
+ getSourceFiles: function () { return sourceFilesForJsEmit; },
+ getLibFileFromReference: ts.notImplemented,
+ isSourceFileFromExternalLibrary: ts.returnFalse,
+ writeFile: function (name, text, writeByteOrderMark) {
+ switch (name) {
+ case jsFilePath:
+ if (jsFileText === text)
+ return;
+ break;
+ case sourceMapFilePath:
+ if (sourceMapText === text)
+ return;
+ break;
+ case buildInfoPath:
+ var newBuildInfo = getBuildInfo(text);
+ newBuildInfo.program = buildInfo.program;
+ // Update sourceFileInfo
+ var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
+ newBuildInfo.bundle.js.sources = js.sources;
+ if (dts) {
+ newBuildInfo.bundle.dts.sources = dts.sources;
+ }
+ newBuildInfo.bundle.sourceFiles = sourceFiles;
+ outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
+ return;
+ case declarationFilePath:
+ if (declarationText === text)
+ return;
+ break;
+ case declarationMapPath:
+ if (declarationMapText === text)
+ return;
+ break;
+ default:
+ ts.Debug.fail("Unexpected path: " + name);
+ }
+ outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
+ },
+ isEmitBlocked: ts.returnFalse,
+ readFile: function (f) { return host.readFile(f); },
+ fileExists: function (f) { return host.fileExists(f); },
+ directoryExists: host.directoryExists && (function (f) { return host.directoryExists(f); }),
+ useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
+ getProgramBuildInfo: function () { return undefined; }
+ };
+ emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, /*emitOnlyDtsFiles*/ false, ts.getTransformers(config.options));
+ return outputFiles;
+ }
+ ts.emitUsingBuildInfo = emitUsingBuildInfo;
var PipelinePhase;
(function (PipelinePhase) {
PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
@@ -82741,6 +83397,10 @@ var ts;
var ownWriter; // Reusable `EmitTextWriter` for basic printing.
var write = writeBase;
var isOwnFileEmit;
+ var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
+ var recordInternalSection = printerOptions.recordInternalSection;
+ var sourceFileTextPos = 0;
+ var sourceFileTextKind = "text" /* Text */;
// Source Maps
var sourceMapsDisabled = true;
var sourceMapGenerator;
@@ -82766,7 +83426,8 @@ var ts;
writeNode: writeNode,
writeList: writeList,
writeFile: writeFile,
- writeBundle: writeBundle
+ writeBundle: writeBundle,
+ bundleFileInfo: bundleFileInfo
};
function printNode(hint, node, sourceFile) {
switch (hint) {
@@ -82781,9 +83442,9 @@ var ts;
break;
}
switch (node.kind) {
- case 279 /* SourceFile */: return printFile(node);
- case 280 /* Bundle */: return printBundle(node);
- case 281 /* UnparsedSource */: return printUnparsedSource(node);
+ case 284 /* SourceFile */: return printFile(node);
+ case 285 /* Bundle */: return printBundle(node);
+ case 286 /* UnparsedSource */: return printUnparsedSource(node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
@@ -82793,7 +83454,7 @@ var ts;
return endPrint();
}
function printBundle(bundle) {
- writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined);
+ writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
return endPrint();
}
function printFile(sourceFile) {
@@ -82821,7 +83482,49 @@ var ts;
reset();
writer = previousWriter;
}
- function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) {
+ function getTextPosWithWriteLine() {
+ return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
+ }
+ function updateOrPushBundleFileTextLike(pos, end, kind) {
+ var last = ts.lastOrUndefined(bundleFileInfo.sections);
+ if (last && last.kind === kind) {
+ last.end = end;
+ }
+ else {
+ bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
+ }
+ }
+ function recordBundleFileInternalSectionStart(node) {
+ if (recordInternalSection &&
+ bundleFileInfo &&
+ currentSourceFile &&
+ (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
+ ts.isInternalDeclaration(node, currentSourceFile) &&
+ sourceFileTextKind !== "internal" /* Internal */) {
+ var prevSourceFileTextKind = sourceFileTextKind;
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = "internal" /* Internal */;
+ return prevSourceFileTextKind;
+ }
+ return undefined;
+ }
+ function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
+ if (prevSourceFileTextKind) {
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = prevSourceFileTextKind;
+ }
+ }
+ function recordBundleFileTextLikeSection(end) {
+ if (sourceFileTextPos < end) {
+ updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
+ return true;
+ }
+ return false;
+ }
+ function writeBundle(bundle, output, sourceMapGenerator) {
+ var _a;
isOwnFileEmit = false;
var previousWriter = writer;
setWriter(output, sourceMapGenerator);
@@ -82829,18 +83532,49 @@ var ts;
emitPrologueDirectivesIfNeeded(bundle);
emitHelpers(bundle);
emitSyntheticTripleSlashReferencesIfNeeded(bundle);
- for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) {
- var prepend = _b[_a];
+ for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
+ var prepend = _c[_b];
writeLine();
+ var pos = writer.getTextPos();
+ var savedSections = bundleFileInfo && bundleFileInfo.sections;
+ if (savedSections)
+ bundleFileInfo.sections = [];
print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
+ if (bundleFileInfo) {
+ var newSections = bundleFileInfo.sections;
+ bundleFileInfo.sections = savedSections;
+ if (prepend.oldFileOfCurrentEmit)
+ (_a = bundleFileInfo.sections).push.apply(_a, newSections);
+ else {
+ newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prepend" /* Prepend */, data: prepend.fileName, texts: newSections });
+ }
+ }
}
- if (bundleInfo) {
- bundleInfo.originalOffset = writer.getTextPos();
- }
- for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) {
- var sourceFile = _d[_c];
+ sourceFileTextPos = getTextPosWithWriteLine();
+ for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
+ var sourceFile = _e[_d];
print(0 /* SourceFile */, sourceFile, sourceFile);
}
+ if (bundleFileInfo && bundle.sourceFiles.length) {
+ var end = writer.getTextPos();
+ if (recordBundleFileTextLikeSection(end)) {
+ // Store prologues
+ var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
+ if (prologues) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.prologues = prologues;
+ }
+ // Store helpes
+ var helpers = getHelpersFromBundledSourceFiles(bundle);
+ if (helpers) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.helpers = helpers;
+ }
+ }
+ }
reset();
writer = previousWriter;
}
@@ -82910,8 +83644,10 @@ var ts;
function emit(node) {
if (node === undefined)
return;
+ var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
var pipelinePhase = getPipelinePhase(0 /* Notification */, node);
pipelinePhase(4 /* Unspecified */, node);
+ recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
}
function emitIdentifierName(node) {
if (node === undefined)
@@ -82938,12 +83674,12 @@ var ts;
}
// falls through
case 2 /* Comments */:
- if (!commentsDisabled && node.kind !== 279 /* SourceFile */) {
+ if (!commentsDisabled && node.kind !== 284 /* SourceFile */) {
return pipelineEmitWithComments;
}
// falls through
case 3 /* SourceMaps */:
- if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) {
+ if (!sourceMapsDisabled && node.kind !== 284 /* SourceFile */ && !ts.isInJsonFile(node)) {
return pipelineEmitWithSourceMap;
}
// falls through
@@ -82980,8 +83716,16 @@ var ts;
case 16 /* TemplateMiddle */:
case 17 /* TemplateTail */:
return emitLiteral(node);
- case 281 /* UnparsedSource */:
- return emitUnparsedSource(node);
+ case 286 /* UnparsedSource */:
+ case 280 /* UnparsedPrepend */:
+ return emitUnparsedSourceOrPrepend(node);
+ case 279 /* UnparsedPrologue */:
+ return writeUnparsedNode(node);
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return emitUnparsedTextLike(node);
+ case 283 /* UnparsedSyntheticReference */:
+ return emitUnparsedSyntheticReference(node);
// Identifiers
case 72 /* Identifier */:
return emitIdentifier(node);
@@ -83025,7 +83769,7 @@ var ts;
return emitTypeReference(node);
case 165 /* FunctionType */:
return emitFunctionType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return emitJSDocFunctionType(node);
case 166 /* ConstructorType */:
return emitConstructorType(node);
@@ -83063,20 +83807,20 @@ var ts;
return emitLiteralType(node);
case 183 /* ImportType */:
return emitImportTypeNode(node);
- case 284 /* JSDocAllType */:
+ case 289 /* JSDocAllType */:
writePunctuation("*");
return;
- case 285 /* JSDocUnknownType */:
+ case 290 /* JSDocUnknownType */:
writePunctuation("?");
return;
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return emitJSDocNullableType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return emitJSDocNonNullableType(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return emitJSDocOptionalType(node);
case 172 /* RestType */:
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return emitRestOrJSDocVariadicType(node);
// Binding patterns
case 184 /* ObjectBindingPattern */:
@@ -83214,30 +83958,30 @@ var ts;
case 278 /* EnumMember */:
return emitEnumMember(node);
// JSDoc nodes (only used in codefixes currently)
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return emitJSDocPropertyLikeTag(node);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return emitJSDocSimpleTypedTag(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return emitJSDocAugmentsTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return emitJSDocTemplateTag(node);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return emitJSDocTypedefTag(node);
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return emitJSDocCallbackTag(node);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return emitJSDocSignature(node);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return emitJSDocTypeLiteral(node);
- case 296 /* JSDocClassTag */:
- case 294 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
return emitJSDocSimpleTag(node);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return emitJSDoc(node);
// Transformation nodes (ignored)
}
@@ -83336,9 +84080,9 @@ var ts;
case 264 /* JsxFragment */:
return emitJsxFragment(node);
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return emitPartiallyEmittedExpression(node);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return emitCommaList(node);
}
}
@@ -83354,22 +84098,45 @@ var ts;
var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node);
pipelinePhase(hint, substituteNode(hint, node));
}
+ function getHelpersFromBundledSourceFiles(bundle) {
+ var result;
+ if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
+ return undefined;
+ }
+ var bundledHelpers = ts.createMap();
+ for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
+ var sourceFile = _b[_a];
+ var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
+ var helpers = getSortedEmitHelpers(sourceFile);
+ if (!helpers)
+ continue;
+ for (var _c = 0, helpers_3 = helpers; _c < helpers_3.length; _c++) {
+ var helper = helpers_3[_c];
+ if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
+ bundledHelpers.set(helper.name, true);
+ (result || (result = [])).push(helper.name);
+ }
+ }
+ }
+ return result;
+ }
function emitHelpers(node) {
var helpersEmitted = false;
- var bundle = node.kind === 280 /* Bundle */ ? node : undefined;
+ var bundle = node.kind === 285 /* Bundle */ ? node : undefined;
if (bundle && moduleKind === ts.ModuleKind.None) {
return;
}
- var numNodes = bundle ? bundle.sourceFiles.length : 1;
+ var numPrepends = bundle ? bundle.prepends.length : 0;
+ var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
for (var i = 0; i < numNodes; i++) {
- var currentNode = bundle ? bundle.sourceFiles[i] : node;
- var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile;
- var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined;
- var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit;
- var helpers = ts.getEmitHelpers(currentNode);
+ var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
+ var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
+ var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined);
+ var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
+ var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
if (helpers) {
- for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) {
- var helper = _b[_a];
+ for (var _a = 0, helpers_4 = helpers; _a < helpers_4.length; _a++) {
+ var helper = helpers_4[_a];
if (!helper.scoped) {
// Skip the helper if it can be skipped and the noEmitHelpers compiler
// option is set, or if it can be imported and the importHelpers compiler
@@ -83389,18 +84156,25 @@ var ts;
// Skip the helper if it is scoped and we are emitting bundled helpers
continue;
}
+ var pos = getTextPosWithWriteLine();
if (typeof helper.text === "string") {
writeLines(helper.text);
}
else {
writeLines(helper.text(makeFileLevelOptimisticUniqueName));
}
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
helpersEmitted = true;
}
}
}
return helpersEmitted;
}
+ function getSortedEmitHelpers(node) {
+ var helpers = ts.getEmitHelpers(node);
+ return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
+ }
//
// Literals/Pseudo-literals
//
@@ -83427,8 +84201,42 @@ var ts;
}
}
// SyntaxKind.UnparsedSource
- function emitUnparsedSource(unparsed) {
- writer.rawWrite(unparsed.text);
+ // SyntaxKind.UnparsedPrepend
+ function emitUnparsedSourceOrPrepend(unparsed) {
+ for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
+ var text = _b[_a];
+ writeLine();
+ emit(text);
+ }
+ }
+ // SyntaxKind.UnparsedPrologue
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ // SyntaxKind.UnparsedSyntheticReference
+ function writeUnparsedNode(unparsed) {
+ writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
+ }
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ function emitUnparsedTextLike(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 281 /* UnparsedText */ ?
+ "text" /* Text */ :
+ "internal" /* Internal */);
+ }
+ }
+ // SyntaxKind.UnparsedSyntheticReference
+ function emitUnparsedSyntheticReference(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ var section = ts.clone(unparsed.section);
+ section.pos = pos;
+ section.end = writer.getTextPos();
+ bundleFileInfo.sections.push(section);
+ }
}
//
// Identifiers
@@ -83483,7 +84291,7 @@ var ts;
emit(node.dotDotDotToken);
emitNodeWithWriter(node.name, writeParameter);
emit(node.questionToken);
- if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) {
+ if (node.parent && node.parent.kind === 294 /* JSDocFunctionType */ && !node.name) {
emit(node.type);
}
else {
@@ -84363,7 +85171,7 @@ var ts;
}
function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
// Emit all the prologue directives (like "use strict").
- var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true);
+ var statementOffset = emitPrologueDirectives(body.statements);
var pos = writer.getTextPos();
emitHelpers(body);
if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
@@ -84768,7 +85576,7 @@ var ts;
}
}
if (node.tags) {
- if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) {
+ if (node.tags.length === 1 && node.tags[0].kind === 307 /* JSDocTypeTag */ && !node.comment) {
writeSpace();
emit(node.tags[0]);
}
@@ -84802,7 +85610,7 @@ var ts;
function emitJSDocTypedefTag(tag) {
emitJSDocTagName(tag.tagName);
if (tag.typeExpression) {
- if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
emitJSDocTypeExpression(tag.typeExpression);
}
else {
@@ -84821,7 +85629,7 @@ var ts;
emit(tag.fullName);
}
emitJSDocComment(tag.comment);
- if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) {
+ if (tag.typeExpression && tag.typeExpression.kind === 297 /* JSDocTypeLiteral */) {
emitJSDocTypeLiteral(tag.typeExpression);
}
}
@@ -84908,6 +85716,16 @@ var ts;
}
function emitSyntheticTripleSlashReferencesIfNeeded(node) {
emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
+ for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
+ for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
+ var ref = _d[_c];
+ emit(ref);
+ writeLine();
+ }
+ }
+ }
}
function emitTripleSlashDirectivesIfNeeded(node) {
if (node.isDeclarationFile)
@@ -84915,7 +85733,10 @@ var ts;
}
function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
if (hasNoDefaultLib) {
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
writeLine();
}
if (currentSourceFile && currentSourceFile.moduleName) {
@@ -84936,17 +85757,26 @@ var ts;
}
for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
var directive = files_1[_c];
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
writeLine();
}
for (var _d = 0, types_19 = types; _d < types_19.length; _d++) {
var directive = types_19[_d];
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
writeLine();
}
for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
var directive = libs_1[_e];
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
writeLine();
}
}
@@ -84971,16 +85801,22 @@ var ts;
* Emits any prologue directives at the start of a Statement list, returning the
* number of prologue directives written to the output.
*/
- function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) {
+ function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
+ var needsToSetSourceFile = !!sourceFile;
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (ts.isPrologueDirective(statement)) {
var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
if (shouldEmitPrologueDirective) {
- if (startWithNewLine || i > 0) {
- writeLine();
+ if (needsToSetSourceFile) {
+ needsToSetSourceFile = false;
+ setSourceFile(sourceFile);
}
+ writeLine();
+ var pos = writer.getTextPos();
emit(statement);
+ if (recordBundleFileSection && bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
if (seenPrologueDirectives) {
seenPrologueDirectives.set(statement.expression.text, true);
}
@@ -84993,23 +85829,70 @@ var ts;
}
return statements.length;
}
+ function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
+ for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
+ var prologue = prologues_1[_a];
+ if (!seenPrologueDirectives.has(prologue.data)) {
+ writeLine();
+ var pos = writer.getTextPos();
+ emit(prologue);
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
+ if (seenPrologueDirectives) {
+ seenPrologueDirectives.set(prologue.data, true);
+ }
+ }
+ }
+ }
function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
if (ts.isSourceFile(sourceFileOrBundle)) {
- setSourceFile(sourceFileOrBundle);
- emitPrologueDirectives(sourceFileOrBundle.statements);
+ emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
}
else {
var seenPrologueDirectives = ts.createMap();
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
- setSourceFile(sourceFile);
- emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives);
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
+ emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
}
setSourceFile(undefined);
}
}
+ function getPrologueDirectivesFromBundledSourceFiles(bundle) {
+ var seenPrologueDirectives = ts.createMap();
+ var prologues;
+ for (var index = 0; index < bundle.sourceFiles.length; index++) {
+ var sourceFile = bundle.sourceFiles[index];
+ var directives = void 0;
+ var end = 0;
+ for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
+ var statement = _b[_a];
+ if (!ts.isPrologueDirective(statement))
+ break;
+ if (seenPrologueDirectives.has(statement.expression.text))
+ continue;
+ seenPrologueDirectives.set(statement.expression.text, true);
+ (directives || (directives = [])).push({
+ pos: statement.pos,
+ end: statement.end,
+ expression: {
+ pos: statement.expression.pos,
+ end: statement.expression.end,
+ text: statement.expression.text
+ }
+ });
+ end = end < statement.end ? statement.end : end;
+ }
+ if (directives)
+ (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
+ }
+ return prologues;
+ }
function emitShebangIfNeeded(sourceFileOrBundle) {
- if (ts.isSourceFile(sourceFileOrBundle)) {
+ if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
var shebang = ts.getShebang(sourceFileOrBundle.text);
if (shebang) {
writeComment(shebang);
@@ -85018,11 +85901,18 @@ var ts;
}
}
else {
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ ts.Debug.assertNode(prepend, ts.isUnparsedSource);
+ if (emitShebangIfNeeded(prepend)) {
+ return true;
+ }
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
// Emit only the first encountered shebang
if (emitShebangIfNeeded(sourceFile)) {
- break;
+ return true;
}
}
}
@@ -85225,6 +86115,7 @@ var ts;
}
// Emit each child.
var previousSibling = void 0;
+ var previousSourceFileTextKind = void 0;
var shouldDecreaseIndentAfterEmit = false;
for (var i = 0; i < count; i++) {
var child = children[start + i];
@@ -85245,6 +86136,7 @@ var ts;
emitLeadingCommentsOfPosition(previousSibling.end);
}
writeDelimiter(format);
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write either a line terminator or whitespace to separate the elements.
if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) {
// If a synthesized node in a single-line list starts on a new
@@ -85261,6 +86153,7 @@ var ts;
}
}
// Emit this child.
+ previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
if (shouldEmitInterveningComments) {
if (emitTrailingCommentsOfPosition) {
var commentRange = ts.getCommentRange(child);
@@ -85295,6 +86188,7 @@ var ts;
if (format & 128 /* Indented */) {
decreaseIndent();
}
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write the closing line terminator or closing whitespace.
if (shouldWriteClosingLineTerminator(parentNode, children, format)) {
writeLine();
@@ -85396,7 +86290,6 @@ var ts;
if (line.length) {
writeLine();
write(line);
- writer.rawWrite(newLine);
}
}
}
@@ -85910,7 +86803,7 @@ var ts;
hasWrittenComment = false;
var emitFlags = ts.getEmitFlags(node);
var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
- var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */;
+ var isEmittedNode = node.kind !== 312 /* NotEmittedStatement */;
// We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
// It is expensive to walk entire tree just to set one kind of node to have no comments.
var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
@@ -86170,19 +87063,28 @@ var ts;
return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
}
// Source Maps
+ function getParsedSourceMap(node) {
+ if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
+ node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
+ }
+ return node.parsedSourceMap || undefined;
+ }
function pipelineEmitWithSourceMap(hint, node) {
var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node);
- if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) {
- var parsed = ts.tryParseRawSourceMap(node.sourceMapText);
- if (parsed) {
- sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath);
+ if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
+ pipelinePhase(hint, node);
+ }
+ else if (ts.isUnparsedNode(node)) {
+ var parsed = getParsedSourceMap(node.parent);
+ if (parsed && sourceMapGenerator) {
+ sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
}
pipelinePhase(hint, node);
}
else {
var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
var emitFlags = ts.getEmitFlags(node);
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 16 /* NoLeadingSourceMap */) === 0
&& pos >= 0) {
emitSourcePos(source, skipSourceTrivia(source, pos));
@@ -86195,7 +87097,7 @@ var ts;
else {
pipelinePhase(hint, node);
}
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 32 /* NoTrailingSourceMap */) === 0
&& end >= 0) {
emitSourcePos(source, end);
@@ -86843,7 +87745,8 @@ var ts;
var value = readFileCache.get(key);
if (value !== undefined)
return value !== false ? value : undefined; // could be .d.ts from output
- if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) {
+ // Cache json or buildInfo
+ if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
return originalReadFile.call(host, fileName);
}
return setReadFileCache(key, fileName);
@@ -86874,7 +87777,7 @@ var ts;
var key = toPath(fileName);
fileExistsCache.delete(key);
var value = readFileCache.get(key);
- if (value && value !== data) {
+ if (value !== undefined && value !== data) {
readFileCache.delete(key);
sourceFileCache.delete(key);
}
@@ -87429,7 +88332,8 @@ var ts;
getProjectReferenceRedirect: getProjectReferenceRedirect,
getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
- forEachResolvedProjectReference: forEachResolvedProjectReference
+ forEachResolvedProjectReference: forEachResolvedProjectReference,
+ emitBuildInfo: emitBuildInfo
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -87856,7 +88760,20 @@ var ts;
return false;
// Before falling back to the host
return host.fileExists(f);
- } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } });
+ } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); } });
+ }
+ function emitBuildInfo(writeFileCallback) {
+ ts.Debug.assert(!options.out && !options.outFile);
+ ts.performance.mark("beforeEmit");
+ var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback),
+ /*targetSourceFile*/ undefined,
+ /*emitOnlyDtsFiles*/ false,
+ /*transformers*/ undefined,
+ /*declaraitonTransformers*/ undefined,
+ /*onlyBuildInfo*/ true);
+ ts.performance.mark("afterEmit");
+ ts.performance.measure("Emit", "beforeEmit", "afterEmit");
+ return emitResult;
}
function getResolvedProjectReferences() {
return resolvedProjectReferences;
@@ -87865,28 +88782,11 @@ var ts;
return projectReferences;
}
function getPrependNodes() {
- if (!projectReferences) {
- return ts.emptyArray;
- }
- var nodes = [];
- for (var i = 0; i < projectReferences.length; i++) {
- var ref = projectReferences[i];
- var resolvedRefOpts = resolvedProjectReferences[i].commandLine;
- if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
- var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
- // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
- if (!out)
- continue;
- var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
- var node = ts.createInputFiles(function (fileName) {
- var path = toPath(fileName);
- var sourceFile = getSourceFileByPath(path);
- return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
- }, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath);
- nodes.push(node);
- }
- }
- return nodes;
+ return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
+ var path = toPath(fileName);
+ var sourceFile = getSourceFileByPath(path);
+ return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
+ });
}
function isSourceFileFromExternalLibrary(file) {
return !!sourceFilesFoundSearchingNodeModules.get(file.path);
@@ -87958,8 +88858,7 @@ var ts;
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
ts.performance.mark("beforeEmit");
var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers);
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217
- emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -88961,6 +89860,14 @@ var ts;
if (options.declaration === false) {
createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
}
+ if (options.incremental === false) {
+ createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
+ }
+ }
+ if (options.tsBuildInfoFile) {
+ if (!ts.isIncrementalCompilation(options)) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
+ }
}
verifyProjectReferences();
// List of collected files is complete; validate exhautiveness if this is a project with a file list
@@ -89155,6 +90062,7 @@ var ts;
}
}
function verifyProjectReferences() {
+ var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getOutputPathForBuildInfo(options) : undefined;
forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
var parentFile = parent && parent.sourceFile;
@@ -89181,6 +90089,10 @@ var ts;
createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
}
}
+ if (!parent && buildInfoPath && buildInfoPath === ts.getOutputPathForBuildInfo(options)) {
+ createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
+ hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
+ }
});
}
function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
@@ -89330,6 +90242,27 @@ var ts;
};
}
ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
+ /* @internal */
+ function createPrependNodes(projectReferences, getCommandLine, readFile) {
+ if (!projectReferences)
+ return ts.emptyArray;
+ var nodes;
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = getCommandLine(ref, i);
+ if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
+ var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
+ // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
+ if (!out)
+ continue;
+ var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
+ (nodes || (nodes = [])).push(node);
+ }
+ }
+ return nodes || ts.emptyArray;
+ }
+ ts.createPrependNodes = createPrependNodes;
function resolveProjectReferencePath(hostOrRef, ref) {
var passedInRef = ref ? ref : hostOrRef;
return ts.resolveConfigFileProjectName(passedInRef.path);
@@ -89873,11 +90806,14 @@ var ts;
var affectedSignatures = oldState.currentAffectedFilesSignatures;
ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
}
+ var changedFilesSet = oldState.changedFilesSet;
if (canCopySemanticDiagnostics) {
- ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
+ ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
}
// Copy old state's changed files set
- ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet);
+ if (changedFilesSet) {
+ ts.copyEntries(changedFilesSet, state.changedFilesSet);
+ }
if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit;
state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
@@ -89915,7 +90851,7 @@ var ts;
// Unchanged file copy diagnostics
var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
if (diagnostics) {
- state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics);
+ state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics);
if (!state.semanticDiagnosticsFromOldState) {
state.semanticDiagnosticsFromOldState = ts.createMap();
}
@@ -89923,8 +90859,45 @@ var ts;
}
}
});
+ if (oldCompilerOptions &&
+ (oldCompilerOptions.outDir !== compilerOptions.outDir ||
+ oldCompilerOptions.declarationDir !== compilerOptions.declarationDir ||
+ (oldCompilerOptions.outFile || oldCompilerOptions.out) !== (compilerOptions.outFile || compilerOptions.out))) {
+ // Add all files to affectedFilesPendingEmit since emit changed
+ state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, newProgram.getSourceFiles().map(function (f) { return f.path; }));
+ if (state.affectedFilesPendingEmitIndex === undefined) {
+ state.affectedFilesPendingEmitIndex = 0;
+ }
+ ts.Debug.assert(state.seenAffectedFiles === undefined);
+ state.seenAffectedFiles = ts.createMap();
+ }
return state;
}
+ function convertToDiagnostics(diagnostics, newProgram) {
+ if (!diagnostics.length)
+ return ts.emptyArray;
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToDiagnosticRelatedInformation(diagnostic, newProgram) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && newProgram.getSourceFileByPath(file), messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToDiagnosticMessageChain(messageText, newProgram) });
+ }
+ function convertToDiagnosticMessageChain(diagnostic, newProgram) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToDiagnosticMessageChain(diagnostic.next, newProgram) });
+ }
/**
* Releases program and other related not needed properties
*/
@@ -90144,8 +91117,11 @@ var ts;
* This is called after completing operation on the next affected file.
* The operations here are postponed to ensure that cancellation during the iteration is handled correctly
*/
- function doneWithAffectedFile(state, affected, isPendingEmit) {
- if (affected === state.program) {
+ function doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit) {
+ if (isBuildInfoEmit) {
+ state.emittedBuildInfo = true;
+ }
+ else if (affected === state.program) {
state.changedFilesSet.clear();
state.programEmitComplete = true;
}
@@ -90162,8 +91138,8 @@ var ts;
/**
* Returns the result with affected file
*/
- function toAffectedFileResult(state, result, affected, isPendingEmit) {
- doneWithAffectedFile(state, affected, isPendingEmit);
+ function toAffectedFileResult(state, result, affected, isPendingEmit, isBuildInfoEmit) {
+ doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit);
return { result: result, affected: affected };
}
/**
@@ -90186,6 +91162,77 @@ var ts;
}
return diagnostics;
}
+ /**
+ * Gets the program information to be emitted in buildInfo so that we can use it to create new program
+ */
+ function getProgramBuildInfo(state) {
+ if (state.compilerOptions.outFile || state.compilerOptions.out)
+ return undefined;
+ var fileInfos = {};
+ state.fileInfos.forEach(function (value, key) {
+ var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
+ fileInfos[key] = signature === undefined ? value : { version: value.version, signature: signature };
+ });
+ var result = { fileInfos: fileInfos, options: state.compilerOptions };
+ if (state.referencedMap) {
+ var referencedMap_1 = {};
+ state.referencedMap.forEach(function (value, key) {
+ referencedMap_1[key] = ts.arrayFrom(value.keys());
+ });
+ result.referencedMap = referencedMap_1;
+ }
+ if (state.exportedModulesMap) {
+ var exportedModulesMap_1 = {};
+ state.exportedModulesMap.forEach(function (value, key) {
+ var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
+ // Not in temporary cache, use existing value
+ if (newValue === undefined)
+ exportedModulesMap_1[key] = ts.arrayFrom(value.keys());
+ // Value in cache and has updated value map, use that
+ else if (newValue)
+ exportedModulesMap_1[key] = ts.arrayFrom(newValue.keys());
+ });
+ result.exportedModulesMap = exportedModulesMap_1;
+ }
+ if (state.semanticDiagnosticsPerFile) {
+ var semanticDiagnosticsPerFile_1 = [];
+ // Currently not recording actual errors since those mean no emit for tsc --build
+ state.semanticDiagnosticsPerFile.forEach(function (value, key) { return semanticDiagnosticsPerFile_1.push(value.length ?
+ [
+ key,
+ state.hasReusableDiagnostic ?
+ value :
+ convertToReusableDiagnostics(value)
+ ] :
+ key); });
+ result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile_1;
+ }
+ return result;
+ }
+ function convertToReusableDiagnostics(diagnostics) {
+ ts.Debug.assert(!!diagnostics.length);
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToReusableDiagnosticRelatedInformation(diagnostic);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToReusableDiagnosticRelatedInformation(diagnostic) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && file.path, messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToReusableDiagnosticMessageChain(messageText) });
+ }
+ function convertToReusableDiagnosticMessageChain(diagnostic) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToReusableDiagnosticMessageChain(diagnostic.next) });
+ }
var BuilderProgramKind;
(function (BuilderProgramKind) {
BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
@@ -90242,6 +91289,7 @@ var ts;
var computeHash = host.createHash || ts.generateDjb2Hash;
var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
var backupState;
+ newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state); };
// To ensure that we arent storing any references to old program or new program without state
newProgram = undefined; // TODO: GH#18217
oldProgram = undefined;
@@ -90285,7 +91333,16 @@ var ts;
if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
affected = getNextAffectedFilePendingEmit(state);
if (!affected) {
- return undefined;
+ if (state.emittedBuildInfo) {
+ return undefined;
+ }
+ var affected_1 = ts.Debug.assertDefined(state.program);
+ return toAffectedFileResult(state,
+ // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
+ // Otherwise just affected file
+ affected_1.emitBuildInfo(writeFile || host.writeFile, cancellationToken), affected_1,
+ /*isPendingEmitFile*/ false,
+ /*isBuildInfoEmit*/ true);
}
isPendingEmitFile = true;
}
@@ -90418,6 +91475,53 @@ var ts;
}
}
ts.createBuilderProgram = createBuilderProgram;
+ function getMapOfReferencedSet(mapLike) {
+ if (!mapLike)
+ return undefined;
+ var map = ts.createMap();
+ // Copies keys/values from template. Note that for..in will not throw if
+ // template is undefined, and instead will just exit the loop.
+ for (var key in mapLike) {
+ if (ts.hasProperty(mapLike, key)) {
+ map.set(key, ts.arrayToSet(mapLike[key]));
+ }
+ }
+ return map;
+ }
+ function createBuildProgramUsingProgramBuildInfo(program) {
+ var fileInfos = ts.createMapFromTemplate(program.fileInfos);
+ var state = {
+ fileInfos: fileInfos,
+ compilerOptions: program.options,
+ referencedMap: getMapOfReferencedSet(program.referencedMap),
+ exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap),
+ semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return ts.isString(value) ? value : value[0]; }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }),
+ hasReusableDiagnostic: true
+ };
+ return {
+ getState: function () { return state; },
+ backupState: ts.noop,
+ restoreState: ts.noop,
+ getProgram: ts.notImplemented,
+ getProgramOrUndefined: function () { return undefined; },
+ releaseProgram: ts.noop,
+ getCompilerOptions: function () { return state.compilerOptions; },
+ getSourceFile: ts.notImplemented,
+ getSourceFiles: ts.notImplemented,
+ getOptionsDiagnostics: ts.notImplemented,
+ getGlobalDiagnostics: ts.notImplemented,
+ getConfigFileParsingDiagnostics: ts.notImplemented,
+ getSyntacticDiagnostics: ts.notImplemented,
+ getDeclarationDiagnostics: ts.notImplemented,
+ getSemanticDiagnostics: ts.notImplemented,
+ emit: ts.notImplemented,
+ getAllDependencies: ts.notImplemented,
+ getCurrentDirectory: ts.notImplemented,
+ emitNextAffectedFile: ts.notImplemented,
+ getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
+ };
+ }
+ ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
return {
getState: ts.notImplemented,
@@ -90437,7 +91541,7 @@ var ts;
getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
getAllDependencies: ts.notImplemented,
- getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); }
+ getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
};
function getProgram() {
return ts.Debug.assertDefined(state.program);
@@ -90463,10 +91567,10 @@ var ts;
/*@internal*/
var ts;
(function (ts) {
- function isPathInNodeModulesStartingWithDot(path) {
- return ts.stringContains(path, "/node_modules/.");
+ function isPathIgnored(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); });
}
- ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot;
+ ts.isPathIgnored = isPathIgnored;
ts.maxNumberOfFilesToIterateForInvalidation = 256;
function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
var filesWithChangedSetOfUnresolvedImports;
@@ -90988,7 +92092,7 @@ var ts;
}
else {
// If something to do with folder/file starting with "." in node_modules folder, skip it
- if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (isPathIgnored(fileOrDirectoryPath))
return false;
// Some file or directory in the watching directory is created
// Return early if it does not have any of the watching extension or not the custom failed lookup path
@@ -91465,6 +92569,8 @@ var ts;
case ".jsx" /* Jsx */:
case ".json" /* Json */:
return ext;
+ case ".tsbuildinfo" /* TsBuildInfo */:
+ return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
default:
return ts.Debug.assertNever(ext);
}
@@ -91746,7 +92852,7 @@ var ts;
writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; },
createHash: ts.maybeBind(system, system.createHash),
- createProgram: createProgram
+ createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
};
}
ts.createProgramHost = createProgramHost;
@@ -91756,7 +92862,7 @@ var ts;
function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
var writeFileName = function (s) { return system.write(s + system.newLine); };
- var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram);
+ var result = createProgramHost(system, createProgram);
ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
result.afterProgramCreate = function (builderProgram) {
var compilerOptions = builderProgram.getCompilerOptions();
@@ -92185,7 +93291,7 @@ var ts;
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
nextSourceFileVersion(fileOrDirectoryPath);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
// If the the added or created file or directory is not supported file name, ignore the file
// But when watched directory is added/removed, we need to reload the file list
@@ -92239,16 +93345,23 @@ var ts;
* This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
*/
UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
- UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream";
- UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate";
- UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked";
- UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream";
+ /**
+ * The project appears out of date because its upstream inputs are newer than its outputs,
+ * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
+ * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
+ */
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
+ UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
+ UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
+ UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
+ UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
+ UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
/**
* Projects with no outputs (i.e. "solution" files)
*/
- UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly";
+ UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
})(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
function createFileMap(toPath) {
// tslint:disable-next-line:no-null-keyword
@@ -92329,24 +93442,18 @@ var ts;
}
return outputs;
}
- function getOutFileOutputs(project) {
- var out = project.options.outFile || project.options.out;
- if (!out) {
- return ts.Debug.fail("outFile must be set");
- }
+ function getOutFileOutputs(project, ignoreBuildInfo) {
+ ts.Debug.assert(!!project.options.outFile || !!project.options.out, "outFile must be set");
+ var _a = ts.getOutputPathsForBundle(project.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
var outputs = [];
- outputs.push(out);
- if (project.options.sourceMap) {
- outputs.push(out + ".map");
- }
- if (ts.getEmitDeclarations(project.options)) {
- var dts = ts.changeExtension(out, ".d.ts" /* Dts */);
- outputs.push(dts);
- if (project.options.declarationMap) {
- outputs.push(dts + ".map");
- }
- }
- return outputs;
+ var addOutput = function (path) { return path && (outputs || (outputs = [])).push(path); };
+ addOutput(jsFilePath);
+ addOutput(sourceMapFilePath);
+ addOutput(declarationFilePath);
+ addOutput(declarationMapPath);
+ if (!ignoreBuildInfo)
+ addOutput(buildInfoPath);
+ return outputs || ts.emptyArray;
}
function rootDirOfOptions(opts, configFileName) {
return opts.rootDir || ts.getDirectoryPath(configFileName);
@@ -92379,14 +93486,14 @@ var ts;
}
function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
host.reportErrorSummary = reportErrorSummary;
return host;
}
ts.createSolutionBuilderHost = createSolutionBuilderHost;
function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
var watchHost = ts.createWatchHost(system, reportWatchStatus);
ts.copyProperties(host, watchHost);
return host;
@@ -92420,7 +93527,18 @@ var ts;
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; });
var originalGetSourceFile = compilerHost.getSourceFile;
var computeHash = host.createHash || ts.generateDjb2Hash;
- updateGetSourceFile();
+ compilerHost.getSourceFile = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
+ if (result) {
+ result.version = computeHash.call(host, result.text);
+ }
+ return result;
+ };
+ var buildInfoChecked = createFileMap(toPath);
// Watch state
var builderPrograms = createFileMap(toPath);
var diagnostics = createFileMap(toPath);
@@ -92458,6 +93576,7 @@ var ts;
projectStatus.clear();
missingRoots.clear();
globalDependencyGraph = undefined;
+ buildInfoChecked.clear();
diagnostics.clear();
projectPendingBuild.clear();
projectErrorsReported.clear();
@@ -92472,29 +93591,6 @@ var ts;
ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); });
ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher);
builderPrograms.clear();
- updateGetSourceFile();
- }
- function updateGetSourceFile() {
- if (options.watch) {
- if (compilerHost.getSourceFile === originalGetSourceFile) {
- compilerHost.getSourceFile = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
- if (result && options.watch) {
- result.version = computeHash.call(host, result.text);
- }
- return result;
- };
- }
- }
- else {
- if (compilerHost.getSourceFile !== originalGetSourceFile) {
- compilerHost.getSourceFile = originalGetSourceFile;
- }
- }
}
function isParsedCommandLine(entry) {
return !!entry.options;
@@ -92726,25 +93822,28 @@ var ts;
upstreamProjectName: ref.path
};
}
- // If the upstream project's newest file is older than our oldest output, we
- // can't be out of date because of it
- if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
- continue;
- }
- // If the upstream project has only change .d.ts files, and we've built
- // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
- if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
- pseudoUpToDate = true;
- upstreamChangedProject = ref.path;
- continue;
+ // Check oldest output file name only if there is no missing output file name
+ if (!missingOutputFileName) {
+ // If the upstream project's newest file is older than our oldest output, we
+ // can't be out of date because of it
+ if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
+ continue;
+ }
+ // If the upstream project has only change .d.ts files, and we've built
+ // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
+ if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
+ pseudoUpToDate = true;
+ upstreamChangedProject = ref.path;
+ continue;
+ }
+ // We have an output older than an upstream output - we are out of date
+ ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
+ return {
+ type: UpToDateStatusType.OutOfDateWithUpstream,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerProjectName: ref.path
+ };
}
- // We have an output older than an upstream output - we are out of date
- ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
- return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: oldestOutputFileName,
- newerProjectName: ref.path
- };
}
}
if (missingOutputFileName !== undefined) {
@@ -92760,9 +93859,23 @@ var ts;
newerInputFileName: newestInputFileName
};
}
+ if (!buildInfoChecked.hasKey(project.options.configFilePath)) {
+ buildInfoChecked.setValue(project.options.configFilePath, true);
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath) {
+ var value = readFileWithCache(buildInfoPath);
+ var buildInfo = value && ts.getBuildInfo(value);
+ if (buildInfo && buildInfo.version !== ts.version) {
+ return {
+ type: UpToDateStatusType.TsVersionOutputOfDate,
+ version: buildInfo.version
+ };
+ }
+ }
+ }
if (usesPrepend && pseudoUpToDate) {
return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
+ type: UpToDateStatusType.OutOfDateWithPrepend,
outOfDateOutputFileName: oldestOutputFileName,
newerProjectName: upstreamChangedProject
};
@@ -92896,7 +94009,9 @@ var ts;
updateOutputTimestamps(proj);
return;
}
- var buildResult = buildSingleProject(resolved);
+ var buildResult = status.type === UpToDateStatusType.OutOfDateWithPrepend ?
+ updateBundle(resolved) : // Fake that files have been built by manipulating prepend and existing output
+ buildSingleProject(resolved); // Actual build
if (buildResult & BuildResultFlags.AnyErrors)
return;
var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue;
@@ -92912,17 +94027,26 @@ var ts;
// If declaration output is changed, build the project
// otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
var status_1 = projectStatus.getValue(project);
- if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
- if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) {
+ if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
+ if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes || status_1.type === UpToDateStatusType.OutOfDateWithPrepend)) {
projectStatus.setValue(project, {
type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: status_1.oldestOutputFileName,
+ outOfDateOutputFileName: status_1.type === UpToDateStatusType.OutOfDateWithPrepend ? status_1.outOfDateOutputFileName : status_1.oldestOutputFileName,
newerProjectName: resolved
});
}
}
else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) {
- status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
+ if (prepend) {
+ projectStatus.setValue(project, {
+ type: UpToDateStatusType.OutOfDateWithPrepend,
+ outOfDateOutputFileName: status_1.oldestOutputFileName,
+ newerProjectName: resolved
+ });
+ }
+ else {
+ status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
+ }
}
addProjToQueue(project);
}
@@ -92979,8 +94103,7 @@ var ts;
}
if (options.verbose)
reportStatus(ts.Diagnostics.Building_project_0, proj);
- var resultFlags = BuildResultFlags.None;
- resultFlags |= BuildResultFlags.DeclarationOutputUnchanged;
+ var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
var configFile = parseConfigFile(proj);
if (!configFile) {
// Failed to read the config file
@@ -92996,8 +94119,7 @@ var ts;
}
// TODO: handle resolve module name to cache result in project reference redirect
projectCompilerOptions = configFile.options;
- var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences);
- projectCompilerOptions = baseCompilerOptions;
+ var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, getOldProgram(proj, configFile), configFile.errors, configFile.projectReferences);
// Don't emit anything in the presence of syntactic errors or options diagnostics
var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
@@ -93058,12 +94180,14 @@ var ts;
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
}
}
@@ -93076,9 +94200,67 @@ var ts;
builderPrograms.setValue(proj, program);
}
}
+ function getOldProgram(proj, parsed) {
+ var value = builderPrograms.getValue(proj);
+ if (value)
+ return value;
+ var buildInfoPath = ts.getOutputPathForBuildInfo(parsed.options);
+ if (!buildInfoPath)
+ return undefined;
+ var content = readFileWithCache(buildInfoPath);
+ if (!content)
+ return undefined;
+ var buildInfo = ts.getBuildInfo(content);
+ if (buildInfo.version !== ts.version)
+ return undefined;
+ return buildInfo.program && ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program);
+ }
+ function updateBundle(proj) {
+ if (options.dry) {
+ reportStatus(ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, proj);
+ return BuildResultFlags.Success;
+ }
+ if (options.verbose)
+ reportStatus(ts.Diagnostics.Updating_output_of_project_0, proj);
+ // Update js, and source map
+ var config = ts.Debug.assertDefined(parseConfigFile(proj));
+ projectCompilerOptions = config.options;
+ var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) { return parseConfigFile(resolveProjectName(ref.path)); });
+ if (ts.isString(outputFiles)) {
+ reportStatus(ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, proj, relName(outputFiles));
+ return buildSingleProject(proj);
+ }
+ // Actual Emit
+ ts.Debug.assert(!!outputFiles.length);
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ var emittedOutputs = createFileMap(toPath);
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
+ emittedOutputs.setValue(name, true);
+ ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
+ });
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
+ reportAndStoreErrors(proj, emitDiagnostics);
+ projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Emit errors" });
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged | BuildResultFlags.EmitErrors;
+ }
+ // Update timestamps for dts
+ var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(config, minimumDate, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
+ oldestOutputFileName: outputFiles[0].name
+ };
+ diagnostics.removeKey(proj);
+ projectStatus.setValue(proj, status);
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged;
+ }
function updateOutputTimestamps(proj) {
if (options.dry) {
- return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath);
+ return reportStatus(ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
}
var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime });
@@ -93205,7 +94387,9 @@ var ts;
// Do nothing
continue;
}
- var buildResult = buildSingleProject(next);
+ var buildResult = status.type === UpToDateStatusType.OutOfDateWithPrepend && !options.force ?
+ updateBundle(next) : // Fake that files have been built by manipulating prepend and existing output
+ buildSingleProject(next); // Actual build
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
@@ -93267,6 +94451,9 @@ var ts;
var inputFile = _a[_i];
outputs.push.apply(outputs, getOutputFileNames(inputFile, project));
}
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath)
+ outputs.push(buildInfoPath);
return outputs;
}
}
@@ -93298,6 +94485,8 @@ var ts;
}
// Don't report anything for "up to date because it was already built" -- too verbose
break;
+ case UpToDateStatusType.OutOfDateWithPrepend:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(configFileName), relName(status.newerProjectName));
case UpToDateStatusType.UpToDateWithUpstreamTypes:
return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName));
case UpToDateStatusType.UpstreamOutOfDate:
@@ -93306,6 +94495,8 @@ var ts;
return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName));
case UpToDateStatusType.Unbuildable:
return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason);
+ case UpToDateStatusType.TsVersionOutputOfDate:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(configFileName), status.version, ts.version);
case UpToDateStatusType.ContainerOnly:
// Don't report status on "solution" projects
case UpToDateStatusType.ComputingUpstream:
@@ -93455,32 +94646,6 @@ var ts;
}
}
})(ts || (ts = {}));
-//# sourceMappingURL=compiler.js.map
-"use strict";
-var __assign = (this && this.__assign) || function () {
- __assign = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-var __extends = (this && this.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
-})();
var ts;
(function (ts) {
var ScriptSnapshot;
@@ -93798,7 +94963,7 @@ var ts;
case 242 /* TypeAliasDeclaration */:
case 168 /* TypeLiteral */:
return 2 /* Type */;
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
// If it has no name node, it shares the name with the value declaration below it.
return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */;
case 278 /* EnumMember */:
@@ -93823,14 +94988,14 @@ var ts;
case 255 /* ExportDeclaration */:
return 7 /* All */;
// An external module can be a Value
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 4 /* Namespace */ | 1 /* Value */;
}
return 7 /* All */;
}
ts.getMeaningFromDeclaration = getMeaningFromDeclaration;
function getMeaningFromLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return 1 /* Value */;
}
else if (node.parent.kind === 254 /* ExportAssignment */ || node.parent.kind === 259 /* ExternalModuleReference */) {
@@ -94036,7 +95201,7 @@ var ts;
return undefined;
}
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
case 239 /* FunctionDeclaration */:
@@ -94054,7 +95219,7 @@ var ts;
ts.getContainerNode = getContainerNode;
function getNodeKind(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */;
case 244 /* ModuleDeclaration */:
return "module" /* moduleElement */;
@@ -94063,8 +95228,8 @@ var ts;
return "class" /* classElement */;
case 241 /* InterfaceDeclaration */: return "interface" /* interfaceElement */;
case 242 /* TypeAliasDeclaration */:
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
return "type" /* typeElement */;
case 243 /* EnumDeclaration */: return "enum" /* enumElement */;
case 237 /* VariableDeclaration */:
@@ -94490,7 +95655,7 @@ var ts;
}
}
}
- ts.Debug.assert(startNode !== undefined || n.kind === 279 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
+ ts.Debug.assert(startNode !== undefined || n.kind === 284 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
// Here we know that none of child token nodes embrace the position,
// the only known case is when position is at the end of the file.
// Try to find the rightmost token in the file without filtering.
@@ -95337,6 +96502,17 @@ var ts;
return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName));
}
ts.getScriptKind = getScriptKind;
+ function getSymbolTarget(symbol) {
+ var next = symbol;
+ while (isTransientSymbol(next) && next.target) {
+ next = next.target;
+ }
+ return next;
+ }
+ ts.getSymbolTarget = getSymbolTarget;
+ function isTransientSymbol(symbol) {
+ return (symbol.flags & 33554432 /* Transient */) !== 0;
+ }
function getUniqueSymbolId(symbol, checker) {
return ts.getSymbolId(ts.skipAlias(symbol, checker));
}
@@ -95488,8 +96664,27 @@ var ts;
return lastPos;
}
ts.getRenameLocation = getRenameLocation;
- function copyComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
- ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) {
+ function copyLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
+ }
+ ts.copyLeadingComments = copyLeadingComments;
+ function copyTrailingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticTrailingComment));
+ }
+ ts.copyTrailingComments = copyTrailingComments;
+ /**
+ * This function copies the trailing comments for the token that comes before `sourceNode`, as leading comments of `targetNode`.
+ * This is useful because sometimes a comment that refers to `sourceNode` will be a leading comment for `sourceNode`, according to the
+ * notion of trivia ownership, and instead will be a trailing comment for the token before `sourceNode`, e.g.:
+ * `function foo(\* not leading comment for a *\ a: string) {}`
+ * The comment refers to `a` but belongs to the `(` token, but we might want to copy it.
+ */
+ function copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
+ }
+ ts.copyTrailingAsLeadingComments = copyTrailingAsLeadingComments;
+ function getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, cb) {
+ return function (pos, end, kind, htnl) {
if (kind === 3 /* MultiLineCommentTrivia */) {
// Remove leading /*
pos += 2;
@@ -95500,10 +96695,9 @@ var ts;
// Remove leading //
pos += 2;
}
- ts.addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
- });
+ cb(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
+ };
}
- ts.copyComments = copyComments;
function indexInTextChange(change, name) {
if (ts.startsWith(change, name))
return 0;
@@ -95584,6 +96778,30 @@ var ts;
return checker.getTypeAtLocation(caseClause.parent.parent.expression);
}
ts.getSwitchedType = getSwitchedType;
+ function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
+ var checker = program.getTypeChecker();
+ var typeIsAccessible = true;
+ var notAccessible = function () { typeIsAccessible = false; };
+ var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
+ trackSymbol: function (symbol, declaration, meaning) {
+ // TODO: GH#18217
+ typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
+ },
+ reportInaccessibleThisError: notAccessible,
+ reportPrivateInBaseOfClassExpression: notAccessible,
+ reportInaccessibleUniqueSymbolError: notAccessible,
+ moduleResolverHost: {
+ readFile: host.readFile,
+ fileExists: host.fileExists,
+ directoryExists: host.directoryExists,
+ getSourceFiles: program.getSourceFiles,
+ getCurrentDirectory: program.getCurrentDirectory,
+ getCommonSourceDirectory: program.getCommonSourceDirectory,
+ }
+ });
+ return typeIsAccessible ? res : undefined;
+ }
+ ts.getTypeNodeIfAccessible = getTypeNodeIfAccessible;
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -96235,18 +97453,18 @@ var ts;
pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param"
pos = tag.tagName.end;
switch (tag.kind) {
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
processJSDocParameterTag(tag);
break;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
processJSDocTemplateTag(tag);
pos = tag.end;
break;
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
- case 300 /* JSDocReturnTag */:
+ case 305 /* JSDocReturnTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
@@ -96550,6 +97768,7 @@ var ts;
case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */;
case ".ts" /* Ts */: return ".ts" /* tsModifier */;
case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */;
+ case ".tsbuildinfo" /* TsBuildInfo */: return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported.");
case undefined: return "" /* none */;
default:
return ts.Debug.assertNever(extension);
@@ -97574,7 +98793,7 @@ var ts;
return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker));
}
function isModuleSymbol(symbol) {
- return symbol.declarations.some(function (d) { return d.kind === 279 /* SourceFile */; });
+ return symbol.declarations.some(function (d) { return d.kind === 284 /* SourceFile */; });
}
function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) {
var typeChecker = program.getTypeChecker();
@@ -97625,11 +98844,11 @@ var ts;
if (tag.tagName.pos <= position && position <= tag.tagName.end) {
return { kind: 1 /* JsDocTagName */ };
}
- if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
currentToken = ts.getTokenAtPosition(sourceFile, position);
if (!currentToken ||
(!ts.isDeclarationName(currentToken) &&
- (currentToken.parent.kind !== 305 /* JSDocPropertyTag */ ||
+ (currentToken.parent.kind !== 310 /* JSDocPropertyTag */ ||
currentToken.parent.name !== currentToken))) {
// Use as type location if inside tag's type expression
insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
@@ -97800,11 +99019,11 @@ var ts;
return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer };
function isTagWithTypeExpression(tag) {
switch (tag.kind) {
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 304 /* JSDocTypedefTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 309 /* JSDocTypedefTag */:
return true;
default:
return false;
@@ -97844,7 +99063,7 @@ var ts;
}
}
// If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods).
- if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 279 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) {
+ if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 284 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) {
addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node));
}
return;
@@ -97977,7 +99196,7 @@ var ts;
var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */;
symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined");
// Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
- if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 279 /* SourceFile */) {
+ if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 284 /* SourceFile */) {
var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false);
if (thisType) {
for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) {
@@ -98010,7 +99229,7 @@ var ts;
}
function isSnippetScope(scopeNode) {
switch (scopeNode.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 206 /* TemplateExpression */:
case 270 /* JsxExpression */:
case 218 /* Block */:
@@ -98842,7 +100061,7 @@ var ts;
function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) {
// class c { method() { } | method2() { } }
switch (location.kind) {
- case 306 /* SyntaxList */:
+ case 311 /* SyntaxList */:
return ts.tryCast(location.parent, ts.isObjectTypeDeclaration);
case 1 /* EndOfFileToken */:
var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration);
@@ -99027,7 +100246,7 @@ var ts;
var child = throwStatement;
while (child.parent) {
var parent = child.parent;
- if (ts.isFunctionBlock(parent) || parent.kind === 279 /* SourceFile */) {
+ if (ts.isFunctionBlock(parent) || parent.kind === 284 /* SourceFile */) {
return parent;
}
// A throw-statement is only owned by a try-statement if the try-statement has
@@ -99085,7 +100304,7 @@ var ts;
var container = declaration.parent;
switch (container.kind) {
case 245 /* ModuleBlock */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 218 /* Block */:
case 271 /* CaseClause */:
case 272 /* DefaultClause */:
@@ -99583,7 +100802,7 @@ var ts;
}
else if (!isAvailableThroughGlobal) {
var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration);
- ts.Debug.assert(sourceFileLike.kind === 279 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */);
+ ts.Debug.assert(sourceFileLike.kind === 284 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */);
if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) {
addIndirectUsers(sourceFileLike);
}
@@ -99752,7 +100971,7 @@ var ts;
for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
var referencingFile = sourceFiles_1[_i];
var searchSourceFile = searchModuleSymbol.valueDeclaration;
- if (searchSourceFile.kind === 279 /* SourceFile */) {
+ if (searchSourceFile.kind === 284 /* SourceFile */) {
for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
var ref = _b[_a];
if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) {
@@ -99800,7 +101019,7 @@ var ts;
}
/** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */
function forEachPossibleImportOrExportStatement(sourceFileLike, action) {
- return ts.forEach(sourceFileLike.kind === 279 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
+ return ts.forEach(sourceFileLike.kind === 284 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action));
});
}
@@ -100024,7 +101243,7 @@ var ts;
return node.getSourceFile();
}
var parent = node.parent;
- if (parent.kind === 279 /* SourceFile */) {
+ if (parent.kind === 284 /* SourceFile */) {
return parent;
}
ts.Debug.assert(parent.kind === 245 /* ModuleBlock */);
@@ -100086,7 +101305,7 @@ var ts;
}
FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition;
function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return undefined;
}
var checker = program.getTypeChecker();
@@ -100306,8 +101525,8 @@ var ts;
case 248 /* ImportEqualsDeclaration */:
case 253 /* ImportSpecifier */:
case 241 /* InterfaceDeclaration */:
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
case 267 /* JsxAttribute */:
case 244 /* ModuleDeclaration */:
case 247 /* NamespaceExportDeclaration */:
@@ -100332,8 +101551,8 @@ var ts;
return !!decl.initializer || ts.isCatchClause(decl.parent);
case 155 /* MethodSignature */:
case 153 /* PropertySignature */:
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
return false;
default:
return ts.Debug.failBadSyntaxKind(decl);
@@ -100493,7 +101712,7 @@ var ts;
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
switch (decl.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.)
break;
case 244 /* ModuleDeclaration */:
@@ -100864,7 +102083,7 @@ var ts;
// Different declarations have different containers, bail out
return undefined;
}
- if (!container || container.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
+ if (!container || container.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
// This is a global variable and not an external module, any declaration defined
// within this scope is visible outside the file
return undefined;
@@ -101423,7 +102642,7 @@ var ts;
staticFlag &= ts.getModifierFlags(searchSpaceNode);
searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) {
return undefined;
}
@@ -101436,7 +102655,7 @@ var ts;
default:
return undefined;
}
- var references = ts.flatMap(searchSpaceNode.kind === 279 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
+ var references = ts.flatMap(searchSpaceNode.kind === 284 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) {
if (!ts.isThis(node)) {
@@ -101455,8 +102674,8 @@ var ts;
// Make sure the container belongs to the same class
// and has the appropriate static modifier from the original container.
return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag;
- case 279 /* SourceFile */:
- return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
+ case 284 /* SourceFile */:
+ return container.kind === 284 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
}
});
}).map(function (n) { return FindAllReferences.nodeEntry(n); });
@@ -102310,11 +103529,11 @@ var ts;
JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
function getCommentHavingNodes(declaration) {
switch (declaration.kind) {
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return [declaration];
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
return [declaration, declaration.parent];
default:
return ts.getJSDocCommentsAndTags(declaration);
@@ -102335,16 +103554,16 @@ var ts;
function getCommentText(tag) {
var comment = tag.comment;
switch (tag.kind) {
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return withNode(tag.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return withList(tag.typeParameters);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return withNode(tag.typeExpression);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
var name = tag.name;
return name ? withNode(name) : comment;
default:
@@ -102555,7 +103774,7 @@ var ts;
: undefined;
return { commentOwner: commentOwner, parameters: parameters_1 };
}
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return "quit";
case 244 /* ModuleDeclaration */:
// If in walking up the tree, we hit a a nested namespace declaration,
@@ -103115,7 +104334,7 @@ var ts;
}
}
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
var sourceFile = node;
return ts.isExternalModule(sourceFile)
? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\""
@@ -103167,10 +104386,10 @@ var ts;
case 243 /* EnumDeclaration */:
case 241 /* InterfaceDeclaration */:
case 244 /* ModuleDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 242 /* TypeAliasDeclaration */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return true;
case 157 /* Constructor */:
case 156 /* MethodDeclaration */:
@@ -103191,7 +104410,7 @@ var ts;
}
switch (navigationBarNodeKind(item.parent)) {
case 245 /* ModuleBlock */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
return true;
@@ -103276,7 +104495,7 @@ var ts;
return !member.name || member.name.kind === 149 /* ComputedPropertyName */;
}
function getNodeSpan(node) {
- return node.kind === 279 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
+ return node.kind === 284 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
}
function getModifiers(node) {
if (node.parent && node.parent.kind === 237 /* VariableDeclaration */) {
@@ -103397,8 +104616,8 @@ var ts;
else {
// Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: false,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include,
suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
});
}
@@ -105456,8 +106675,8 @@ var ts;
var name = importNameForConvertToDefaultImport(importNode);
if (!name)
continue;
- var module_1 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
- var resolvedFile = module_1 && program.getSourceFile(module_1.resolvedFileName);
+ var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
+ var resolvedFile = module && program.getSourceFile(module.resolvedFileName);
if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
}
@@ -106094,7 +107313,7 @@ var ts;
// For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo`
// there documentation comments might be attached to the right hand side symbol of their declarations.
// The pattern of such special property access is that the parent symbol is the symbol of the file.
- if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 279 /* SourceFile */; })) {
+ if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 284 /* SourceFile */; })) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
if (!declaration.parent || declaration.parent.kind !== 204 /* BinaryExpression */) {
@@ -106219,7 +107438,7 @@ var ts;
// If the parent is not sourceFile or module block it is local variable
for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) {
// Reached source file or module block
- if (parent.kind === 279 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) {
+ if (parent.kind === 284 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) {
return false;
}
}
@@ -107544,7 +108763,7 @@ var ts;
case 244 /* ModuleDeclaration */:
var body = parent.body;
return !!body && body.kind === 245 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 218 /* Block */:
case 245 /* ModuleBlock */:
return ts.rangeContainsRange(parent.statements, node);
@@ -108663,7 +109882,7 @@ var ts;
// - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually
// - parent and child are not on the same line
var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) &&
- (parent.kind === 279 /* SourceFile */ || !parentAndChildShareLine);
+ (parent.kind === 284 /* SourceFile */ || !parentAndChildShareLine);
if (!useActualIndentation) {
return -1 /* Unknown */;
}
@@ -108751,7 +109970,7 @@ var ts;
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return getList(node.typeParameters);
case 192 /* NewExpression */:
case 191 /* CallExpression */:
@@ -109000,11 +110219,23 @@ var ts;
ts.Debug.assert(typeof end === "number");
n.__end = end;
}
- var Position;
- (function (Position) {
- Position[Position["FullStart"] = 0] = "FullStart";
- Position[Position["Start"] = 1] = "Start";
- })(Position = textChanges_3.Position || (textChanges_3.Position = {}));
+ var LeadingTriviaOption;
+ (function (LeadingTriviaOption) {
+ /** Exclude all leading trivia (use getStart()) */
+ LeadingTriviaOption[LeadingTriviaOption["Exclude"] = 0] = "Exclude";
+ /** Include leading trivia and,
+ * if there are no line breaks between the node and the previous token,
+ * include all trivia between the node and the previous token
+ */
+ LeadingTriviaOption[LeadingTriviaOption["IncludeAll"] = 1] = "IncludeAll";
+ })(LeadingTriviaOption = textChanges_3.LeadingTriviaOption || (textChanges_3.LeadingTriviaOption = {}));
+ var TrailingTriviaOption;
+ (function (TrailingTriviaOption) {
+ /** Exclude all trailing trivia (use getEnd()) */
+ TrailingTriviaOption[TrailingTriviaOption["Exclude"] = 0] = "Exclude";
+ /** Include trailing trivia */
+ TrailingTriviaOption[TrailingTriviaOption["Include"] = 1] = "Include";
+ })(TrailingTriviaOption = textChanges_3.TrailingTriviaOption || (textChanges_3.TrailingTriviaOption = {}));
function skipWhitespacesAndLineBreaks(text, start) {
return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
@@ -109020,9 +110251,9 @@ var ts;
}
return false;
}
- textChanges_3.useNonAdjustedPositions = {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: true,
+ var useNonAdjustedPositions = {
+ leadingTriviaOption: LeadingTriviaOption.Exclude,
+ trailingTriviaOption: TrailingTriviaOption.Exclude,
};
var ChangeKind;
(function (ChangeKind) {
@@ -109032,10 +110263,11 @@ var ts;
ChangeKind[ChangeKind["Text"] = 3] = "Text";
})(ChangeKind || (ChangeKind = {}));
function getAdjustedRange(sourceFile, startNode, endNode, options) {
- return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) };
+ return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) };
}
- function getAdjustedStartPosition(sourceFile, node, options, position) {
- if (options.useNonAdjustedStartPosition) {
+ function getAdjustedStartPosition(sourceFile, node, options) {
+ var leadingTriviaOption = options.leadingTriviaOption;
+ if (leadingTriviaOption === LeadingTriviaOption.Exclude) {
return node.getStart(sourceFile);
}
var fullStart = node.getFullStart();
@@ -109053,7 +110285,7 @@ var ts;
// fullstart
// when b is replaced - we usually want to keep the leading trvia
// when b is deleted - we delete it
- return position === Position.Start ? start : fullStart;
+ return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start;
}
// get start position of the line following the line that contains fullstart position
// (but only if the fullstart isn't the very beginning of the file)
@@ -109065,11 +110297,12 @@ var ts;
}
function getAdjustedEndPosition(sourceFile, node, options) {
var end = node.end;
- if (options.useNonAdjustedEndPosition || ts.isExpression(node)) {
+ var trailingTriviaOption = options.trailingTriviaOption;
+ if (trailingTriviaOption === TrailingTriviaOption.Exclude || (ts.isExpression(node) && trailingTriviaOption !== TrailingTriviaOption.Include)) {
return end;
}
var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
- return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))
+ return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)))
? newEnd
: end;
}
@@ -109114,15 +110347,15 @@ var ts;
this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) });
};
ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
- var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
+ var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
@@ -109130,11 +110363,11 @@ var ts;
this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode });
};
ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
};
ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options);
};
ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) {
@@ -109142,14 +110375,14 @@ var ts;
this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes });
};
ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
};
ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) {
- this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text);
+ this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text);
};
ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
};
ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
@@ -109177,7 +110410,7 @@ var ts;
};
ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) {
if (blankLineBetween === void 0) { blankLineBetween = false; }
- this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
+ this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
};
ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) {
var pos = before.getStart(sourceFile);
@@ -109284,7 +110517,7 @@ var ts;
this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true));
};
ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) {
- var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start);
+ var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {});
this.insertNodeAt(sourceFile, pos, newNode, {
prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter,
suffix: this.newLineCharacter
@@ -109574,7 +110807,7 @@ var ts;
textChanges_3.ChangeTracker = ChangeTracker;
// find first non-whitespace position in the leading trivia of the node
function startPositionToDeleteNodeInList(sourceFile, node) {
- return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
+ return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
function getClassOrObjectBraceEnds(cls, sourceFile) {
return [ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile).end];
@@ -109911,7 +111144,7 @@ var ts;
case 249 /* ImportDeclaration */:
deleteNode(changes, sourceFile, node,
// For first import, leave header comment in place
- node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined);
+ node === sourceFile.imports[0].parent ? { leadingTriviaOption: LeadingTriviaOption.Exclude } : undefined);
break;
case 186 /* BindingElement */:
var pattern = node.parent;
@@ -109949,7 +111182,7 @@ var ts;
deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
}
else {
- deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined);
+ deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { trailingTriviaOption: TrailingTriviaOption.Exclude } : undefined);
}
}
}
@@ -110020,8 +111253,8 @@ var ts;
/** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */
// Exported for tests only! (TODO: improve tests to not need this)
function deleteNode(changes, sourceFile, node, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, node, options);
var endPosition = getAdjustedEndPosition(sourceFile, node, options);
changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
}
@@ -110314,18 +111547,18 @@ var ts;
}
function transformJSDocType(node) {
switch (node.kind) {
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return transformJSDocOptionalType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return transformJSDocType(node.type);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return transformJSDocNullableType(node);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return transformJSDocVariadicType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return transformJSDocFunctionType(node);
case 164 /* TypeReference */:
return transformJSDocTypeReference(node);
@@ -110349,7 +111582,7 @@ var ts;
}
function transformJSDocParameter(node) {
var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 290 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
+ var isRest = node.type.kind === 295 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
var name = node.name || (isRest ? "rest" : "arg" + index);
var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken;
return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
@@ -110505,7 +111738,7 @@ var ts;
}
if (ts.isPropertyAccessExpression(parent)) {
var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken);
- var typeNode = getTypeNodeIfAccessible(type, parent, program, host);
+ var typeNode = ts.getTypeNodeIfAccessible(type, parent, program, host);
if (typeNode) {
// Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags
var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ "");
@@ -110609,7 +111842,7 @@ var ts;
}
}
function annotate(changes, sourceFile, declaration, type, program, host) {
- var typeNode = getTypeNodeIfAccessible(type, declaration, program, host);
+ var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host);
if (typeNode) {
if (ts.isInJSFile(sourceFile) && declaration.kind !== 153 /* PropertySignature */) {
var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration;
@@ -110635,7 +111868,7 @@ var ts;
// only infer parameters that have (1) no type and (2) an accessible inferred type
if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name))
return;
- var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host);
+ var typeNode = inference.type && ts.getTypeNodeIfAccessible(inference.type, param, program, host);
var name = ts.getSynthesizedClone(param.name);
ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), "");
@@ -110668,40 +111901,17 @@ var ts;
return undefined;
}
switch (oldTag.kind) {
- case 299 /* JSDocParameterTag */: {
+ case 304 /* JSDocParameterTag */: {
var oldParam = oldTag;
var newParam = newTag;
return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText
? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment)
: undefined;
}
- case 300 /* JSDocReturnTag */:
+ case 305 /* JSDocReturnTag */:
return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment);
}
}
- function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
- var checker = program.getTypeChecker();
- var typeIsAccessible = true;
- var notAccessible = function () { typeIsAccessible = false; };
- var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
- trackSymbol: function (symbol, declaration, meaning) {
- // TODO: GH#18217
- typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
- },
- reportInaccessibleThisError: notAccessible,
- reportPrivateInBaseOfClassExpression: notAccessible,
- reportInaccessibleUniqueSymbolError: notAccessible,
- moduleResolverHost: {
- readFile: host.readFile,
- fileExists: host.fileExists,
- directoryExists: host.directoryExists,
- getSourceFiles: program.getSourceFiles,
- getCurrentDirectory: program.getCurrentDirectory,
- getCommonSourceDirectory: program.getCommonSourceDirectory,
- }
- });
- return typeIsAccessible ? res : undefined;
- }
function getReferences(token, program, cancellationToken) {
// Position shouldn't matter since token is not a SourceFile.
return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) {
@@ -111214,7 +112424,7 @@ var ts;
precedingNode = ctorDeclaration.parent.parent;
newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
if (ctorDeclaration.parent.declarations.length === 1) {
- ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
+ ts.copyLeadingComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
changes.delete(sourceFile, precedingNode);
}
else {
@@ -111225,7 +112435,7 @@ var ts;
if (!newClassDeclaration) {
return undefined;
}
- ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile);
+ ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile);
// Because the preceding node could be touched, we need to insert nodes before delete nodes.
changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
function createClassElementsFromSymbol(symbol) {
@@ -111278,7 +112488,7 @@ var ts;
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 121 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
- ts.copyComments(assignmentBinaryExpression, method, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
case 197 /* ArrowFunction */: {
@@ -111296,7 +112506,7 @@ var ts;
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 121 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
- ts.copyComments(assignmentBinaryExpression, method, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
default: {
@@ -111306,7 +112516,7 @@ var ts;
}
var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
/*type*/ undefined, assignmentBinaryExpression.right);
- ts.copyComments(assignmentBinaryExpression.parent, prop, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile);
return prop;
}
}
@@ -114055,7 +115265,7 @@ var ts;
var typeNode = info.typeNode, type = info.type;
var original = typeNode.getText(sourceFile);
var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)];
- if (typeNode.kind === 286 /* JSDocNullableType */) {
+ if (typeNode.kind === 291 /* JSDocNullableType */) {
// for nullable types, suggest the flow-compatible `T | null | undefined`
// in addition to the jsdoc/closure-compatible `T | null`
actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
@@ -114075,7 +115285,7 @@ var ts;
if (!info)
return;
var typeNode = info.typeNode, type = info.type;
- var fixedType = typeNode.kind === 286 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
+ var fixedType = typeNode.kind === 291 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
doChange(changes, sourceFile, typeNode, fixedType, checker);
});
}
@@ -114707,6 +115917,7 @@ var ts;
return ts.textChanges.getNewFileText(toStatements(valueInfo, outputKind), 3 /* TS */, formatSettings.newLineCharacter || "\n", ts.formatting.getFormatContext(formatSettings));
}
ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText;
+ /* @internal */
var OutputKind;
(function (OutputKind) {
OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals";
@@ -115874,7 +117085,7 @@ var ts;
// * Module/namespace or source file
if (isScope(current)) {
scopes.push(current);
- if (current.kind === 279 /* SourceFile */) {
+ if (current.kind === 284 /* SourceFile */) {
return scopes;
}
}
@@ -116888,7 +118099,7 @@ var ts;
function isBlockLike(node) {
switch (node.kind) {
case 218 /* Block */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 245 /* ModuleBlock */:
case 271 /* CaseClause */:
return true;
@@ -117350,9 +118561,9 @@ var ts;
if (isTopLevelDeclarationStatement(statement) &&
!isExported(sourceFile, statement, useEs6Exports) &&
forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) {
- var exports_1 = addExport(statement, useEs6Exports);
- if (exports_1)
- return exports_1;
+ var exports = addExport(statement, useEs6Exports);
+ if (exports)
+ return exports;
}
return statement;
});
@@ -117827,13 +119038,13 @@ var ts;
var returnStatement_1 = ts.createReturn(expression);
body = ts.createBlock([returnStatement_1], /* multiLine */ true);
ts.suppressLeadingAndTrailingTrivia(body);
- ts.copyComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
+ ts.copyLeadingComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
}
else if (actionName === removeBracesActionName && returnStatement) {
var actualExpression = expression || ts.createVoidZero();
body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression;
ts.suppressLeadingAndTrailingTrivia(body);
- ts.copyComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
+ ts.copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
}
else {
ts.Debug.fail("invalid action");
@@ -117872,6 +119083,410 @@ var ts;
})(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var refactor;
+ (function (refactor) {
+ var convertToNamedParameters;
+ (function (convertToNamedParameters) {
+ var refactorName = "Convert to named parameters";
+ var minimumParameterLength = 2;
+ refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
+ function getAvailableActions(context) {
+ var file = context.file, startPosition = context.startPosition;
+ var isJSFile = ts.isSourceFileJS(file);
+ if (isJSFile)
+ return ts.emptyArray; // TODO: GH#30113
+ var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker());
+ if (!functionDeclaration)
+ return ts.emptyArray;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_named_parameters);
+ return [{
+ name: refactorName,
+ description: description,
+ actions: [{
+ name: refactorName,
+ description: description
+ }]
+ }];
+ }
+ function getEditsForAction(context, actionName) {
+ ts.Debug.assert(actionName === refactorName);
+ var file = context.file, startPosition = context.startPosition, program = context.program, cancellationToken = context.cancellationToken, host = context.host;
+ var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker());
+ if (!functionDeclaration || !cancellationToken)
+ return undefined;
+ var groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken);
+ if (groupedReferences.valid) {
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(file, program, host, t, functionDeclaration, groupedReferences); });
+ return { renameFilename: undefined, renameLocation: undefined, edits: edits };
+ }
+ return { edits: [] }; // TODO: GH#30113
+ }
+ function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) {
+ var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); });
+ changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ",
+ // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter
+ indentation: 0,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include
+ });
+ var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); });
+ for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) {
+ var call = functionCalls_1[_i];
+ if (call.arguments && call.arguments.length) {
+ var newArgument = ts.getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true);
+ changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include });
+ }
+ }
+ }
+ function getGroupedReferences(functionDeclaration, program, cancellationToken) {
+ var functionNames = getFunctionNames(functionDeclaration);
+ var classNames = ts.isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : [];
+ var names = ts.deduplicate(functionNames.concat(classNames), ts.equateValues);
+ var checker = program.getTypeChecker();
+ var references = ts.flatMap(names, /*mapfn*/ function (/*mapfn*/ name) { return ts.FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken); });
+ var groupedReferences = groupReferences(references);
+ if (!ts.every(groupedReferences.declarations, function (decl) { return ts.contains(names, decl); })) {
+ groupedReferences.valid = false;
+ }
+ return groupedReferences;
+ function groupReferences(referenceEntries) {
+ var classReferences = { accessExpressions: [], typeUsages: [] };
+ var groupedReferences = { functionCalls: [], declarations: [], classReferences: classReferences, valid: true };
+ var functionSymbols = ts.map(functionNames, checker.getSymbolAtLocation);
+ var classSymbols = ts.map(classNames, checker.getSymbolAtLocation);
+ var isConstructor = ts.isConstructorDeclaration(functionDeclaration);
+ for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) {
+ var entry = referenceEntries_1[_i];
+ if (entry.kind !== 1 /* Node */) {
+ groupedReferences.valid = false;
+ continue;
+ }
+ if (ts.contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ var call = entryToFunctionCall(entry);
+ if (call) {
+ groupedReferences.functionCalls.push(call);
+ continue;
+ }
+ }
+ // if the refactored function is a constructor, we must also check if the references to its class are valid
+ if (isConstructor && ts.contains(classSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ var accessExpression = entryToAccessExpression(entry);
+ if (accessExpression) {
+ classReferences.accessExpressions.push(accessExpression);
+ continue;
+ }
+ // Only class declarations are allowed to be used as a type (in a heritage clause),
+ // otherwise `findAllReferences` might not be able to track constructor calls.
+ if (ts.isClassDeclaration(functionDeclaration.parent)) {
+ var type = entryToType(entry);
+ if (type) {
+ classReferences.typeUsages.push(type);
+ continue;
+ }
+ }
+ }
+ groupedReferences.valid = false;
+ }
+ return groupedReferences;
+ }
+ }
+ function symbolComparer(a, b) {
+ return ts.getSymbolTarget(a) === ts.getSymbolTarget(b);
+ }
+ function entryToDeclaration(entry) {
+ if (ts.isDeclaration(entry.node.parent)) {
+ return entry.node;
+ }
+ return undefined;
+ }
+ function entryToFunctionCall(entry) {
+ if (entry.node.parent) {
+ var functionReference = entry.node;
+ var parent = functionReference.parent;
+ switch (parent.kind) {
+ // Function call (foo(...) or super(...))
+ case 191 /* CallExpression */:
+ var callExpression = ts.tryCast(parent, ts.isCallExpression);
+ if (callExpression && callExpression.expression === functionReference) {
+ return callExpression;
+ }
+ break;
+ // Constructor call (new Foo(...))
+ case 192 /* NewExpression */:
+ var newExpression = ts.tryCast(parent, ts.isNewExpression);
+ if (newExpression && newExpression.expression === functionReference) {
+ return newExpression;
+ }
+ break;
+ // Method call (x.foo(...))
+ case 189 /* PropertyAccessExpression */:
+ var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
+ if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) {
+ var callExpression_1 = ts.tryCast(propertyAccessExpression.parent, ts.isCallExpression);
+ if (callExpression_1 && callExpression_1.expression === propertyAccessExpression) {
+ return callExpression_1;
+ }
+ }
+ break;
+ // Method call (x["foo"](...))
+ case 190 /* ElementAccessExpression */:
+ var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
+ if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) {
+ var callExpression_2 = ts.tryCast(elementAccessExpression.parent, ts.isCallExpression);
+ if (callExpression_2 && callExpression_2.expression === elementAccessExpression) {
+ return callExpression_2;
+ }
+ }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function entryToAccessExpression(entry) {
+ if (entry.node.parent) {
+ var reference = entry.node;
+ var parent = reference.parent;
+ switch (parent.kind) {
+ // `C.foo`
+ case 189 /* PropertyAccessExpression */:
+ var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
+ if (propertyAccessExpression && propertyAccessExpression.expression === reference) {
+ return propertyAccessExpression;
+ }
+ break;
+ // `C["foo"]`
+ case 190 /* ElementAccessExpression */:
+ var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
+ if (elementAccessExpression && elementAccessExpression.expression === reference) {
+ return elementAccessExpression;
+ }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function entryToType(entry) {
+ var reference = entry.node;
+ if (ts.getMeaningFromLocation(reference) === 2 /* Type */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) {
+ return reference;
+ }
+ return undefined;
+ }
+ function getFunctionDeclarationAtPosition(file, startPosition, checker) {
+ var node = ts.getTouchingToken(file, startPosition);
+ var functionDeclaration = ts.getContainingFunction(node);
+ if (functionDeclaration
+ && isValidFunctionDeclaration(functionDeclaration, checker)
+ && ts.rangeContainsRange(functionDeclaration, node)
+ && !(functionDeclaration.body && ts.rangeContainsRange(functionDeclaration.body, node)))
+ return functionDeclaration;
+ return undefined;
+ }
+ function isValidFunctionDeclaration(functionDeclaration, checker) {
+ if (!isValidParameterNodeArray(functionDeclaration.parameters))
+ return false;
+ switch (functionDeclaration.kind) {
+ case 239 /* FunctionDeclaration */:
+ case 156 /* MethodDeclaration */:
+ return !!functionDeclaration.name && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration);
+ case 157 /* Constructor */:
+ if (ts.isClassDeclaration(functionDeclaration.parent)) {
+ return !!functionDeclaration.body && !!functionDeclaration.parent.name && !checker.isImplementationOfOverload(functionDeclaration);
+ }
+ else {
+ return isValidVariableDeclaration(functionDeclaration.parent.parent) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration);
+ }
+ case 196 /* FunctionExpression */:
+ case 197 /* ArrowFunction */:
+ return isValidVariableDeclaration(functionDeclaration.parent);
+ }
+ return false;
+ }
+ function isValidParameterNodeArray(parameters) {
+ return getRefactorableParametersLength(parameters) >= minimumParameterLength && ts.every(parameters, isValidParameterDeclaration);
+ }
+ function isValidParameterDeclaration(paramDeclaration) {
+ return !paramDeclaration.modifiers && !paramDeclaration.decorators && ts.isIdentifier(paramDeclaration.name);
+ }
+ function isValidVariableDeclaration(node) {
+ return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113
+ }
+ function hasThisParameter(parameters) {
+ return parameters.length > 0 && ts.isThis(parameters[0].name);
+ }
+ function getRefactorableParametersLength(parameters) {
+ if (hasThisParameter(parameters)) {
+ return parameters.length - 1;
+ }
+ return parameters.length;
+ }
+ function getRefactorableParameters(parameters) {
+ if (hasThisParameter(parameters)) {
+ parameters = ts.createNodeArray(parameters.slice(1), parameters.hasTrailingComma);
+ }
+ return parameters;
+ }
+ function createNewArgument(functionDeclaration, functionArguments) {
+ var parameters = getRefactorableParameters(functionDeclaration.parameters);
+ var hasRestParameter = ts.isRestParameter(ts.last(parameters));
+ var nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments;
+ var properties = ts.map(nonRestArguments, function (arg, i) {
+ var property = ts.createPropertyAssignment(getParameterName(parameters[i]), arg);
+ ts.suppressLeadingAndTrailingTrivia(property.initializer);
+ copyComments(arg, property);
+ return property;
+ });
+ if (hasRestParameter && functionArguments.length >= parameters.length) {
+ var restArguments = functionArguments.slice(parameters.length - 1);
+ var restProperty = ts.createPropertyAssignment(getParameterName(ts.last(parameters)), ts.createArrayLiteral(restArguments));
+ properties.push(restProperty);
+ }
+ var objectLiteral = ts.createObjectLiteral(properties, /*multiLine*/ false);
+ return objectLiteral;
+ }
+ function createNewParameters(functionDeclaration, program, host) {
+ var refactorableParameters = getRefactorableParameters(functionDeclaration.parameters);
+ var bindingElements = ts.map(refactorableParameters, createBindingElementFromParameterDeclaration);
+ var objectParameterName = ts.createObjectBindingPattern(bindingElements);
+ var objectParameterType = createParameterTypeNode(refactorableParameters);
+ var checker = program.getTypeChecker();
+ var objectInitializer;
+ // If every parameter in the original function was optional, add an empty object initializer to the new object parameter
+ if (ts.every(refactorableParameters, checker.isOptionalParameter)) {
+ objectInitializer = ts.createObjectLiteral();
+ }
+ var objectParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, objectParameterName,
+ /*questionToken*/ undefined, objectParameterType, objectInitializer);
+ if (hasThisParameter(functionDeclaration.parameters)) {
+ var thisParameter = functionDeclaration.parameters[0];
+ var newThisParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, thisParameter.name,
+ /*questionToken*/ undefined, thisParameter.type);
+ ts.suppressLeadingAndTrailingTrivia(newThisParameter.name);
+ copyComments(thisParameter.name, newThisParameter.name);
+ if (thisParameter.type) {
+ ts.suppressLeadingAndTrailingTrivia(newThisParameter.type);
+ copyComments(thisParameter.type, newThisParameter.type);
+ }
+ return ts.createNodeArray([newThisParameter, objectParameter]);
+ }
+ return ts.createNodeArray([objectParameter]);
+ function createParameterTypeNode(parameters) {
+ var members = ts.map(parameters, createPropertySignatureFromParameterDeclaration);
+ var typeNode = ts.addEmitFlags(ts.createTypeLiteralNode(members), 1 /* SingleLine */);
+ return typeNode;
+ }
+ function createPropertySignatureFromParameterDeclaration(parameterDeclaration) {
+ var parameterType = parameterDeclaration.type;
+ if (!parameterType && (parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration))) {
+ parameterType = getTypeNode(parameterDeclaration);
+ }
+ var propertySignature = ts.createPropertySignature(
+ /*modifiers*/ undefined, getParameterName(parameterDeclaration), parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration) ? ts.createToken(56 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType,
+ /*initializer*/ undefined);
+ ts.suppressLeadingAndTrailingTrivia(propertySignature);
+ copyComments(parameterDeclaration.name, propertySignature.name);
+ if (parameterDeclaration.type && propertySignature.type) {
+ copyComments(parameterDeclaration.type, propertySignature.type);
+ }
+ return propertySignature;
+ }
+ function getTypeNode(node) {
+ var checker = program.getTypeChecker();
+ var type = checker.getTypeAtLocation(node);
+ return ts.getTypeNodeIfAccessible(type, node, program, host);
+ }
+ }
+ function createBindingElementFromParameterDeclaration(parameterDeclaration) {
+ var element = ts.createBindingElement(
+ /*dotDotDotToken*/ undefined,
+ /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer);
+ ts.suppressLeadingAndTrailingTrivia(element);
+ if (parameterDeclaration.initializer && element.initializer) {
+ copyComments(parameterDeclaration.initializer, element.initializer);
+ }
+ return element;
+ }
+ function copyComments(sourceNode, targetNode) {
+ var sourceFile = sourceNode.getSourceFile();
+ var text = sourceFile.text;
+ if (hasLeadingLineBreak(sourceNode, text)) {
+ ts.copyLeadingComments(sourceNode, targetNode, sourceFile);
+ }
+ else {
+ ts.copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile);
+ }
+ ts.copyTrailingComments(sourceNode, targetNode, sourceFile);
+ }
+ function hasLeadingLineBreak(node, text) {
+ var start = node.getFullStart();
+ var end = node.getStart();
+ for (var i = start; i < end; i++) {
+ if (text.charCodeAt(i) === 10 /* lineFeed */)
+ return true;
+ }
+ return false;
+ }
+ function getParameterName(paramDeclaration) {
+ return ts.getTextOfIdentifierOrLiteral(paramDeclaration.name);
+ }
+ function getClassNames(constructorDeclaration) {
+ switch (constructorDeclaration.parent.kind) {
+ case 240 /* ClassDeclaration */:
+ var classDeclaration = constructorDeclaration.parent;
+ return [classDeclaration.name];
+ case 209 /* ClassExpression */:
+ var classExpression = constructorDeclaration.parent;
+ var variableDeclaration = constructorDeclaration.parent.parent;
+ var className = classExpression.name;
+ if (className)
+ return [className, variableDeclaration.name];
+ return [variableDeclaration.name];
+ }
+ }
+ function getFunctionNames(functionDeclaration) {
+ switch (functionDeclaration.kind) {
+ case 239 /* FunctionDeclaration */:
+ case 156 /* MethodDeclaration */:
+ return [functionDeclaration.name];
+ case 157 /* Constructor */:
+ var ctrKeyword = ts.findChildOfKind(functionDeclaration, 124 /* ConstructorKeyword */, functionDeclaration.getSourceFile());
+ if (functionDeclaration.parent.kind === 209 /* ClassExpression */) {
+ var variableDeclaration = functionDeclaration.parent.parent;
+ return [variableDeclaration.name, ctrKeyword];
+ }
+ return [ctrKeyword];
+ case 197 /* ArrowFunction */:
+ return [functionDeclaration.parent.name];
+ case 196 /* FunctionExpression */:
+ if (functionDeclaration.name)
+ return [functionDeclaration.name, functionDeclaration.parent.name];
+ return [functionDeclaration.parent.name];
+ default:
+ return ts.Debug.assertNever(functionDeclaration);
+ }
+ }
+ })(convertToNamedParameters = refactor.convertToNamedParameters || (refactor.convertToNamedParameters = {}));
+ })(refactor = ts.refactor || (ts.refactor = {}));
+})(ts || (ts = {}));
var ts;
(function (ts) {
/** The version of the language service API */
@@ -117952,7 +119567,7 @@ var ts;
if (!children.length) {
return undefined;
}
- var child = ts.find(children, function (kid) { return kid.kind < 283 /* FirstJSDocNode */ || kid.kind > 305 /* LastJSDocNode */; });
+ var child = ts.find(children, function (kid) { return kid.kind < 288 /* FirstJSDocNode */ || kid.kind > 310 /* LastJSDocNode */; });
return child.kind < 148 /* FirstNode */ ?
child :
child.getFirstToken(sourceFile);
@@ -118022,7 +119637,7 @@ var ts;
}
}
function createSyntaxList(nodes, parent) {
- var list = createNode(306 /* SyntaxList */, nodes.pos, nodes.end, parent);
+ var list = createNode(311 /* SyntaxList */, nodes.pos, nodes.end, parent);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
@@ -121141,8 +122756,6 @@ var TypeScript;
// TODO: it should be moved into a namespace though.
/* @internal */
var toolsVersion = ts.versionMajorMinor;
-//# sourceMappingURL=services.js.map
-"use strict";
/* @internal */
var ts;
(function (ts) {
@@ -121483,41 +123096,6 @@ var ts;
JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
})(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
})(ts || (ts = {}));
-//# sourceMappingURL=jsTyping.js.map
-"use strict";
-var __assign = (this && this.__assign) || function () {
- __assign = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-var __extends = (this && this.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
-})();
-var __rest = (this && this.__rest) || function (s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
- t[p[i]] = s[p[i]];
- return t;
-};
var ts;
(function (ts) {
var server;
@@ -121530,6 +123108,7 @@ var ts;
LogLevel[LogLevel["verbose"] = 3] = "verbose";
})(LogLevel = server.LogLevel || (server.LogLevel = {}));
server.emptyArray = createSortedArray();
+ // TODO: Use a const enum (https://github.com/Microsoft/TypeScript/issues/16804)
var Msg;
(function (Msg) {
Msg["Err"] = "Err";
@@ -121539,7 +123118,7 @@ var ts;
function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) {
return {
projectName: project.getProjectName(),
- fileNames: project.getFileNames(true, true).concat(project.getExcludedFiles()),
+ fileNames: project.getFileNames(/*excludeFilesFromExternalLibraries*/ true, /*excludeConfigFiles*/ true).concat(project.getExcludedFiles()),
compilerOptions: project.getCompilationSettings(),
typeAcquisition: typeAcquisition,
unresolvedImports: unresolvedImports,
@@ -121596,6 +123175,7 @@ var ts;
}
server.createNormalizedPathMap = createNormalizedPathMap;
function isInferredProjectName(name) {
+ // POSIX defines /dev/null as a device - there should be no file with this prefix
return /dev\/null\/inferredProject\d+\*/.test(name);
}
server.isInferredProjectName = isInferredProjectName;
@@ -121604,25 +123184,34 @@ var ts;
}
server.makeInferredProjectName = makeInferredProjectName;
function createSortedArray() {
- return [];
+ return []; // TODO: GH#19873
}
server.createSortedArray = createSortedArray;
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
+/* @internal */
(function (ts) {
var server;
(function (server) {
- var ThrottledOperations = (function () {
+ var ThrottledOperations = /** @class */ (function () {
function ThrottledOperations(host, logger) {
this.host = host;
this.pendingTimeouts = ts.createMap();
this.logger = logger.hasLevel(server.LogLevel.verbose) ? logger : undefined;
}
+ /**
+ * Wait `number` milliseconds and then invoke `cb`. If, while waiting, schedule
+ * is called again with the same `operationId`, cancel this operation in favor
+ * of the new one. (Note that the amount of time the canceled operation had been
+ * waiting does not affect the amount of time that the new operation waits.)
+ */
ThrottledOperations.prototype.schedule = function (operationId, delay, cb) {
var pendingTimeout = this.pendingTimeouts.get(operationId);
if (pendingTimeout) {
+ // another operation was already scheduled for this id - cancel it
this.host.clearTimeout(pendingTimeout);
}
+ // schedule new operation, pass arguments
this.pendingTimeouts.set(operationId, this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb));
if (this.logger) {
this.logger.info("Scheduled: " + operationId + (pendingTimeout ? ", Cancelled earlier one" : ""));
@@ -121638,7 +123227,7 @@ var ts;
return ThrottledOperations;
}());
server.ThrottledOperations = ThrottledOperations;
- var GcTimer = (function () {
+ var GcTimer = /** @class */ (function () {
function GcTimer(host, delay, logger) {
this.host = host;
this.delay = delay;
@@ -121646,6 +123235,7 @@ var ts;
}
GcTimer.prototype.scheduleCollect = function () {
if (!this.host.gc || this.timerId !== undefined) {
+ // no global.gc or collection was already scheduled - skip this request
return;
}
this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this);
@@ -121653,10 +123243,10 @@ var ts;
GcTimer.run = function (self) {
self.timerId = undefined;
var log = self.logger.hasLevel(server.LogLevel.requestTime);
- var before = log && self.host.getMemoryUsage();
- self.host.gc();
+ var before = log && self.host.getMemoryUsage(); // TODO: GH#18217
+ self.host.gc(); // TODO: GH#18217
if (log) {
- var after = self.host.getMemoryUsage();
+ var after = self.host.getMemoryUsage(); // TODO: GH#18217
self.logger.perftrc("GC::before " + before + ", after " + after);
}
};
@@ -121687,13 +123277,16 @@ var ts;
return indentStr + str.replace(/\n/g, indentStr);
}
server.indent = indent;
+ /** Put stringified JSON on the next line, indented. */
function stringifyIndented(json) {
return indentStr + JSON.stringify(json);
}
server.stringifyIndented = stringifyIndented;
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
+/* @internal */
(function (ts) {
+ // Additional tsserver specific watch information
var WatchType;
(function (WatchType) {
WatchType["ClosedScriptInfo"] = "Closed Script info";
@@ -121702,41 +123295,57 @@ var ts;
WatchType["MissingSourceMapFile"] = "Missing source map file";
})(WatchType = ts.WatchType || (ts.WatchType = {}));
})(ts || (ts = {}));
+// tslint:disable no-unnecessary-qualifier
+/**
+ * Declaration module describing the TypeScript Server protocol
+ */
var ts;
(function (ts) {
var server;
(function (server) {
var protocol;
(function (protocol) {
+ // NOTE: If updating this, be sure to also update `allCommandNames` in `harness/unittests/session.ts`.
var CommandTypes;
(function (CommandTypes) {
CommandTypes["JsxClosingTag"] = "jsxClosingTag";
CommandTypes["Brace"] = "brace";
+ /* @internal */
CommandTypes["BraceFull"] = "brace-full";
CommandTypes["BraceCompletion"] = "braceCompletion";
CommandTypes["GetSpanOfEnclosingComment"] = "getSpanOfEnclosingComment";
CommandTypes["Change"] = "change";
CommandTypes["Close"] = "close";
+ /** @deprecated Prefer CompletionInfo -- see comment on CompletionsResponse */
CommandTypes["Completions"] = "completions";
CommandTypes["CompletionInfo"] = "completionInfo";
+ /* @internal */
CommandTypes["CompletionsFull"] = "completions-full";
CommandTypes["CompletionDetails"] = "completionEntryDetails";
+ /* @internal */
CommandTypes["CompletionDetailsFull"] = "completionEntryDetails-full";
CommandTypes["CompileOnSaveAffectedFileList"] = "compileOnSaveAffectedFileList";
CommandTypes["CompileOnSaveEmitFile"] = "compileOnSaveEmitFile";
CommandTypes["Configure"] = "configure";
CommandTypes["Definition"] = "definition";
+ /* @internal */
CommandTypes["DefinitionFull"] = "definition-full";
CommandTypes["DefinitionAndBoundSpan"] = "definitionAndBoundSpan";
+ /* @internal */
CommandTypes["DefinitionAndBoundSpanFull"] = "definitionAndBoundSpan-full";
CommandTypes["Implementation"] = "implementation";
+ /* @internal */
CommandTypes["ImplementationFull"] = "implementation-full";
+ /* @internal */
CommandTypes["EmitOutput"] = "emit-output";
CommandTypes["Exit"] = "exit";
CommandTypes["Format"] = "format";
CommandTypes["Formatonkey"] = "formatonkey";
+ /* @internal */
CommandTypes["FormatFull"] = "format-full";
+ /* @internal */
CommandTypes["FormatonkeyFull"] = "formatonkey-full";
+ /* @internal */
CommandTypes["FormatRangeFull"] = "formatRange-full";
CommandTypes["Geterr"] = "geterr";
CommandTypes["GeterrForProject"] = "geterrForProject";
@@ -121744,25 +123353,34 @@ var ts;
CommandTypes["SyntacticDiagnosticsSync"] = "syntacticDiagnosticsSync";
CommandTypes["SuggestionDiagnosticsSync"] = "suggestionDiagnosticsSync";
CommandTypes["NavBar"] = "navbar";
+ /* @internal */
CommandTypes["NavBarFull"] = "navbar-full";
CommandTypes["Navto"] = "navto";
+ /* @internal */
CommandTypes["NavtoFull"] = "navto-full";
CommandTypes["NavTree"] = "navtree";
CommandTypes["NavTreeFull"] = "navtree-full";
+ /** @deprecated */
CommandTypes["Occurrences"] = "occurrences";
CommandTypes["DocumentHighlights"] = "documentHighlights";
+ /* @internal */
CommandTypes["DocumentHighlightsFull"] = "documentHighlights-full";
CommandTypes["Open"] = "open";
CommandTypes["Quickinfo"] = "quickinfo";
+ /* @internal */
CommandTypes["QuickinfoFull"] = "quickinfo-full";
CommandTypes["References"] = "references";
+ /* @internal */
CommandTypes["ReferencesFull"] = "references-full";
CommandTypes["Reload"] = "reload";
CommandTypes["Rename"] = "rename";
+ /* @internal */
CommandTypes["RenameInfoFull"] = "rename-full";
+ /* @internal */
CommandTypes["RenameLocationsFull"] = "renameLocations-full";
CommandTypes["Saveto"] = "saveto";
CommandTypes["SignatureHelp"] = "signatureHelp";
+ /* @internal */
CommandTypes["SignatureHelpFull"] = "signatureHelp-full";
CommandTypes["Status"] = "status";
CommandTypes["TypeDefinition"] = "typeDefinition";
@@ -121772,33 +123390,48 @@ var ts;
CommandTypes["OpenExternalProject"] = "openExternalProject";
CommandTypes["OpenExternalProjects"] = "openExternalProjects";
CommandTypes["CloseExternalProject"] = "closeExternalProject";
+ /* @internal */
CommandTypes["SynchronizeProjectList"] = "synchronizeProjectList";
+ /* @internal */
CommandTypes["ApplyChangedToOpenFiles"] = "applyChangedToOpenFiles";
+ CommandTypes["UpdateOpen"] = "updateOpen";
+ /* @internal */
CommandTypes["EncodedSemanticClassificationsFull"] = "encodedSemanticClassifications-full";
+ /* @internal */
CommandTypes["Cleanup"] = "cleanup";
CommandTypes["GetOutliningSpans"] = "getOutliningSpans";
+ /* @internal */
CommandTypes["GetOutliningSpansFull"] = "outliningSpans";
CommandTypes["TodoComments"] = "todoComments";
CommandTypes["Indentation"] = "indentation";
CommandTypes["DocCommentTemplate"] = "docCommentTemplate";
+ /* @internal */
CommandTypes["CompilerOptionsDiagnosticsFull"] = "compilerOptionsDiagnostics-full";
+ /* @internal */
CommandTypes["NameOrDottedNameSpan"] = "nameOrDottedNameSpan";
+ /* @internal */
CommandTypes["BreakpointStatement"] = "breakpointStatement";
CommandTypes["CompilerOptionsForInferredProjects"] = "compilerOptionsForInferredProjects";
CommandTypes["GetCodeFixes"] = "getCodeFixes";
+ /* @internal */
CommandTypes["GetCodeFixesFull"] = "getCodeFixes-full";
CommandTypes["GetCombinedCodeFix"] = "getCombinedCodeFix";
+ /* @internal */
CommandTypes["GetCombinedCodeFixFull"] = "getCombinedCodeFix-full";
CommandTypes["ApplyCodeActionCommand"] = "applyCodeActionCommand";
CommandTypes["GetSupportedCodeFixes"] = "getSupportedCodeFixes";
CommandTypes["GetApplicableRefactors"] = "getApplicableRefactors";
CommandTypes["GetEditsForRefactor"] = "getEditsForRefactor";
+ /* @internal */
CommandTypes["GetEditsForRefactorFull"] = "getEditsForRefactor-full";
CommandTypes["OrganizeImports"] = "organizeImports";
+ /* @internal */
CommandTypes["OrganizeImportsFull"] = "organizeImports-full";
CommandTypes["GetEditsForFileRename"] = "getEditsForFileRename";
+ /* @internal */
CommandTypes["GetEditsForFileRenameFull"] = "getEditsForFileRename-full";
CommandTypes["ConfigurePlugin"] = "configurePlugin";
+ // NOTE: If updating this, be sure to also update `allCommandNames` in `harness/unittests/session.ts`.
})(CommandTypes = protocol.CommandTypes || (protocol.CommandTypes = {}));
var IndentStyle;
(function (IndentStyle) {
@@ -121851,13 +123484,23 @@ var ts;
(function (ts) {
var server;
(function (server) {
- var TextStorage = (function () {
+ /* @internal */
+ var TextStorage = /** @class */ (function () {
function TextStorage(host, fileName, initialVersion, info) {
this.host = host;
this.fileName = fileName;
this.info = info;
+ /**
+ * True if the text is for the file thats open in the editor
+ */
this.isOpen = false;
+ /**
+ * True if the text present is the text from the file on the disk
+ */
this.ownFileText = false;
+ /**
+ * True when reloading contents of file from the disk is pending
+ */
this.pendingReloadFromDisk = false;
this.version = initialVersion || { svc: 0, text: 0 };
}
@@ -121880,6 +123523,7 @@ var ts;
this.info.sourceInfos = undefined;
this.info.documentPositionMapper = undefined;
};
+ /** Public for testing */
TextStorage.prototype.useText = function (newText) {
this.svc = undefined;
this.text = newText;
@@ -121896,23 +123540,42 @@ var ts;
this.fileSize = undefined;
this.resetSourceMapInfo();
};
+ /**
+ * Set the contents as newText
+ * returns true if text changed
+ */
TextStorage.prototype.reload = function (newText) {
ts.Debug.assert(newText !== undefined);
+ // Reload always has fresh content
this.pendingReloadFromDisk = false;
+ // If text changed set the text
+ // This also ensures that if we had switched to version cache,
+ // we are switching back to text.
+ // The change to version cache will happen when needed
+ // Thus avoiding the computation if there are no changes
if (this.text !== newText) {
this.useText(newText);
+ // We cant guarantee new text is own file text
this.ownFileText = false;
return true;
}
return false;
};
+ /**
+ * Reads the contents from tempFile(if supplied) or own file and sets it as contents
+ * returns true if text changed
+ */
TextStorage.prototype.reloadWithFileText = function (tempFileName) {
var _a = this.getFileTextAndSize(tempFileName), newText = _a.text, fileSize = _a.fileSize;
var reloaded = this.reload(newText);
- this.fileSize = fileSize;
+ this.fileSize = fileSize; // NB: after reload since reload clears it
this.ownFileText = !tempFileName || tempFileName === this.fileName;
return reloaded;
};
+ /**
+ * Reloads the contents from the file if there is no pending reload from disk or the contents of file are same as file text
+ * returns true if text changed
+ */
TextStorage.prototype.reloadFromDisk = function () {
if (!this.pendingReloadFromDisk && !this.ownFileText) {
return this.reloadWithFileText();
@@ -121922,14 +123585,21 @@ var ts;
TextStorage.prototype.delayReloadFromFileIntoText = function () {
this.pendingReloadFromDisk = true;
};
+ /**
+ * For telemetry purposes, we would like to be able to report the size of the file.
+ * However, we do not want telemetry to require extra file I/O so we report a size
+ * that may be stale (e.g. may not reflect change made on disk since the last reload).
+ * NB: Will read from disk if the file contents have never been loaded because
+ * telemetry falsely indicating size 0 would be counter-productive.
+ */
TextStorage.prototype.getTelemetryFileSize = function () {
return !!this.fileSize
? this.fileSize
- : !!this.text
- ? this.text.length
+ : !!this.text // Check text before svc because its length is cheaper
+ ? this.text.length // Could be wrong if this.pendingReloadFromDisk
: !!this.svc
- ? this.svc.getSnapshot().getLength()
- : this.getSnapshot().getLength();
+ ? this.svc.getSnapshot().getLength() // Could be wrong if this.pendingReloadFromDisk
+ : this.getSnapshot().getLength(); // Should be strictly correct
};
TextStorage.prototype.getSnapshot = function () {
return this.useScriptVersionCacheIfValidOrOpen()
@@ -121939,19 +123609,27 @@ var ts;
TextStorage.prototype.getAbsolutePositionAndLineText = function (line) {
return this.switchToScriptVersionCache().getAbsolutePositionAndLineText(line);
};
+ /**
+ * @param line 0 based index
+ */
TextStorage.prototype.lineToTextSpan = function (line) {
if (!this.useScriptVersionCacheIfValidOrOpen()) {
var lineMap = this.getLineMap();
- var start = lineMap[line];
+ var start = lineMap[line]; // -1 since line is 1-based
var end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length;
return ts.createTextSpanFromBounds(start, end);
}
return this.svc.lineToTextSpan(line);
};
+ /**
+ * @param line 1 based index
+ * @param offset 1 based index
+ */
TextStorage.prototype.lineOffsetToPosition = function (line, offset, allowEdits) {
if (!this.useScriptVersionCacheIfValidOrOpen()) {
return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text, allowEdits);
}
+ // TODO: assert this offset is actually on the line
return this.svc.lineOffsetToPosition(line, offset);
};
TextStorage.prototype.positionToLineOffset = function (position) {
@@ -121966,6 +123644,7 @@ var ts;
var text;
var fileName = tempFileName || this.fileName;
var getText = function () { return text === undefined ? (text = _this.host.readFile(fileName) || "") : text; };
+ // Only non typescript files have size limitation
if (!ts.hasTSFileExtension(this.fileName)) {
var fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length;
if (fileSize > server.maxFileSize) {
@@ -121986,12 +123665,15 @@ var ts;
return this.svc;
};
TextStorage.prototype.useScriptVersionCacheIfValidOrOpen = function () {
+ // If this is open script, use the cache
if (this.isOpen) {
return this.switchToScriptVersionCache();
}
+ // If there is pending reload from the disk then, reload the text
if (this.pendingReloadFromDisk) {
this.reloadWithFileText();
}
+ // At this point if svc is present its valid
return this.svc;
};
TextStorage.prototype.getOrLoadText = function () {
@@ -122019,17 +123701,21 @@ var ts;
return TextStorage;
}());
server.TextStorage = TextStorage;
+ /*@internal*/
function isDynamicFileName(fileName) {
return fileName[0] === "^" || ts.getBaseFileName(fileName)[0] === "^";
}
server.isDynamicFileName = isDynamicFileName;
- var ScriptInfo = (function () {
+ var ScriptInfo = /** @class */ (function () {
function ScriptInfo(host, fileName, scriptKind, hasMixedContent, path, initialVersion) {
this.host = host;
this.fileName = fileName;
this.scriptKind = scriptKind;
this.hasMixedContent = hasMixedContent;
this.path = path;
+ /**
+ * All projects that include this file
+ */
this.containingProjects = [];
this.isDynamic = isDynamicFileName(fileName);
this.textStorage = new TextStorage(host, fileName, initialVersion, this);
@@ -122041,12 +123727,15 @@ var ts;
? scriptKind
: ts.getScriptKindFromFileName(fileName);
}
+ /*@internal*/
ScriptInfo.prototype.getVersion = function () {
return this.textStorage.version;
};
+ /*@internal*/
ScriptInfo.prototype.getTelemetryFileSize = function () {
return this.textStorage.getTelemetryFileSize();
};
+ /*@internal*/
ScriptInfo.prototype.isDynamicOrHasMixedContent = function () {
return this.hasMixedContent || this.isDynamic;
};
@@ -122057,6 +123746,7 @@ var ts;
this.textStorage.isOpen = true;
if (newText !== undefined &&
this.textStorage.reload(newText)) {
+ // reload new contents only if the existing contents changed
this.markContainingProjectsAsDirty();
}
};
@@ -122077,6 +123767,7 @@ var ts;
};
ScriptInfo.prototype.ensureRealPath = function () {
if (this.realpath === undefined) {
+ // Default is just the path
this.realpath = this.path;
if (this.host.realpath) {
ts.Debug.assert(!!this.containingProjects.length);
@@ -122084,13 +123775,15 @@ var ts;
var realpath = this.host.realpath(this.path);
if (realpath) {
this.realpath = project.toPath(realpath);
+ // If it is different from this.path, add to the map
if (this.realpath !== this.path) {
- project.projectService.realpathToScriptInfos.add(this.realpath, this);
+ project.projectService.realpathToScriptInfos.add(this.realpath, this); // TODO: GH#18217
}
}
}
}
};
+ /*@internal*/
ScriptInfo.prototype.getRealpathIfDifferent = function () {
return this.realpath && this.realpath !== this.path ? this.realpath : undefined;
};
@@ -122108,6 +123801,7 @@ var ts;
return isNew;
};
ScriptInfo.prototype.isAttached = function (project) {
+ // unrolled for common cases
switch (this.containingProjects.length) {
case 0: return false;
case 1: return this.containingProjects[0] === project;
@@ -122116,6 +123810,7 @@ var ts;
}
};
ScriptInfo.prototype.detachFromProject = function (project) {
+ // unrolled for common cases
switch (this.containingProjects.length) {
case 0:
return;
@@ -122149,7 +123844,10 @@ var ts;
p.getCachedDirectoryStructureHost().addOrDeleteFile(this.fileName, this.path, ts.FileWatcherEventKind.Deleted);
}
var isInfoRoot = p.isRoot(this);
- p.removeFile(this, false, false);
+ // detach is unnecessary since we'll clean the list of containing projects anyways
+ p.removeFile(this, /*fileExists*/ false, /*detachFromProjects*/ false);
+ // If the info was for the external or configured project's root,
+ // add missing file as the root
if (isInfoRoot && p.projectKind !== server.ProjectKind.Inferred) {
p.addMissingFileRoot(this.fileName);
}
@@ -122163,6 +123861,9 @@ var ts;
case 1:
return this.containingProjects[0];
default:
+ // if this file belongs to multiple projects, the first configured project should be
+ // the default project; if no configured projects, the first external project should
+ // be the default project; otherwise the first inferred project should be the default.
var firstExternalProject = void 0;
for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) {
var project = _a[_i];
@@ -122205,6 +123906,7 @@ var ts;
ScriptInfo.prototype.saveTo = function (fileName) {
this.host.writeFile(fileName, ts.getSnapshotText(this.textStorage.getSnapshot()));
};
+ /*@internal*/
ScriptInfo.prototype.delayReloadNonMixedContentFile = function () {
ts.Debug.assert(!this.isDynamicOrHasMixedContent());
this.textStorage.delayReloadFromFileIntoText();
@@ -122224,6 +123926,7 @@ var ts;
}
return false;
};
+ /*@internal*/
ScriptInfo.prototype.getAbsolutePositionAndLineText = function (line) {
return this.textStorage.getAbsolutePositionAndLineText(line);
};
@@ -122240,6 +123943,9 @@ var ts;
ScriptInfo.prototype.isOrphan = function () {
return !ts.forEach(this.containingProjects, function (p) { return !p.isOrphan(); });
};
+ /**
+ * @param line 1 based index
+ */
ScriptInfo.prototype.lineToTextSpan = function (line) {
return this.textStorage.lineToTextSpan(line);
};
@@ -122250,11 +123956,13 @@ var ts;
return this.textStorage.positionToLineOffset(position);
};
ScriptInfo.prototype.isJavaScript = function () {
- return this.scriptKind === 1 || this.scriptKind === 2;
+ return this.scriptKind === 1 /* JS */ || this.scriptKind === 2 /* JSX */;
};
+ /*@internal*/
ScriptInfo.prototype.getLineInfo = function () {
return this.textStorage.getLineInfo();
};
+ /*@internal*/
ScriptInfo.prototype.closeSourceMapFileWatcher = function () {
if (this.sourceMapFilePath && !ts.isString(this.sourceMapFilePath)) {
ts.closeFileWatcherOf(this.sourceMapFilePath);
@@ -122272,12 +123980,13 @@ var ts;
(function (server) {
server.nullTypingsInstaller = {
isKnownTypesPackageName: ts.returnFalse,
+ // Should never be called because we never provide a types registry.
installPackage: ts.notImplemented,
inspectValue: ts.notImplemented,
enqueueInstallTypingsRequest: ts.noop,
attach: ts.noop,
onProjectClosed: ts.noop,
- globalTypingsCacheLocation: undefined
+ globalTypingsCacheLocation: undefined // TODO: GH#18217
};
function setIsEqualTo(arr1, arr2) {
if (arr1 === arr2) {
@@ -122314,6 +124023,7 @@ var ts;
!setIsEqualTo(opt1.exclude, opt2.exclude);
}
function compilerOptionsChanged(opt1, opt2) {
+ // TODO: add more relevant properties
return opt1.allowJs !== opt2.allowJs;
}
function unresolvedImportsChanged(imports1, imports2) {
@@ -122322,7 +124032,8 @@ var ts;
}
return !ts.arrayIsEqualTo(imports1, imports2);
}
- var TypingsCache = (function () {
+ /*@internal*/
+ var TypingsCache = /** @class */ (function () {
function TypingsCache(installer) {
this.installer = installer;
this.perProjectCache = ts.createMap();
@@ -122347,6 +124058,8 @@ var ts;
typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) ||
compilerOptionsChanged(project.getCompilationSettings(), entry.compilerOptions) ||
unresolvedImportsChanged(unresolvedImports, entry.unresolvedImports)) {
+ // Note: entry is now poisoned since it does not really contain typings for a given combination of compiler options\typings options.
+ // instead it acts as a placeholder to prevent issuing multiple requests
this.perProjectCache.set(project.getProjectName(), {
compilerOptions: project.getCompilationSettings(),
typeAcquisition: typeAcquisition,
@@ -122354,6 +124067,7 @@ var ts;
unresolvedImports: unresolvedImports,
poisoned: true
});
+ // something has been changed, issue a request to update typings
this.installer.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports);
}
};
@@ -122387,6 +124101,7 @@ var ts;
ProjectKind[ProjectKind["Configured"] = 1] = "Configured";
ProjectKind[ProjectKind["External"] = 2] = "External";
})(ProjectKind = server.ProjectKind || (server.ProjectKind = {}));
+ /* @internal */
function countEachFileTypes(infos, includeSizes) {
if (includeSizes === void 0) { includeSizes = false; }
var result = {
@@ -122401,16 +124116,16 @@ var ts;
var info = infos_1[_i];
var fileSize = includeSizes ? info.getTelemetryFileSize() : 0;
switch (info.scriptKind) {
- case 1:
+ case 1 /* JS */:
result.js += 1;
result.jsSize += fileSize;
break;
- case 2:
+ case 2 /* JSX */:
result.jsx += 1;
result.jsxSize += fileSize;
break;
- case 3:
- if (ts.fileExtensionIs(info.fileName, ".d.ts")) {
+ case 3 /* TS */:
+ if (ts.fileExtensionIs(info.fileName, ".d.ts" /* Dts */)) {
result.dts += 1;
result.dtsSize += fileSize;
}
@@ -122419,11 +124134,11 @@ var ts;
result.tsSize += fileSize;
}
break;
- case 4:
+ case 4 /* TSX */:
result.tsx += 1;
result.tsxSize += fileSize;
break;
- case 7:
+ case 7 /* Deferred */:
result.deferred += 1;
result.deferredSize += fileSize;
break;
@@ -122446,15 +124161,18 @@ var ts;
return counts.ts === 0 && counts.tsx === 0;
}
server.allFilesAreJsOrDts = allFilesAreJsOrDts;
+ /* @internal */
function hasNoTypeScriptSource(fileNames) {
- return !fileNames.some(function (fileName) { return (ts.fileExtensionIs(fileName, ".ts") && !ts.fileExtensionIs(fileName, ".d.ts")) || ts.fileExtensionIs(fileName, ".tsx"); });
+ return !fileNames.some(function (fileName) { return (ts.fileExtensionIs(fileName, ".ts" /* Ts */) && !ts.fileExtensionIs(fileName, ".d.ts" /* Dts */)) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */); });
}
server.hasNoTypeScriptSource = hasNoTypeScriptSource;
+ /* @internal */
function isScriptInfo(value) {
return value instanceof server.ScriptInfo;
}
server.isScriptInfo = isScriptInfo;
- var Project = (function () {
+ var Project = /** @class */ (function () {
+ /*@internal*/
function Project(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) {
var _this = this;
this.projectName = projectName;
@@ -122466,14 +124184,37 @@ var ts;
this.rootFiles = [];
this.rootFilesMap = ts.createMap();
this.plugins = [];
+ /*@internal*/
+ /**
+ * This is map from files to unresolved imports in it
+ * Maop does not contain entries for files that do not have unresolved imports
+ * This helps in containing the set of files to invalidate
+ */
this.cachedUnresolvedImportsPerFile = ts.createMap();
+ /*@internal*/
this.hasAddedorRemovedFiles = false;
+ /**
+ * Last version that was reported.
+ */
this.lastReportedVersion = 0;
+ /**
+ * Current project's program version. (incremented everytime new program is created that is not complete reuse from the old one)
+ * This property is changed in 'updateGraph' based on the set of files in program
+ */
this.projectProgramVersion = 0;
+ /**
+ * Current version of the project state. It is changed when:
+ * - new root file was added/removed
+ * - edit happen in some file that is currently included in the project.
+ * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project
+ */
this.projectStateVersion = 0;
this.isInitialLoadPending = ts.returnFalse;
+ /*@internal*/
this.dirty = false;
+ /*@internal*/
this.hasChangedAutomaticTypeDirectiveNames = false;
+ /*@internal*/
this.typingFiles = server.emptyArray;
this.directoryStructureHost = directoryStructureHost;
this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || "");
@@ -122485,6 +124226,7 @@ var ts;
this.compilerOptions.allowJs = true;
}
else if (hasExplicitListOfFiles || this.compilerOptions.allowJs || this.projectService.hasDeferredExtension()) {
+ // If files are listed explicitly or allowJs is specified, allow all extensions
this.compilerOptions.allowNonTsExtensions = true;
}
this.languageServiceEnabled = !projectService.syntaxOnly;
@@ -122499,7 +124241,8 @@ var ts;
if (host.realpath) {
this.realpath = function (path) { return host.realpath(path); };
}
- this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory, true);
+ // Use the current directory as resolution root only if the project created using current directory string
+ this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory, /*logChangesWhenResolvingModule*/ true);
this.languageService = ts.createLanguageService(this, this.documentRegistry, projectService.syntaxOnly);
if (lastFileExceededProgramSize) {
this.disableLanguageService(lastFileExceededProgramSize);
@@ -122518,7 +124261,7 @@ var ts;
Project.resolveModule = function (moduleName, initialDir, host, log) {
var resolvedPath = ts.normalizeSlashes(host.resolvePath(ts.combinePaths(initialDir, "node_modules")));
log("Loading " + moduleName + " from " + initialDir + " (resolved to " + resolvedPath + ")");
- var result = host.require(resolvedPath, moduleName);
+ var result = host.require(resolvedPath, moduleName); // TODO: GH#18217
if (result.error) {
var err = result.error.stack || result.error.message || JSON.stringify(result.error);
log("Failed to load module '" + moduleName + "': " + err);
@@ -122532,6 +124275,7 @@ var ts;
Project.prototype.installPackage = function (options) {
return this.typingsCache.installPackage(__assign({}, options, { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) }));
};
+ /* @internal */
Project.prototype.inspectValue = function (options) {
return this.typingsCache.inspectValue(options);
};
@@ -122542,9 +124286,11 @@ var ts;
enumerable: true,
configurable: true
});
+ // Method of LanguageServiceHost
Project.prototype.getCompilationSettings = function () {
return this.compilerOptions;
};
+ // Method to support public API
Project.prototype.getCompilerOptions = function () {
return this.getCompilationSettings();
};
@@ -122565,6 +124311,7 @@ var ts;
var result;
this.rootFilesMap.forEach(function (value) {
if (_this.languageServiceEnabled || (isScriptInfo(value) && value.isScriptOpen())) {
+ // if language service is disabled - process only files that are open
(result || (result = [])).push(isScriptInfo(value) ? value.fileName : value);
}
});
@@ -122575,6 +124322,7 @@ var ts;
if (scriptInfo) {
var existingValue = this.rootFilesMap.get(scriptInfo.path);
if (existingValue !== scriptInfo && existingValue !== undefined) {
+ // This was missing path earlier but now the file exists. Update the root
this.rootFiles.push(scriptInfo);
this.rootFilesMap.set(scriptInfo.path, scriptInfo);
}
@@ -122584,11 +124332,11 @@ var ts;
};
Project.prototype.getScriptKind = function (fileName) {
var info = this.getOrCreateScriptInfoAndAttachToProject(fileName);
- return (info && info.scriptKind);
+ return (info && info.scriptKind); // TODO: GH#18217
};
Project.prototype.getScriptVersion = function (filename) {
var info = this.getOrCreateScriptInfoAndAttachToProject(filename);
- return (info && info.getLatestVersion());
+ return (info && info.getLatestVersion()); // TODO: GH#18217
};
Project.prototype.getScriptSnapshot = function (filename) {
var scriptInfo = this.getOrCreateScriptInfoAndAttachToProject(filename);
@@ -122619,6 +124367,8 @@ var ts;
return this.projectService.host.writeFile(fileName, content);
};
Project.prototype.fileExists = function (file) {
+ // As an optimization, don't hit the disks for files we already know don't exist
+ // (because we're watching for their creation).
var path = this.toPath(file);
return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file);
};
@@ -122632,33 +124382,41 @@ var ts;
return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference);
};
Project.prototype.directoryExists = function (path) {
- return this.directoryStructureHost.directoryExists(path);
+ return this.directoryStructureHost.directoryExists(path); // TODO: GH#18217
};
Project.prototype.getDirectories = function (path) {
- return this.directoryStructureHost.getDirectories(path);
+ return this.directoryStructureHost.getDirectories(path); // TODO: GH#18217
};
+ /*@internal*/
Project.prototype.getCachedDirectoryStructureHost = function () {
- return undefined;
+ return undefined; // TODO: GH#18217
};
+ /*@internal*/
Project.prototype.toPath = function (fileName) {
return ts.toPath(fileName, this.currentDirectory, this.projectService.toCanonicalFileName);
};
+ /*@internal*/
Project.prototype.watchDirectoryOfFailedLookupLocation = function (directory, cb, flags) {
- return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Failed Lookup Locations", this);
+ return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Failed Lookup Locations" /* FailedLookupLocations */, this);
};
+ /*@internal*/
Project.prototype.onInvalidatedResolution = function () {
this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
};
+ /*@internal*/
Project.prototype.watchTypeRootsDirectory = function (directory, cb, flags) {
- return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Type roots", this);
+ return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Type roots" /* TypeRoots */, this);
};
+ /*@internal*/
Project.prototype.onChangedAutomaticTypeDirectiveNames = function () {
this.hasChangedAutomaticTypeDirectiveNames = true;
this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this);
};
+ /*@internal*/
Project.prototype.getGlobalCache = function () {
return this.getTypeAcquisition().enable ? this.projectService.typingsInstaller.globalTypingsCacheLocation : undefined;
};
+ /*@internal*/
Project.prototype.writeLog = function (s) {
this.projectService.logger.info(s);
};
@@ -122673,6 +124431,9 @@ var ts;
this.compilerOptions.noEmitForJsFiles = true;
}
};
+ /**
+ * Get the errors that dont have any file name associated
+ */
Project.prototype.getGlobalProjectErrors = function () {
return server.emptyArray;
};
@@ -122686,12 +124447,15 @@ var ts;
}
return this.languageService;
};
+ /** @internal */
Project.prototype.getSourceMapper = function () {
return this.getLanguageService().getSourceMapper();
};
+ /*@internal*/
Project.prototype.getDocumentPositionMapper = function (generatedFileName, sourceFileName) {
return this.projectService.getDocumentPositionMapper(this, generatedFileName, sourceFileName);
};
+ /*@internal*/
Project.prototype.getSourceFileLike = function (fileName) {
return this.projectService.getSourceFileLike(fileName, this);
};
@@ -122705,13 +124469,18 @@ var ts;
}
server.updateProjectIfDirty(this);
this.builderState = ts.BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState);
- return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, function (data) { return _this.projectService.host.createHash(data); }), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; });
+ return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, function (data) { return _this.projectService.host.createHash(data); }), // TODO: GH#18217
+ function (// TODO: GH#18217
+ sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; });
};
+ /**
+ * Returns true if emit was conducted
+ */
Project.prototype.emitFile = function (scriptInfo, writeFile) {
if (!this.languageServiceEnabled || !this.shouldEmitFile(scriptInfo)) {
return false;
}
- var _a = this.getLanguageService(false).getEmitOutput(scriptInfo.fileName), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles;
+ var _a = this.getLanguageService(/*ensureSynchronized*/ false).getEmitOutput(scriptInfo.fileName), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles;
if (!emitSkipped) {
for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) {
var outputFile = outputFiles_1[_i];
@@ -122727,7 +124496,7 @@ var ts;
}
this.languageServiceEnabled = true;
this.lastFileExceededProgramSize = undefined;
- this.projectService.onUpdateLanguageServiceStateForProject(this, true);
+ this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ true);
};
Project.prototype.disableLanguageService = function (lastFileExceededProgramSize) {
if (!this.languageServiceEnabled) {
@@ -122739,13 +124508,14 @@ var ts;
this.lastFileExceededProgramSize = lastFileExceededProgramSize;
this.builderState = undefined;
this.resolutionCache.closeTypeRootsWatch();
- this.projectService.onUpdateLanguageServiceStateForProject(this, false);
+ this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ false);
};
Project.prototype.getProjectName = function () {
return this.projectName;
};
Project.prototype.removeLocalTypingsFromTypeAcquisition = function (newTypeAcquisition) {
if (!newTypeAcquisition || !newTypeAcquisition.include) {
+ // Nothing to filter out, so just return as-is
return newTypeAcquisition;
}
return __assign({}, newTypeAcquisition, { include: this.removeExistingTypings(newTypeAcquisition.include) });
@@ -122772,6 +124542,7 @@ var ts;
}
return this.program.getSourceFileByPath(path);
};
+ /* @internal */
Project.prototype.getSourceFileOrConfigFile = function (path) {
var options = this.program.getCompilerOptions();
return path === options.configFilePath ? options.configFile : this.getSourceFile(path);
@@ -122779,6 +124550,9 @@ var ts;
Project.prototype.close = function () {
var _this = this;
if (this.program) {
+ // if we have a program - release all files that are enlisted in program but arent root
+ // The releasing of the roots happens later
+ // The project could have pending update remaining and hence the info could be in the files but not in program graph
for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) {
var f = _a[_i];
this.detachScriptInfoIfNotRoot(f.fileName);
@@ -122789,7 +124563,9 @@ var ts;
}
});
}
+ // Release external files
ts.forEach(this.externalFiles, function (externalFile) { return _this.detachScriptInfoIfNotRoot(externalFile); });
+ // Always remove root files from the project
for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) {
var root = _c[_b];
root.detachFromProject(this);
@@ -122804,15 +124580,19 @@ var ts;
this.resolutionCache = undefined;
this.cachedUnresolvedImportsPerFile = undefined;
this.directoryStructureHost = undefined;
+ // Clean up file watchers waiting for missing files
if (this.missingFilesMap) {
ts.clearMap(this.missingFilesMap, ts.closeFileWatcher);
this.missingFilesMap = undefined;
}
+ // signal language service to release source files acquired from document registry
this.languageService.dispose();
this.languageService = undefined;
};
Project.prototype.detachScriptInfoIfNotRoot = function (uncheckedFilename) {
var info = this.projectService.getScriptInfo(uncheckedFilename);
+ // We might not find the script info in case its not associated with the project any more
+ // and project graph was not updated (eg delayed update graph in case of files changed/deleted on the disk)
if (info && !this.isRoot(info)) {
info.detachFromProject(this);
}
@@ -122823,12 +124603,14 @@ var ts;
Project.prototype.hasRoots = function () {
return this.rootFiles && this.rootFiles.length > 0;
};
+ /*@internal*/
Project.prototype.isOrphan = function () {
return false;
};
Project.prototype.getRootFiles = function () {
return this.rootFiles && this.rootFiles.map(function (info) { return info.fileName; });
};
+ /*@internal*/
Project.prototype.getRootFilesMap = function () {
return this.rootFilesMap;
};
@@ -122838,6 +124620,7 @@ var ts;
Project.prototype.getScriptInfos = function () {
var _this = this;
if (!this.languageServiceEnabled) {
+ // if language service is not enabled - return just root files
return this.rootFiles;
}
return ts.map(this.program.getSourceFiles(), function (sourceFile) {
@@ -122854,6 +124637,7 @@ var ts;
return [];
}
if (!this.languageServiceEnabled) {
+ // if language service is disabled assume that all files in program are root files + default library
var rootFiles = this.getRootFiles();
if (this.compilerOptions) {
var defaultLibrary = ts.getDefaultLibFilePath(this.compilerOptions);
@@ -122922,6 +124706,7 @@ var ts;
Project.prototype.isRoot = function (info) {
return this.rootFilesMap && this.rootFilesMap.get(info.path) === info;
};
+ // add a root file to project
Project.prototype.addRoot = function (info) {
ts.Debug.assert(!this.isRoot(info));
this.rootFiles.push(info);
@@ -122929,6 +124714,7 @@ var ts;
info.attachToProject(this);
this.markAsDirty();
};
+ // add a root file that doesnt exist on host
Project.prototype.addMissingFileRoot = function (fileName) {
var path = this.projectService.toPath(fileName);
this.rootFilesMap.set(path, fileName);
@@ -122939,6 +124725,7 @@ var ts;
this.removeRoot(info);
}
if (fileExists) {
+ // If file is present, just remove the resolutions for the file
this.resolutionCache.removeResolutionsOfFile(info.path);
}
else {
@@ -122959,9 +124746,14 @@ var ts;
this.dirty = true;
}
};
+ /* @internal */
Project.prototype.onFileAddedOrRemoved = function () {
this.hasAddedorRemovedFiles = true;
};
+ /**
+ * Updates set of files that contribute to this project
+ * @returns: true if set of files in the project stays the same and false - otherwise.
+ */
Project.prototype.updateGraph = function () {
this.resolutionCache.startRecordingFilesWithChangedResolutions();
var hasNewProgram = this.updateGraphWorker();
@@ -122970,9 +124762,18 @@ var ts;
var changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || server.emptyArray;
for (var _i = 0, changedFiles_1 = changedFiles; _i < changedFiles_1.length; _i++) {
var file = changedFiles_1[_i];
+ // delete cached information for changed files
this.cachedUnresolvedImportsPerFile.delete(file);
}
+ // update builder only if language service is enabled
+ // otherwise tell it to drop its internal state
if (this.languageServiceEnabled) {
+ // 1. no changes in structure, no changes in unresolved imports - do nothing
+ // 2. no changes in structure, unresolved imports were changed - collect unresolved imports for all files
+ // (can reuse cached imports for files that were not changed)
+ // 3. new files were added/removed, but compilation settings stays the same - collect unresolved imports for all new/modified files
+ // (can reuse cached imports for files that were not changed)
+ // 4. compilation settings were changed in the way that might affect module resolution - drop all caches and collect all data from the scratch
if (hasNewProgram || changedFiles.length) {
this.lastCachedUnresolvedImportsList = getUnresolvedImports(this.program, this.cachedUnresolvedImportsPerFile);
}
@@ -122986,12 +124787,16 @@ var ts;
}
return !hasNewProgram;
};
+ /*@internal*/
Project.prototype.updateTypingFiles = function (typingFiles) {
var _this = this;
- ts.enumerateInsertsAndDeletes(typingFiles, this.typingFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), ts.noop, function (removed) { return _this.detachScriptInfoFromProject(removed); });
+ ts.enumerateInsertsAndDeletes(typingFiles, this.typingFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()),
+ /*inserted*/ ts.noop, function (removed) { return _this.detachScriptInfoFromProject(removed); });
this.typingFiles = typingFiles;
+ // Invalidate files with unresolved imports
this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile);
};
+ /* @internal */
Project.prototype.getCurrentProgram = function () {
return this.program;
};
@@ -123007,11 +124812,14 @@ var ts;
var start = ts.timestamp();
this.hasInvalidatedResolution = this.resolutionCache.createHasInvalidatedResolution();
this.resolutionCache.startCachingPerDirectoryResolution();
- this.program = this.languageService.getProgram();
+ this.program = this.languageService.getProgram(); // TODO: GH#18217
this.dirty = false;
this.resolutionCache.finishCachingPerDirectoryResolution();
ts.Debug.assert(oldProgram === undefined || this.program !== undefined);
- var hasNewProgram = this.program && (!oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2)));
+ // bump up the version if
+ // - oldProgram is not set - this is a first time updateGraph is called
+ // - newProgram is different from the old program and structure of the old program was not reused.
+ var hasNewProgram = this.program && (!oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2 /* Completely */)));
this.hasChangedAutomaticTypeDirectiveNames = false;
if (hasNewProgram) {
if (oldProgram) {
@@ -123019,6 +124827,8 @@ var ts;
var f = _a[_i];
var newFile = this.program.getSourceFileByPath(f.resolvedPath);
if (!newFile || (f.resolvedPath === f.path && newFile.resolvedPath !== f.path)) {
+ // new program does not contain this file - detach it from the project
+ // - remove resolutions only if the new program doesnt contain source file by the path (not resolvedPath since path is used for resolution)
this.detachScriptInfoFromProject(f.fileName, !!this.program.getSourceFileByPath(f.path));
}
}
@@ -123028,14 +124838,22 @@ var ts;
}
});
}
- ts.updateMissingFilePathsWatch(this.program, this.missingFilesMap || (this.missingFilesMap = ts.createMap()), function (missingFilePath) { return _this.addMissingFileWatcher(missingFilePath); });
+ // Update the missing file paths watcher
+ ts.updateMissingFilePathsWatch(this.program, this.missingFilesMap || (this.missingFilesMap = ts.createMap()),
+ // Watch the missing files
+ function (missingFilePath) { return _this.addMissingFileWatcher(missingFilePath); });
+ // Watch the type locations that would be added to program as part of automatic type resolutions
if (this.languageServiceEnabled) {
this.resolutionCache.updateTypeRootsWatch();
}
}
var oldExternalFiles = this.externalFiles || server.emptyArray;
this.externalFiles = this.getExternalFiles();
- ts.enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()), function (inserted) {
+ ts.enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, ts.getStringComparer(!this.useCaseSensitiveFileNames()),
+ // Ensure a ScriptInfo is created for new external files. This is performed indirectly
+ // by the LSHost for files in the program when the program is retrieved above but
+ // the program doesn't contain external files so this must be done explicitly.
+ function (inserted) {
var scriptInfo = _this.projectService.getOrCreateScriptInfoNotOpenedByClient(inserted, _this.currentDirectory, _this.directoryStructureHost);
scriptInfo.attachToProject(_this);
}, function (removed) { return _this.detachScriptInfoFromProject(removed); });
@@ -123061,9 +124879,10 @@ var ts;
if (eventKind === ts.FileWatcherEventKind.Created && _this.missingFilesMap.has(missingFilePath)) {
_this.missingFilesMap.delete(missingFilePath);
fileWatcher.close();
+ // When a missing file is created, we should update the graph.
_this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(_this);
}
- }, ts.PollingInterval.Medium, "Missing file", this);
+ }, ts.PollingInterval.Medium, "Missing file" /* MissingFile */, this);
return fileWatcher;
};
Project.prototype.isWatchedMissingFile = function (path) {
@@ -123093,6 +124912,7 @@ var ts;
}
return strBuilder;
};
+ /*@internal*/
Project.prototype.print = function (counter) {
this.writeLog("Project '" + this.projectName + "' (" + ProjectKind[this.projectKind] + ") " + (counter === undefined ? "" : counter));
this.writeLog(this.filesToString(this.projectService.logger.hasLevel(server.LogLevel.verbose)));
@@ -123105,6 +124925,7 @@ var ts;
this.compilerOptions = compilerOptions;
this.setInternalCompilerOptionsForEmittingJsFiles();
if (ts.changesAffectModuleResolution(oldOptions, compilerOptions)) {
+ // reset cached unresolved imports if changes in compiler options affected module resolution
this.cachedUnresolvedImportsPerFile.clear();
this.lastCachedUnresolvedImportsList = undefined;
this.resolutionCache.clear();
@@ -123112,7 +124933,9 @@ var ts;
this.markAsDirty();
}
};
+ /* @internal */
Project.prototype.getChangesSinceVersion = function (lastKnownVersion) {
+ // Update the graph only if initial configured project load is not pending
if (!this.isInitialLoadPending()) {
server.updateProjectIfDirty(this);
}
@@ -123126,10 +124949,13 @@ var ts;
};
var updatedFileNames = this.updatedFileNames;
this.updatedFileNames = undefined;
+ // check if requested version is the same that we have reported last time
if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) {
+ // if current structure version is the same - return info without any changes
if (this.projectProgramVersion === this.lastReportedVersion && !updatedFileNames) {
return { info: info, projectErrors: this.getGlobalProjectErrors() };
}
+ // compute and return the difference
var lastReportedFileNames_1 = this.lastReportedFileNames;
var externalFiles = this.getExternalFiles().map(function (f) { return server.toNormalizedPath(f); });
var currentFiles_1 = ts.arrayToSet(this.getFileNames().concat(externalFiles));
@@ -123151,6 +124977,7 @@ var ts;
return { info: info, changes: { added: added_1, removed: removed_1, updated: updated }, projectErrors: this.getGlobalProjectErrors() };
}
else {
+ // unknown version - return everything
var projectFileNames = this.getFileNames();
var externalFiles = this.getExternalFiles().map(function (f) { return server.toNormalizedPath(f); });
var allFiles = projectFileNames.concat(externalFiles);
@@ -123159,6 +124986,7 @@ var ts;
return { info: info, files: allFiles, projectErrors: this.getGlobalProjectErrors() };
}
};
+ // remove a root file from project
Project.prototype.removeRoot = function (info) {
ts.orderedRemoveItem(this.rootFiles, info);
this.rootFilesMap.delete(info.path);
@@ -123169,17 +124997,23 @@ var ts;
this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded");
return;
}
+ // Search our peer node_modules, then any globally-specified probe paths
+ // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/
var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations);
if (this.projectService.globalPlugins) {
var _loop_1 = function (globalPluginName) {
+ // Skip empty names from odd commandline parses
if (!globalPluginName)
return "continue";
+ // Skip already-locally-loaded plugins
if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; }))
return "continue";
+ // Provide global: true so plugins can detect why they can't find their config
this_1.projectService.logger.info("Loading global plugin " + globalPluginName);
this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths, pluginConfigOverrides);
};
var this_1 = this;
+ // Enable global plugins with synthetic configuration entries
for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) {
var globalPluginName = _a[_i];
_loop_1(globalPluginName);
@@ -123198,6 +125032,7 @@ var ts;
if (resolvedModule) {
var configurationOverride = pluginConfigOverrides && pluginConfigOverrides.get(pluginConfigEntry.name);
if (configurationOverride) {
+ // Preserve the name property since it's immutable
var pluginName = pluginConfigEntry.name;
pluginConfigEntry = configurationOverride;
pluginConfigEntry.name = pluginName;
@@ -123238,6 +125073,7 @@ var ts;
this.projectService.logger.info("Plugin activation failed: " + e);
}
};
+ /*@internal*/
Project.prototype.onPluginConfigurationChanged = function (pluginName, configuration) {
this.plugins.filter(function (plugin) { return plugin.name === pluginName; }).forEach(function (plugin) {
if (plugin.module.onConfigurationChanged) {
@@ -123245,6 +125081,7 @@ var ts;
}
});
};
+ /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */
Project.prototype.refreshDiagnostics = function () {
this.projectService.sendProjectsUpdatedInBackgroundEvent();
};
@@ -123263,6 +125100,7 @@ var ts;
return server.emptyArray;
var unresolvedImports;
file.resolvedModules.forEach(function (resolvedModule, name) {
+ // pick unresolved non-relative names
if ((!resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) &&
!ts.isExternalModuleNameRelative(name) &&
!ambientModules.some(function (m) { return m === name; })) {
@@ -123272,10 +125110,19 @@ var ts;
return unresolvedImports || server.emptyArray;
});
}
- var InferredProject = (function (_super) {
+ /**
+ * If a file is opened and no tsconfig (or jsconfig) is found,
+ * the file and its imports/references are put into an InferredProject.
+ */
+ var InferredProject = /** @class */ (function (_super) {
__extends(InferredProject, _super);
+ /*@internal*/
function InferredProject(projectService, documentRegistry, compilerOptions, projectRootPath, currentDirectory, pluginConfigOverrides) {
- var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry, undefined, undefined, compilerOptions, false, projectService.host, currentDirectory) || this;
+ var _this = _super.call(this, InferredProject.newName(), ProjectKind.Inferred, projectService, documentRegistry,
+ // TODO: GH#18217
+ /*files*/ undefined,
+ /*lastFileExceededProgramSize*/ undefined, compilerOptions,
+ /*compileOnSaveEnabled*/ false, projectService.host, currentDirectory) || this;
_this._isJsInferredProject = false;
_this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath);
if (!projectRootPath && !projectService.useSingleInferredProject) {
@@ -123291,6 +125138,7 @@ var ts;
}
};
InferredProject.prototype.setCompilerOptions = function (options) {
+ // Avoid manipulating the given options directly
if (!options && !this.getCompilationSettings()) {
return;
}
@@ -123308,7 +125156,7 @@ var ts;
ts.Debug.assert(info.isScriptOpen());
this.projectService.startWatchingConfigFilesForInferredProjectRoot(info);
if (!this._isJsInferredProject && info.isJavaScript()) {
- this.toggleJsInferredProject(true);
+ this.toggleJsInferredProject(/*isJsInferredProject*/ true);
}
_super.prototype.addRoot.call(this, info);
};
@@ -123317,14 +125165,18 @@ var ts;
_super.prototype.removeRoot.call(this, info);
if (this._isJsInferredProject && info.isJavaScript()) {
if (ts.every(this.getRootScriptInfos(), function (rootInfo) { return !rootInfo.isJavaScript(); })) {
- this.toggleJsInferredProject(false);
+ this.toggleJsInferredProject(/*isJsInferredProject*/ false);
}
}
};
+ /*@internal*/
InferredProject.prototype.isOrphan = function () {
return !this.hasRoots();
};
InferredProject.prototype.isProjectWithSingleRoot = function () {
+ // - when useSingleInferredProject is not set and projectRootPath is not set,
+ // we can guarantee that this will be the only root
+ // - other wise it has single root if it has single root script info
return (!this.projectRootPath && !this.projectService.useSingleInferredProject) ||
this.getRootScriptInfos().length === 1;
};
@@ -123351,17 +125203,34 @@ var ts;
return InferredProject;
}(Project));
server.InferredProject = InferredProject;
- var ConfiguredProject = (function (_super) {
+ /**
+ * If a file is opened, the server will look for a tsconfig (or jsconfig)
+ * and if successfull create a ConfiguredProject for it.
+ * Otherwise it will create an InferredProject.
+ */
+ var ConfiguredProject = /** @class */ (function (_super) {
__extends(ConfiguredProject, _super);
+ /*@internal*/
function ConfiguredProject(configFileName, projectService, documentRegistry, cachedDirectoryStructureHost) {
- var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, false, undefined, {}, false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this;
+ var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry,
+ /*hasExplicitListOfFiles*/ false,
+ /*lastFileExceededProgramSize*/ undefined,
+ /*compilerOptions*/ {},
+ /*compileOnSaveEnabled*/ false, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this;
+ /*@internal*/
_this.canConfigFileJsonReportNoInputFiles = false;
+ /** Ref count to the project when opened from external project */
_this.externalProjectRefCount = 0;
_this.isInitialLoadPending = ts.returnTrue;
+ /*@internal*/
_this.sendLoadingProjectFinish = false;
_this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName));
return _this;
}
+ /**
+ * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph
+ * @returns: true if set of files in the project stays the same and false - otherwise.
+ */
ConfiguredProject.prototype.updateGraph = function () {
this.isInitialLoadPending = ts.returnFalse;
var reloadLevel = this.pendingReload;
@@ -123384,6 +125253,7 @@ var ts;
this.projectService.sendProjectTelemetry(this);
return result;
};
+ /*@internal*/
ConfiguredProject.prototype.getCachedDirectoryStructureHost = function () {
return this.directoryStructureHost;
};
@@ -123396,22 +125266,27 @@ var ts;
ConfiguredProject.prototype.updateReferences = function (refs) {
this.projectReferences = refs;
};
+ /*@internal*/
ConfiguredProject.prototype.forEachResolvedProjectReference = function (cb) {
var program = this.getCurrentProgram();
return program && program.forEachResolvedProjectReference(cb);
};
+ /*@internal*/
ConfiguredProject.prototype.enablePluginsWithOptions = function (options, pluginConfigOverrides) {
var host = this.projectService.host;
if (!host.require) {
this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded");
return;
}
+ // Search our peer node_modules, then any globally-specified probe paths
+ // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/
var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations);
if (this.projectService.allowLocalPluginLoads) {
var local = ts.getDirectoryPath(this.canonicalConfigFilePath);
this.projectService.logger.info("Local plugin loading enabled; adding " + local + " to search paths");
searchPaths.unshift(local);
}
+ // Enable tsconfig-specified plugins
if (options.plugins) {
for (var _i = 0, _a = options.plugins; _i < _a.length; _i++) {
var pluginConfigEntry = _a[_i];
@@ -123420,9 +125295,15 @@ var ts;
}
this.enableGlobalPlugins(options, pluginConfigOverrides);
};
+ /**
+ * Get the errors that dont have any file name associated
+ */
ConfiguredProject.prototype.getGlobalProjectErrors = function () {
return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }) || server.emptyArray;
};
+ /**
+ * Get all the project errors
+ */
ConfiguredProject.prototype.getAllProjectErrors = function () {
return this.projectErrors || server.emptyArray;
};
@@ -123435,10 +125316,14 @@ var ts;
ConfiguredProject.prototype.getTypeAcquisition = function () {
return this.typeAcquisition;
};
+ /*@internal*/
ConfiguredProject.prototype.watchWildcards = function (wildcardDirectories) {
var _this = this;
- ts.updateWatchingWildcardDirectories(this.directoriesWatchedForWildcards || (this.directoriesWatchedForWildcards = ts.createMap()), wildcardDirectories, function (directory, flags) { return _this.projectService.watchWildcardDirectory(directory, flags, _this); });
+ ts.updateWatchingWildcardDirectories(this.directoriesWatchedForWildcards || (this.directoriesWatchedForWildcards = ts.createMap()), wildcardDirectories,
+ // Create new directory watcher
+ function (directory, flags) { return _this.projectService.watchWildcardDirectory(directory, flags, _this); });
};
+ /*@internal*/
ConfiguredProject.prototype.stopWatchingWildCards = function () {
if (this.directoriesWatchedForWildcards) {
ts.clearMap(this.directoriesWatchedForWildcards, ts.closeFileWatcherOf);
@@ -123455,42 +125340,61 @@ var ts;
this.configFileSpecs = undefined;
_super.prototype.close.call(this);
};
+ /* @internal */
ConfiguredProject.prototype.addExternalProjectReference = function () {
this.externalProjectRefCount++;
};
+ /* @internal */
ConfiguredProject.prototype.deleteExternalProjectReference = function () {
this.externalProjectRefCount--;
};
+ /** Returns true if the project is needed by any of the open script info/external project */
+ /* @internal */
ConfiguredProject.prototype.hasOpenRef = function () {
var _this = this;
if (!!this.externalProjectRefCount) {
return true;
}
+ // Closed project doesnt have any reference
if (this.isClosed()) {
return false;
}
var configFileExistenceInfo = this.projectService.getConfigFileExistenceInfo(this);
if (this.projectService.hasPendingProjectUpdate(this)) {
+ // If there is pending update for this project,
+ // we dont know if this project would be needed by any of the open files impacted by this config file
+ // In that case keep the project alive if there are open files impacted by this project
return !!configFileExistenceInfo.openFilesImpactedByConfigFile.size;
}
+ // If there is no pending update for this project,
+ // We know exact set of open files that get impacted by this configured project as the files in the project
+ // The project is referenced only if open files impacted by this project are present in this project
return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (_value, infoPath) { return _this.containsScriptInfo(_this.projectService.getScriptInfoForPath(infoPath)); }) || false;
};
+ /*@internal*/
ConfiguredProject.prototype.hasExternalProjectRef = function () {
return !!this.externalProjectRefCount;
};
ConfiguredProject.prototype.getEffectiveTypeRoots = function () {
return ts.getEffectiveTypeRoots(this.getCompilationSettings(), this.directoryStructureHost) || [];
};
+ /*@internal*/
ConfiguredProject.prototype.updateErrorOnNoInputFiles = function (fileNameResult) {
ts.updateErrorForNoInputFiles(fileNameResult, this.getConfigFilePath(), this.configFileSpecs, this.projectErrors, this.canConfigFileJsonReportNoInputFiles);
};
return ConfiguredProject;
}(Project));
server.ConfiguredProject = ConfiguredProject;
- var ExternalProject = (function (_super) {
+ /**
+ * Project whose configuration is handled externally, such as in a '.csproj'.
+ * These are created only if a host explicitly calls `openExternalProject`.
+ */
+ var ExternalProject = /** @class */ (function (_super) {
__extends(ExternalProject, _super);
+ /*@internal*/
function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath) {
- var _this = _super.call(this, externalProjectName, ProjectKind.External, projectService, documentRegistry, true, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, projectService.host, ts.getDirectoryPath(projectFilePath || ts.normalizeSlashes(externalProjectName))) || this;
+ var _this = _super.call(this, externalProjectName, ProjectKind.External, projectService, documentRegistry,
+ /*hasExplicitListOfFiles*/ true, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, projectService.host, ts.getDirectoryPath(projectFilePath || ts.normalizeSlashes(externalProjectName))) || this;
_this.externalProjectName = externalProjectName;
_this.compileOnSaveEnabled = compileOnSaveEnabled;
_this.excludedFiles = [];
@@ -123524,7 +125428,9 @@ var ts;
var server;
(function (server) {
server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024;
+ /*@internal*/
server.maxFileSize = 4 * 1024 * 1024;
+ // tslint:disable variable-name
server.ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground";
server.ProjectLoadingStartEvent = "projectLoadingStart";
server.ProjectLoadingFinishEvent = "projectLoadingFinish";
@@ -123539,6 +125445,7 @@ var ts;
var option = commandLineOptions_1[_i];
if (typeof option.type === "object") {
var optionMap = option.type;
+ // verify that map contains only numbers
optionMap.forEach(function (value) {
ts.Debug.assert(typeof value === "number");
});
@@ -123553,25 +125460,47 @@ var ts;
block: ts.IndentStyle.Block,
smart: ts.IndentStyle.Smart
});
+ /**
+ * How to understand this block:
+ * * The 'match' property is a regexp that matches a filename.
+ * * If 'match' is successful, then:
+ * * All files from 'exclude' are removed from the project. See below.
+ * * All 'types' are included in ATA
+ * * What the heck is 'exclude' ?
+ * * An array of an array of strings and numbers
+ * * Each array is:
+ * * An array of strings and numbers
+ * * The strings are literals
+ * * The numbers refer to capture group indices from the 'match' regexp
+ * * Remember that '1' is the first group
+ * * These are concatenated together to form a new regexp
+ * * Filenames matching these regexps are excluded from the project
+ * This default value is tested in tsserverProjectSystem.ts; add tests there
+ * if you are changing this so that you can be sure your regexp works!
+ */
var defaultTypeSafeList = {
"jquery": {
+ // jquery files can have names like "jquery-1.10.2.min.js" (or "jquery.intellisense.js")
match: /jquery(-(\.?\d+)+)?(\.intellisense)?(\.min)?\.js$/i,
types: ["jquery"]
},
"WinJS": {
+ // e.g. c:/temp/UWApp1/lib/winjs-4.0.1/js/base.js
match: /^(.*\/winjs-[.\d]+)\/js\/base\.js$/i,
exclude: [["^", 1, "/.*"]],
- types: ["winjs"]
+ types: ["winjs"] // And fetch the @types package for WinJS
},
"Kendo": {
+ // e.g. /Kendo3/wwwroot/lib/kendo/kendo.all.min.js
match: /^(.*\/kendo(-ui)?)\/kendo\.all(\.min)?\.js$/i,
exclude: [["^", 1, "/.*"]],
types: ["kendo-ui"]
},
"Office Nuget": {
+ // e.g. /scripts/Office/1/excel-15.debug.js
match: /^(.*\/office\/1)\/excel-\d+\.debug\.js$/i,
exclude: [["^", 1, "/.*"]],
- types: ["office"]
+ types: ["office"] // @types package to fetch instead
},
"References": {
match: /^(.*\/_references\.js)$/i,
@@ -123603,18 +125532,19 @@ var ts;
function convertScriptKindName(scriptKindName) {
switch (scriptKindName) {
case "JS":
- return 1;
+ return 1 /* JS */;
case "JSX":
- return 2;
+ return 2 /* JSX */;
case "TS":
- return 3;
+ return 3 /* TS */;
case "TSX":
- return 4;
+ return 4 /* TSX */;
default:
- return 0;
+ return 0 /* Unknown */;
}
}
server.convertScriptKindName = convertScriptKindName;
+ /*@internal*/
function convertUserPreferences(preferences) {
var lazyConfiguredProjectsFromExternalProject = preferences.lazyConfiguredProjectsFromExternalProject, userPreferences = __rest(preferences, ["lazyConfiguredProjectsFromExternalProject"]);
return userPreferences;
@@ -123636,7 +125566,7 @@ var ts;
});
}
}
- return result;
+ return result; // TODO: GH#18217
},
hasMixedContent: function (fileName, extraFileExtensions) { return ts.some(extraFileExtensions, function (ext) { return ext.isMixedContent && ts.fileExtensionIs(fileName, ext.extension); }); },
};
@@ -123672,6 +125602,7 @@ var ts;
function isScriptInfoWatchedFromNodeModules(info) {
return !info.isScriptOpen() && info.mTime !== undefined;
}
+ /*@internal*/
function updateProjectIfDirty(project) {
return project.dirty && project.updateGraph();
}
@@ -123681,26 +125612,66 @@ var ts;
project.projectOptions = true;
}
}
- var ProjectService = (function () {
+ var ProjectService = /** @class */ (function () {
function ProjectService(opts) {
var _this = this;
+ /**
+ * Container of all known scripts
+ */
+ /*@internal*/
this.filenameToScriptInfo = ts.createMap();
this.scriptInfoInNodeModulesWatchers = ts.createMap();
+ /**
+ * Contains all the deleted script info's version information so that
+ * it does not reset when creating script info again
+ * (and could have potentially collided with version where contents mismatch)
+ */
this.filenameToScriptInfoVersion = ts.createMap();
+ // Set of all '.js' files ever opened.
this.allJsFilesForOpenFileTelemetry = ts.createMap();
+ /**
+ * maps external project file name to list of config files that were the part of this project
+ */
this.externalProjectToConfiguredProjectMap = ts.createMap();
+ /**
+ * external projects (configuration and list of root files is not controlled by tsserver)
+ */
this.externalProjects = [];
+ /**
+ * projects built from openFileRoots
+ */
this.inferredProjects = [];
+ /**
+ * projects specified by a tsconfig.json file
+ */
this.configuredProjects = ts.createMap();
+ /**
+ * Open files: with value being project root path, and key being Path of the file that is open
+ */
this.openFiles = ts.createMap();
+ /**
+ * Map of open files that are opened without complete path but have projectRoot as current directory
+ */
this.openFilesWithNonRootedDiskPath = ts.createMap();
this.compilerOptionsForInferredProjectsPerProjectRoot = ts.createMap();
+ /**
+ * Project size for configured or external projects
+ */
this.projectToSizeMap = ts.createMap();
+ /**
+ * This is a map of config file paths existance that doesnt need query to disk
+ * - The entry can be present because there is inferred project that needs to watch addition of config file to directory
+ * In this case the exists could be true/false based on config file is present or not
+ * - Or it is present if we have configured project open with config file at that location
+ * In this case the exists property is always true
+ */
this.configFileExistenceInfoCache = ts.createMap();
this.safelist = defaultTypeSafeList;
this.legacySafelist = ts.createMap();
this.pendingProjectUpdates = ts.createMap();
+ /* @internal */
this.pendingEnsureProjectForOpenFiles = false;
+ /** Tracks projects that we have already sent telemetry for. */
this.seenProjects = ts.createMap();
this.host = opts.host;
this.logger = opts.logger;
@@ -123749,26 +125720,33 @@ var ts;
ProjectService.prototype.toPath = function (fileName) {
return ts.toPath(fileName, this.currentDirectory, this.toCanonicalFileName);
};
+ /*@internal*/
ProjectService.prototype.getExecutingFilePath = function () {
return this.getNormalizedAbsolutePath(this.host.getExecutingFilePath());
};
+ /*@internal*/
ProjectService.prototype.getNormalizedAbsolutePath = function (fileName) {
return ts.getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory());
};
+ /*@internal*/
ProjectService.prototype.setDocument = function (key, path, sourceFile) {
var info = ts.Debug.assertDefined(this.getScriptInfoForPath(path));
info.cacheSourceFile = { key: key, sourceFile: sourceFile };
};
+ /*@internal*/
ProjectService.prototype.getDocument = function (key, path) {
var info = this.getScriptInfoForPath(path);
return info && info.cacheSourceFile && info.cacheSourceFile.key === key ? info.cacheSourceFile.sourceFile : undefined;
};
+ /* @internal */
ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () {
this.ensureProjectStructuresUptoDate();
};
+ /* @internal */
ProjectService.prototype.getCompilerOptionsForInferredProjects = function () {
return this.compilerOptionsForInferredProjects;
};
+ /* @internal */
ProjectService.prototype.onUpdateLanguageServiceStateForProject = function (project, languageServiceEnabled) {
if (!this.eventHandler) {
return;
@@ -123781,16 +125759,18 @@ var ts;
};
ProjectService.prototype.loadTypesMap = function () {
try {
- var fileContent = this.host.readFile(this.typesMapLocation);
+ var fileContent = this.host.readFile(this.typesMapLocation); // TODO: GH#18217
if (fileContent === undefined) {
this.logger.info("Provided types map file \"" + this.typesMapLocation + "\" doesn't exist");
return;
}
var raw = JSON.parse(fileContent);
+ // Parse the regexps
for (var _i = 0, _a = Object.keys(raw.typesMap); _i < _a.length; _i++) {
var k = _a[_i];
raw.typesMap[k].match = new RegExp(raw.typesMap[k].match, "i");
}
+ // raw is now fixed and ready
this.safelist = raw.typesMap;
for (var key in raw.simpleMap) {
if (raw.simpleMap.hasOwnProperty(key)) {
@@ -123811,10 +125791,12 @@ var ts;
}
switch (response.kind) {
case server.ActionSet:
+ // Update the typing files and update the project
project.updateTypingFiles(this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings));
break;
case server.ActionInvalidate:
- this.typingsCache.enqueueInstallTypingsForProject(project, project.lastCachedUnresolvedImportsList, true);
+ // Do not clear resolution cache, there was changes detected in typings, so enque typing request and let it get us correct results
+ this.typingsCache.enqueueInstallTypingsForProject(project, project.lastCachedUnresolvedImportsList, /*forceRefresh*/ true);
return;
}
this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project);
@@ -123822,13 +125804,15 @@ var ts;
ProjectService.prototype.delayEnsureProjectForOpenFiles = function () {
var _this = this;
this.pendingEnsureProjectForOpenFiles = true;
- this.throttledOperations.schedule("*ensureProjectForOpenFiles*", 250, function () {
+ this.throttledOperations.schedule("*ensureProjectForOpenFiles*", /*delay*/ 250, function () {
if (_this.pendingProjectUpdates.size !== 0) {
_this.delayEnsureProjectForOpenFiles();
}
else {
if (_this.pendingEnsureProjectForOpenFiles) {
_this.ensureProjectForOpenFiles();
+ // Send the event to notify that there were background project updates
+ // send current list of open files
_this.sendProjectsUpdatedInBackgroundEvent();
}
}
@@ -123839,15 +125823,17 @@ var ts;
project.markAsDirty();
var projectName = project.getProjectName();
this.pendingProjectUpdates.set(projectName, project);
- this.throttledOperations.schedule(projectName, 250, function () {
+ this.throttledOperations.schedule(projectName, /*delay*/ 250, function () {
if (_this.pendingProjectUpdates.delete(projectName)) {
updateProjectIfDirty(project);
}
});
};
+ /*@internal*/
ProjectService.prototype.hasPendingProjectUpdate = function (project) {
return this.pendingProjectUpdates.has(project.getProjectName());
};
+ /* @internal */
ProjectService.prototype.sendProjectsUpdatedInBackgroundEvent = function () {
var _this = this;
if (!this.eventHandler) {
@@ -123861,6 +125847,7 @@ var ts;
};
this.eventHandler(event);
};
+ /* @internal */
ProjectService.prototype.sendLargeFileReferencedEvent = function (file, fileSize) {
if (!this.eventHandler) {
return;
@@ -123871,6 +125858,7 @@ var ts;
};
this.eventHandler(event);
};
+ /* @internal */
ProjectService.prototype.sendProjectLoadingStartEvent = function (project, reason) {
if (!this.eventHandler) {
return;
@@ -123882,6 +125870,7 @@ var ts;
};
this.eventHandler(event);
};
+ /* @internal */
ProjectService.prototype.sendProjectLoadingFinishEvent = function (project) {
if (!this.eventHandler || !project.sendLoadingProjectFinish) {
return;
@@ -123893,6 +125882,7 @@ var ts;
};
this.eventHandler(event);
};
+ /* @internal */
ProjectService.prototype.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles = function (project) {
this.delayUpdateProjectGraph(project);
this.delayEnsureProjectForOpenFiles();
@@ -123909,6 +125899,8 @@ var ts;
ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions, projectRootPath) {
ts.Debug.assert(projectRootPath === undefined || this.useInferredProjectPerProjectRoot, "Setting compiler options per project root path is only supported when useInferredProjectPerProjectRoot is enabled");
var compilerOptions = convertCompilerOptions(projectCompilerOptions);
+ // always set 'allowNonTsExtensions' for inferred projects since user cannot configure it from the outside
+ // previously we did not expose a way for user to change these settings and this option was enabled by default
compilerOptions.allowNonTsExtensions = true;
var canonicalProjectRootPath = projectRootPath && this.toCanonicalFileName(projectRootPath);
if (canonicalProjectRootPath) {
@@ -123919,6 +125911,14 @@ var ts;
}
for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) {
var project = _a[_i];
+ // Only update compiler options in the following cases:
+ // - Inferred projects without a projectRootPath, if the new options do not apply to
+ // a workspace root
+ // - Inferred projects with a projectRootPath, if the new options do not apply to a
+ // workspace root and there is no more specific set of options for that project's
+ // root path
+ // - Inferred projects with a projectRootPath, if the new options apply to that
+ // project root path.
if (canonicalProjectRootPath ?
project.projectRootPath === canonicalProjectRootPath :
!project.projectRootPath || !this.compilerOptionsForInferredProjectsPerProjectRoot.has(project.projectRootPath)) {
@@ -123939,11 +125939,13 @@ var ts;
}
return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName));
};
+ /* @internal */
ProjectService.prototype.forEachProject = function (cb) {
this.externalProjects.forEach(cb);
this.configuredProjects.forEach(cb);
this.inferredProjects.forEach(cb);
};
+ /* @internal */
ProjectService.prototype.forEachEnabledProject = function (cb) {
this.forEachProject(function (project) {
if (!project.isOrphan() && project.languageServiceEnabled) {
@@ -123954,10 +125956,12 @@ var ts;
ProjectService.prototype.getDefaultProjectForFile = function (fileName, ensureProject) {
return ensureProject ? this.ensureDefaultProjectForFile(fileName) : this.tryGetDefaultProjectForFile(fileName);
};
+ /* @internal */
ProjectService.prototype.tryGetDefaultProjectForFile = function (fileName) {
var scriptInfo = this.getScriptInfoForNormalizedPath(fileName);
return scriptInfo && !scriptInfo.isOrphan() ? scriptInfo.getDefaultProject() : undefined;
};
+ /* @internal */
ProjectService.prototype.ensureDefaultProjectForFile = function (fileName) {
return this.tryGetDefaultProjectForFile(fileName) || this.doEnsureDefaultProjectForFile(fileName);
};
@@ -123970,6 +125974,13 @@ var ts;
this.ensureProjectStructuresUptoDate();
return this.getScriptInfo(uncheckedFileName);
};
+ /**
+ * Ensures the project structures are upto date
+ * This means,
+ * - we go through all the projects and update them if they are dirty
+ * - if updates reflect some change in structure or there was pending request to ensure projects for open files
+ * ensure that each open script info has project
+ */
ProjectService.prototype.ensureProjectStructuresUptoDate = function () {
var hasChanges = this.pendingEnsureProjectForOpenFiles;
this.pendingProjectUpdates.clear();
@@ -124007,9 +126018,12 @@ var ts;
info.containingProjects.forEach(function (project) { return project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(info.path); });
}
if (eventKind === ts.FileWatcherEventKind.Deleted) {
+ // File was deleted
this.handleDeletedFile(info);
}
else if (!info.isScriptOpen()) {
+ // file has been changed which might affect the set of referenced files in projects that include
+ // this file and set of inferred projects
info.delayReloadNonMixedContentFile();
this.delayUpdateProjectGraphs(info.containingProjects);
this.handleSourceMapProjects(info);
@@ -124017,6 +126031,7 @@ var ts;
}
};
ProjectService.prototype.handleSourceMapProjects = function (info) {
+ // Change in d.ts, update source projects as well
if (info.sourceMapFilePath) {
if (ts.isString(info.sourceMapFilePath)) {
var sourceMapFileInfo = this.getScriptInfoForPath(info.sourceMapFilePath);
@@ -124026,6 +126041,7 @@ var ts;
this.delayUpdateSourceInfoProjects(info.sourceMapFilePath.sourceInfos);
}
}
+ // Change in mapInfo, update declarationProjects and source projects
this.delayUpdateSourceInfoProjects(info.sourceInfos);
if (info.declarationInfoPath) {
this.delayUpdateProjectsOfScriptInfoPath(info.declarationInfoPath);
@@ -124047,11 +126063,14 @@ var ts;
this.stopWatchingScriptInfo(info);
if (!info.isScriptOpen()) {
this.deleteScriptInfo(info);
+ // capture list of projects since detachAllProjects will wipe out original list
var containingProjects = info.containingProjects.slice();
info.detachAllProjects();
+ // update projects to make sure that set of referenced files is correct
this.delayUpdateProjectGraphs(containingProjects);
this.handleSourceMapProjects(info);
info.closeSourceMapFileWatcher();
+ // need to recalculate source map from declaration file
if (info.declarationInfoPath) {
var declarationInfo = this.getScriptInfoForPath(info.declarationInfoPath);
if (declarationInfo) {
@@ -124060,58 +126079,85 @@ var ts;
}
}
};
+ /**
+ * This is to watch whenever files are added or removed to the wildcard directories
+ */
+ /*@internal*/
ProjectService.prototype.watchWildcardDirectory = function (directory, flags, project) {
var _this = this;
return this.watchFactory.watchDirectory(this.host, directory, function (fileOrDirectory) {
var fileOrDirectoryPath = _this.toPath(fileOrDirectory);
project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
var configFilename = project.getConfigFilePath();
+ // If the the added or created file or directory is not supported file name, ignore the file
+ // But when watched directory is added/removed, we need to reload the file list
if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, project.getCompilationSettings(), _this.hostConfiguration.extraFileExtensions)) {
_this.logger.info("Project: " + configFilename + " Detected file add/remove of non supported extension: " + fileOrDirectory);
return;
}
+ // Reload is pending, do the reload
if (project.pendingReload !== ts.ConfigFileProgramReloadLevel.Full) {
project.pendingReload = ts.ConfigFileProgramReloadLevel.Partial;
_this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project);
}
- }, flags, "Wild card directory", project);
+ }, flags, "Wild card directory" /* WildcardDirectory */, project);
};
+ /** Gets the config file existence info for the configured project */
+ /*@internal*/
ProjectService.prototype.getConfigFileExistenceInfo = function (project) {
return this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath);
};
ProjectService.prototype.onConfigChangedForConfiguredProject = function (project, eventKind) {
var configFileExistenceInfo = this.getConfigFileExistenceInfo(project);
if (eventKind === ts.FileWatcherEventKind.Deleted) {
+ // Update the cached status
+ // We arent updating or removing the cached config file presence info as that will be taken care of by
+ // setConfigFilePresenceByClosedConfigFile when the project is closed (depending on tracking open files)
configFileExistenceInfo.exists = false;
this.removeProject(project);
- this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for files");
- this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, false);
+ // Reload the configured projects for the open files in the map as they are affected by this config file
+ // Since the configured project was deleted, we want to reload projects for all the open files including files
+ // that are not root of the inferred project
+ this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for files" /* ReloadingFiles */);
+ this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false);
}
else {
- this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files");
+ this.logConfigFileWatchUpdate(project.getConfigFilePath(), project.canonicalConfigFilePath, configFileExistenceInfo, "Reloading configured projects for only inferred root files" /* ReloadingInferredRootFiles */);
project.pendingReload = ts.ConfigFileProgramReloadLevel.Full;
project.pendingReloadReason = "Change in config file detected";
this.delayUpdateProjectGraph(project);
- this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, true);
+ // As we scheduled the update on configured project graph,
+ // we would need to schedule the project reload for only the root of inferred projects
+ this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ true);
}
};
+ /**
+ * This is the callback function for the config file add/remove/change at any location
+ * that matters to open script info but doesnt have configured project open
+ * for the config file
+ */
ProjectService.prototype.onConfigFileChangeForOpenScriptInfo = function (configFileName, eventKind) {
+ // This callback is called only if we dont have config file project for this config file
var canonicalConfigPath = server.normalizedPathToPath(configFileName, this.currentDirectory, this.toCanonicalFileName);
var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigPath);
configFileExistenceInfo.exists = (eventKind !== ts.FileWatcherEventKind.Deleted);
- this.logConfigFileWatchUpdate(configFileName, canonicalConfigPath, configFileExistenceInfo, "Reloading configured projects for files");
- this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, false);
+ this.logConfigFileWatchUpdate(configFileName, canonicalConfigPath, configFileExistenceInfo, "Reloading configured projects for files" /* ReloadingFiles */);
+ // Because there is no configured project open for the config file, the tracking open files map
+ // will only have open files that need the re-detection of the project and hence
+ // reload projects for all the tracking open files in the map
+ this.delayReloadConfiguredProjectForFiles(configFileExistenceInfo, /*ignoreIfNotInferredProjectRoot*/ false);
};
ProjectService.prototype.removeProject = function (project) {
var _this = this;
this.logger.info("`remove Project::");
project.print();
project.close();
- if (ts.Debug.shouldAssert(1)) {
+ if (ts.Debug.shouldAssert(1 /* Normal */)) {
this.filenameToScriptInfo.forEach(function (info) { return ts.Debug.assert(!info.isAttached(project), "Found script Info still attached to project", function () { return project.projectName + ": ScriptInfos still attached: " + JSON.stringify(ts.mapDefined(ts.arrayFrom(_this.filenameToScriptInfo.values()), function (info) { return info.isAttached(project) ? info : undefined; })); }); });
}
+ // Remove the project from pending project updates
this.pendingProjectUpdates.delete(project.getProjectName());
switch (project.projectKind) {
case server.ProjectKind.External:
@@ -124128,6 +126174,7 @@ var ts;
break;
}
};
+ /*@internal*/
ProjectService.prototype.assignOrphanScriptInfoToInferredProject = function (info, projectRootPath) {
ts.Debug.assert(info.isOrphan());
var project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) ||
@@ -124135,6 +126182,7 @@ var ts;
this.getOrCreateSingleInferredWithoutProjectRoot(info.isDynamic ? this.currentDirectory : ts.getDirectoryPath(info.path));
project.addRoot(info);
if (info.containingProjects[0] !== project) {
+ // Ensure this is first project, we could be in this scenario because info could be part of orphan project
info.detachFromProject(project);
info.containingProjects.unshift(project);
}
@@ -124144,12 +126192,21 @@ var ts;
if (inferredProject === project || inferredProject.isOrphan()) {
return "continue";
}
+ // Remove the inferred project if the root of it is now part of newly created inferred project
+ // e.g through references
+ // Which means if any root of inferred project is part of more than 1 project can be removed
+ // This logic is same as iterating over all open files and calling
+ // this.removeRootOfInferredProjectIfNowPartOfOtherProject(f);
+ // Since this is also called from refreshInferredProject and closeOpen file
+ // to update inferred projects of the open file, this iteration might be faster
+ // instead of scanning all open files
var roots = inferredProject.getRootScriptInfos();
ts.Debug.assert(roots.length === 1 || !!inferredProject.projectRootPath);
if (roots.length === 1 && ts.forEach(roots[0].containingProjects, function (p) { return p !== roots[0].containingProjects[0] && !p.isOrphan(); })) {
- inferredProject.removeFile(roots[0], true, true);
+ inferredProject.removeFile(roots[0], /*fileExists*/ true, /*detachFromProject*/ true);
}
};
+ // Note that we need to create a copy of the array since the list of project can change
for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) {
var inferredProject = _a[_i];
_loop_2(inferredProject);
@@ -124157,8 +126214,25 @@ var ts;
}
return project;
};
- ProjectService.prototype.closeOpenFile = function (info) {
+ ProjectService.prototype.assignOrphanScriptInfosToInferredProject = function () {
var _this = this;
+ // collect orphaned files and assign them to inferred project just like we treat open of a file
+ this.openFiles.forEach(function (projectRootPath, path) {
+ var info = _this.getScriptInfoForPath(path);
+ // collect all orphaned script infos from open files
+ if (info.isOrphan()) {
+ _this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
+ }
+ });
+ };
+ /**
+ * Remove this file from the set of open, non-configured files.
+ * @param info The file that has been closed or newly configured
+ */
+ ProjectService.prototype.closeOpenFile = function (info, skipAssignOrphanScriptInfosToInferredProject) {
+ // Closing file should trigger re-reading the file content from disk. This is
+ // because the user may chose to discard the buffer content before saving
+ // to the disk, and the server's version of the file can be out of sync.
var fileExists = this.host.fileExists(info.fileName);
info.close(fileExists);
this.stopWatchingConfigFilesForClosedScriptInfo(info);
@@ -124166,6 +126240,7 @@ var ts;
if (this.openFilesWithNonRootedDiskPath.get(canonicalFileName) === info) {
this.openFilesWithNonRootedDiskPath.delete(canonicalFileName);
}
+ // collect all projects that should be removed
var ensureProjectsForOpenFiles = false;
for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) {
var p = _a[_i];
@@ -124173,50 +126248,69 @@ var ts;
if (info.hasMixedContent) {
info.registerFileUpdate();
}
+ // Do not remove the project so that we can reuse this project
+ // if it would need to be re-created with next file open
}
else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) {
+ // If this was the last open root file of inferred project
if (p.isProjectWithSingleRoot()) {
ensureProjectsForOpenFiles = true;
}
- p.removeFile(info, fileExists, true);
+ p.removeFile(info, fileExists, /*detachFromProject*/ true);
+ // Do not remove the project even if this was last root of the inferred project
+ // so that we can reuse this project, if it would need to be re-created with next file open
}
if (!p.languageServiceEnabled) {
+ // if project language service is disabled then we create a program only for open files.
+ // this means that project should be marked as dirty to force rebuilding of the program
+ // on the next request
p.markAsDirty();
}
}
this.openFiles.delete(info.path);
- if (ensureProjectsForOpenFiles) {
- this.openFiles.forEach(function (projectRootPath, path) {
- var info = _this.getScriptInfoForPath(path);
- if (info.isOrphan()) {
- _this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
- }
- });
- }
+ if (!skipAssignOrphanScriptInfosToInferredProject && ensureProjectsForOpenFiles) {
+ this.assignOrphanScriptInfosToInferredProject();
+ }
+ // Cleanup script infos that arent part of any project (eg. those could be closed script infos not referenced by any project)
+ // is postponed to next file open so that if file from same project is opened,
+ // we wont end up creating same script infos
+ // If the current info is being just closed - add the watcher file to track changes
+ // But if file was deleted, handle that part
if (fileExists) {
this.watchClosedScriptInfo(info);
}
else {
this.handleDeletedFile(info);
}
+ return ensureProjectsForOpenFiles;
};
ProjectService.prototype.deleteScriptInfo = function (info) {
this.filenameToScriptInfo.delete(info.path);
this.filenameToScriptInfoVersion.set(info.path, info.getVersion());
var realpath = info.getRealpathIfDifferent();
if (realpath) {
- this.realpathToScriptInfos.remove(realpath, info);
+ this.realpathToScriptInfos.remove(realpath, info); // TODO: GH#18217
}
};
ProjectService.prototype.configFileExists = function (configFileName, canonicalConfigFilePath, info) {
var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
if (configFileExistenceInfo) {
+ // By default the info would get impacted by presence of config file since its in the detection path
+ // Only adding the info as a root to inferred project will need the existence to be watched by file watcher
if (isOpenScriptInfo(info) && !configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) {
configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false);
- this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file");
+ this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file" /* OpenFilesImpactedByConfigFileAdd */);
}
return configFileExistenceInfo.exists;
}
+ // Theoretically we should be adding watch for the directory here itself.
+ // In practice there will be very few scenarios where the config file gets added
+ // somewhere inside the another config file directory.
+ // And technically we could handle that case in configFile's directory watcher in some cases
+ // But given that its a rare scenario it seems like too much overhead. (we werent watching those directories earlier either)
+ // So what we are now watching is: configFile if the configured project corresponding to it is open
+ // Or the whole chain of config files for the roots of the inferred projects
+ // Cache the host value of file exists and add the info to map of open files impacted by this config file
var exists = this.host.fileExists(configFileName);
var openFilesImpactedByConfigFile = ts.createMap();
if (isOpenScriptInfo(info)) {
@@ -124224,27 +126318,34 @@ var ts;
}
configFileExistenceInfo = { exists: exists, openFilesImpactedByConfigFile: openFilesImpactedByConfigFile };
this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo);
- this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file");
+ this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File added to open files impacted by this config file" /* OpenFilesImpactedByConfigFileAdd */);
return exists;
};
ProjectService.prototype.setConfigFileExistenceByNewConfiguredProject = function (project) {
var configFileExistenceInfo = this.getConfigFileExistenceInfo(project);
if (configFileExistenceInfo) {
+ // The existance might not be set if the file watcher is not invoked by the time config project is created by external project
configFileExistenceInfo.exists = true;
+ // close existing watcher
if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) {
var configFileName = project.getConfigFilePath();
configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close();
configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined;
- this.logConfigFileWatchUpdate(configFileName, project.canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback");
+ this.logConfigFileWatchUpdate(configFileName, project.canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback" /* UpdatedCallback */);
}
}
else {
+ // We could be in this scenario if project is the configured project tracked by external project
+ // Since that route doesnt check if the config file is present or not
this.configFileExistenceInfoCache.set(project.canonicalConfigFilePath, {
exists: true,
openFilesImpactedByConfigFile: ts.createMap()
});
}
};
+ /**
+ * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project
+ */
ProjectService.prototype.configFileExistenceImpactsRootOfInferredProject = function (configFileExistenceInfo) {
return ts.forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, function (isRootOfInferredProject) { return isRootOfInferredProject; });
};
@@ -124253,12 +126354,16 @@ var ts;
ts.Debug.assert(!!configFileExistenceInfo);
if (configFileExistenceInfo.openFilesImpactedByConfigFile.size) {
var configFileName = closedProject.getConfigFilePath();
+ // If there are open files that are impacted by this config file existence
+ // but none of them are root of inferred project, the config file watcher will be
+ // created when any of the script infos are added as root of inferred project
if (this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) {
ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject);
this.createConfigFileWatcherOfConfigFileExistence(configFileName, closedProject.canonicalConfigFilePath, configFileExistenceInfo);
}
}
else {
+ // There is not a single file open thats tracking the status of this config file. Remove from cache
this.configFileExistenceInfoCache.delete(closedProject.canonicalConfigFilePath);
}
};
@@ -124275,25 +126380,36 @@ var ts;
});
var watches = [];
if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) {
- watches.push("Config file for the inferred project root");
+ watches.push("Config file for the inferred project root" /* ConfigFileForInferredRoot */);
}
if (this.configuredProjects.has(canonicalConfigFilePath)) {
- watches.push("Config file");
+ watches.push("Config file" /* ConfigFile */);
}
this.logger.info("ConfigFilePresence:: Current Watches: " + watches + ":: File: " + configFileName + " Currently impacted open files: RootsOfInferredProjects: " + inferredRoots + " OtherOpenFiles: " + otherFiles + " Status: " + status);
};
+ /**
+ * Create the watcher for the configFileExistenceInfo
+ */
ProjectService.prototype.createConfigFileWatcherOfConfigFileExistence = function (configFileName, canonicalConfigFilePath, configFileExistenceInfo) {
var _this = this;
- configFileExistenceInfo.configFileWatcherForRootOfInferredProject = this.watchFactory.watchFile(this.host, configFileName, function (_filename, eventKind) { return _this.onConfigFileChangeForOpenScriptInfo(configFileName, eventKind); }, ts.PollingInterval.High, "Config file for the inferred project root");
- this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback");
+ configFileExistenceInfo.configFileWatcherForRootOfInferredProject = this.watchFactory.watchFile(this.host, configFileName, function (_filename, eventKind) { return _this.onConfigFileChangeForOpenScriptInfo(configFileName, eventKind); }, ts.PollingInterval.High, "Config file for the inferred project root" /* ConfigFileForInferredRoot */);
+ this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Updated the callback" /* UpdatedCallback */);
};
+ /**
+ * Close the config file watcher in the cached ConfigFileExistenceInfo
+ * if there arent any open files that are root of inferred project
+ */
ProjectService.prototype.closeConfigFileWatcherOfConfigFileExistenceInfo = function (configFileExistenceInfo) {
+ // Close the config file watcher if there are no more open files that are root of inferred project
if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject &&
!this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) {
configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close();
configFileExistenceInfo.configFileWatcherForRootOfInferredProject = undefined;
}
};
+ /**
+ * This is called on file close, so that we stop watching the config file for this script info
+ */
ProjectService.prototype.stopWatchingConfigFilesForClosedScriptInfo = function (info) {
var _this = this;
ts.Debug.assert(!info.isScriptOpen());
@@ -124301,11 +126417,18 @@ var ts;
var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
if (configFileExistenceInfo) {
var infoIsRootOfInferredProject = configFileExistenceInfo.openFilesImpactedByConfigFile.get(info.path);
+ // Delete the info from map, since this file is no more open
configFileExistenceInfo.openFilesImpactedByConfigFile.delete(info.path);
- _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File removed from open files impacted by this config file");
+ _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "File removed from open files impacted by this config file" /* OpenFilesImpactedByConfigFileRemove */);
+ // If the script info was not root of inferred project,
+ // there wont be config file watch open because of this script info
if (infoIsRootOfInferredProject) {
+ // But if it is a root, it could be the last script info that is root of inferred project
+ // and hence we would need to close the config file watcher
_this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo);
}
+ // If there are no open files that are impacted by configFileExistenceInfo after closing this script info
+ // there is no configured project present, remove the cached existence info
if (!configFileExistenceInfo.openFilesImpactedByConfigFile.size &&
!_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) {
ts.Debug.assert(!configFileExistenceInfo.configFileWatcherForRootOfInferredProject);
@@ -124314,38 +126437,59 @@ var ts;
}
});
};
+ /**
+ * This is called by inferred project whenever script info is added as a root
+ */
+ /* @internal */
ProjectService.prototype.startWatchingConfigFilesForInferredProjectRoot = function (info) {
var _this = this;
ts.Debug.assert(info.isScriptOpen());
this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) {
var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
if (!configFileExistenceInfo) {
+ // Create the cache
configFileExistenceInfo = {
exists: _this.host.fileExists(configFileName),
openFilesImpactedByConfigFile: ts.createMap()
};
_this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo);
}
+ // Set this file as the root of inferred project
configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, true);
- _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as Inferred root");
+ _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as Inferred root" /* RootOfInferredProjectTrue */);
+ // If there is no configured project for this config file, add the file watcher
if (!configFileExistenceInfo.configFileWatcherForRootOfInferredProject &&
!_this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath)) {
_this.createConfigFileWatcherOfConfigFileExistence(configFileName, canonicalConfigFilePath, configFileExistenceInfo);
}
});
};
+ /**
+ * This is called by inferred project whenever root script info is removed from it
+ */
+ /* @internal */
ProjectService.prototype.stopWatchingConfigFilesForInferredProjectRoot = function (info) {
var _this = this;
this.forEachConfigFileLocation(info, function (configFileName, canonicalConfigFilePath) {
var configFileExistenceInfo = _this.configFileExistenceInfoCache.get(canonicalConfigFilePath);
if (configFileExistenceInfo && configFileExistenceInfo.openFilesImpactedByConfigFile.has(info.path)) {
ts.Debug.assert(info.isScriptOpen());
+ // Info is not root of inferred project any more
configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false);
- _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as not inferred root");
+ _this.logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, "Open file was set as not inferred root" /* RootOfInferredProjectFalse */);
+ // Close the config file watcher
_this.closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo);
}
});
};
+ /**
+ * This function tries to search for a tsconfig.json for the given file.
+ * This is different from the method the compiler uses because
+ * the compiler can assume it will always start searching in the
+ * current directory (the directory in which tsc was invoked).
+ * The server must start searching from the directory containing
+ * the newly opened file.
+ */
ProjectService.prototype.forEachConfigFileLocation = function (info, action) {
var _this = this;
if (this.syntaxOnly) {
@@ -124355,6 +126499,7 @@ var ts;
var projectRootPath = this.openFiles.get(info.path);
var searchPath = server.asNormalizedPath(ts.getDirectoryPath(info.fileName));
var isSearchPathInProjectRoot = function () { return ts.containsPath(projectRootPath, searchPath, _this.currentDirectory, !_this.host.useCaseSensitiveFileNames); };
+ // If projectRootPath doesn't contain info.path, then do normal search for config file
var anySearchPathOk = !projectRootPath || !isSearchPathInProjectRoot();
do {
var canonicalSearchPath = server.normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName);
@@ -124376,6 +126521,16 @@ var ts;
} while (anySearchPathOk || isSearchPathInProjectRoot());
return undefined;
};
+ /**
+ * This function tries to search for a tsconfig.json for the given file.
+ * This is different from the method the compiler uses because
+ * the compiler can assume it will always start searching in the
+ * current directory (the directory in which tsc was invoked).
+ * The server must start searching from the directory containing
+ * the newly opened file.
+ * If script info is passed in, it is asserted to be open script info
+ * otherwise just file name
+ */
ProjectService.prototype.getConfigFileNameForFile = function (info) {
var _this = this;
if (isOpenScriptInfo(info))
@@ -124413,6 +126568,7 @@ var ts;
this.logger.endGroup();
};
ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) {
+ // make sure that casing of config file name is consistent
var canonicalConfigFilePath = server.asNormalizedPath(this.toCanonicalFileName(configFileName));
return this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath);
};
@@ -124422,6 +126578,7 @@ var ts;
ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) {
return findProjectByName(projectFileName, this.externalProjects);
};
+ /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */
ProjectService.prototype.getFilenameForExceededTotalSizeLimitForNonTsFiles = function (name, options, fileNames, propertyReader) {
if (options && options.disableSizeLimit || !this.host.getFileSize) {
return;
@@ -124439,6 +126596,7 @@ var ts;
totalNonTsFileSize += this.host.getFileSize(fileName);
if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) {
this.logger.info(getExceedLimitMessage({ propertyReader: propertyReader, hasTSFileExtension: ts.hasTSFileExtension, host: this.host }, totalNonTsFileSize));
+ // Keep the size as zero since it's disabled
return fileName;
}
}
@@ -124452,19 +126610,21 @@ var ts;
var propertyReader = _a.propertyReader, hasTSFileExtension = _a.hasTSFileExtension, host = _a.host;
return fileNames.map(function (f) { return propertyReader.getFileName(f); })
.filter(function (name) { return hasTSFileExtension(name); })
- .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); })
+ .map(function (name) { return ({ name: name, size: host.getFileSize(name) }); }) // TODO: GH#18217
.sort(function (a, b) { return b.size - a.size; })
.slice(0, 5);
}
};
ProjectService.prototype.createExternalProject = function (projectFileName, files, options, typeAcquisition, excludedFiles) {
var compilerOptions = convertCompilerOptions(options);
- var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave);
+ var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions,
+ /*lastFileExceededProgramSize*/ this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave);
project.excludedFiles = excludedFiles;
this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition);
this.externalProjects.push(project);
return project;
};
+ /*@internal*/
ProjectService.prototype.sendProjectTelemetry = function (project) {
if (this.seenProjects.has(project.projectName)) {
setProjectOptionsUsed(project);
@@ -124479,7 +126639,7 @@ var ts;
setProjectOptionsUsed(project);
var data = {
projectId: this.host.createSHA256Hash(project.projectName),
- fileStats: server.countEachFileTypes(project.getScriptInfos(), true),
+ fileStats: server.countEachFileTypes(project.getScriptInfos(), /*includeSizes*/ true),
compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()),
typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()),
extends: projectOptions && projectOptions.configHasExtendsProperty,
@@ -124514,45 +126674,57 @@ var ts;
};
ProjectService.prototype.createConfiguredProject = function (configFileName) {
var _this = this;
- var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames);
+ var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); // TODO: GH#18217
this.logger.info("Opened configuration file " + configFileName);
var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, cachedDirectoryStructureHost);
- project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file", project);
+ // TODO: We probably should also watch the configFiles that are extended
+ project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file" /* ConfigFile */, project);
this.configuredProjects.set(project.canonicalConfigFilePath, project);
this.setConfigFileExistenceByNewConfiguredProject(project);
return project;
};
+ /* @internal */
ProjectService.prototype.createConfiguredProjectWithDelayLoad = function (configFileName, reason) {
var project = this.createConfiguredProject(configFileName);
project.pendingReload = ts.ConfigFileProgramReloadLevel.Full;
project.pendingReloadReason = reason;
return project;
};
+ /* @internal */
ProjectService.prototype.createAndLoadConfiguredProject = function (configFileName, reason) {
var project = this.createConfiguredProject(configFileName);
this.loadConfiguredProject(project, reason);
return project;
};
+ /* @internal */
ProjectService.prototype.createLoadAndUpdateConfiguredProject = function (configFileName, reason) {
var project = this.createAndLoadConfiguredProject(configFileName, reason);
project.updateGraph();
return project;
};
+ /**
+ * Read the config file of the project, and update the project root file names.
+ */
+ /* @internal */
ProjectService.prototype.loadConfiguredProject = function (project, reason) {
this.sendProjectLoadingStartEvent(project, reason);
+ // Read updated contents from disk
var configFilename = ts.normalizePath(project.getConfigFilePath());
- var configFileContent = this.host.readFile(configFilename);
+ var configFileContent = this.host.readFile(configFilename); // TODO: GH#18217
var result = ts.parseJsonText(configFilename, configFileContent);
if (!result.endOfFileToken) {
- result.endOfFileToken = { kind: 1 };
+ result.endOfFileToken = { kind: 1 /* EndOfFileToken */ };
}
var configFileErrors = result.parseDiagnostics;
- var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions);
+ var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, project.getCachedDirectoryStructureHost(), ts.getDirectoryPath(configFilename),
+ /*existingOptions*/ {}, configFilename,
+ /*resolutionStack*/ [], this.hostConfiguration.extraFileExtensions);
if (parsedCommandLine.errors.length) {
configFileErrors.push.apply(configFileErrors, parsedCommandLine.errors);
}
ts.Debug.assert(!!parsedCommandLine.fileNames);
var compilerOptions = parsedCommandLine.options;
+ // Update the project
if (!project.projectOptions) {
project.projectOptions = {
configHasExtendsProperty: parsedCommandLine.raw.extends !== undefined,
@@ -124572,11 +126744,11 @@ var ts;
}
else {
project.enableLanguageService();
- project.watchWildcards(ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories));
+ project.watchWildcards(ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories)); // TODO: GH#18217
}
project.enablePluginsWithOptions(compilerOptions, this.currentPluginConfigOverrides);
var filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles());
- this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave);
+ this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave); // TODO: GH#18217
};
ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) {
var projectRootFilesMap = project.getRootFilesMap();
@@ -124588,11 +126760,12 @@ var ts;
var isDynamic = server.isDynamicFileName(normalizedPath);
var scriptInfo = void 0;
var path = void 0;
+ // Use the project's fileExists so that it can use caching instead of reaching to disk for the query
if (!isDynamic && !project.fileExists(newRootFile)) {
path = server.normalizedPathToPath(normalizedPath, this.currentDirectory, this.toCanonicalFileName);
var existingValue = projectRootFilesMap.get(path);
if (server.isScriptInfo(existingValue)) {
- project.removeFile(existingValue, false, true);
+ project.removeFile(existingValue, /*fileExists*/ false, /*detachFromProject*/ true);
}
projectRootFilesMap.set(path, normalizedPath);
scriptInfo = normalizedPath;
@@ -124600,22 +126773,27 @@ var ts;
else {
var scriptKind = propertyReader.getScriptKind(f, this.hostConfiguration.extraFileExtensions);
var hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
- scriptInfo = this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(normalizedPath, project.currentDirectory, scriptKind, hasMixedContent, project.directoryStructureHost);
+ scriptInfo = this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(normalizedPath, project.currentDirectory, scriptKind, hasMixedContent, project.directoryStructureHost); // TODO: GH#18217
path = scriptInfo.path;
+ // If this script info is not already a root add it
if (!project.isRoot(scriptInfo)) {
project.addRoot(scriptInfo);
if (scriptInfo.isScriptOpen()) {
+ // if file is already root in some inferred project
+ // - remove the file from that project and delete the project if necessary
this.removeRootOfInferredProjectIfNowPartOfOtherProject(scriptInfo);
}
}
}
newRootScriptInfoMap.set(path, scriptInfo);
}
+ // project's root file map size is always going to be same or larger than new roots map
+ // as we have already all the new files to the project
if (projectRootFilesMap.size > newRootScriptInfoMap.size) {
projectRootFilesMap.forEach(function (value, path) {
if (!newRootScriptInfoMap.has(path)) {
if (server.isScriptInfo(value)) {
- project.removeFile(value, project.fileExists(path), true);
+ project.removeFile(value, project.fileExists(path), /*detachFromProject*/ true);
}
else {
projectRootFilesMap.delete(path);
@@ -124623,28 +126801,43 @@ var ts;
}
});
}
+ // Just to ensure that even if root files dont change, the changes to the non root file are picked up,
+ // mark the project as dirty unconditionally
project.markAsDirty();
};
ProjectService.prototype.updateRootAndOptionsOfNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave) {
project.setCompilerOptions(newOptions);
+ // VS only set the CompileOnSaveEnabled option in the request if the option was changed recently
+ // therefore if it is undefined, it should not be updated.
if (compileOnSave !== undefined) {
project.compileOnSaveEnabled = compileOnSave;
}
this.addFilesToNonInferredProject(project, newUncheckedFiles, propertyReader, newTypeAcquisition);
};
+ /**
+ * Reload the file names from config file specs and update the project graph
+ */
+ /*@internal*/
ProjectService.prototype.reloadFileNamesOfConfiguredProject = function (project) {
- var configFileSpecs = project.configFileSpecs;
+ var configFileSpecs = project.configFileSpecs; // TODO: GH#18217
var configFileName = project.getConfigFilePath();
var fileNamesResult = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), project.getCompilationSettings(), project.getCachedDirectoryStructureHost(), this.hostConfiguration.extraFileExtensions);
project.updateErrorOnNoInputFiles(fileNamesResult);
this.updateNonInferredProjectFiles(project, fileNamesResult.fileNames.concat(project.getExternalFiles()), fileNamePropertyReader);
return project.updateGraph();
};
+ /**
+ * Read the config file of the project again by clearing the cache and update the project graph
+ */
+ /* @internal */
ProjectService.prototype.reloadConfiguredProject = function (project, reason) {
+ // At this point, there is no reason to not have configFile in the host
var host = project.getCachedDirectoryStructureHost();
+ // Clear the cache since we are reloading the project from disk
host.clearCache();
var configFileName = project.getConfigFilePath();
this.logger.info("Reloading configured project " + configFileName);
+ // Load project from the disk
this.loadConfiguredProject(project, reason);
project.updateGraph();
this.sendConfigFileDiagEvent(project, configFileName);
@@ -124666,21 +126859,28 @@ var ts;
}
if (projectRootPath) {
var canonicalProjectRootPath = this.toCanonicalFileName(projectRootPath);
+ // if we have an explicit project root path, find (or create) the matching inferred project.
for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) {
var project = _a[_i];
if (project.projectRootPath === canonicalProjectRootPath) {
return project;
}
}
- return this.createInferredProject(projectRootPath, false, projectRootPath);
+ return this.createInferredProject(projectRootPath, /*isSingleInferredProject*/ false, projectRootPath);
}
+ // we don't have an explicit root path, so we should try to find an inferred project
+ // that more closely contains the file.
var bestMatch;
for (var _b = 0, _c = this.inferredProjects; _b < _c.length; _b++) {
var project = _c[_b];
+ // ignore single inferred projects (handled elsewhere)
if (!project.projectRootPath)
continue;
+ // ignore inferred projects that don't contain the root's path
if (!ts.containsPath(project.projectRootPath, info.path, this.host.getCurrentDirectory(), !this.host.useCaseSensitiveFileNames))
continue;
+ // ignore inferred projects that are higher up in the project root.
+ // TODO(rbuckton): Should we add the file as a root to these as well?
if (bestMatch && bestMatch.projectRootPath.length > project.projectRootPath.length)
continue;
bestMatch = project;
@@ -124691,14 +126891,24 @@ var ts;
if (!this.useSingleInferredProject) {
return undefined;
}
+ // If `useInferredProjectPerProjectRoot` is not enabled, then there will only be one
+ // inferred project for all files. If `useInferredProjectPerProjectRoot` is enabled
+ // then we want to put all files that are not opened with a `projectRootPath` into
+ // the same inferred project.
+ //
+ // To avoid the cost of searching through the array and to optimize for the case where
+ // `useInferredProjectPerProjectRoot` is not enabled, we will always put the inferred
+ // project for non-rooted files at the front of the array.
if (this.inferredProjects.length > 0 && this.inferredProjects[0].projectRootPath === undefined) {
return this.inferredProjects[0];
}
- return this.createInferredProject(undefined, true);
+ // Single inferred project does not have a project root and hence no current directory
+ return this.createInferredProject(/*currentDirectory*/ undefined, /*isSingleInferredProject*/ true);
};
ProjectService.prototype.getOrCreateSingleInferredWithoutProjectRoot = function (currentDirectory) {
ts.Debug.assert(!this.useSingleInferredProject);
var expectedCurrentDirectory = this.toCanonicalFileName(this.getNormalizedAbsolutePath(currentDirectory || ""));
+ // Reuse the project with same current directory but no roots
for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) {
var inferredProject = _a[_i];
if (!inferredProject.projectRootPath &&
@@ -124710,7 +126920,7 @@ var ts;
return this.createInferredProject(currentDirectory);
};
ProjectService.prototype.createInferredProject = function (currentDirectory, isSingleInferredProject, projectRootPath) {
- var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects;
+ var compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; // TODO: GH#18217
var project = new server.InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory, this.currentPluginConfigOverrides);
if (isSingleInferredProject) {
this.inferredProjects.unshift(project);
@@ -124720,12 +126930,15 @@ var ts;
}
return project;
};
+ /*@internal*/
ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClient = function (uncheckedFileName, currentDirectory, hostToQueryFileExistsOn) {
- return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(server.toNormalizedPath(uncheckedFileName), currentDirectory, undefined, undefined, hostToQueryFileExistsOn);
+ return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(server.toNormalizedPath(uncheckedFileName), currentDirectory, /*scriptKind*/ undefined,
+ /*hasMixedContent*/ undefined, hostToQueryFileExistsOn);
};
ProjectService.prototype.getScriptInfo = function (uncheckedFileName) {
return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName));
};
+ /* @internal */
ProjectService.prototype.getScriptInfoOrConfig = function (uncheckedFileName) {
var path = server.toNormalizedPath(uncheckedFileName);
var info = this.getScriptInfoForNormalizedPath(path);
@@ -124734,6 +126947,7 @@ var ts;
var configProject = this.configuredProjects.get(this.toPath(uncheckedFileName));
return configProject && configProject.getCompilerOptions().configFile;
};
+ /* @internal */
ProjectService.prototype.logErrorForScriptInfoNotFound = function (fileName) {
var names = ts.arrayFrom(this.filenameToScriptInfo.entries()).map(function (_a) {
var path = _a[0], scriptInfo = _a[1];
@@ -124741,6 +126955,11 @@ var ts;
});
this.logger.msg("Could not find file " + JSON.stringify(fileName) + ".\nAll files are: " + JSON.stringify(names), server.Msg.Err);
};
+ /**
+ * Returns the projects that contain script info through SymLink
+ * Note that this does not return projects in info.containingProjects
+ */
+ /*@internal*/
ProjectService.prototype.getSymlinkedProjects = function (info) {
var projects;
if (this.realpathToScriptInfos) {
@@ -124754,6 +126973,7 @@ var ts;
function combineProjects(toAddInfo) {
if (toAddInfo !== info) {
var _loop_3 = function (project) {
+ // Add the projects only if they can use symLink targets and not already in the list
if (project.languageServiceEnabled &&
!project.isOrphan() &&
!project.getCompilerOptions().preserveSymlinks &&
@@ -124777,12 +126997,14 @@ var ts;
ProjectService.prototype.watchClosedScriptInfo = function (info) {
var _this = this;
ts.Debug.assert(!info.fileWatcher);
+ // do not watch files with mixed content - server doesn't know how to interpret it
+ // do not watch files in the global cache location
if (!info.isDynamicOrHasMixedContent() &&
(!this.globalCacheLocationDirectoryPath ||
!ts.startsWith(info.path, this.globalCacheLocationDirectoryPath))) {
var indexOfNodeModules = info.path.indexOf("/node_modules/");
if (!this.host.getModifiedTime || indexOfNodeModules === -1) {
- info.fileWatcher = this.watchFactory.watchFilePath(this.host, info.fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info");
+ info.fileWatcher = this.watchFactory.watchFilePath(this.host, info.fileName, function (fileName, eventKind, path) { return _this.onSourceFileChanged(fileName, eventKind, path); }, ts.PollingInterval.Medium, info.path, "Closed Script info" /* ClosedScriptInfo */);
}
else {
info.mTime = this.getModifiedTime(info);
@@ -124792,6 +127014,7 @@ var ts;
};
ProjectService.prototype.watchClosedScriptInfoInNodeModules = function (dir) {
var _this = this;
+ // Watch only directory
var existing = this.scriptInfoInNodeModulesWatchers.get(dir);
if (existing) {
existing.refCount++;
@@ -124800,8 +127023,9 @@ var ts;
var watchDir = dir + "/node_modules";
var watcher = this.watchFactory.watchDirectory(this.host, watchDir, function (fileOrDirectory) {
var fileOrDirectoryPath = _this.toPath(fileOrDirectory);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
+ // Has extension
ts.Debug.assert(result.refCount > 0);
if (watchDir === fileOrDirectoryPath) {
_this.refreshScriptInfosInDirectory(watchDir);
@@ -124813,11 +127037,12 @@ var ts;
_this.refreshScriptInfo(info);
}
}
+ // Folder
else if (!ts.hasExtension(fileOrDirectoryPath)) {
_this.refreshScriptInfosInDirectory(fileOrDirectoryPath);
}
}
- }, 1, "node_modules for closed script infos in them");
+ }, 1 /* Recursive */, "node_modules for closed script infos in them" /* NodeModulesForClosedScriptInfo */);
var result = {
close: function () {
if (result.refCount === 1) {
@@ -124861,16 +127086,20 @@ var ts;
};
ProjectService.prototype.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath = function (fileName, currentDirectory, scriptKind, hasMixedContent, hostToQueryFileExistsOn) {
if (ts.isRootedDiskPath(fileName) || server.isDynamicFileName(fileName)) {
- return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, false, undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn);
+ return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent, hostToQueryFileExistsOn);
}
+ // This is non rooted path with different current directory than project service current directory
+ // Only paths recognized are open relative file paths
var info = this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName));
if (info) {
return info;
}
+ // This means triple slash references wont be resolved in dynamic and unsaved files
+ // which is intentional since we dont know what it means to be relative to non disk files
return undefined;
};
ProjectService.prototype.getOrCreateScriptInfoOpenedByClientForNormalizedPath = function (fileName, currentDirectory, fileContent, scriptKind, hasMixedContent) {
- return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, true, fileContent, scriptKind, hasMixedContent);
+ return this.getOrCreateScriptInfoWorker(fileName, currentDirectory, /*openedByClient*/ true, fileContent, scriptKind, hasMixedContent);
};
ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) {
return this.getOrCreateScriptInfoWorker(fileName, this.currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn);
@@ -124885,20 +127114,24 @@ var ts;
ts.Debug.assert(ts.isRootedDiskPath(fileName) || isDynamic || openedByClient, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nScript info with non-dynamic relative file name can only be open script info or in context of host currentDirectory"; });
ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nOpen script files with non rooted disk path opened with current directory context cannot have same canonical names"; });
ts.Debug.assert(!isDynamic || this.currentDirectory === currentDirectory, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nDynamic files must always have current directory context since containing external project name will always match the script info name."; });
+ // If the file is not opened by client and the file doesnot exist on the disk, return
if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) {
return;
}
- info = new server.ScriptInfo(this.host, fileName, scriptKind, !!hasMixedContent, path, this.filenameToScriptInfoVersion.get(path));
+ info = new server.ScriptInfo(this.host, fileName, scriptKind, !!hasMixedContent, path, this.filenameToScriptInfoVersion.get(path)); // TODO: GH#18217
this.filenameToScriptInfo.set(info.path, info);
this.filenameToScriptInfoVersion.delete(info.path);
if (!openedByClient) {
this.watchClosedScriptInfo(info);
}
else if (!ts.isRootedDiskPath(fileName) && !isDynamic) {
+ // File that is opened by user but isn't rooted disk path
this.openFilesWithNonRootedDiskPath.set(this.toCanonicalFileName(fileName), info);
}
}
if (openedByClient && !info.isScriptOpen()) {
+ // Opening closed script info
+ // either it was created just now, or was part of projects but was closed
this.stopWatchingScriptInfo(info);
info.open(fileContent);
if (hasMixedContent) {
@@ -124910,6 +127143,9 @@ var ts;
}
return info;
};
+ /**
+ * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred
+ */
ProjectService.prototype.getScriptInfoForNormalizedPath = function (fileName) {
return !ts.isRootedDiskPath(fileName) && this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)) ||
this.getScriptInfoForPath(server.normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName));
@@ -124917,13 +127153,17 @@ var ts;
ProjectService.prototype.getScriptInfoForPath = function (fileName) {
return this.filenameToScriptInfo.get(fileName);
};
+ /*@internal*/
ProjectService.prototype.getDocumentPositionMapper = function (project, generatedFileName, sourceFileName) {
var _this = this;
+ // Since declaration info and map file watches arent updating project's directory structure host (which can cache file structure) use host
var declarationInfo = this.getOrCreateScriptInfoNotOpenedByClient(generatedFileName, project.currentDirectory, this.host);
if (!declarationInfo)
return undefined;
- declarationInfo.getSnapshot();
+ // Try to get from cache
+ declarationInfo.getSnapshot(); // Ensure synchronized
if (ts.isString(declarationInfo.sourceMapFilePath)) {
+ // Ensure mapper is synchronized
var sourceMapFileInfo_1 = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath);
if (sourceMapFileInfo_1) {
sourceMapFileInfo_1.getSnapshot();
@@ -124939,8 +127179,10 @@ var ts;
return undefined;
}
else if (declarationInfo.sourceMapFilePath !== undefined) {
+ // Doesnt have sourceMap
return undefined;
}
+ // Create the mapper
var sourceMapFileInfo;
var mapFileNameFromDeclarationInfo;
var readMapFile = function (mapFileName, mapFileNameFromDts) {
@@ -124957,7 +127199,7 @@ var ts;
};
var projectName = project.projectName;
var documentPositionMapper = ts.getDocumentPositionMapper({ getCanonicalFileName: this.toCanonicalFileName, log: function (s) { return _this.logger.info(s); }, getSourceFileLike: function (f) { return _this.getSourceFileLike(f, projectName, declarationInfo); } }, declarationInfo.fileName, declarationInfo.getLineInfo(), readMapFile);
- readMapFile = undefined;
+ readMapFile = undefined; // Remove ref to project
if (sourceMapFileInfo) {
declarationInfo.sourceMapFilePath = sourceMapFileInfo.path;
sourceMapFileInfo.declarationInfoPath = declarationInfo.path;
@@ -124979,6 +127221,7 @@ var ts;
};
ProjectService.prototype.addSourceInfoToSourceMap = function (sourceFileName, project, sourceInfos) {
if (sourceFileName) {
+ // Attach as source
var sourceInfo = this.getOrCreateScriptInfoNotOpenedByClient(sourceFileName, project.currentDirectory, project.directoryStructureHost);
(sourceInfos || (sourceInfos = ts.createMap())).set(sourceInfo.path, true);
}
@@ -124989,13 +127232,15 @@ var ts;
var fileWatcher = this.watchFactory.watchFile(this.host, mapFileName, function () {
var declarationInfo = _this.getScriptInfoForPath(declarationInfoPath);
if (declarationInfo && declarationInfo.sourceMapFilePath && !ts.isString(declarationInfo.sourceMapFilePath)) {
+ // Update declaration and source projects
_this.delayUpdateProjectGraphs(declarationInfo.containingProjects);
_this.delayUpdateSourceInfoProjects(declarationInfo.sourceMapFilePath.sourceInfos);
declarationInfo.closeSourceMapFileWatcher();
}
- }, ts.PollingInterval.High, "Missing source map file");
+ }, ts.PollingInterval.High, "Missing source map file" /* MissingSourceMapFile */);
return fileWatcher;
};
+ /*@internal*/
ProjectService.prototype.getSourceFileLike = function (fileName, projectNameOrProject, declarationInfo) {
var project = projectNameOrProject.projectName ? projectNameOrProject : this.findProject(projectNameOrProject);
if (project) {
@@ -125004,17 +127249,21 @@ var ts;
if (sourceFile && sourceFile.resolvedPath === path)
return sourceFile;
}
+ // Need to look for other files.
var info = this.getOrCreateScriptInfoNotOpenedByClient(fileName, (project || this).currentDirectory, project ? project.directoryStructureHost : this.host);
if (!info)
return undefined;
+ // Attach as source
if (declarationInfo && ts.isString(declarationInfo.sourceMapFilePath) && info !== declarationInfo) {
var sourceMapInfo = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath);
if (sourceMapInfo) {
(sourceMapInfo.sourceInfos || (sourceMapInfo.sourceInfos = ts.createMap())).set(info.path, true);
}
}
+ // Key doesnt matter since its only for text and lines
if (info.cacheSourceFile)
return info.cacheSourceFile.sourceFile;
+ // Create sourceFileLike
if (!info.sourceFileLike) {
info.sourceFileLike = {
get text() {
@@ -125052,6 +127301,7 @@ var ts;
var lazyConfiguredProjectsFromExternalProject = this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject;
this.hostConfiguration.preferences = __assign({}, this.hostConfiguration.preferences, args.preferences);
if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) {
+ // Load configured projects for external projects that are pending reload
this.configuredProjects.forEach(function (project) {
if (project.hasExternalProjectRef() &&
project.pendingReload === ts.ConfigFileProgramReloadLevel.Full &&
@@ -125063,6 +127313,8 @@ var ts;
}
if (args.extraFileExtensions) {
this.hostConfiguration.extraFileExtensions = args.extraFileExtensions;
+ // We need to update the project structures again as it is possible that existing
+ // project structure could have more or less files depending on extensions permitted
this.reloadProjects();
this.logger.info("Host file extension mappings updated");
}
@@ -125071,26 +127323,51 @@ var ts;
ProjectService.prototype.closeLog = function () {
this.logger.close();
};
+ /**
+ * This function rebuilds the project for every file opened by the client
+ * This does not reload contents of open files from disk. But we could do that if needed
+ */
ProjectService.prototype.reloadProjects = function () {
this.logger.info("reload projects.");
- this.reloadConfiguredProjectForFiles(this.openFiles, false, ts.returnTrue, "User requested reload projects");
+ // If we want this to also reload open files from disk, we could do that,
+ // but then we need to make sure we arent calling this function
+ // (and would separate out below reloading of projects to be called when immediate reload is needed)
+ // as there is no need to load contents of the files from the disk
+ // Reload Projects
+ this.reloadConfiguredProjectForFiles(this.openFiles, /*delayReload*/ false, ts.returnTrue, "User requested reload projects");
this.ensureProjectForOpenFiles();
};
ProjectService.prototype.delayReloadConfiguredProjectForFiles = function (configFileExistenceInfo, ignoreIfNotRootOfInferredProject) {
- this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile, true, ignoreIfNotRootOfInferredProject ?
- function (isRootOfInferredProject) { return isRootOfInferredProject; } :
- ts.returnTrue, "Change in config file detected");
+ // Get open files to reload projects for
+ this.reloadConfiguredProjectForFiles(configFileExistenceInfo.openFilesImpactedByConfigFile,
+ /*delayReload*/ true, ignoreIfNotRootOfInferredProject ?
+ function (isRootOfInferredProject) { return isRootOfInferredProject; } : // Reload open files if they are root of inferred project
+ ts.returnTrue, // Reload all the open files impacted by config file
+ "Change in config file detected");
this.delayEnsureProjectForOpenFiles();
};
+ /**
+ * This function goes through all the openFiles and tries to file the config file for them.
+ * If the config file is found and it refers to existing project, it reloads it either immediately
+ * or schedules it for reload depending on delayReload option
+ * If the there is no existing project it just opens the configured project for the config file
+ * reloadForInfo provides a way to filter out files to reload configured project for
+ */
ProjectService.prototype.reloadConfiguredProjectForFiles = function (openFiles, delayReload, shouldReloadProjectFor, reason) {
var _this = this;
var updatedProjects = ts.createMap();
+ // try to reload config file for all open files
openFiles.forEach(function (openFileValue, path) {
+ // Filter out the files that need to be ignored
if (!shouldReloadProjectFor(openFileValue)) {
return;
}
- var info = _this.getScriptInfoForPath(path);
+ var info = _this.getScriptInfoForPath(path); // TODO: GH#18217
ts.Debug.assert(info.isScriptOpen());
+ // This tries to search for a tsconfig.json for the given file. If we found it,
+ // we first detect if there is already a configured project created for it: if so,
+ // we re- read the tsconfig file content and update the project only if we havent already done so
+ // otherwise we create a new one.
var configFileName = _this.getConfigFileNameForFile(info);
if (configFileName) {
var project = _this.findConfiguredProjectByProjectName(configFileName) || _this.createConfiguredProject(configFileName);
@@ -125101,6 +127378,7 @@ var ts;
_this.delayUpdateProjectGraph(project);
}
else {
+ // reload from the disk
_this.reloadConfiguredProject(project, reason);
}
updatedProjects.set(configFileName, true);
@@ -125108,26 +127386,51 @@ var ts;
}
});
};
+ /**
+ * Remove the root of inferred project if script info is part of another project
+ */
ProjectService.prototype.removeRootOfInferredProjectIfNowPartOfOtherProject = function (info) {
+ // If the script info is root of inferred project, it could only be first containing project
+ // since info is added as root to the inferred project only when there are no other projects containing it
+ // So when it is root of the inferred project and after project structure updates its now part
+ // of multiple project it needs to be removed from that inferred project because:
+ // - references in inferred project supercede the root part
+ // - root / reference in non - inferred project beats root in inferred project
+ // eg. say this is structure /a/b/a.ts /a/b/c.ts where c.ts references a.ts
+ // When a.ts is opened, since there is no configured project/external project a.ts can be part of
+ // a.ts is added as root to inferred project.
+ // Now at time of opening c.ts, c.ts is also not aprt of any existing project,
+ // so it will be added to inferred project as a root. (for sake of this example assume single inferred project is false)
+ // So at this poing a.ts is part of first inferred project and second inferred project (of which c.ts is root)
+ // And hence it needs to be removed from the first inferred project.
ts.Debug.assert(info.containingProjects.length > 0);
var firstProject = info.containingProjects[0];
if (!firstProject.isOrphan() &&
firstProject.projectKind === server.ProjectKind.Inferred &&
firstProject.isRoot(info) &&
ts.forEach(info.containingProjects, function (p) { return p !== firstProject && !p.isOrphan(); })) {
- firstProject.removeFile(info, true, true);
+ firstProject.removeFile(info, /*fileExists*/ true, /*detachFromProject*/ true);
}
};
+ /**
+ * This function is to update the project structure for every inferred project.
+ * It is called on the premise that all the configured projects are
+ * up to date.
+ * This will go through open files and assign them to inferred project if open file is not part of any other project
+ * After that all the inferred project graphs are updated
+ */
ProjectService.prototype.ensureProjectForOpenFiles = function () {
var _this = this;
this.logger.info("Structure before ensureProjectForOpenFiles:");
this.printProjects();
this.openFiles.forEach(function (projectRootPath, path) {
var info = _this.getScriptInfoForPath(path);
+ // collect all orphaned script infos from open files
if (info.isOrphan()) {
_this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
}
else {
+ // Or remove the root of inferred project if is referenced in more than one projects
_this.removeRootOfInferredProjectIfNowPartOfOtherProject(info);
}
});
@@ -125136,9 +127439,15 @@ var ts;
this.logger.info("Structure after ensureProjectForOpenFiles:");
this.printProjects();
};
+ /**
+ * Open file whose contents is managed by the client
+ * @param filename is absolute pathname
+ * @param fileContent is a known version of the file content that is more up to date than the one on disk
+ */
ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) {
- return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind, false, projectRootPath ? server.toNormalizedPath(projectRootPath) : undefined);
+ return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath ? server.toNormalizedPath(projectRootPath) : undefined);
};
+ /*@internal*/
ProjectService.prototype.getOriginalLocationEnsuringConfiguredProject = function (project, location) {
var originalLocation = project.getSourceMapper().tryGetSourcePosition(location);
if (!originalLocation)
@@ -125153,10 +127462,12 @@ var ts;
var configuredProject = this.findConfiguredProjectByProjectName(configFileName) ||
this.createAndLoadConfiguredProject(configFileName, "Creating project for original file: " + originalFileInfo.fileName + " for location: " + location.fileName);
updateProjectIfDirty(configuredProject);
+ // Keep this configured project as referenced from project
addOriginalConfiguredProject(configuredProject);
var originalScriptInfo = this.getScriptInfo(fileName);
if (!originalScriptInfo || !originalScriptInfo.containingProjects.length)
return undefined;
+ // Add configured projects as referenced
originalScriptInfo.containingProjects.forEach(function (project) {
if (project.projectKind === server.ProjectKind.Configured) {
addOriginalConfiguredProject(project);
@@ -125170,68 +127481,104 @@ var ts;
project.originalConfiguredProjects.set(originalProject.canonicalConfigFilePath, true);
}
};
+ /** @internal */
ProjectService.prototype.fileExists = function (fileName) {
return !!this.getScriptInfoForNormalizedPath(fileName) || this.host.fileExists(fileName);
};
ProjectService.prototype.findExternalProjectContainingOpenScriptInfo = function (info) {
return ts.find(this.externalProjects, function (proj) {
+ // Ensure project structure is up-to-date to check if info is present in external project
updateProjectIfDirty(proj);
return proj.containsScriptInfo(info);
});
};
- ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
+ ProjectService.prototype.getOrCreateOpenScriptInfo = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
+ var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); // TODO: GH#18217
+ this.openFiles.set(info.path, projectRootPath);
+ return info;
+ };
+ ProjectService.prototype.assignProjectToOpenedScriptInfo = function (info) {
var configFileName;
var configFileErrors;
- var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent);
- this.openFiles.set(info.path, projectRootPath);
var project = this.findExternalProjectContainingOpenScriptInfo(info);
- if (!project && !this.syntaxOnly) {
+ if (!project && !this.syntaxOnly) { // Checking syntaxOnly is an optimization
configFileName = this.getConfigFileNameForFile(info);
if (configFileName) {
project = this.findConfiguredProjectByProjectName(configFileName);
if (!project) {
- project = this.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + fileName + " to open");
+ project = this.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + info.fileName + " to open");
+ // Send the event only if the project got created as part of this open request and info is part of the project
if (info.isOrphan()) {
+ // Since the file isnt part of configured project, do not send config file info
configFileName = undefined;
}
else {
configFileErrors = project.getAllProjectErrors();
- this.sendConfigFileDiagEvent(project, fileName);
+ this.sendConfigFileDiagEvent(project, info.fileName);
}
}
else {
+ // Ensure project is ready to check if it contains opened script info
updateProjectIfDirty(project);
}
}
}
+ // Project we have at this point is going to be updated since its either found through
+ // - external project search, which updates the project before checking if info is present in it
+ // - configured project - either created or updated to ensure we know correct status of info
+ // At this point we need to ensure that containing projects of the info are uptodate
+ // This will ensure that later question of info.isOrphan() will return correct answer
+ // and we correctly create inferred project for the info
info.containingProjects.forEach(updateProjectIfDirty);
+ // At this point if file is part of any any configured or external project, then it would be present in the containing projects
+ // So if it still doesnt have any containing projects, it needs to be part of inferred project
if (info.isOrphan()) {
- this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
+ ts.Debug.assert(this.openFiles.has(info.path));
+ this.assignOrphanScriptInfoToInferredProject(info, this.openFiles.get(info.path));
}
ts.Debug.assert(!info.isOrphan());
+ return { configFileName: configFileName, configFileErrors: configFileErrors };
+ };
+ ProjectService.prototype.cleanupAfterOpeningFile = function () {
+ // This was postponed from closeOpenFile to after opening next file,
+ // so that we can reuse the project if we need to right away
this.removeOrphanConfiguredProjects();
+ // Remove orphan inferred projects now that we have reused projects
+ // We need to create a duplicate because we cant guarantee order after removal
for (var _i = 0, _a = this.inferredProjects.slice(); _i < _a.length; _i++) {
var inferredProject = _a[_i];
if (inferredProject.isOrphan()) {
this.removeProject(inferredProject);
}
}
+ // Delete the orphan files here because there might be orphan script infos (which are not part of project)
+ // when some file/s were closed which resulted in project removal.
+ // It was then postponed to cleanup these script infos so that they can be reused if
+ // the file from that old project is reopened because of opening file from here.
this.removeOrphanScriptInfos();
this.printProjects();
+ };
+ ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
+ var info = this.getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath);
+ var result = this.assignProjectToOpenedScriptInfo(info);
+ this.cleanupAfterOpeningFile();
this.telemetryOnOpenFile(info);
- return { configFileName: configFileName, configFileErrors: configFileErrors };
+ return result;
};
ProjectService.prototype.removeOrphanConfiguredProjects = function () {
var _this = this;
var toRemoveConfiguredProjects = ts.cloneMap(this.configuredProjects);
+ // Do not remove configured projects that are used as original projects of other
this.inferredProjects.forEach(markOriginalProjectsAsUsed);
this.externalProjects.forEach(markOriginalProjectsAsUsed);
this.configuredProjects.forEach(function (project) {
+ // If project has open ref (there are more than zero references from external project/open file), keep it alive as well as any project it references
if (project.hasOpenRef()) {
toRemoveConfiguredProjects.delete(project.canonicalConfigFilePath);
markOriginalProjectsAsUsed(project);
}
else {
+ // If the configured project for project reference has more than zero references, keep it alive
project.forEachResolvedProjectReference(function (ref) {
if (ref) {
var refProject = _this.configuredProjects.get(ref.sourceFile.path);
@@ -125242,6 +127589,7 @@ var ts;
});
}
});
+ // Remove all the non marked projects
toRemoveConfiguredProjects.forEach(function (project) { return _this.removeProject(project); });
function markOriginalProjectsAsUsed(project) {
if (!project.isOrphan() && project.originalConfiguredProjects) {
@@ -125253,7 +127601,9 @@ var ts;
var _this = this;
var toRemoveScriptInfos = ts.cloneMap(this.filenameToScriptInfo);
this.filenameToScriptInfo.forEach(function (info) {
+ // If script info is open or orphan, retain it and its dependencies
if (!info.isScriptOpen() && info.isOrphan()) {
+ // Otherwise if there is any source info that is alive, this alive too
if (!info.sourceMapFilePath)
return;
var sourceInfos = void 0;
@@ -125273,10 +127623,12 @@ var ts;
return;
}
}
+ // Retain this script info
toRemoveScriptInfos.delete(info.path);
if (info.sourceMapFilePath) {
var sourceInfos = void 0;
if (ts.isString(info.sourceMapFilePath)) {
+ // And map file info and source infos
toRemoveScriptInfos.delete(info.sourceMapFilePath);
var sourceMapInfo = _this.getScriptInfoForPath(info.sourceMapFilePath);
sourceInfos = sourceMapInfo && sourceMapInfo.sourceInfos;
@@ -125290,6 +127642,7 @@ var ts;
}
});
toRemoveScriptInfos.forEach(function (info) {
+ // if there are not projects that include this script info - delete it
_this.stopWatchingScriptInfo(info);
_this.deleteScriptInfo(info);
info.closeSourceMapFileWatcher();
@@ -125306,12 +127659,13 @@ var ts;
var info = { checkJs: !!project.getSourceFile(scriptInfo.path).checkJsDirective };
this.eventHandler({ eventName: server.OpenFileInfoTelemetryEvent, data: { info: info } });
};
- ProjectService.prototype.closeClientFile = function (uncheckedFileName) {
+ ProjectService.prototype.closeClientFile = function (uncheckedFileName, skipAssignOrphanScriptInfosToInferredProject) {
var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName));
- if (info) {
- this.closeOpenFile(info);
+ var result = info ? this.closeOpenFile(info, skipAssignOrphanScriptInfosToInferredProject) : false;
+ if (!skipAssignOrphanScriptInfosToInferredProject) {
+ this.printProjects();
}
- this.printProjects();
+ return result;
};
ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) {
var _loop_4 = function (proj) {
@@ -125323,6 +127677,7 @@ var ts;
_loop_4(proj);
}
};
+ /* @internal */
ProjectService.prototype.synchronizeProjectList = function (knownProjects) {
var files = [];
this.collectChanges(knownProjects, this.externalProjects, files);
@@ -125330,34 +127685,61 @@ var ts;
this.collectChanges(knownProjects, this.inferredProjects, files);
return files;
};
+ /* @internal */
ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) {
+ var _this = this;
+ var openScriptInfos;
+ var assignOrphanScriptInfosToInferredProject = false;
if (openFiles) {
- for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) {
- var file = openFiles_1[_i];
+ while (true) {
+ var _a = openFiles.next(), file = _a.value, done = _a.done;
+ if (done)
+ break;
var scriptInfo = this.getScriptInfo(file.fileName);
ts.Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen(), "Script should not exist and not be open already");
- var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName);
- this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent);
+ // Create script infos so we have the new content for all the open files before we do any updates to projects
+ var info = this.getOrCreateOpenScriptInfo(scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName), file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent, file.projectRootPath ? server.toNormalizedPath(file.projectRootPath) : undefined);
+ (openScriptInfos || (openScriptInfos = [])).push(info);
}
}
if (changedFiles) {
- for (var _a = 0, changedFiles_2 = changedFiles; _a < changedFiles_2.length; _a++) {
- var file = changedFiles_2[_a];
+ while (true) {
+ var _b = changedFiles.next(), file = _b.value, done = _b.done;
+ if (done)
+ break;
var scriptInfo = this.getScriptInfo(file.fileName);
ts.Debug.assert(!!scriptInfo);
+ // Make edits to script infos and marks containing project as dirty
this.applyChangesToFile(scriptInfo, file.changes);
}
}
if (closedFiles) {
- for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) {
- var file = closedFiles_1[_b];
- this.closeClientFile(file);
+ for (var _i = 0, closedFiles_1 = closedFiles; _i < closedFiles_1.length; _i++) {
+ var file = closedFiles_1[_i];
+ // Close files, but dont assign projects to orphan open script infos, that part comes later
+ assignOrphanScriptInfosToInferredProject = this.closeClientFile(file, /*skipAssignOrphanScriptInfosToInferredProject*/ true) || assignOrphanScriptInfosToInferredProject;
}
}
+ // All the script infos now exist, so ok to go update projects for open files
+ if (openScriptInfos) {
+ openScriptInfos.forEach(function (info) { return _this.assignProjectToOpenedScriptInfo(info); });
+ }
+ // While closing files there could be open files that needed assigning new inferred projects, do it now
+ if (assignOrphanScriptInfosToInferredProject) {
+ this.assignOrphanScriptInfosToInferredProject();
+ }
+ // Cleanup projects
+ this.cleanupAfterOpeningFile();
+ // Telemetry
+ ts.forEach(openScriptInfos, function (info) { return _this.telemetryOnOpenFile(info); });
+ this.printProjects();
};
+ /* @internal */
ProjectService.prototype.applyChangesToFile = function (scriptInfo, changes) {
- for (var i = changes.length - 1; i >= 0; i--) {
- var change = changes[i];
+ while (true) {
+ var _a = changes.next(), change = _a.value, done = _a.done;
+ if (done)
+ break;
scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText);
}
};
@@ -125382,6 +127764,7 @@ var ts;
this.externalProjectToConfiguredProjectMap.delete(fileName);
}
else {
+ // close external project
var externalProject = this.findExternalProjectByProjectName(uncheckedFileName);
if (externalProject) {
this.removeProject(externalProject);
@@ -125390,6 +127773,7 @@ var ts;
};
ProjectService.prototype.openExternalProjects = function (projects) {
var _this = this;
+ // record project list before the update
var projectsToClose = ts.arrayToMap(this.externalProjects, function (p) { return p.getProjectName(); }, function (_) { return true; });
ts.forEachKey(this.externalProjectToConfiguredProjectMap, function (externalProjectName) {
projectsToClose.set(externalProjectName, true);
@@ -125397,8 +127781,10 @@ var ts;
for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) {
var externalProject = projects_3[_i];
this.openExternalProject(externalProject);
+ // delete project that is present in input list
projectsToClose.delete(externalProject.projectFileName);
}
+ // close projects that were missing in the input list
ts.forEachKey(projectsToClose, function (externalProjectName) {
_this.closeExternalProject(externalProjectName);
});
@@ -125414,6 +127800,7 @@ var ts;
var rootFiles = proj.rootFiles;
var typeAcquisition = proj.typeAcquisition;
ts.Debug.assert(!!typeAcquisition, "proj.typeAcquisition should be set by now");
+ // If type acquisition has been explicitly disabled, do not exclude anything from the project
if (typeAcquisition.enable === false) {
return [];
}
@@ -125427,9 +127814,12 @@ var ts;
var root = normalizedNames_1[_i];
if (rule.match.test(root)) {
this_2.logger.info("Excluding files based on rule " + name + " matching file '" + root + "'");
+ // If the file matches, collect its types packages and exclude rules
if (rule.types) {
for (var _a = 0, _b = rule.types; _a < _b.length; _a++) {
var type = _b[_a];
+ // Best-effort de-duping here - doesn't need to be unduplicated but
+ // we don't want the list to become a 400-element array of just 'kendo'
if (typeAcqInclude.indexOf(type) < 0) {
typeAcqInclude.push(type);
}
@@ -125443,9 +127833,13 @@ var ts;
groups[_i] = arguments[_i];
}
return exclude.map(function (groupNumberOrString) {
+ // RegExp group numbers are 1-based, but the first element in groups
+ // is actually the original string, so it all works out in the end.
if (typeof groupNumberOrString === "number") {
if (!ts.isString(groups[groupNumberOrString])) {
+ // Specification was wrong - exclude nothing!
_this.logger.info("Incorrect RegExp specification in safelist rule " + name + " - not enough groups");
+ // * can't appear in a filename; escape it because it's feeding into a RegExp
return "\\*";
}
return ProjectService.escapeFilenameForRegex(groups[groupNumberOrString]);
@@ -125463,6 +127857,7 @@ var ts;
}
}
else {
+ // If not rules listed, add the default rule to exclude the matched file
var escaped = ProjectService.escapeFilenameForRegex(root);
if (excludeRules.indexOf(escaped) < 0) {
excludeRules.push(escaped);
@@ -125493,7 +127888,10 @@ var ts;
if (typeName !== undefined) {
this_3.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist");
excludedFiles.push(normalizedNames[i]);
+ // *exclude* it from the project...
exclude = true;
+ // ... but *include* it in the list of types to acquire
+ // Same best-effort dedupe as above
if (typeAcqInclude.indexOf(typeName) < 0) {
typeAcqInclude.push(typeName);
}
@@ -125501,6 +127899,7 @@ var ts;
}
}
if (!exclude) {
+ // Exclude any minified files that get this far
if (/^.+[\.-]min\.js$/.test(normalizedNames[i])) {
excludedFiles.push(normalizedNames[i]);
}
@@ -125518,6 +127917,8 @@ var ts;
return excludedFiles;
};
ProjectService.prototype.openExternalProject = function (proj) {
+ // typingOptions has been deprecated and is only supported for backward compatibility
+ // purposes. It should be removed in future releases - use typeAcquisition instead.
if (proj.typingOptions && !proj.typeAcquisition) {
var typeAcquisition = ts.convertEnableAutoDiscoveryToEnable(proj.typingOptions);
proj.typeAcquisition = typeAcquisition;
@@ -125543,6 +127944,7 @@ var ts;
rootFiles.push(file);
}
}
+ // sort config files to simplify comparison later
if (tsConfigFiles) {
tsConfigFiles.sort();
}
@@ -125559,17 +127961,24 @@ var ts;
else {
externalProject.enableLanguageService();
}
+ // external project already exists and not config files were added - update the project and return;
+ // The graph update here isnt postponed since any file open operation needs all updated external projects
this.updateRootAndOptionsOfNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, compilerOptions, proj.typeAcquisition, proj.options.compileOnSave);
externalProject.updateGraph();
return;
}
+ // some config files were added to external project (that previously were not there)
+ // close existing project and later we'll open a set of configured projects for these files
this.closeExternalProject(proj.projectFileName);
}
else if (this.externalProjectToConfiguredProjectMap.get(proj.projectFileName)) {
+ // this project used to include config files
if (!tsConfigFiles) {
+ // config files were removed from the project - close existing external project which in turn will close configured projects
this.closeExternalProject(proj.projectFileName);
}
else {
+ // project previously had some config files - compare them with new set of files and close all configured projects that correspond to unused files
var oldConfigFiles = this.externalProjectToConfiguredProjectMap.get(proj.projectFileName);
var iNew = 0;
var iOld = 0;
@@ -125584,55 +127993,68 @@ var ts;
iNew++;
}
else {
+ // record existing config files so avoid extra add-refs
(exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig);
iOld++;
iNew++;
}
}
for (var i = iOld; i < oldConfigFiles.length; i++) {
+ // projects for all remaining old config files should be closed
this.closeConfiguredProjectReferencedFromExternalProject(oldConfigFiles[i]);
}
}
}
if (tsConfigFiles) {
+ // store the list of tsconfig files that belong to the external project
this.externalProjectToConfiguredProjectMap.set(proj.projectFileName, tsConfigFiles);
for (var _b = 0, tsConfigFiles_1 = tsConfigFiles; _b < tsConfigFiles_1.length; _b++) {
var tsconfigFile = tsConfigFiles_1[_b];
var project = this.findConfiguredProjectByProjectName(tsconfigFile);
if (!project) {
+ // errors are stored in the project, do not need to update the graph
project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ?
this.createConfiguredProjectWithDelayLoad(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName) :
this.createLoadAndUpdateConfiguredProject(tsconfigFile, "Creating configured project in external project: " + proj.projectFileName);
}
if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) {
+ // keep project alive even if no documents are opened - its lifetime is bound to the lifetime of containing external project
project.addExternalProjectReference();
}
}
}
else {
+ // no config files - remove the item from the collection
+ // Create external project and update its graph, do not delay update since
+ // any file open operation needs all updated external projects
this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName);
var project = this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles);
project.updateGraph();
}
};
ProjectService.prototype.hasDeferredExtension = function () {
- for (var _i = 0, _a = this.hostConfiguration.extraFileExtensions; _i < _a.length; _i++) {
+ for (var _i = 0, _a = this.hostConfiguration.extraFileExtensions; _i < _a.length; _i++) { // TODO: GH#18217
var extension = _a[_i];
- if (extension.scriptKind === 7) {
+ if (extension.scriptKind === 7 /* Deferred */) {
return true;
}
}
return false;
};
ProjectService.prototype.configurePlugin = function (args) {
+ // For any projects that already have the plugin loaded, configure the plugin
this.forEachEnabledProject(function (project) { return project.onPluginConfigurationChanged(args.pluginName, args.configuration); });
+ // Also save the current configuration to pass on to any projects that are yet to be loaded.
+ // If a plugin is configured twice, only the latest configuration will be remembered.
this.currentPluginConfigOverrides = this.currentPluginConfigOverrides || ts.createMap();
this.currentPluginConfigOverrides.set(args.pluginName, args.configuration);
};
+ /** Makes a filename safe to insert in a RegExp */
ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g;
return ProjectService;
}());
server.ProjectService = ProjectService;
+ /* @internal */
function isConfigFile(config) {
return config.kind !== undefined;
}
@@ -125662,6 +128084,18 @@ var ts;
return ((1e9 * seconds) + nanoseconds) / 1000000.0;
}
function isDeclarationFileInJSOnlyNonConfiguredProject(project, file) {
+ // Checking for semantic diagnostics is an expensive process. We want to avoid it if we
+ // know for sure it is not needed.
+ // For instance, .d.ts files injected by ATA automatically do not produce any relevant
+ // errors to a JS- only project.
+ //
+ // Note that configured projects can set skipLibCheck (on by default in jsconfig.json) to
+ // disable checking for declaration files. We only need to verify for inferred projects (e.g.
+ // miscellaneous context in VS) and external projects(e.g.VS.csproj project) with only JS
+ // files.
+ //
+ // We still want to check .js files in a JS-only inferred or external project (e.g. if the
+ // file has '// @ts-check').
if ((project.projectKind === server.ProjectKind.Inferred || project.projectKind === server.ProjectKind.External) &&
project.isJsOnlyProject()) {
var scriptInfo = project.getScriptInfoForNormalizedPath(file);
@@ -125670,7 +128104,7 @@ var ts;
return false;
}
function formatDiag(fileName, project, diag) {
- var scriptInfo = project.getScriptInfoForNormalizedPath(fileName);
+ var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); // TODO: GH#18217
return {
start: scriptInfo.positionToLineOffset(diag.start),
end: scriptInfo.positionToLineOffset(diag.start + diag.length),
@@ -125705,8 +128139,8 @@ var ts;
return { line: lineAndCharacter.line + 1, offset: lineAndCharacter.character + 1 };
}
function formatConfigFileDiag(diag, includeFileName) {
- var start = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start)));
- var end = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start + diag.length)));
+ var start = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start))); // TODO: GH#18217
+ var end = (diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start + diag.length))); // TODO: GH#18217
var text = ts.flattenDiagnosticMessageText(diag.messageText, "\n");
var code = diag.code, source = diag.source;
var category = ts.diagnosticCategoryName(diag);
@@ -125726,7 +128160,7 @@ var ts;
function allEditsBeforePos(edits, pos) {
return edits.every(function (edit) { return ts.textSpanEnd(edit.span) < pos; });
}
- server.CommandNames = server.protocol.CommandTypes;
+ server.CommandNames = server.protocol.CommandTypes; // tslint:disable-line variable-name
function formatMessage(msg, logger, byteLength, newLine) {
var verboseLogging = logger.hasLevel(server.LogLevel.verbose);
var json = JSON.stringify(msg);
@@ -125737,7 +128171,11 @@ var ts;
return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine;
}
server.formatMessage = formatMessage;
- var MultistepOperation = (function () {
+ /**
+ * Represents operation that can schedule its next step to be executed later.
+ * Scheduling is done via instance of NextStep. If on current step subsequent step was not scheduled - operation is assumed to be completed.
+ */
+ var MultistepOperation = /** @class */ (function () {
function MultistepOperation(operationHost) {
this.operationHost = operationHost;
}
@@ -125784,6 +128222,7 @@ var ts;
}
catch (e) {
stop = true;
+ // ignore cancellation request
if (!(e instanceof ts.OperationCanceledException)) {
this.operationHost.logError(e, "delayed processing of request " + this.requestId);
}
@@ -125809,6 +128248,7 @@ var ts;
};
return MultistepOperation;
}());
+ /** @internal */
function toEvent(eventName, body) {
return {
seq: 0,
@@ -125818,6 +128258,9 @@ var ts;
};
}
server.toEvent = toEvent;
+ /**
+ * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project.
+ */
function combineProjectOutput(defaultValue, getValue, projects, action) {
var outputs = ts.flatMapToMutable(ts.isArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); });
if (!ts.isArray(projects) && projects.symLinkedProjects) {
@@ -125838,7 +128281,8 @@ var ts;
}
function combineProjectOutputWhileOpeningReferencedProjects(projects, defaultProject, action, getLocation, resultsEqual) {
var outputs = [];
- combineProjectOutputWorker(projects, defaultProject, undefined, function (_a, tryAddToTodo) {
+ combineProjectOutputWorker(projects, defaultProject,
+ /*initialLocation*/ undefined, function (_a, tryAddToTodo) {
var project = _a.project;
for (var _i = 0, _b = action(project); _i < _b.length; _i++) {
var output = _b[_i];
@@ -125846,7 +128290,8 @@ var ts;
outputs.push(output);
}
}
- }, undefined);
+ },
+ /*getDefinition*/ undefined);
return outputs;
}
function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, findInStrings, findInComments, hostPreferences) {
@@ -125881,6 +128326,7 @@ var ts;
}
for (var _i = 0, _a = outputReferencedSymbol.references; _i < _a.length; _i++) {
var ref = _a[_i];
+ // If it's in a mapped file, that is added to the todo list by `getMappedLocation`.
if (!ts.contains(symbolToAddTo.references, ref, ts.documentSpansEqual) && !getMappedLocation(project, documentSpanLocation(ref))) {
symbolToAddTo.references.push(ref);
}
@@ -125912,9 +128358,11 @@ var ts;
var toDo;
var seenProjects = ts.createMap();
forEachProjectInProjects(projects, initialLocation && initialLocation.fileName, function (project, path) {
+ // TLocation shoud be either `DocumentPosition` or `undefined`. Since `initialLocation` is `TLocation` this cast should be valid.
var location = (initialLocation ? { fileName: path, pos: initialLocation.pos } : undefined);
toDo = callbackProjectAndLocation({ project: project, location: location }, projectService, toDo, seenProjects, cb);
});
+ // After initial references are collected, go over every other project and see if it has a reference for the symbol definition.
if (getDefinition) {
var memGetDefinition_1 = ts.memoize(getDefinition);
projectService.forEachEnabledProject(function (project) {
@@ -125938,7 +128386,7 @@ var ts;
}
function callbackProjectAndLocation(projectAndLocation, projectService, toDo, seenProjects, cb) {
if (projectAndLocation.project.getCancellationToken().isCancellationRequested())
- return undefined;
+ return undefined; // Skip rest of toDo if cancelled
cb(projectAndLocation, function (project, location) {
seenProjects.set(projectAndLocation.project.projectName, true);
var originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, location);
@@ -125975,7 +128423,7 @@ var ts;
var mapsTo = project.getSourceMapper().tryGetSourcePosition(location);
return mapsTo && projectService.fileExists(server.toNormalizedPath(mapsTo.fileName)) ? mapsTo : undefined;
}
- var Session = (function () {
+ var Session = /** @class */ (function () {
function Session(opts) {
var _a;
var _this = this;
@@ -125987,15 +128435,18 @@ var ts;
},
_a[server.CommandNames.OpenExternalProject] = function (request) {
_this.projectService.openExternalProject(request.arguments);
- return _this.requiredResponse(true);
+ // TODO: GH#20447 report errors
+ return _this.requiredResponse(/*response*/ true);
},
_a[server.CommandNames.OpenExternalProjects] = function (request) {
_this.projectService.openExternalProjects(request.arguments.projects);
- return _this.requiredResponse(true);
+ // TODO: GH#20447 report errors
+ return _this.requiredResponse(/*response*/ true);
},
_a[server.CommandNames.CloseExternalProject] = function (request) {
_this.projectService.closeExternalProject(request.arguments.projectFileName);
- return _this.requiredResponse(true);
+ // TODO: GH#20447 report errors
+ return _this.requiredResponse(/*response*/ true);
},
_a[server.CommandNames.SynchronizeProjectList] = function (request) {
var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects);
@@ -126010,31 +128461,54 @@ var ts;
info: p.info,
changes: p.changes,
files: p.files,
- projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, undefined)
+ projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, /*scriptInfo*/ undefined)
};
});
return _this.requiredResponse(converted);
},
+ _a[server.CommandNames.UpdateOpen] = function (request) {
+ _this.changeSeq++;
+ _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles && ts.mapIterator(ts.arrayIterator(request.arguments.openFiles), function (file) { return ({
+ fileName: file.file,
+ content: file.fileContent,
+ scriptKind: file.scriptKindName,
+ projectRootPath: file.projectRootPath
+ }); }), request.arguments.changedFiles && ts.mapIterator(ts.arrayIterator(request.arguments.changedFiles), function (file) { return ({
+ fileName: file.fileName,
+ changes: ts.mapDefinedIterator(ts.arrayReverseIterator(file.textChanges), function (change) {
+ var scriptInfo = ts.Debug.assertDefined(_this.projectService.getScriptInfo(file.fileName));
+ var start = scriptInfo.lineOffsetToPosition(change.start.line, change.start.offset);
+ var end = scriptInfo.lineOffsetToPosition(change.end.line, change.end.offset);
+ return start >= 0 ? { span: { start: start, length: end - start }, newText: change.newText } : undefined;
+ })
+ }); }), request.arguments.closedFiles);
+ return _this.requiredResponse(/*response*/ true);
+ },
_a[server.CommandNames.ApplyChangedToOpenFiles] = function (request) {
_this.changeSeq++;
- _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles);
- return _this.requiredResponse(true);
+ _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles && ts.arrayIterator(request.arguments.openFiles), request.arguments.changedFiles && ts.mapIterator(ts.arrayIterator(request.arguments.changedFiles), function (file) { return ({
+ fileName: file.fileName,
+ // apply changes in reverse order
+ changes: ts.arrayReverseIterator(file.changes)
+ }); }), request.arguments.closedFiles);
+ // TODO: report errors
+ return _this.requiredResponse(/*response*/ true);
},
_a[server.CommandNames.Exit] = function () {
_this.exit();
return _this.notRequired();
},
_a[server.CommandNames.Definition] = function (request) {
- return _this.requiredResponse(_this.getDefinition(request.arguments, true));
+ return _this.requiredResponse(_this.getDefinition(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.DefinitionFull] = function (request) {
- return _this.requiredResponse(_this.getDefinition(request.arguments, false));
+ return _this.requiredResponse(_this.getDefinition(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.DefinitionAndBoundSpan] = function (request) {
- return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, true));
+ return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.DefinitionAndBoundSpanFull] = function (request) {
- return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, false));
+ return _this.requiredResponse(_this.getDefinitionAndBoundSpan(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.EmitOutput] = function (request) {
return _this.requiredResponse(_this.getEmitOutput(request.arguments));
@@ -126043,41 +128517,42 @@ var ts;
return _this.requiredResponse(_this.getTypeDefinition(request.arguments));
},
_a[server.CommandNames.Implementation] = function (request) {
- return _this.requiredResponse(_this.getImplementation(request.arguments, true));
+ return _this.requiredResponse(_this.getImplementation(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.ImplementationFull] = function (request) {
- return _this.requiredResponse(_this.getImplementation(request.arguments, false));
+ return _this.requiredResponse(_this.getImplementation(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.References] = function (request) {
- return _this.requiredResponse(_this.getReferences(request.arguments, true));
+ return _this.requiredResponse(_this.getReferences(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.ReferencesFull] = function (request) {
- return _this.requiredResponse(_this.getReferences(request.arguments, false));
+ return _this.requiredResponse(_this.getReferences(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.Rename] = function (request) {
- return _this.requiredResponse(_this.getRenameLocations(request.arguments, true));
+ return _this.requiredResponse(_this.getRenameLocations(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.RenameLocationsFull] = function (request) {
- return _this.requiredResponse(_this.getRenameLocations(request.arguments, false));
+ return _this.requiredResponse(_this.getRenameLocations(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.RenameInfoFull] = function (request) {
return _this.requiredResponse(_this.getRenameInfo(request.arguments));
},
_a[server.CommandNames.Open] = function (request) {
- _this.openClientFile(server.toNormalizedPath(request.arguments.file), request.arguments.fileContent, server.convertScriptKindName(request.arguments.scriptKindName), request.arguments.projectRootPath ? server.toNormalizedPath(request.arguments.projectRootPath) : undefined);
+ _this.openClientFile(server.toNormalizedPath(request.arguments.file), request.arguments.fileContent, server.convertScriptKindName(request.arguments.scriptKindName), // TODO: GH#18217
+ request.arguments.projectRootPath ? server.toNormalizedPath(request.arguments.projectRootPath) : undefined);
return _this.notRequired();
},
_a[server.CommandNames.Quickinfo] = function (request) {
- return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, true));
+ return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.QuickinfoFull] = function (request) {
- return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, false));
+ return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.GetOutliningSpans] = function (request) {
- return _this.requiredResponse(_this.getOutliningSpans(request.arguments, true));
+ return _this.requiredResponse(_this.getOutliningSpans(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.GetOutliningSpansFull] = function (request) {
- return _this.requiredResponse(_this.getOutliningSpans(request.arguments, false));
+ return _this.requiredResponse(_this.getOutliningSpans(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.TodoComments] = function (request) {
return _this.requiredResponse(_this.getTodoComments(request.arguments));
@@ -126125,10 +128600,10 @@ var ts;
return _this.requiredResponse(_this.getCompletions(request.arguments, server.CommandNames.CompletionsFull));
},
_a[server.CommandNames.CompletionDetails] = function (request) {
- return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, true));
+ return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.CompletionDetailsFull] = function (request) {
- return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, false));
+ return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.CompileOnSaveAffectedFileList] = function (request) {
return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments));
@@ -126137,10 +128612,10 @@ var ts;
return _this.requiredResponse(_this.emitFile(request.arguments));
},
_a[server.CommandNames.SignatureHelp] = function (request) {
- return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, true));
+ return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.SignatureHelpFull] = function (request) {
- return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, false));
+ return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.CompilerOptionsDiagnosticsFull] = function (request) {
return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments));
@@ -126150,7 +128625,7 @@ var ts;
},
_a[server.CommandNames.Cleanup] = function () {
_this.cleanup();
- return _this.requiredResponse(true);
+ return _this.requiredResponse(/*response*/ true);
},
_a[server.CommandNames.SemanticDiagnosticsSync] = function (request) {
return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments));
@@ -126175,7 +128650,7 @@ var ts;
},
_a[server.CommandNames.Configure] = function (request) {
_this.projectService.setHostConfiguration(request.arguments);
- _this.doOutput(undefined, server.CommandNames.Configure, request.seq, true);
+ _this.doOutput(/*info*/ undefined, server.CommandNames.Configure, request.seq, /*success*/ true);
return _this.notRequired();
},
_a[server.CommandNames.Reload] = function (request) {
@@ -126193,41 +128668,41 @@ var ts;
return _this.notRequired();
},
_a[server.CommandNames.Navto] = function (request) {
- return _this.requiredResponse(_this.getNavigateToItems(request.arguments, true));
+ return _this.requiredResponse(_this.getNavigateToItems(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.NavtoFull] = function (request) {
- return _this.requiredResponse(_this.getNavigateToItems(request.arguments, false));
+ return _this.requiredResponse(_this.getNavigateToItems(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.Brace] = function (request) {
- return _this.requiredResponse(_this.getBraceMatching(request.arguments, true));
+ return _this.requiredResponse(_this.getBraceMatching(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.BraceFull] = function (request) {
- return _this.requiredResponse(_this.getBraceMatching(request.arguments, false));
+ return _this.requiredResponse(_this.getBraceMatching(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.NavBar] = function (request) {
- return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, true));
+ return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.NavBarFull] = function (request) {
- return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false));
+ return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.NavTree] = function (request) {
- return _this.requiredResponse(_this.getNavigationTree(request.arguments, true));
+ return _this.requiredResponse(_this.getNavigationTree(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.NavTreeFull] = function (request) {
- return _this.requiredResponse(_this.getNavigationTree(request.arguments, false));
+ return _this.requiredResponse(_this.getNavigationTree(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.Occurrences] = function (request) {
return _this.requiredResponse(_this.getOccurrences(request.arguments));
},
_a[server.CommandNames.DocumentHighlights] = function (request) {
- return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, true));
+ return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.DocumentHighlightsFull] = function (request) {
- return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false));
+ return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.CompilerOptionsForInferredProjects] = function (request) {
_this.setCompilerOptionsForInferredProjects(request.arguments);
- return _this.requiredResponse(true);
+ return _this.requiredResponse(/*response*/ true);
},
_a[server.CommandNames.ProjectInfo] = function (request) {
return _this.requiredResponse(_this.getProjectInfo(request.arguments));
@@ -126240,16 +128715,16 @@ var ts;
return _this.requiredResponse(_this.getJsxClosingTag(request.arguments));
},
_a[server.CommandNames.GetCodeFixes] = function (request) {
- return _this.requiredResponse(_this.getCodeFixes(request.arguments, true));
+ return _this.requiredResponse(_this.getCodeFixes(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.GetCodeFixesFull] = function (request) {
- return _this.requiredResponse(_this.getCodeFixes(request.arguments, false));
+ return _this.requiredResponse(_this.getCodeFixes(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.GetCombinedCodeFix] = function (request) {
- return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, true));
+ return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.GetCombinedCodeFixFull] = function (request) {
- return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, false));
+ return _this.requiredResponse(_this.getCombinedCodeFix(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.ApplyCodeActionCommand] = function (request) {
return _this.requiredResponse(_this.applyCodeActionCommand(request.arguments));
@@ -126261,22 +128736,22 @@ var ts;
return _this.requiredResponse(_this.getApplicableRefactors(request.arguments));
},
_a[server.CommandNames.GetEditsForRefactor] = function (request) {
- return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, true));
+ return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.GetEditsForRefactorFull] = function (request) {
- return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, false));
+ return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.OrganizeImports] = function (request) {
- return _this.requiredResponse(_this.organizeImports(request.arguments, true));
+ return _this.requiredResponse(_this.organizeImports(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.OrganizeImportsFull] = function (request) {
- return _this.requiredResponse(_this.organizeImports(request.arguments, false));
+ return _this.requiredResponse(_this.organizeImports(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.GetEditsForFileRename] = function (request) {
- return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, true));
+ return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, /*simplifiedResult*/ true));
},
_a[server.CommandNames.GetEditsForFileRenameFull] = function (request) {
- return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, false));
+ return _this.requiredResponse(_this.getEditsForFileRename(request.arguments, /*simplifiedResult*/ false));
},
_a[server.CommandNames.ConfigurePlugin] = function (request) {
_this.configurePlugin(request.arguments);
@@ -126322,7 +128797,7 @@ var ts;
syntaxOnly: opts.syntaxOnly,
};
this.projectService = new server.ProjectService(settings);
- this.gcTimer = new server.GcTimer(this.host, 7000, this.logger);
+ this.gcTimer = new server.GcTimer(this.host, /*delay*/ 7000, this.logger);
}
Session.prototype.sendRequestCompletedEvent = function (requestId) {
this.event({ request_seq: requestId }, "requestCompleted");
@@ -126347,7 +128822,7 @@ var ts;
break;
case server.ConfigFileDiagEvent:
var _c = event.data, triggerFile = _c.triggerFile, configFile = _c.configFileName, diagnostics = _c.diagnostics;
- var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, true); });
+ var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, /*includeFileName*/ true); });
this.event({
triggerFile: triggerFile,
configFile: configFile,
@@ -126378,8 +128853,10 @@ var ts;
if (openFiles.length) {
if (!this.suppressDiagnosticEvents && !this.noGetErrOnBackgroundUpdate) {
var checkList_1 = this.createCheckList(openFiles);
- this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, checkList_1, 100, true); });
+ // For now only queue error checking for open files. We can change this to include non open files as well
+ this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, checkList_1, 100, /*requireOpen*/ true); });
}
+ // Send project changed event
this.event({
openFiles: openFiles
}, server.ProjectsUpdatedInBackgroundEvent);
@@ -126405,7 +128882,7 @@ var ts;
msg += "\n\nFile text of " + fileRequest.file + ":" + server.indent(text) + "\n";
}
}
- catch (_b) { }
+ catch (_b) { } // tslint:disable-line no-empty
}
this.logger.msg(msg, server.Msg.Err);
};
@@ -126421,8 +128898,10 @@ var ts;
Session.prototype.event = function (body, eventName) {
this.send(toEvent(eventName, body));
};
+ // For backwards-compatibility only.
+ /** @deprecated */
Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) {
- this.doOutput(info, cmdName, reqSeq, !errorMsg, errorMsg);
+ this.doOutput(info, cmdName, reqSeq, /*success*/ !errorMsg, errorMsg); // TODO: GH#18217
};
Session.prototype.doOutput = function (info, cmdName, reqSeq, success, message) {
var res = {
@@ -126483,10 +128962,11 @@ var ts;
this.logError(err, kind);
}
};
+ /** It is the caller's responsibility to verify that `!this.suppressDiagnosticEvents`. */
Session.prototype.updateErrorCheck = function (next, checkList, ms, requireOpen) {
var _this = this;
if (requireOpen === void 0) { requireOpen = true; }
- ts.Debug.assert(!this.suppressDiagnosticEvents);
+ ts.Debug.assert(!this.suppressDiagnosticEvents); // Caller's responsibility
var seq = this.changeSeq;
var followMs = Math.min(ms, 200);
var index = 0;
@@ -126496,6 +128976,7 @@ var ts;
}
var _a = checkList[index], fileName = _a.fileName, project = _a.project;
index++;
+ // Ensure the project is upto date before checking if this file is present in the project
server.updateProjectIfDirty(project);
if (!project.containsFile(fileName, requireOpen)) {
return;
@@ -126536,7 +129017,7 @@ var ts;
this.logger.info("cleaning " + caption);
for (var _i = 0, projects_5 = projects; _i < projects_5.length; _i++) {
var p = projects_5[_i];
- p.getLanguageService(false).cleanupSemanticCache();
+ p.getLanguageService(/*ensureSynchronized*/ false).cleanupSemanticCache();
}
};
Session.prototype.cleanup = function () {
@@ -126569,7 +129050,7 @@ var ts;
var diagnosticsForConfigFile = ts.filter(ts.concatenate(projectErrors, optionsErrors), function (diagnostic) { return !!diagnostic.file && diagnostic.file.fileName === configFile; });
return includeLinePosition ?
this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnosticsForConfigFile) :
- ts.map(diagnosticsForConfigFile, function (diagnostic) { return formatConfigFileDiag(diagnostic, false); });
+ ts.map(diagnosticsForConfigFile, function (diagnostic) { return formatConfigFileDiag(diagnostic, /*includeFileName*/ false); });
};
Session.prototype.convertToDiagnosticsWithLinePositionFromDiagnosticFile = function (diagnostics) {
var _this = this;
@@ -126586,7 +129067,11 @@ var ts;
};
Session.prototype.getCompilerOptionsDiagnostics = function (args) {
var project = this.getProject(args.projectFileName);
- return this.convertToDiagnosticsWithLinePosition(ts.filter(project.getLanguageService().getCompilerOptionsDiagnostics(), function (diagnostic) { return !diagnostic.file; }), undefined);
+ // Get diagnostics that dont have associated file with them
+ // The diagnostics which have file would be in config file and
+ // would be reported as part of configFileDiagnostics
+ return this.convertToDiagnosticsWithLinePosition(ts.filter(project.getLanguageService().getCompilerOptionsDiagnostics(), function (diagnostic) { return !diagnostic.file; }),
+ /*scriptInfo*/ undefined);
};
Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) {
var _this = this;
@@ -126647,7 +129132,7 @@ var ts;
if (!unmappedDefinitionAndBoundSpan || !unmappedDefinitionAndBoundSpan.definitions) {
return {
definitions: server.emptyArray,
- textSpan: undefined
+ textSpan: undefined // TODO: GH#18217
};
}
var definitions = this.mapDefinitionInfoLocations(unmappedDefinitionAndBoundSpan.definitions, project);
@@ -126671,6 +129156,13 @@ var ts;
var _this = this;
return definitions.map(function (def) { return _this.toFileSpan(def.fileName, def.textSpan, project); });
};
+ /*
+ * When we map a .d.ts location to .ts, Visual Studio gets confused because there's no associated Roslyn Document in
+ * the same project which corresponds to the file. VS Code has no problem with this, and luckily we have two protocols.
+ * This retains the existing behavior for the "simplified" (VS Code) protocol but stores the .d.ts location in a
+ * set of additional fields, and does the reverse for VS (store the .d.ts location where
+ * it used to be and stores the .ts location in the additional fields).
+ */
Session.mapToOriginalLocation = function (def) {
if (def.originalFileName) {
ts.Debug.assert(def.originalTextSpan !== undefined, "originalTextSpan should be present if originalFileName is");
@@ -126680,7 +129172,7 @@ var ts;
};
Session.prototype.toFileSpan = function (fileName, textSpan, project) {
var ls = project.getLanguageService();
- var start = ls.toLineColumnOffset(fileName, textSpan.start);
+ var start = ls.toLineColumnOffset(fileName, textSpan.start); // TODO: GH#18217
var end = ls.toLineColumnOffset(fileName, ts.textSpanEnd(textSpan));
return {
file: fileName,
@@ -126740,6 +129232,7 @@ var ts;
file: fileName,
isWriteAccess: isWriteAccess,
};
+ // no need to serialize the property if it is not true
if (isInString) {
result.isInString = isInString;
}
@@ -126749,23 +129242,26 @@ var ts;
Session.prototype.getSyntacticDiagnosticsSync = function (args) {
var configFile = this.getConfigFileAndProject(args).configFile;
if (configFile) {
+ // all the config file errors are reported as part of semantic check so nothing to report here
return server.emptyArray;
}
- return this.getDiagnosticsWorker(args, false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, !!args.includeLinePosition);
+ return this.getDiagnosticsWorker(args, /*isSemantic*/ false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, !!args.includeLinePosition);
};
Session.prototype.getSemanticDiagnosticsSync = function (args) {
var _a = this.getConfigFileAndProject(args), configFile = _a.configFile, project = _a.project;
if (configFile) {
- return this.getConfigFileDiagnostics(configFile, project, !!args.includeLinePosition);
+ return this.getConfigFileDiagnostics(configFile, project, !!args.includeLinePosition); // TODO: GH#18217
}
- return this.getDiagnosticsWorker(args, true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, !!args.includeLinePosition);
+ return this.getDiagnosticsWorker(args, /*isSemantic*/ true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, !!args.includeLinePosition);
};
Session.prototype.getSuggestionDiagnosticsSync = function (args) {
var configFile = this.getConfigFileAndProject(args).configFile;
if (configFile) {
+ // Currently there are no info diagnostics for config files.
return server.emptyArray;
}
- return this.getDiagnosticsWorker(args, true, function (project, file) { return project.getLanguageService().getSuggestionDiagnostics(file); }, !!args.includeLinePosition);
+ // isSemantic because we don't want to info diagnostics in declaration files for JS-only users
+ return this.getDiagnosticsWorker(args, /*isSemantic*/ true, function (project, file) { return project.getLanguageService().getSuggestionDiagnostics(file); }, !!args.includeLinePosition);
};
Session.prototype.getJsxClosingTag = function (args) {
var _a = this.getFileAndProject(args), file = _a.file, project = _a.project;
@@ -126805,7 +129301,7 @@ var ts;
this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath);
};
Session.prototype.getProjectInfo = function (args) {
- return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList, false);
+ return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList, /*excludeConfigFiles*/ false);
};
Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles) {
var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName).project;
@@ -126813,7 +129309,7 @@ var ts;
var projectInfo = {
configFileName: project.getProjectName(),
languageServiceDisabled: !project.languageServiceEnabled,
- fileNames: needFileNameList ? project.getFileNames(false, excludeConfigFiles) : undefined
+ fileNames: needFileNameList ? project.getFileNames(/*excludeFilesFromExternalLibraries*/ false, excludeConfigFiles) : undefined
};
return projectInfo;
};
@@ -126844,12 +129340,13 @@ var ts;
projects = scriptInfo.containingProjects;
symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo);
}
+ // filter handles case when 'projects' is undefined
projects = ts.filter(projects, function (p) { return p.languageServiceEnabled && !p.isOrphan(); });
if (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) {
this.projectService.logErrorForScriptInfoNotFound(args.file);
return server.Errors.ThrowNoProject();
}
- return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects;
+ return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects; // TODO: GH#18217
};
Session.prototype.getDefaultProject = function (args) {
if (args.projectFileName) {
@@ -126925,8 +129422,12 @@ var ts;
return references;
}
};
+ /**
+ * @param fileName is the name of the file to be opened
+ * @param fileContent is a version of the file content that is known to be more up to date than the one on disk
+ */
Session.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) {
- this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, false, projectRootPath);
+ this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath);
};
Session.prototype.getPosition = function (args, scriptInfo) {
return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset);
@@ -126939,6 +129440,8 @@ var ts;
return this.getFileAndProjectWorker(args.file, args.projectFileName);
};
Session.prototype.getFileAndLanguageServiceForSyntacticOperation = function (args) {
+ // Since this is syntactic operation, there should always be project for the file
+ // we wouldnt have to ensure project but rather throw if we dont get project
var file = server.toNormalizedPath(args.file);
var project = this.getProject(args.projectFileName) || this.projectService.tryGetDefaultProjectForFile(file);
if (!project) {
@@ -126946,7 +129449,7 @@ var ts;
}
return {
file: file,
- languageService: project.getLanguageService(false)
+ languageService: project.getLanguageService(/*ensureSynchronized*/ false)
};
};
Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName) {
@@ -127039,6 +129542,7 @@ var ts;
var scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file);
var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset);
var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
+ // TODO: avoid duplicate code (with formatonkey)
var edits = languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.getFormatOptions(file));
if (!edits) {
return undefined;
@@ -127048,7 +129552,7 @@ var ts;
Session.prototype.getFormattingEditsForRangeFull = function (args) {
var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file);
- return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options);
+ return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options); // TODO: GH#18217
};
Session.prototype.getFormattingEditsForDocumentFull = function (args) {
var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
@@ -127058,7 +129562,7 @@ var ts;
Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) {
var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
var options = args.options ? server.convertFormatOptions(args.options) : this.getFormatOptions(file);
- return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options);
+ return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options); // TODO: GH#18217
};
Session.prototype.getFormattingEditsAfterKeystroke = function (args) {
var _a = this.getFileAndLanguageServiceForSyntacticOperation(args), file = _a.file, languageService = _a.languageService;
@@ -127066,6 +129570,12 @@ var ts;
var position = scriptInfo.lineOffsetToPosition(args.line, args.offset);
var formatOptions = this.getFormatOptions(file);
var edits = languageService.getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions);
+ // Check whether we should auto-indent. This will be when
+ // the position is on a line containing only whitespace.
+ // This should leave the edits returned from
+ // getFormattingEditsAfterKeystroke either empty or pertaining
+ // only to the previous line. If all this is true, then
+ // add edits necessary to properly indent the current line.
if ((args.key === "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) {
var _b = scriptInfo.getAbsolutePositionAndLineText(args.line), lineText = _b.lineText, absolutePosition = _b.absolutePosition;
if (lineText && lineText.search("\\S") < 0) {
@@ -127077,12 +129587,13 @@ var ts;
hasIndent++;
}
else if (lineText.charAt(i) === "\t") {
- hasIndent += formatOptions.tabSize;
+ hasIndent += formatOptions.tabSize; // TODO: GH#18217
}
else {
break;
}
}
+ // i points to the first non whitespace character
if (preferredIndent !== hasIndent) {
var firstNoWhiteSpacePosition = absolutePosition + i;
edits.push({
@@ -127111,17 +129622,18 @@ var ts;
var completions = project.getLanguageService().getCompletionsAtPosition(file, position, __assign({}, server.convertUserPreferences(this.getPreferences(file)), { triggerCharacter: args.triggerCharacter, includeExternalModuleExports: args.includeExternalModuleExports, includeInsertTextCompletions: args.includeInsertTextCompletions }));
if (completions === undefined)
return undefined;
- if (kind === "completions-full")
+ if (kind === "completions-full" /* CompletionsFull */)
return completions;
var prefix = args.prefix || "";
var entries = ts.mapDefined(completions.entries, function (entry) {
if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) {
var name = entry.name, kind_1 = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended;
var convertedSpan = replacementSpan ? _this.toLocationTextSpan(replacementSpan, scriptInfo) : undefined;
+ // Use `hasAction || undefined` to avoid serializing `false`.
return { name: name, kind: kind_1, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended };
}
}).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); });
- if (kind === "completions") {
+ if (kind === "completions" /* Completions */) {
if (completions.metadata)
entries.metadata = completions.metadata;
return entries;
@@ -127145,7 +129657,7 @@ var ts;
};
Session.prototype.getCompileOnSaveAffectedFileList = function (args) {
var _this = this;
- var projects = this.getProjects(args, true, true);
+ var projects = this.getProjects(args, /*getScriptInfoEnsuringProjectsUptoDate*/ true, /*ignoreNoProjectError*/ true);
var info = this.projectService.getScriptInfo(args.file);
if (!info) {
return server.emptyArray;
@@ -127223,10 +129735,10 @@ var ts;
var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
if (start >= 0) {
this.changeSeq++;
- this.projectService.applyChangesToFile(scriptInfo, [{
- span: { start: start, length: end - start },
- newText: args.insertString
- }]);
+ this.projectService.applyChangesToFile(scriptInfo, ts.singleIterator({
+ span: { start: start, length: end - start },
+ newText: args.insertString // TODO: GH#18217
+ }));
}
};
Session.prototype.reload = function (args, reqSeq) {
@@ -127235,8 +129747,9 @@ var ts;
var info = this.projectService.getScriptInfoForNormalizedPath(file);
if (info) {
this.changeSeq++;
+ // make sure no changes happen before this one is finished
if (info.reloadFromFile(tempFileName)) {
- this.doOutput(undefined, server.CommandNames.Reload, reqSeq, true);
+ this.doOutput(/*info*/ undefined, server.CommandNames.Reload, reqSeq, /*success*/ true);
}
}
};
@@ -127334,7 +129847,7 @@ var ts;
}
else {
return combineProjectOutputWhileOpeningReferencedProjects(this.getProjects(args), this.getDefaultProject(args), function (project) {
- return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, undefined, project.isNonTsProject());
+ return project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, /*fileName*/ undefined, /*excludeDts*/ project.isNonTsProject());
}, documentSpanLocation, navigateToItemIsEqualTo);
}
function navigateToItemIsEqualTo(a, b) {
@@ -127446,7 +129959,7 @@ var ts;
}
};
Session.prototype.applyCodeActionCommand = function (args) {
- var commands = args.command;
+ var commands = args.command; // They should be sending back the command we sent them.
for (var _i = 0, _a = ts.toArray(commands); _i < _a.length; _i++) {
var command = _a[_i];
var _b = this.getFileAndProject(command), file = _b.file, project = _b.project;
@@ -127461,6 +129974,7 @@ var ts;
}
else {
startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset);
+ // save the result so we don't always recompute
args.startPosition = startPosition;
}
if (args.endPosition !== undefined) {
@@ -127487,7 +130001,7 @@ var ts;
Session.prototype.mapTextChangeToCodeEdit = function (textChanges) {
var scriptInfo = this.projectService.getScriptInfoOrConfig(textChanges.fileName);
if (!!textChanges.isNewFile === !!scriptInfo) {
- if (!scriptInfo) {
+ if (!scriptInfo) { // and !isNewFile
this.projectService.logErrorForScriptInfoNotFound(textChanges.fileName);
}
ts.Debug.fail("Expected isNewFile for (only) new files. " + JSON.stringify({ isNewFile: !!textChanges.isNewFile, hasScriptInfo: !!scriptInfo }));
@@ -127519,14 +130033,16 @@ var ts;
if (this.suppressDiagnosticEvents) {
return;
}
- var _a = this.getProjectInfoWorker(fileName, undefined, true, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled;
+ var _a = this.getProjectInfoWorker(fileName, /*projectFileName*/ undefined, /*needFileNameList*/ true, /*excludeConfigFiles*/ true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled;
if (languageServiceDisabled) {
return;
}
- var fileNamesInProject = fileNames.filter(function (value) { return !ts.stringContains(value, "lib.d.ts"); });
+ // No need to analyze lib.d.ts
+ var fileNamesInProject = fileNames.filter(function (value) { return !ts.stringContains(value, "lib.d.ts"); }); // TODO: GH#18217
if (fileNamesInProject.length === 0) {
return;
}
+ // Sort the file name list to make the recently touched files come first
var highPriorityFiles = [];
var mediumPriorityFiles = [];
var lowPriorityFiles = [];
@@ -127539,9 +130055,9 @@ var ts;
highPriorityFiles.push(fileNameInProject);
}
else {
- var info = this.projectService.getScriptInfo(fileNameInProject);
+ var info = this.projectService.getScriptInfo(fileNameInProject); // TODO: GH#18217
if (!info.isScriptOpen()) {
- if (ts.fileExtensionIs(fileNameInProject, ".d.ts")) {
+ if (ts.fileExtensionIs(fileNameInProject, ".d.ts" /* Dts */)) {
veryLowPriorityFiles.push(fileNameInProject);
}
else {
@@ -127555,7 +130071,9 @@ var ts;
}
var sortedFiles = highPriorityFiles.concat(mediumPriorityFiles, lowPriorityFiles, veryLowPriorityFiles);
var checkList = sortedFiles.map(function (fileName) { return ({ fileName: fileName, project: project }); });
- this.updateErrorCheck(next, checkList, delay, false);
+ // Project level error analysis runs on background files too, therefore
+ // doesn't require the file to be opened
+ this.updateErrorCheck(next, checkList, delay, /*requireOpen*/ false);
};
Session.prototype.configurePlugin = function (args) {
this.projectService.configurePlugin(args);
@@ -127584,7 +130102,7 @@ var ts;
};
Session.prototype.resetCurrentRequest = function (requestId) {
ts.Debug.assert(this.currentRequestId === requestId);
- this.currentRequestId = undefined;
+ this.currentRequestId = undefined; // TODO: GH#18217
this.cancellationToken.resetRequest(requestId);
};
Session.prototype.executeWithRequestId = function (requestId, f) {
@@ -127603,7 +130121,7 @@ var ts;
}
else {
this.logger.msg("Unrecognized JSON command:" + server.stringifyIndented(request), server.Msg.Err);
- this.doOutput(undefined, server.CommandNames.Unknown, request.seq, false, "Unrecognized JSON command: " + request.command);
+ this.doOutput(/*info*/ undefined, server.CommandNames.Unknown, request.seq, /*success*/ false, "Unrecognized JSON command: " + request.command);
return { responseRequired: false };
}
};
@@ -127632,19 +130150,22 @@ var ts;
}
}
if (response) {
- this.doOutput(response, request.command, request.seq, true);
+ this.doOutput(response, request.command, request.seq, /*success*/ true);
}
else if (responseRequired) {
- this.doOutput(undefined, request.command, request.seq, false, "No content available.");
+ this.doOutput(/*info*/ undefined, request.command, request.seq, /*success*/ false, "No content available.");
}
}
catch (err) {
if (err instanceof ts.OperationCanceledException) {
- this.doOutput({ canceled: true }, request.command, request.seq, true);
+ // Handle cancellation exceptions
+ this.doOutput({ canceled: true }, request.command, request.seq, /*success*/ true);
return;
}
this.logErrorWorker(err, message, relevantFile);
- this.doOutput(undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, false, "Error processing request. " + err.message + "\n" + err.stack);
+ this.doOutput(
+ /*info*/ undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0,
+ /*success*/ false, "Error processing request. " + err.message + "\n" + err.stack);
}
};
Session.prototype.getFormatOptions = function (file) {
@@ -127680,6 +130201,7 @@ var ts;
ts.Debug.assert(change.span.start === 0 && change.span.length === 0);
return { fileName: textChanges.fileName, textChanges: [{ start: { line: 0, offset: 0 }, end: { line: 0, offset: 0 }, newText: change.newText }] };
}
+ /* @internal */ // Exported only for tests
function getLocationInNewDocument(oldText, renameFilename, renameLocation, edits) {
var newText = applyEdits(oldText, renameFilename, edits);
var _a = ts.computeLineAndCharacterOfPosition(ts.computeLineStarts(newText), renameLocation), line = _a.line, character = _a.character;
@@ -127701,6 +130223,7 @@ var ts;
}
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
+/*@internal*/
var ts;
(function (ts) {
var server;
@@ -127715,12 +130238,12 @@ var ts;
CharRangeSection[CharRangeSection["End"] = 4] = "End";
CharRangeSection[CharRangeSection["PostEnd"] = 5] = "PostEnd";
})(CharRangeSection || (CharRangeSection = {}));
- var EditWalker = (function () {
+ var EditWalker = /** @class */ (function () {
function EditWalker() {
this.goSubtree = true;
this.lineIndex = new LineIndex();
this.endBranch = [];
- this.state = 2;
+ this.state = 2 /* Entire */;
this.initialText = "";
this.trailingText = "";
this.lineIndex.root = new LineNode();
@@ -127766,6 +130289,7 @@ var ts;
if (lastZeroCount) {
branchParent.remove(lastZeroCount);
}
+ // path at least length two (root and leaf)
var leafNode = this.startPath[this.startPath.length - 1];
if (lines.length > 0) {
leafNode.text = lines[0];
@@ -127800,6 +130324,7 @@ var ts;
}
else {
var insertionNode = this.startPath[this.startPath.length - 2];
+ // no content for leaf node, so delete it
insertionNode.remove(leafNode);
for (var j = this.startPath.length - 2; j >= 0; j--) {
this.startPath[j].updateCounts();
@@ -127808,15 +130333,20 @@ var ts;
return this.lineIndex;
};
EditWalker.prototype.post = function (_relativeStart, _relativeLength, lineCollection) {
+ // have visited the path for start of range, now looking for end
+ // if range is on single line, we will never make this state transition
if (lineCollection === this.lineCollectionAtBranch) {
- this.state = 4;
+ this.state = 4 /* End */;
}
+ // always pop stack because post only called when child has been visited
this.stack.pop();
};
EditWalker.prototype.pre = function (_relativeStart, _relativeLength, lineCollection, _parent, nodeType) {
+ // currentNode corresponds to parent, but in the new tree
var currentNode = this.stack[this.stack.length - 1];
- if ((this.state === 2) && (nodeType === 1)) {
- this.state = 1;
+ if ((this.state === 2 /* Entire */) && (nodeType === 1 /* Start */)) {
+ // if range is on single line, we will never make this state transition
+ this.state = 1 /* Start */;
this.branchNode = currentNode;
this.lineCollectionAtBranch = lineCollection;
}
@@ -127829,14 +130359,14 @@ var ts;
return new LineNode();
}
switch (nodeType) {
- case 0:
+ case 0 /* PreStart */:
this.goSubtree = false;
- if (this.state !== 4) {
+ if (this.state !== 4 /* End */) {
currentNode.add(lineCollection);
}
break;
- case 1:
- if (this.state === 4) {
+ case 1 /* Start */:
+ if (this.state === 4 /* End */) {
this.goSubtree = false;
}
else {
@@ -127845,8 +130375,8 @@ var ts;
this.startPath.push(child);
}
break;
- case 2:
- if (this.state !== 4) {
+ case 2 /* Entire */:
+ if (this.state !== 4 /* End */) {
child = fresh(lineCollection);
currentNode.add(child);
this.startPath.push(child);
@@ -127859,11 +130389,11 @@ var ts;
}
}
break;
- case 3:
+ case 3 /* Mid */:
this.goSubtree = false;
break;
- case 4:
- if (this.state !== 4) {
+ case 4 /* End */:
+ if (this.state !== 4 /* End */) {
this.goSubtree = false;
}
else {
@@ -127874,9 +130404,9 @@ var ts;
}
}
break;
- case 5:
+ case 5 /* PostEnd */:
this.goSubtree = false;
- if (this.state !== 1) {
+ if (this.state !== 1 /* Start */) {
currentNode.add(lineCollection);
}
break;
@@ -127885,21 +130415,24 @@ var ts;
this.stack.push(child);
}
};
+ // just gather text from the leaves
EditWalker.prototype.leaf = function (relativeStart, relativeLength, ll) {
- if (this.state === 1) {
+ if (this.state === 1 /* Start */) {
this.initialText = ll.text.substring(0, relativeStart);
}
- else if (this.state === 2) {
+ else if (this.state === 2 /* Entire */) {
this.initialText = ll.text.substring(0, relativeStart);
this.trailingText = ll.text.substring(relativeStart + relativeLength);
}
else {
+ // state is CharRangeSection.End
this.trailingText = ll.text.substring(relativeStart + relativeLength);
}
};
return EditWalker;
}());
- var TextChange = (function () {
+ // text change information
+ var TextChange = /** @class */ (function () {
function TextChange(pos, deleteLen, insertedText) {
this.pos = pos;
this.deleteLen = deleteLen;
@@ -127910,11 +130443,11 @@ var ts;
};
return TextChange;
}());
- var ScriptVersionCache = (function () {
+ var ScriptVersionCache = /** @class */ (function () {
function ScriptVersionCache() {
this.changes = [];
this.versions = new Array(ScriptVersionCache.maxVersions);
- this.minVersion = 0;
+ this.minVersion = 0; // no versions earlier than min version will maintain change history
this.currentVersion = 0;
}
ScriptVersionCache.prototype.versionToIndex = function (version) {
@@ -127926,6 +130459,7 @@ var ts;
ScriptVersionCache.prototype.currentVersionToIndex = function () {
return this.currentVersion % ScriptVersionCache.maxVersions;
};
+ // REVIEW: can optimize by coalescing simple edits
ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) {
this.changes.push(new TextChange(pos, deleteLen, insertedText));
if (this.changes.length > ScriptVersionCache.changeNumberThreshold ||
@@ -127976,7 +130510,7 @@ var ts;
if (oldVersion >= this.minVersion) {
var textChangeRanges = [];
for (var i = oldVersion + 1; i <= newVersion; i++) {
- var snap = this.versions[this.versionToIndex(i)];
+ var snap = this.versions[this.versionToIndex(i)]; // TODO: GH#18217
for (var _i = 0, _a = snap.changesSincePreviousVersion; _i < _a.length; _i++) {
var textChange = _a[_i];
textChangeRanges.push(textChange.getTextChangeRange());
@@ -128009,7 +130543,7 @@ var ts;
return ScriptVersionCache;
}());
server.ScriptVersionCache = ScriptVersionCache;
- var LineIndexSnapshot = (function () {
+ var LineIndexSnapshot = /** @class */ (function () {
function LineIndexSnapshot(version, cache, index, changesSincePreviousVersion) {
if (changesSincePreviousVersion === void 0) { changesSincePreviousVersion = server.emptyArray; }
this.version = version;
@@ -128035,8 +130569,9 @@ var ts;
};
return LineIndexSnapshot;
}());
- var LineIndex = (function () {
+ var LineIndex = /** @class */ (function () {
function LineIndex() {
+ // set this to true to check each edit for accuracy
this.checkEdits = false;
}
LineIndex.prototype.absolutePositionOfStartOfLine = function (oneBasedLine) {
@@ -128111,12 +130646,12 @@ var ts;
};
LineIndex.prototype.edit = function (pos, deleteLength, newText) {
if (this.root.charCount() === 0) {
- ts.Debug.assert(deleteLength === 0);
+ ts.Debug.assert(deleteLength === 0); // Can't delete from empty document
if (newText !== undefined) {
this.load(LineIndex.linesFromText(newText).lines);
return this;
}
- return undefined;
+ return undefined; // TODO: GH#18217
}
else {
var checkText = void 0;
@@ -128127,6 +130662,7 @@ var ts;
var walker = new EditWalker();
var suppressTrailingText = false;
if (pos >= this.root.charCount()) {
+ // insert at end
pos = this.root.charCount() - 1;
var endString = this.getText(pos, 1);
if (newText) {
@@ -128139,10 +130675,13 @@ var ts;
suppressTrailingText = true;
}
else if (deleteLength > 0) {
+ // check whether last characters deleted are line break
var e = pos + deleteLength;
var _a = this.positionToColumnAndLineText(e), zeroBasedColumn = _a.zeroBasedColumn, lineText = _a.lineText;
if (zeroBasedColumn === 0) {
- deleteLength += lineText.length;
+ // move range end just past line that will merge with previous line
+ deleteLength += lineText.length; // TODO: GH#18217
+ // store text by appending to end of insertedText
newText = newText ? newText + lineText : lineText;
}
}
@@ -128190,7 +130729,7 @@ var ts;
return LineIndex;
}());
server.LineIndex = LineIndex;
- var LineNode = (function () {
+ var LineNode = /** @class */ (function () {
function LineNode(children) {
if (children === void 0) { children = []; }
this.children = children;
@@ -128233,22 +130772,26 @@ var ts;
}
};
LineNode.prototype.walk = function (rangeStart, rangeLength, walkFns) {
+ // assume (rangeStart < this.totalChars) && (rangeLength <= this.totalChars)
var childIndex = 0;
var childCharCount = this.children[childIndex].charCount();
+ // find sub-tree containing start
var adjustedStart = rangeStart;
while (adjustedStart >= childCharCount) {
- this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, 0);
+ this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, 0 /* PreStart */);
adjustedStart -= childCharCount;
childIndex++;
childCharCount = this.children[childIndex].charCount();
}
+ // Case I: both start and end of range in same subtree
if ((adjustedStart + rangeLength) <= childCharCount) {
- if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, 2)) {
+ if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, 2 /* Entire */)) {
return;
}
}
else {
- if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, 1)) {
+ // Case II: start and end of range in different subtrees (possibly with subtrees in the middle)
+ if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, 1 /* Start */)) {
return;
}
var adjustedLength = rangeLength - (childCharCount - adjustedStart);
@@ -128256,7 +130799,7 @@ var ts;
var child = this.children[childIndex];
childCharCount = child.charCount();
while (adjustedLength > childCharCount) {
- if (this.execWalk(0, childCharCount, walkFns, childIndex, 3)) {
+ if (this.execWalk(0, childCharCount, walkFns, childIndex, 3 /* Mid */)) {
return;
}
adjustedLength -= childCharCount;
@@ -128264,22 +130807,26 @@ var ts;
childCharCount = this.children[childIndex].charCount();
}
if (adjustedLength > 0) {
- if (this.execWalk(0, adjustedLength, walkFns, childIndex, 4)) {
+ if (this.execWalk(0, adjustedLength, walkFns, childIndex, 4 /* End */)) {
return;
}
}
}
+ // Process any subtrees after the one containing range end
if (walkFns.pre) {
var clen = this.children.length;
if (childIndex < (clen - 1)) {
for (var ej = childIndex + 1; ej < clen; ej++) {
- this.skipChild(0, 0, ej, walkFns, 5);
+ this.skipChild(0, 0, ej, walkFns, 5 /* PostEnd */);
}
}
}
};
+ // Input position is relative to the start of this node.
+ // Output line number is absolute.
LineNode.prototype.charOffsetToLineInfo = function (lineNumberAccumulator, relativePosition) {
if (this.children.length === 0) {
+ // Root node might have no children if this is an empty document.
return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: undefined };
}
for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
@@ -128297,9 +130844,15 @@ var ts;
lineNumberAccumulator += child.lineCount();
}
}
+ // Skipped all children
var leaf = this.lineNumberToInfo(this.lineCount(), 0).leaf;
return { oneBasedLine: this.lineCount(), zeroBasedColumn: leaf ? leaf.charCount() : 0, lineText: undefined };
};
+ /**
+ * Input line number is relative to the start of this node.
+ * Output line number is relative to the child.
+ * positionAccumulator will be an absolute position once relativeLineNumber reaches 0.
+ */
LineNode.prototype.lineNumberToInfo = function (relativeOneBasedLine, positionAccumulator) {
for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
var child = _a[_i];
@@ -128349,6 +130902,7 @@ var ts;
var childIndex = this.findChildIndex(child);
var clen = this.children.length;
var nodeCount = nodes.length;
+ // if child is last and there is more room and only one node to place, place it
if ((clen < lineCollectionCapacity) && (childIndex === (clen - 1)) && (nodeCount === 1)) {
this.add(nodes[0]);
this.updateCounts();
@@ -128397,6 +130951,7 @@ var ts;
return splitNodes;
}
};
+ // assume there is room for the item; return true if more room
LineNode.prototype.add = function (collection) {
this.children.push(collection);
ts.Debug.assert(this.children.length <= lineCollectionCapacity);
@@ -128409,7 +130964,7 @@ var ts;
};
return LineNode;
}());
- var LineLeaf = (function () {
+ var LineLeaf = /** @class */ (function () {
function LineLeaf(text) {
this.text = text;
}
@@ -128429,7 +130984,6 @@ var ts;
}());
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
-//# sourceMappingURL=server.js.map
// tslint:disable no-unnecessary-type-assertion (TODO: tslint can't find node types)
var ts;
(function (ts) {
diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts
index fab6f905efcca..e99261be3f3b5 100644
--- a/lib/tsserverlibrary.d.ts
+++ b/lib/tsserverlibrary.d.ts
@@ -355,40 +355,45 @@ declare namespace ts {
ShorthandPropertyAssignment = 276,
SpreadAssignment = 277,
EnumMember = 278,
- SourceFile = 279,
- Bundle = 280,
- UnparsedSource = 281,
- InputFiles = 282,
- JSDocTypeExpression = 283,
- JSDocAllType = 284,
- JSDocUnknownType = 285,
- JSDocNullableType = 286,
- JSDocNonNullableType = 287,
- JSDocOptionalType = 288,
- JSDocFunctionType = 289,
- JSDocVariadicType = 290,
- JSDocComment = 291,
- JSDocTypeLiteral = 292,
- JSDocSignature = 293,
- JSDocTag = 294,
- JSDocAugmentsTag = 295,
- JSDocClassTag = 296,
- JSDocCallbackTag = 297,
- JSDocEnumTag = 298,
- JSDocParameterTag = 299,
- JSDocReturnTag = 300,
- JSDocThisTag = 301,
- JSDocTypeTag = 302,
- JSDocTemplateTag = 303,
- JSDocTypedefTag = 304,
- JSDocPropertyTag = 305,
- SyntaxList = 306,
- NotEmittedStatement = 307,
- PartiallyEmittedExpression = 308,
- CommaListExpression = 309,
- MergeDeclarationMarker = 310,
- EndOfDeclarationMarker = 311,
- Count = 312,
+ UnparsedPrologue = 279,
+ UnparsedPrepend = 280,
+ UnparsedText = 281,
+ UnparsedInternalText = 282,
+ UnparsedSyntheticReference = 283,
+ SourceFile = 284,
+ Bundle = 285,
+ UnparsedSource = 286,
+ InputFiles = 287,
+ JSDocTypeExpression = 288,
+ JSDocAllType = 289,
+ JSDocUnknownType = 290,
+ JSDocNullableType = 291,
+ JSDocNonNullableType = 292,
+ JSDocOptionalType = 293,
+ JSDocFunctionType = 294,
+ JSDocVariadicType = 295,
+ JSDocComment = 296,
+ JSDocTypeLiteral = 297,
+ JSDocSignature = 298,
+ JSDocTag = 299,
+ JSDocAugmentsTag = 300,
+ JSDocClassTag = 301,
+ JSDocCallbackTag = 302,
+ JSDocEnumTag = 303,
+ JSDocParameterTag = 304,
+ JSDocReturnTag = 305,
+ JSDocThisTag = 306,
+ JSDocTypeTag = 307,
+ JSDocTemplateTag = 308,
+ JSDocTypedefTag = 309,
+ JSDocPropertyTag = 310,
+ SyntaxList = 311,
+ NotEmittedStatement = 312,
+ PartiallyEmittedExpression = 313,
+ CommaListExpression = 314,
+ MergeDeclarationMarker = 315,
+ EndOfDeclarationMarker = 316,
+ Count = 317,
FirstAssignment = 59,
LastAssignment = 71,
FirstCompoundAssignment = 60,
@@ -414,10 +419,10 @@ declare namespace ts {
FirstBinaryOperator = 28,
LastBinaryOperator = 71,
FirstNode = 148,
- FirstJSDocNode = 283,
- LastJSDocNode = 305,
- FirstJSDocTagNode = 294,
- LastJSDocTagNode = 305
+ FirstJSDocNode = 288,
+ LastJSDocNode = 310,
+ FirstJSDocTagNode = 299,
+ LastJSDocTagNode = 310,
}
enum NodeFlags {
None = 0,
@@ -446,7 +451,7 @@ declare namespace ts {
ReachabilityCheckFlags = 384,
ReachabilityAndEmitFlags = 1408,
ContextFlags = 12679168,
- TypeExcludesFlags = 20480
+ TypeExcludesFlags = 20480,
}
enum ModifierFlags {
None = 0,
@@ -1003,7 +1008,7 @@ declare namespace ts {
Octal = 32,
HexSpecifier = 64,
BinarySpecifier = 128,
- OctalSpecifier = 256
+ OctalSpecifier = 256,
}
interface NumericLiteral extends LiteralExpression {
kind: SyntaxKind.NumericLiteral;
@@ -1745,10 +1750,44 @@ declare namespace ts {
}
interface UnparsedSource extends Node {
kind: SyntaxKind.UnparsedSource;
- fileName?: string;
+ fileName: string;
text: string;
+ prologues: ReadonlyArray;
+ helpers: ReadonlyArray | undefined;
+ referencedFiles: ReadonlyArray;
+ typeReferenceDirectives: ReadonlyArray | undefined;
+ libReferenceDirectives: ReadonlyArray;
+ hasNoDefaultLib?: boolean;
sourceMapPath?: string;
sourceMapText?: string;
+ syntheticReferences?: ReadonlyArray;
+ texts: ReadonlyArray;
+ }
+ type UnparsedSourceText = UnparsedPrepend | UnparsedTextLike;
+ type UnparsedNode = UnparsedPrologue | UnparsedSourceText | UnparsedSyntheticReference;
+ interface UnparsedSection extends Node {
+ kind: SyntaxKind;
+ data?: string;
+ parent: UnparsedSource;
+ }
+ interface UnparsedPrologue extends UnparsedSection {
+ kind: SyntaxKind.UnparsedPrologue;
+ data: string;
+ parent: UnparsedSource;
+ }
+ interface UnparsedPrepend extends UnparsedSection {
+ kind: SyntaxKind.UnparsedPrepend;
+ data: string;
+ parent: UnparsedSource;
+ texts: ReadonlyArray;
+ }
+ interface UnparsedTextLike extends UnparsedSection {
+ kind: SyntaxKind.UnparsedText | SyntaxKind.UnparsedInternalText;
+ parent: UnparsedSource;
+ }
+ interface UnparsedSyntheticReference extends UnparsedSection {
+ kind: SyntaxKind.UnparsedSyntheticReference;
+ parent: UnparsedSource;
}
interface JsonSourceFile extends SourceFile {
statements: NodeArray;
@@ -2022,7 +2061,7 @@ declare namespace ts {
WriteTypeParametersOrArguments = 1,
UseOnlyExternalAliasing = 2,
AllowAnyNodeKind = 4,
- UseAliasDefinedOutsideCurrentScope = 8
+ UseAliasDefinedOutsideCurrentScope = 8,
}
enum TypePredicateKind {
This = 0,
@@ -2100,7 +2139,7 @@ declare namespace ts {
ExportHasLocal = 944,
BlockScoped = 418,
PropertyOrAccessor = 98308,
- ClassMember = 106500
+ ClassMember = 106500,
}
interface Symbol {
flags: SymbolFlags;
@@ -2208,7 +2247,7 @@ declare namespace ts {
Instantiable = 63176704,
StructuredOrInstantiable = 66846720,
Narrowable = 133970943,
- NotUnionOrUnit = 67637251
+ NotUnionOrUnit = 67637251,
}
type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
interface Type {
@@ -2255,7 +2294,7 @@ declare namespace ts {
MarkerType = 8192,
JSLiteral = 16384,
FreshLiteral = 32768,
- ClassOrInterface = 3
+ ClassOrInterface = 3,
}
interface ObjectType extends Type {
objectFlags: ObjectFlags;
@@ -2503,6 +2542,8 @@ declare namespace ts {
reactNamespace?: string;
jsxFactory?: string;
composite?: boolean;
+ incremental?: boolean;
+ tsBuildInfoFile?: string;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
@@ -2679,7 +2720,8 @@ declare namespace ts {
Dts = ".d.ts",
Js = ".js",
Jsx = ".jsx",
- Json = ".json"
+ Json = ".json",
+ TsBuildInfo = ".tsbuildinfo"
}
interface ResolvedModuleWithFailedLookupLocations {
readonly resolvedModule: ResolvedModuleFull | undefined;
@@ -2752,7 +2794,7 @@ declare namespace ts {
NoHoisting = 2097152,
HasEndOfDeclarationMarker = 4194304,
Iterator = 8388608,
- NoAsciiEscaping = 16777216
+ NoAsciiEscaping = 16777216,
}
interface EmitHelper {
readonly name: string;
@@ -2760,6 +2802,10 @@ declare namespace ts {
readonly text: string | ((node: EmitHelperUniqueNameCallback) => string);
readonly priority?: number;
}
+ interface UnscopedEmitHelper extends EmitHelper {
+ readonly scoped: false;
+ readonly text: string;
+ }
type EmitHelperUniqueNameCallback = (name: string) => string;
enum EmitHint {
SourceFile = 0,
@@ -3459,6 +3505,9 @@ declare namespace ts {
function isSourceFile(node: Node): node is SourceFile;
function isBundle(node: Node): node is Bundle;
function isUnparsedSource(node: Node): node is UnparsedSource;
+ function isUnparsedPrepend(node: Node): node is UnparsedPrepend;
+ function isUnparsedTextLike(node: Node): node is UnparsedTextLike;
+ function isUnparsedNode(node: Node): node is UnparsedNode;
function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression;
function isJSDocAllType(node: JSDocAllType): node is JSDocAllType;
function isJSDocUnknownType(node: Node): node is JSDocUnknownType;
@@ -3994,10 +4043,10 @@ declare namespace ts {
function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression;
function createBundle(sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle;
function createUnparsedSourceFile(text: string): UnparsedSource;
- function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts"): UnparsedSource;
+ function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts", stripInternal?: boolean): UnparsedSource;
function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource;
function createInputFiles(javascriptText: string, declarationText: string): InputFiles;
- function createInputFiles(readFileText: (path: string) => string | undefined, javascriptPath: string, javascriptMapPath: string | undefined, declarationPath: string, declarationMapPath: string | undefined): InputFiles;
+ function createInputFiles(readFileText: (path: string) => string | undefined, javascriptPath: string, javascriptMapPath: string | undefined, declarationPath: string, declarationMapPath: string | undefined, buildInfoPath: string | undefined): InputFiles;
function createInputFiles(javascriptText: string, declarationText: string, javascriptMapPath: string | undefined, javascriptMapText: string | undefined, declarationMapPath: string | undefined, declarationMapText: string | undefined): InputFiles;
function updateBundle(node: Bundle, sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray): CallExpression;
@@ -5720,6 +5769,7 @@ declare namespace ts.server.protocol {
OpenExternalProject = "openExternalProject",
OpenExternalProjects = "openExternalProjects",
CloseExternalProject = "closeExternalProject",
+ UpdateOpen = "updateOpen",
GetOutliningSpans = "getOutliningSpans",
TodoComments = "todoComments",
Indentation = "indentation",
@@ -6788,6 +6838,30 @@ declare namespace ts.server.protocol {
*/
interface CloseExternalProjectResponse extends Response {
}
+ /**
+ * Request to synchronize list of open files with the client
+ */
+ interface UpdateOpenRequest extends Request {
+ command: CommandTypes.UpdateOpen;
+ arguments: UpdateOpenRequestArgs;
+ }
+ /**
+ * Arguments to UpdateOpenRequest
+ */
+ interface UpdateOpenRequestArgs {
+ /**
+ * List of newly open files
+ */
+ openFiles?: OpenRequestArgs[];
+ /**
+ * List of open files files that were changes
+ */
+ changedFiles?: FileCodeEdits[];
+ /**
+ * List of files that were closed
+ */
+ closedFiles?: string[];
+ }
/**
* Request to set compiler options for inferred projects.
* External projects are opened / closed explicitly.
@@ -8355,7 +8429,7 @@ declare namespace ts.server {
excludedFiles: ReadonlyArray;
private typeAcquisition;
updateGraph(): boolean;
- getExcludedFiles(): ReadonlyArray;
+ getExcludedFiles(): readonly NormalizedPath[];
getTypeAcquisition(): TypeAcquisition;
setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void;
}
@@ -8627,6 +8701,7 @@ declare namespace ts.server {
*/
private onConfigFileChangeForOpenScriptInfo;
private removeProject;
+ private assignOrphanScriptInfosToInferredProject;
/**
* Remove this file from the set of open, non-configured files.
* @param info The file that has been closed or newly configured
@@ -8745,6 +8820,9 @@ declare namespace ts.server {
*/
openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind, projectRootPath?: string): OpenConfiguredProjectResult;
private findExternalProjectContainingOpenScriptInfo;
+ private getOrCreateOpenScriptInfo;
+ private assignProjectToOpenedScriptInfo;
+ private cleanupAfterOpeningFile;
openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult;
private removeOrphanConfiguredProjects;
private removeOrphanScriptInfos;
diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js
index e6bc5dd0d8374..2ac08ff8378bf 100644
--- a/lib/tsserverlibrary.js
+++ b/lib/tsserverlibrary.js
@@ -821,7 +821,7 @@ var ts;
}
/**
* Deduplicates an unsorted array.
- * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates.
+ * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates.
* @param comparer An optional `Comparer` used to sort entries before comparison, though the
* result will remain in the original order in `array`.
*/
@@ -1037,6 +1037,21 @@ var ts;
} };
}
ts.arrayIterator = arrayIterator;
+ function arrayReverseIterator(array) {
+ var i = array.length;
+ return {
+ next: function () {
+ if (i === 0) {
+ return { value: undefined, done: true };
+ }
+ else {
+ i--;
+ return { value: array[i], done: false };
+ }
+ }
+ };
+ }
+ ts.arrayReverseIterator = arrayReverseIterator;
/**
* Stable sort of an array. Elements equal to each other maintain their relative position in the array.
*/
@@ -2876,47 +2891,53 @@ var ts;
SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment";
// Enum
SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember";
+ // Unparsed
+ SyntaxKind[SyntaxKind["UnparsedPrologue"] = 279] = "UnparsedPrologue";
+ SyntaxKind[SyntaxKind["UnparsedPrepend"] = 280] = "UnparsedPrepend";
+ SyntaxKind[SyntaxKind["UnparsedText"] = 281] = "UnparsedText";
+ SyntaxKind[SyntaxKind["UnparsedInternalText"] = 282] = "UnparsedInternalText";
+ SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 283] = "UnparsedSyntheticReference";
// Top-level nodes
- SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile";
- SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle";
- SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource";
- SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles";
+ SyntaxKind[SyntaxKind["SourceFile"] = 284] = "SourceFile";
+ SyntaxKind[SyntaxKind["Bundle"] = 285] = "Bundle";
+ SyntaxKind[SyntaxKind["UnparsedSource"] = 286] = "UnparsedSource";
+ SyntaxKind[SyntaxKind["InputFiles"] = 287] = "InputFiles";
// JSDoc nodes
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression";
+ SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 288] = "JSDocTypeExpression";
// The * type
- SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType";
+ SyntaxKind[SyntaxKind["JSDocAllType"] = 289] = "JSDocAllType";
// The ? type
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature";
- SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag";
- SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag";
- SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag";
+ SyntaxKind[SyntaxKind["JSDocUnknownType"] = 290] = "JSDocUnknownType";
+ SyntaxKind[SyntaxKind["JSDocNullableType"] = 291] = "JSDocNullableType";
+ SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 292] = "JSDocNonNullableType";
+ SyntaxKind[SyntaxKind["JSDocOptionalType"] = 293] = "JSDocOptionalType";
+ SyntaxKind[SyntaxKind["JSDocFunctionType"] = 294] = "JSDocFunctionType";
+ SyntaxKind[SyntaxKind["JSDocVariadicType"] = 295] = "JSDocVariadicType";
+ SyntaxKind[SyntaxKind["JSDocComment"] = 296] = "JSDocComment";
+ SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 297] = "JSDocTypeLiteral";
+ SyntaxKind[SyntaxKind["JSDocSignature"] = 298] = "JSDocSignature";
+ SyntaxKind[SyntaxKind["JSDocTag"] = 299] = "JSDocTag";
+ SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 300] = "JSDocAugmentsTag";
+ SyntaxKind[SyntaxKind["JSDocClassTag"] = 301] = "JSDocClassTag";
+ SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 302] = "JSDocCallbackTag";
+ SyntaxKind[SyntaxKind["JSDocEnumTag"] = 303] = "JSDocEnumTag";
+ SyntaxKind[SyntaxKind["JSDocParameterTag"] = 304] = "JSDocParameterTag";
+ SyntaxKind[SyntaxKind["JSDocReturnTag"] = 305] = "JSDocReturnTag";
+ SyntaxKind[SyntaxKind["JSDocThisTag"] = 306] = "JSDocThisTag";
+ SyntaxKind[SyntaxKind["JSDocTypeTag"] = 307] = "JSDocTypeTag";
+ SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 308] = "JSDocTemplateTag";
+ SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 309] = "JSDocTypedefTag";
+ SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 310] = "JSDocPropertyTag";
// Synthesized list
- SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList";
+ SyntaxKind[SyntaxKind["SyntaxList"] = 311] = "SyntaxList";
// Transformation nodes
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker";
+ SyntaxKind[SyntaxKind["NotEmittedStatement"] = 312] = "NotEmittedStatement";
+ SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 313] = "PartiallyEmittedExpression";
+ SyntaxKind[SyntaxKind["CommaListExpression"] = 314] = "CommaListExpression";
+ SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 315] = "MergeDeclarationMarker";
+ SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 316] = "EndOfDeclarationMarker";
// Enum value count
- SyntaxKind[SyntaxKind["Count"] = 312] = "Count";
+ SyntaxKind[SyntaxKind["Count"] = 317] = "Count";
// Markers
SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment";
SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment";
@@ -2943,10 +2964,10 @@ var ts;
SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator";
SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator";
SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode";
+ SyntaxKind[SyntaxKind["FirstJSDocNode"] = 288] = "FirstJSDocNode";
+ SyntaxKind[SyntaxKind["LastJSDocNode"] = 310] = "LastJSDocNode";
+ SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 299] = "FirstJSDocTagNode";
+ SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 310] = "LastJSDocTagNode";
/* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword";
/* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword";
})(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
@@ -3564,6 +3585,7 @@ var ts;
InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
InferenceFlags[InferenceFlags["NoFixing"] = 4] = "NoFixing";
+ InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 8] = "SkippedGenericFunction";
})(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
/**
* Ternary values are defined such that
@@ -3823,6 +3845,7 @@ var ts;
Extension["Js"] = ".js";
Extension["Jsx"] = ".jsx";
Extension["Json"] = ".json";
+ Extension["TsBuildInfo"] = ".tsbuildinfo";
})(Extension = ts.Extension || (ts.Extension = {}));
/* @internal */
var TransformFlags;
@@ -3980,6 +4003,20 @@ var ts;
EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
})(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
+ /*@internal*/
+ var BundleFileSectionKind;
+ (function (BundleFileSectionKind) {
+ BundleFileSectionKind["Prologue"] = "prologue";
+ BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
+ BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
+ BundleFileSectionKind["Reference"] = "reference";
+ BundleFileSectionKind["Type"] = "type";
+ BundleFileSectionKind["Lib"] = "lib";
+ BundleFileSectionKind["Prepend"] = "prepend";
+ BundleFileSectionKind["Text"] = "text";
+ BundleFileSectionKind["Internal"] = "internal";
+ // comments?
+ })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
var ListFormat;
(function (ListFormat) {
ListFormat[ListFormat["None"] = 0] = "None";
@@ -4387,6 +4424,8 @@ var ts;
: FileWatcherEventKind.Changed;
}
ts.getFileWatcherEventKind = getFileWatcherEventKind;
+ /*@internal*/
+ ts.ignoredPaths = ["/node_modules/.", "/.git"];
/**
* Watch the directory recursively using host provided method to watch child directories
* that means if this is recursive watcher, watch the children directories as well
@@ -4411,6 +4450,8 @@ var ts;
else {
directoryWatcher = {
watcher: host.watchDirectory(dirName, function (fileName) {
+ if (isIgnoredPath(fileName))
+ return;
// Call the actual callback
callbackCache.forEach(function (callbacks, rootDirName) {
if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
@@ -4460,7 +4501,7 @@ var ts;
var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
// Filter our the symbolic link directories since those arent included in recursive watch
// which is same behaviour when recursive: true is passed to fs.watch
- return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
+ return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
}) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
return newChildWatches || ts.emptyArray;
/**
@@ -4477,6 +4518,16 @@ var ts;
(newChildWatches || (newChildWatches = [])).push(childWatcher);
}
}
+ function isIgnoredPath(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
+ }
+ function isInPath(path, searchPath) {
+ if (ts.stringContains(path, searchPath))
+ return true;
+ if (host.useCaseSensitiveFileNames)
+ return false;
+ return ts.stringContains(toCanonicalFilePath(path), searchPath);
+ }
}
ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher;
function getNodeMajorVersion() {
@@ -5842,6 +5893,7 @@ var ts;
Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."),
Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."),
+ Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."),
The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."),
Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."),
File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),
@@ -6109,6 +6161,16 @@ var ts;
Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."),
Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."),
Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."),
+ Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"),
+ Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
+ A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"),
+ A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"),
+ Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"),
+ Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"),
+ Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
+ Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."),
+ Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"),
+ Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"),
The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"),
The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."),
The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."),
@@ -6325,6 +6387,7 @@ var ts;
Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"),
+ Convert_to_named_parameters: diag(95075, ts.DiagnosticCategory.Message, "Convert_to_named_parameters_95075", "Convert to named parameters"),
};
})(ts || (ts = {}));
var ts;
@@ -6812,16 +6875,20 @@ var ts;
return pos;
}
var shebangTriviaRegex = /^#!.*/;
+ /*@internal*/
function isShebangTrivia(text, pos) {
// Shebangs check must only be done at the start of the file
ts.Debug.assert(pos === 0);
return shebangTriviaRegex.test(text);
}
+ ts.isShebangTrivia = isShebangTrivia;
+ /*@internal*/
function scanShebangTrivia(text, pos) {
var shebang = shebangTriviaRegex.exec(text)[0];
pos = pos + shebang.length;
return pos;
}
+ ts.scanShebangTrivia = scanShebangTrivia;
/**
* Invokes a callback for each comment range following the provided position.
*
@@ -8531,7 +8598,7 @@ var ts;
}
}
function getSourceFileOfNode(node) {
- while (node && node.kind !== 279 /* SourceFile */) {
+ while (node && node.kind !== 284 /* SourceFile */) {
node = node.parent;
}
return node;
@@ -8677,7 +8744,7 @@ var ts;
// the syntax list itself considers them as normal trivia. Therefore if we simply skip
// trivia for the list, we may have skipped the JSDocComment as well. So we should process its
// first child to determine the actual position of its first token.
- if (node.kind === 306 /* SyntaxList */ && node._children.length > 0) {
+ if (node.kind === 311 /* SyntaxList */ && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -8696,7 +8763,7 @@ var ts;
}
ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
function isJSDocTypeExpressionOrChild(node) {
- return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
+ return node.kind === 288 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
}
function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
if (includeTrivia === void 0) { includeTrivia = false; }
@@ -8823,7 +8890,7 @@ var ts;
return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body);
}
function isBlockScopedContainerTopLevel(node) {
- return node.kind === 279 /* SourceFile */ ||
+ return node.kind === 284 /* SourceFile */ ||
node.kind === 244 /* ModuleDeclaration */ ||
ts.isFunctionLike(node);
}
@@ -8841,7 +8908,7 @@ var ts;
// - defined in the top level scope and source file is an external module
// - defined inside ambient module declaration located in the top level scope and source file not an external module
switch (node.parent.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node.parent);
case 245 /* ModuleBlock */:
return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
@@ -8859,7 +8926,7 @@ var ts;
ts.isEffectiveExternalModule = isEffectiveExternalModule;
function isBlockScope(node, parentNode) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 274 /* CatchClause */:
case 244 /* ModuleDeclaration */:
@@ -8884,9 +8951,9 @@ var ts;
ts.isBlockScope = isBlockScope;
function isDeclarationWithTypeParameters(node) {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
- case 293 /* JSDocSignature */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 298 /* JSDocSignature */:
return true;
default:
ts.assertType(node);
@@ -8902,12 +8969,12 @@ var ts;
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 240 /* ClassDeclaration */:
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
@@ -9052,7 +9119,7 @@ var ts;
function getErrorSpanForNode(sourceFile, node) {
var errorNode = node;
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
if (pos_1 === sourceFile.text.length) {
// file is empty - return span for the beginning of the file
@@ -9227,7 +9294,7 @@ var ts;
return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
case 150 /* TypeParameter */:
return node === parent.constraint;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return node === parent.constraint;
case 154 /* PropertyDeclaration */:
case 153 /* PropertySignature */:
@@ -9487,7 +9554,7 @@ var ts;
}
ts.getContainingClass = getContainingClass;
function getThisContainer(node, includeArrowFunctions) {
- ts.Debug.assert(node.kind !== 279 /* SourceFile */);
+ ts.Debug.assert(node.kind !== 284 /* SourceFile */);
while (true) {
node = node.parent;
if (!node) {
@@ -9541,7 +9608,7 @@ var ts;
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 243 /* EnumDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return node;
}
}
@@ -10249,7 +10316,7 @@ var ts;
}
ts.isJSDocConstructSignature = isJSDocConstructSignature;
function isJSDocTypeAlias(node) {
- return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 309 /* JSDocTypedefTag */ || node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocTypeAlias = isJSDocTypeAlias;
function isTypeAlias(node) {
@@ -10393,7 +10460,7 @@ var ts;
ts.hasRestParameter = hasRestParameter;
function isRestParameter(node) {
var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
- return node.dotDotDotToken !== undefined || !!type && type.kind === 290 /* JSDocVariadicType */;
+ return node.dotDotDotToken !== undefined || !!type && type.kind === 295 /* JSDocVariadicType */;
}
ts.isRestParameter = isRestParameter;
var AssignmentKind;
@@ -10878,7 +10945,7 @@ var ts;
|| kind === 158 /* GetAccessor */
|| kind === 159 /* SetAccessor */
|| kind === 244 /* ModuleDeclaration */
- || kind === 279 /* SourceFile */;
+ || kind === 284 /* SourceFile */;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(range) {
@@ -10955,7 +11022,7 @@ var ts;
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return 0;
case 208 /* SpreadElement */:
return 1;
@@ -11273,6 +11340,9 @@ var ts;
lineStart = true;
}
}
+ function getTextPosWithWriteLine() {
+ return lineStart ? output.length : (output.length + newLine.length);
+ }
reset();
return {
write: write,
@@ -11301,7 +11371,8 @@ var ts;
writeStringLiteral: write,
writeSymbol: function (s, _) { return write(s); },
writeTrailingSemicolon: write,
- writeComment: write
+ writeComment: write,
+ getTextPosWithWriteLine: getTextPosWithWriteLine
};
}
ts.createTextWriter = createTextWriter;
@@ -11592,7 +11663,7 @@ var ts;
ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
/** template tags are only available when a typedef isn't already using them */
function isNonTypeAliasTemplate(tag) {
- return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
+ return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 296 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
}
/**
* Gets the effective type annotation of the value parameter of a set accessor. If the node
@@ -12564,19 +12635,29 @@ var ts;
|| kind === 96 /* NullKeyword */
|| kind === 132 /* NeverKeyword */
|| kind === 211 /* ExpressionWithTypeArguments */
- || kind === 284 /* JSDocAllType */
- || kind === 285 /* JSDocUnknownType */
- || kind === 286 /* JSDocNullableType */
- || kind === 287 /* JSDocNonNullableType */
- || kind === 288 /* JSDocOptionalType */
- || kind === 289 /* JSDocFunctionType */
- || kind === 290 /* JSDocVariadicType */;
+ || kind === 289 /* JSDocAllType */
+ || kind === 290 /* JSDocUnknownType */
+ || kind === 291 /* JSDocNullableType */
+ || kind === 292 /* JSDocNonNullableType */
+ || kind === 293 /* JSDocOptionalType */
+ || kind === 294 /* JSDocFunctionType */
+ || kind === 295 /* JSDocVariadicType */;
}
ts.isTypeNodeKind = isTypeNodeKind;
function isAccessExpression(node) {
return node.kind === 189 /* PropertyAccessExpression */ || node.kind === 190 /* ElementAccessExpression */;
}
ts.isAccessExpression = isAccessExpression;
+ function isBundleFileTextLike(section) {
+ switch (section.kind) {
+ case "text" /* Text */:
+ case "internal" /* Internal */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isBundleFileTextLike = isBundleFileTextLike;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
@@ -13038,8 +13119,8 @@ var ts;
switch (declaration.kind) {
case 72 /* Identifier */:
return declaration;
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */: {
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */: {
var name = declaration.name;
if (name.kind === 148 /* QualifiedName */) {
return name.right;
@@ -13063,7 +13144,7 @@ var ts;
return undefined;
}
}
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return getNameOfJSDocTypedef(declaration);
case 254 /* ExportAssignment */: {
var expression = declaration.expression;
@@ -13267,7 +13348,7 @@ var ts;
return ts.emptyArray;
}
if (ts.isJSDocTypeAlias(node)) {
- ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */);
+ ts.Debug.assert(node.parent.kind === 296 /* JSDocComment */);
return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
}
if (node.typeParameters) {
@@ -13539,7 +13620,7 @@ var ts;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 308 /* PartiallyEmittedExpression */) {
+ while (node.kind === 313 /* PartiallyEmittedExpression */) {
node = node.expression;
}
return node;
@@ -13886,108 +13967,128 @@ var ts;
ts.isEnumMember = isEnumMember;
// Top-level nodes
function isSourceFile(node) {
- return node.kind === 279 /* SourceFile */;
+ return node.kind === 284 /* SourceFile */;
}
ts.isSourceFile = isSourceFile;
function isBundle(node) {
- return node.kind === 280 /* Bundle */;
+ return node.kind === 285 /* Bundle */;
}
ts.isBundle = isBundle;
function isUnparsedSource(node) {
- return node.kind === 281 /* UnparsedSource */;
+ return node.kind === 286 /* UnparsedSource */;
}
ts.isUnparsedSource = isUnparsedSource;
+ function isUnparsedPrepend(node) {
+ return node.kind === 280 /* UnparsedPrepend */;
+ }
+ ts.isUnparsedPrepend = isUnparsedPrepend;
+ function isUnparsedTextLike(node) {
+ switch (node.kind) {
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isUnparsedTextLike = isUnparsedTextLike;
+ function isUnparsedNode(node) {
+ return isUnparsedTextLike(node) ||
+ node.kind === 279 /* UnparsedPrologue */ ||
+ node.kind === 283 /* UnparsedSyntheticReference */;
+ }
+ ts.isUnparsedNode = isUnparsedNode;
// JSDoc
function isJSDocTypeExpression(node) {
- return node.kind === 283 /* JSDocTypeExpression */;
+ return node.kind === 288 /* JSDocTypeExpression */;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 284 /* JSDocAllType */;
+ return node.kind === 289 /* JSDocAllType */;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 285 /* JSDocUnknownType */;
+ return node.kind === 290 /* JSDocUnknownType */;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 286 /* JSDocNullableType */;
+ return node.kind === 291 /* JSDocNullableType */;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 287 /* JSDocNonNullableType */;
+ return node.kind === 292 /* JSDocNonNullableType */;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 288 /* JSDocOptionalType */;
+ return node.kind === 293 /* JSDocOptionalType */;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 289 /* JSDocFunctionType */;
+ return node.kind === 294 /* JSDocFunctionType */;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 290 /* JSDocVariadicType */;
+ return node.kind === 295 /* JSDocVariadicType */;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 291 /* JSDocComment */;
+ return node.kind === 296 /* JSDocComment */;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 295 /* JSDocAugmentsTag */;
+ return node.kind === 300 /* JSDocAugmentsTag */;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 296 /* JSDocClassTag */;
+ return node.kind === 301 /* JSDocClassTag */;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocEnumTag(node) {
- return node.kind === 298 /* JSDocEnumTag */;
+ return node.kind === 303 /* JSDocEnumTag */;
}
ts.isJSDocEnumTag = isJSDocEnumTag;
function isJSDocThisTag(node) {
- return node.kind === 301 /* JSDocThisTag */;
+ return node.kind === 306 /* JSDocThisTag */;
}
ts.isJSDocThisTag = isJSDocThisTag;
function isJSDocParameterTag(node) {
- return node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 300 /* JSDocReturnTag */;
+ return node.kind === 305 /* JSDocReturnTag */;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 302 /* JSDocTypeTag */;
+ return node.kind === 307 /* JSDocTypeTag */;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 303 /* JSDocTemplateTag */;
+ return node.kind === 308 /* JSDocTemplateTag */;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 304 /* JSDocTypedefTag */;
+ return node.kind === 309 /* JSDocTypedefTag */;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */;
+ return node.kind === 310 /* JSDocPropertyTag */;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 310 /* JSDocPropertyTag */ || node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 292 /* JSDocTypeLiteral */;
+ return node.kind === 297 /* JSDocTypeLiteral */;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
function isJSDocCallbackTag(node) {
- return node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocCallbackTag = isJSDocCallbackTag;
function isJSDocSignature(node) {
- return node.kind === 293 /* JSDocSignature */;
+ return node.kind === 298 /* JSDocSignature */;
}
ts.isJSDocSignature = isJSDocSignature;
})(ts || (ts = {}));
@@ -13998,7 +14099,7 @@ var ts;
(function (ts) {
/* @internal */
function isSyntaxList(n) {
- return n.kind === 306 /* SyntaxList */;
+ return n.kind === 311 /* SyntaxList */;
}
ts.isSyntaxList = isSyntaxList;
/* @internal */
@@ -14150,11 +14251,11 @@ var ts;
switch (kind) {
case 155 /* MethodSignature */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 166 /* ConstructorType */:
return true;
default:
@@ -14445,8 +14546,8 @@ var ts;
case 208 /* SpreadElement */:
case 212 /* AsExpression */:
case 210 /* OmittedExpression */:
- case 309 /* CommaListExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 314 /* CommaListExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -14460,12 +14561,12 @@ var ts;
ts.isAssertionExpression = isAssertionExpression;
/* @internal */
function isPartiallyEmittedExpression(node) {
- return node.kind === 308 /* PartiallyEmittedExpression */;
+ return node.kind === 313 /* PartiallyEmittedExpression */;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
/* @internal */
function isNotEmittedStatement(node) {
- return node.kind === 307 /* NotEmittedStatement */;
+ return node.kind === 312 /* NotEmittedStatement */;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
/* @internal */
@@ -14576,9 +14677,9 @@ var ts;
|| kind === 242 /* TypeAliasDeclaration */
|| kind === 150 /* TypeParameter */
|| kind === 237 /* VariableDeclaration */
- || kind === 304 /* JSDocTypedefTag */
- || kind === 297 /* JSDocCallbackTag */
- || kind === 305 /* JSDocPropertyTag */;
+ || kind === 309 /* JSDocTypedefTag */
+ || kind === 302 /* JSDocCallbackTag */
+ || kind === 310 /* JSDocPropertyTag */;
}
function isDeclarationStatementKind(kind) {
return kind === 239 /* FunctionDeclaration */
@@ -14613,14 +14714,14 @@ var ts;
|| kind === 219 /* VariableStatement */
|| kind === 224 /* WhileStatement */
|| kind === 231 /* WithStatement */
- || kind === 307 /* NotEmittedStatement */
- || kind === 311 /* EndOfDeclarationMarker */
- || kind === 310 /* MergeDeclarationMarker */;
+ || kind === 312 /* NotEmittedStatement */
+ || kind === 316 /* EndOfDeclarationMarker */
+ || kind === 315 /* MergeDeclarationMarker */;
}
/* @internal */
function isDeclaration(node) {
if (node.kind === 150 /* TypeParameter */) {
- return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node);
+ return (node.parent && node.parent.kind !== 308 /* JSDocTemplateTag */) || ts.isInJSFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -14715,18 +14816,18 @@ var ts;
/** True if node is of some JSDoc syntax kind. */
/* @internal */
function isJSDocNode(node) {
- return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */;
+ return node.kind >= 288 /* FirstJSDocNode */ && node.kind <= 310 /* LastJSDocNode */;
}
ts.isJSDocNode = isJSDocNode;
/** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node) {
- return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
+ return node.kind === 296 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
}
ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
// TODO: determine what this does before making it public.
/* @internal */
function isJSDocTag(node) {
- return node.kind >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */;
+ return node.kind >= 299 /* FirstJSDocTagNode */ && node.kind <= 310 /* LastJSDocTagNode */;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -15043,6 +15144,10 @@ var ts;
return !!(compilerOptions.declaration || compilerOptions.composite);
}
ts.getEmitDeclarations = getEmitDeclarations;
+ function isIncrementalCompilation(options) {
+ return !!(options.incremental || options.composite);
+ }
+ ts.isIncrementalCompilation = isIncrementalCompilation;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
}
@@ -16327,7 +16432,7 @@ var ts;
var SourceFileConstructor;
// tslint:enable variable-name
function createNode(kind, pos, end) {
- if (kind === 279 /* SourceFile */) {
+ if (kind === 284 /* SourceFile */) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 72 /* Identifier */) {
@@ -16578,7 +16683,7 @@ var ts;
case 218 /* Block */:
case 245 /* ModuleBlock */:
return visitNodes(cbNode, cbNodes, node.statements);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return visitNodes(cbNode, cbNodes, node.statements) ||
visitNode(cbNode, node.endOfFileToken);
case 219 /* VariableStatement */:
@@ -16727,7 +16832,7 @@ var ts;
return visitNode(cbNode, node.expression);
case 258 /* MissingDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return visitNodes(cbNode, cbNodes, node.elements);
case 260 /* JsxElement */:
return visitNode(cbNode, node.openingElement) ||
@@ -16756,60 +16861,60 @@ var ts;
return visitNode(cbNode, node.tagName);
case 171 /* OptionalType */:
case 172 /* RestType */:
- case 283 /* JSDocTypeExpression */:
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 288 /* JSDocOptionalType */:
- case 290 /* JSDocVariadicType */:
+ case 288 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 293 /* JSDocOptionalType */:
+ case 295 /* JSDocVariadicType */:
return visitNode(cbNode, node.type);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return visitNodes(cbNode, cbNodes, node.tags);
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return visitNode(cbNode, node.tagName) ||
(node.isNameFirst
? visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression)
: visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name));
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.constraint) ||
visitNodes(cbNode, cbNodes, node.typeParameters);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return visitNode(cbNode, node.tagName) ||
(node.typeExpression &&
- node.typeExpression.kind === 283 /* JSDocTypeExpression */
+ node.typeExpression.kind === 288 /* JSDocTypeExpression */
? visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName)
: visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression));
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.typeExpression);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return ts.forEach(node.jsDocPropertyTags, cbNode);
- case 294 /* JSDocTag */:
- case 296 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
return visitNode(cbNode, node.tagName);
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
}
@@ -17183,7 +17288,7 @@ var ts;
function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
// code from createNode is inlined here so createNode won't have to deal with special case of creating source files
// this is quite rare comparing to other nodes and createNode should be as fast as possible
- var sourceFile = new SourceFileConstructor(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
+ var sourceFile = new SourceFileConstructor(284 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
@@ -18383,9 +18488,9 @@ var ts;
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(284 /* JSDocAllType */);
+ var result = createNode(289 /* JSDocAllType */);
if (postFixEquals) {
- return createPostfixType(288 /* JSDocOptionalType */, result);
+ return createPostfixType(293 /* JSDocOptionalType */, result);
}
else {
nextToken();
@@ -18393,7 +18498,7 @@ var ts;
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(287 /* JSDocNonNullableType */);
+ var result = createNode(292 /* JSDocNonNullableType */);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -18417,18 +18522,18 @@ var ts;
token() === 30 /* GreaterThanToken */ ||
token() === 59 /* EqualsToken */ ||
token() === 50 /* BarToken */) {
- var result = createNode(285 /* JSDocUnknownType */, pos);
+ var result = createNode(290 /* JSDocUnknownType */, pos);
return finishNode(result);
}
else {
- var result = createNode(286 /* JSDocNullableType */, pos);
+ var result = createNode(291 /* JSDocNullableType */, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(289 /* JSDocFunctionType */);
+ var result = createNodeWithJSDoc(294 /* JSDocFunctionType */);
nextToken();
fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
return finishNode(result);
@@ -18452,12 +18557,12 @@ var ts;
var type = parseTypeOrTypePredicate();
scanner.setInJSDocType(false);
if (dotdotdot) {
- var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos);
+ var variadic = createNode(295 /* JSDocVariadicType */, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 59 /* EqualsToken */) {
- return createPostfixType(288 /* JSDocOptionalType */, type);
+ return createPostfixType(293 /* JSDocOptionalType */, type);
}
return type;
}
@@ -18829,7 +18934,7 @@ var ts;
return finishNode(node);
}
var type = parseType();
- if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) {
+ if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 291 /* JSDocNullableType */ && type.pos === type.type.pos) {
type.kind = 171 /* OptionalType */;
}
return type;
@@ -19016,14 +19121,14 @@ var ts;
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 52 /* ExclamationToken */:
- type = createPostfixType(287 /* JSDocNonNullableType */, type);
+ type = createPostfixType(292 /* JSDocNonNullableType */, type);
break;
case 56 /* QuestionToken */:
// If not in JSDoc and next token is start of a type we have a conditional type
if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
return type;
}
- type = createPostfixType(286 /* JSDocNullableType */, type);
+ type = createPostfixType(291 /* JSDocNullableType */, type);
break;
case 22 /* OpenBracketToken */:
parseExpected(22 /* OpenBracketToken */);
@@ -21960,7 +22065,7 @@ var ts;
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
// Parses out a JSDoc type expression.
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(283 /* JSDocTypeExpression */);
+ var result = createNode(288 /* JSDocTypeExpression */);
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -22123,7 +22228,7 @@ var ts;
}
}
function createJSDocComment() {
- var result = createNode(291 /* JSDocComment */, start);
+ var result = createNode(296 /* JSDocComment */, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
@@ -22290,7 +22395,7 @@ var ts;
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(start, tagName) {
- var result = createNode(294 /* JSDocTag */, start);
+ var result = createNode(299 /* JSDocTag */, start);
result.tagName = tagName;
return finishNode(result);
}
@@ -22349,8 +22454,8 @@ var ts;
typeExpression = tryParseTypeExpression();
}
var result = target === 1 /* Property */ ?
- createNode(305 /* JSDocPropertyTag */, start) :
- createNode(299 /* JSDocParameterTag */, start);
+ createNode(310 /* JSDocPropertyTag */, start) :
+ createNode(304 /* JSDocParameterTag */, start);
var comment = parseTagComments(indent + scanner.getStartPos() - start);
var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
if (nestedTypeLiteral) {
@@ -22367,18 +22472,18 @@ var ts;
}
function parseNestedTypeLiteral(typeExpression, name, target, indent) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(288 /* JSDocTypeExpression */, scanner.getTokenPos());
var child = void 0;
var jsdocTypeLiteral = void 0;
var start_2 = scanner.getStartPos();
var children = void 0;
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
- if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) {
+ if (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 169 /* ArrayType */) {
jsdocTypeLiteral.isArrayType = true;
@@ -22389,25 +22494,25 @@ var ts;
}
}
function parseReturnTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 305 /* JSDocReturnTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(300 /* JSDocReturnTag */, start);
+ var result = createNode(305 /* JSDocReturnTag */, start);
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 307 /* JSDocTypeTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(302 /* JSDocTypeTag */, start);
+ var result = createNode(307 /* JSDocTypeTag */, start);
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
return finishNode(result);
}
function parseAugmentsTag(start, tagName) {
- var result = createNode(295 /* JSDocAugmentsTag */, start);
+ var result = createNode(300 /* JSDocAugmentsTag */, start);
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
return finishNode(result);
@@ -22434,19 +22539,19 @@ var ts;
return node;
}
function parseClassTag(start, tagName) {
- var tag = createNode(296 /* JSDocClassTag */, start);
+ var tag = createNode(301 /* JSDocClassTag */, start);
tag.tagName = tagName;
return finishNode(tag);
}
function parseThisTag(start, tagName) {
- var tag = createNode(301 /* JSDocThisTag */, start);
+ var tag = createNode(306 /* JSDocThisTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
return finishNode(tag);
}
function parseEnumTag(start, tagName) {
- var tag = createNode(298 /* JSDocEnumTag */, start);
+ var tag = createNode(303 /* JSDocEnumTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
@@ -22455,7 +22560,7 @@ var ts;
function parseTypedefTag(start, tagName, indent) {
var typeExpression = tryParseTypeExpression();
skipWhitespaceOrAsterisk();
- var typedefTag = createNode(304 /* JSDocTypedefTag */, start);
+ var typedefTag = createNode(309 /* JSDocTypedefTag */, start);
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace();
typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
@@ -22469,9 +22574,9 @@ var ts;
var childTypeTag = void 0;
while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start);
}
- if (child.kind === 302 /* JSDocTypeTag */) {
+ if (child.kind === 307 /* JSDocTypeTag */) {
if (childTypeTag) {
break;
}
@@ -22517,14 +22622,14 @@ var ts;
return typeNameOrNamespaceName;
}
function parseCallbackTag(start, tagName, indent) {
- var callbackTag = createNode(297 /* JSDocCallbackTag */, start);
+ var callbackTag = createNode(302 /* JSDocCallbackTag */, start);
callbackTag.tagName = tagName;
callbackTag.fullName = parseJSDocTypeNameWithNamespace();
callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
skipWhitespace();
callbackTag.comment = parseTagComments(indent);
var child;
- var jsdocSignature = createNode(293 /* JSDocSignature */, start);
+ var jsdocSignature = createNode(298 /* JSDocSignature */, start);
jsdocSignature.parameters = [];
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
@@ -22532,7 +22637,7 @@ var ts;
var returnTag = tryParse(function () {
if (parseOptionalJsdoc(58 /* AtToken */)) {
var tag = parseTag(indent);
- if (tag && tag.kind === 300 /* JSDocReturnTag */) {
+ if (tag && tag.kind === 305 /* JSDocReturnTag */) {
return tag;
}
}
@@ -22577,7 +22682,7 @@ var ts;
case 58 /* AtToken */:
if (canParseTag) {
var child = tryParseChildTag(target, indent);
- if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) &&
+ if (child && (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) &&
target !== 4 /* CallbackParameter */ &&
name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
@@ -22647,7 +22752,7 @@ var ts;
skipWhitespace();
typeParameters.push(typeParameter);
} while (parseOptionalJsdoc(27 /* CommaToken */));
- var result = createNode(303 /* JSDocTemplateTag */, start);
+ var result = createNode(308 /* JSDocTemplateTag */, start);
result.tagName = tagName;
result.constraint = constraint;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -23733,6 +23838,22 @@ var ts;
category: ts.Diagnostics.Basic_Options,
description: ts.Diagnostics.Enable_project_compilation,
},
+ {
+ name: "incremental",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_incremental_compilation,
+ },
+ {
+ name: "tsBuildInfoFile",
+ type: "string",
+ isFilePath: true,
+ paramType: ts.Diagnostics.FILE,
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
+ },
{
name: "removeComments",
type: "boolean",
@@ -27451,7 +27572,7 @@ var ts;
return "__constructor" /* Constructor */;
case 165 /* FunctionType */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return "__call" /* Call */;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
@@ -27460,7 +27581,7 @@ var ts;
return "__index" /* Index */;
case 255 /* ExportDeclaration */:
return "__export" /* ExportStar */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// json file should behave as
// module.exports = ...
return "export=" /* ExportEquals */;
@@ -27471,12 +27592,12 @@ var ts;
}
ts.Debug.fail("Unknown binary declaration kind");
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
case 151 /* Parameter */:
// Parameters with names are handled at the top of this function. Parameters
// without names can only come from JSDocFunctionTypes.
- ts.Debug.assert(node.parent.kind === 289 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
+ ts.Debug.assert(node.parent.kind === 294 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
var functionType = node.parent;
var index = functionType.parameters.indexOf(node);
return "arg" + index;
@@ -27715,7 +27836,7 @@ var ts;
if (hasExplicitReturn)
node.flags |= 256 /* HasExplicitReturn */;
}
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
node.flags |= emitFlags;
}
if (currentReturnTarget) {
@@ -27859,12 +27980,12 @@ var ts;
case 191 /* CallExpression */:
bindCallExpressionFlow(node);
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
bindJSDocTypeAlias(node);
break;
// In source files and blocks, bind functions first to match hoisting that occurs at runtime
- case 279 /* SourceFile */: {
+ case 284 /* SourceFile */: {
bindEachFunctionsFirst(node.statements);
bind(node.endOfFileToken);
break;
@@ -28551,7 +28672,7 @@ var ts;
case 243 /* EnumDeclaration */:
case 188 /* ObjectLiteralExpression */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 268 /* JsxAttributes */:
return 1 /* IsContainer */;
case 241 /* InterfaceDeclaration */:
@@ -28560,7 +28681,7 @@ var ts;
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
return 1 /* IsContainer */ | 32 /* HasLocals */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
case 156 /* MethodDeclaration */:
if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
@@ -28573,8 +28694,8 @@ var ts;
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
- case 289 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
case 165 /* FunctionType */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
@@ -28628,7 +28749,7 @@ var ts;
// handlers to take care of declaring these child members.
case 244 /* ModuleDeclaration */:
return declareModuleMember(node, symbolFlags, symbolExcludes);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return declareSourceFileMember(node, symbolFlags, symbolExcludes);
case 209 /* ClassExpression */:
case 240 /* ClassDeclaration */:
@@ -28636,7 +28757,7 @@ var ts;
case 243 /* EnumDeclaration */:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 188 /* ObjectLiteralExpression */:
case 241 /* InterfaceDeclaration */:
case 268 /* JsxAttributes */:
@@ -28650,7 +28771,7 @@ var ts;
case 166 /* ConstructorType */:
case 160 /* CallSignature */:
case 161 /* ConstructSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 162 /* IndexSignature */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
@@ -28660,9 +28781,9 @@ var ts;
case 239 /* FunctionDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
- case 289 /* JSDocFunctionType */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 294 /* JSDocFunctionType */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
// All the children of these container types are never visible through another
@@ -28685,8 +28806,8 @@ var ts;
: declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
function hasExportDeclarations(node) {
- var body = node.kind === 279 /* SourceFile */ ? node : node.body;
- if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
+ var body = node.kind === 284 /* SourceFile */ ? node : node.body;
+ if (body && (body.kind === 284 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
var stat = _a[_i];
if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) {
@@ -28820,7 +28941,7 @@ var ts;
case 244 /* ModuleDeclaration */:
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalOrCommonJsModule(container)) {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
@@ -28958,7 +29079,7 @@ var ts;
function checkStrictModeFunctionDeclaration(node) {
if (languageVersion < 2 /* ES2015 */) {
// Report error if function is not top level function declaration
- if (blockScopeContainer.kind !== 279 /* SourceFile */ &&
+ if (blockScopeContainer.kind !== 284 /* SourceFile */ &&
blockScopeContainer.kind !== 244 /* ModuleDeclaration */ &&
!ts.isFunctionLike(blockScopeContainer)) {
// We check first if the name is inside class declaration or class expression; if so give explicit message
@@ -29233,12 +29354,12 @@ var ts;
case 159 /* SetAccessor */:
return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */);
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
case 166 /* ConstructorType */:
return bindFunctionOrConstructorType(node);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 181 /* MappedType */:
return bindAnonymousTypeWorker(node);
case 188 /* ObjectLiteralExpression */:
@@ -29297,7 +29418,7 @@ var ts;
return bindExportDeclaration(node);
case 254 /* ExportAssignment */:
return bindExportAssignment(node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
updateStrictModeStatementList(node.statements);
return bindSourceFileIfExternalModule();
case 218 /* Block */:
@@ -29307,22 +29428,22 @@ var ts;
// falls through
case 245 /* ModuleBlock */:
return updateStrictModeStatementList(node.statements);
- case 299 /* JSDocParameterTag */:
- if (node.parent.kind === 293 /* JSDocSignature */) {
+ case 304 /* JSDocParameterTag */:
+ if (node.parent.kind === 298 /* JSDocSignature */) {
return bindParameter(node);
}
- if (node.parent.kind !== 292 /* JSDocTypeLiteral */) {
+ if (node.parent.kind !== 297 /* JSDocTypeLiteral */) {
break;
}
// falls through
- case 305 /* JSDocPropertyTag */:
+ case 310 /* JSDocPropertyTag */:
var propTag = node;
- var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ?
+ var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 293 /* JSDocOptionalType */ ?
4 /* Property */ | 16777216 /* Optional */ :
4 /* Property */;
return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
}
}
@@ -29494,7 +29615,7 @@ var ts;
var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
if (thisContainer.commonJsModuleIndicator) {
declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
@@ -29511,7 +29632,7 @@ var ts;
if (node.expression.kind === 100 /* ThisKeyword */) {
bindThisPropertyAssignment(node);
}
- else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) {
+ else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 284 /* SourceFile */) {
if (ts.isPrototypeAccess(node.expression)) {
bindPrototypePropertyAssignment(node, node.parent);
}
@@ -29548,7 +29669,7 @@ var ts;
}
function bindObjectDefinePropertyAssignment(node) {
var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
- var isToplevel = node.parent.parent.kind === 279 /* SourceFile */;
+ var isToplevel = node.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false);
bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
}
@@ -29615,8 +29736,8 @@ var ts;
function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) {
var namespaceSymbol = lookupSymbolForPropertyAccess(name);
var isToplevel = ts.isBinaryExpression(propertyAccess.parent)
- ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */
- : propertyAccess.parent.parent.kind === 279 /* SourceFile */;
+ ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 284 /* SourceFile */
+ : propertyAccess.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty);
bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
}
@@ -29754,7 +29875,7 @@ var ts;
}
}
function bindParameter(node) {
- if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) {
+ if (node.kind === 304 /* JSDocParameterTag */ && container.kind !== 298 /* JSDocSignature */) {
return;
}
if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) {
@@ -30497,7 +30618,7 @@ var ts;
break;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
// These nodes are TypeScript syntax.
transformFlags |= 3 /* AssertTypeScript */;
excludeFlags = 536872257 /* OuterExpressionExcludes */;
@@ -30698,7 +30819,7 @@ var ts;
transformFlags |= 192 /* AssertES2015 */;
}
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) {
transformFlags |= 192 /* AssertES2015 */;
}
@@ -30778,7 +30899,7 @@ var ts;
return 637666625 /* BindingPatternExcludes */;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
case 195 /* ParenthesizedExpression */:
case 98 /* SuperKeyword */:
return 536872257 /* OuterExpressionExcludes */;
@@ -31189,10 +31310,10 @@ var ts;
isContextSensitive: isContextSensitive,
getFullyQualifiedName: getFullyQualifiedName,
getResolvedSignature: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 0 /* Normal */);
},
getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16 /* IsForSignatureHelp */);
},
getConstantValue: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
@@ -31319,10 +31440,10 @@ var ts;
},
getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
};
- function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) {
+ function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
apparentArgumentCount = argumentCount;
- var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined;
+ var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
apparentArgumentCount = undefined;
return res;
}
@@ -31597,9 +31718,11 @@ var ts;
var CheckMode;
(function (CheckMode) {
CheckMode[CheckMode["Normal"] = 0] = "Normal";
- CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive";
+ CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
- CheckMode[CheckMode["Contextual"] = 3] = "Contextual";
+ CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
+ CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
+ CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
})(CheckMode || (CheckMode = {}));
var CallbackCheck;
(function (CallbackCheck) {
@@ -31955,7 +32078,7 @@ var ts;
return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 });
}
function isGlobalSourceFile(node) {
- return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
+ return node.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
}
function getSymbol(symbols, name, meaning) {
if (meaning) {
@@ -32129,7 +32252,7 @@ var ts;
// - parameters are only in the scope of function body
// This restriction does not apply to JSDoc comment types because they are parented
// at a higher level than type parameters would normally be
- if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) {
+ if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 296 /* JSDocComment */) {
useResult = result.flags & 262144 /* TypeParameter */
// type parameters are visible in parameter list, return type and type parameter list
? lastLocation === location.type ||
@@ -32171,14 +32294,14 @@ var ts;
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
isInExternalModule = true;
// falls through
case 244 /* ModuleDeclaration */:
var moduleExports = getSymbolOfNode(location).exports;
- if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) {
+ if (location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location)) {
// It's an external module. First see if the module has an export default and if the local
// name of that export default matches.
if (result = moduleExports.get("default" /* Default */)) {
@@ -32350,8 +32473,8 @@ var ts;
location = location.parent;
}
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
// js type aliases do not resolve names from their host, so skip past it
location = ts.getJSDocHost(location);
break;
@@ -32370,7 +32493,7 @@ var ts;
}
if (!result) {
if (lastLocation) {
- ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */);
+ ts.Debug.assert(lastLocation.kind === 284 /* SourceFile */);
if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
return lastLocation.symbol;
}
@@ -33226,7 +33349,7 @@ var ts;
function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) {
var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
if (!dontResolveAlias && symbol) {
- if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) {
+ if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 284 /* SourceFile */)) {
var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
? "allowSyntheticDefaultImports"
: "esModuleInterop";
@@ -33577,7 +33700,7 @@ var ts;
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
@@ -33817,10 +33940,10 @@ var ts;
return node && getSymbolOfNode(node);
}
function hasExternalModuleSymbol(declaration) {
- return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isAmbientModule(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
- return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
var aliasesToMakeVisible;
@@ -34277,7 +34400,7 @@ var ts;
var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
(symbol.parent || // is exported function symbol
ts.forEach(symbol.declarations, function (declaration) {
- return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
+ return declaration.parent.kind === 284 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
}));
if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
// typeof is allowed only for static/non local functions
@@ -34643,7 +34766,7 @@ var ts;
var savedContextFlags = context.flags;
context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
- type.symbol.declarations[0] &&
+ type.symbol.declarations && type.symbol.declarations[0] &&
ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
typeParameterShadowsNameInScope(type, context);
var name = shouldUseGeneratedName
@@ -34662,7 +34785,7 @@ var ts;
function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */);
if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) {
- parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */);
+ parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 304 /* JSDocParameterTag */);
}
var parameterType = getTypeOfSymbol(parameterSymbol);
if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
@@ -34820,7 +34943,7 @@ var ts;
return top;
}
function getSpecifierForModuleSymbol(symbol, context) {
- var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */);
+ var file = ts.getDeclarationOfKind(symbol, 284 /* SourceFile */);
if (file && file.moduleName !== undefined) {
// Use the amd name if it is available
return file.moduleName;
@@ -35073,7 +35196,7 @@ var ts;
ts.isExternalModuleAugmentation(node.parent.parent);
}
function isDefaultBindingContext(location) {
- return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location);
+ return location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location);
}
function getNameOfSymbolFromNameType(symbol, context) {
var nameType = symbol.nameType;
@@ -35150,8 +35273,8 @@ var ts;
return false;
function determineIfDeclarationIsVisible() {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
// Top-level jsdoc type aliases are considered exported
// First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file
return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
@@ -35178,7 +35301,7 @@ var ts;
var parent = getDeclarationContainer(node);
// If the node is not exported or it is not ambient module element (except import declaration)
if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
- !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
+ !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 284 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
return isGlobalSourceFile(parent);
}
// Exported members/ambient module elements (exception import declaration) are visible if parent is visible
@@ -35220,7 +35343,7 @@ var ts;
// Type parameters are always visible
case 150 /* TypeParameter */:
// Source file and namespace export are always visible
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 247 /* NamespaceExportDeclaration */:
return true;
// Export assignments do not create name bindings outside the module
@@ -36330,15 +36453,15 @@ var ts;
case 155 /* MethodSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 308 /* JSDocTemplateTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 181 /* MappedType */:
case 175 /* ConditionalType */:
var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
@@ -38330,10 +38453,10 @@ var ts;
function isJSDocOptionalParameter(node) {
return ts.isInJSFile(node) && (
// node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
- node.type && node.type.kind === 288 /* JSDocOptionalType */
+ node.type && node.type.kind === 293 /* JSDocOptionalType */
|| ts.getJSDocParameterTags(node).some(function (_a) {
var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}));
}
function tryFindAmbientModule(moduleName, withAugmentations) {
@@ -38367,7 +38490,7 @@ var ts;
return false;
}
var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}
function createIdentifierTypePredicate(parameterName, parameterIndex, type) {
return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
@@ -38698,8 +38821,21 @@ var ts;
}
return undefined;
}
- function getSignatureInstantiation(signature, typeArguments, isJavascript) {
- return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ if (inferredTypeParameters) {
+ var returnSignature = getSingleCallSignature(getReturnTypeOfSignature(instantiatedSignature));
+ if (returnSignature) {
+ var newReturnSignature = cloneSignature(returnSignature);
+ newReturnSignature.typeParameters = inferredTypeParameters;
+ newReturnSignature.target = returnSignature.target;
+ newReturnSignature.mapper = returnSignature.mapper;
+ var newInstantiatedSignature = cloneSignature(instantiatedSignature);
+ newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
+ return newInstantiatedSignature;
+ }
+ }
+ return instantiatedSignature;
}
function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
@@ -39071,7 +39207,7 @@ var ts;
}
function getTypeReferenceTypeWorker(node, symbol, typeArguments) {
if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
- if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
+ if (symbol.valueDeclaration && symbol.valueDeclaration.parent && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
var jsdocType = getJSDocTypeReference(node, symbol, typeArguments);
if (jsdocType) {
return jsdocType;
@@ -39107,7 +39243,7 @@ var ts;
}
function getConstrainedTypeVariable(typeVariable, node) {
var constraints;
- while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) {
+ while (node && !ts.isStatement(node) && node.kind !== 296 /* JSDocComment */) {
var parent = node.parent;
if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) {
var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType);
@@ -40680,8 +40816,8 @@ var ts;
function getTypeFromTypeNode(node) {
switch (node.kind) {
case 120 /* AnyKeyword */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return anyType;
case 143 /* UnknownKeyword */:
return unknownType;
@@ -40728,23 +40864,23 @@ var ts;
return getTypeFromUnionTypeNode(node);
case 174 /* IntersectionType */:
return getTypeFromIntersectionTypeNode(node);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return getTypeFromJSDocNullableTypeNode(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return addOptionality(getTypeFromTypeNode(node.type));
case 177 /* ParenthesizedType */:
case 172 /* RestType */:
- case 287 /* JSDocNonNullableType */:
- case 283 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 288 /* JSDocTypeExpression */:
return getTypeFromTypeNode(node.type);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return getTypeFromJSDocVariadicType(node);
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 297 /* JSDocTypeLiteral */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
case 179 /* TypeOperator */:
return getTypeFromTypeOperatorNode(node);
@@ -41682,7 +41818,7 @@ var ts;
return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation);
}
// recreate a tuple from the elements, if possible
- var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true);
+ var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
if (isTupleLikeType(tupleizedType)) {
return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation);
}
@@ -44105,7 +44241,7 @@ var ts;
return;
}
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
return;
case 239 /* FunctionDeclaration */:
@@ -46386,7 +46522,7 @@ var ts;
return ts.findAncestor(node.parent, function (node) {
return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
node.kind === 245 /* ModuleBlock */ ||
- node.kind === 279 /* SourceFile */ ||
+ node.kind === 284 /* SourceFile */ ||
node.kind === 154 /* PropertyDeclaration */;
});
}
@@ -46507,7 +46643,7 @@ var ts;
// to the constructor in the initializer, we will need to substitute that
// binding with an alias as the class name is not in scope.
var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
- while (container.kind !== 279 /* SourceFile */) {
+ while (container.kind !== 284 /* SourceFile */) {
if (container.parent === declaration) {
if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
@@ -46930,7 +47066,7 @@ var ts;
}
function getTypeForThisExpressionFromJSDoc(node) {
var jsdocType = ts.getJSDocType(node);
- if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) {
+ if (jsdocType && jsdocType.kind === 294 /* JSDocFunctionType */) {
var jsDocFunctionType = jsdocType;
if (jsDocFunctionType.parameters.length > 0 &&
jsDocFunctionType.parameters[0].name &&
@@ -49532,23 +49668,34 @@ var ts;
// Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) {
var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
- var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature;
+ // We clone the contextualMapper to avoid fixing. For example, when the source signature is (x: T) => T[] and
+ // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
+ // for T but leave it possible to later infer '[any]' back to A.
+ var restType = getEffectiveRestType(contextualSignature);
+ var mapper = contextualMapper && restType && restType.flags & 262144 /* TypeParameter */ ? cloneTypeMapper(contextualMapper) : contextualMapper;
+ var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
forEachMatchingParameterType(sourceSignature, signature, function (source, target) {
// Type parameters from outer context referenced by source type are fixed by instantiation of the source type
inferTypes(context.inferences, source, target);
});
if (!contextualMapper) {
inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */);
+ var signaturePredicate = getTypePredicateOfSignature(signature);
+ var contextualPredicate = getTypePredicateOfSignature(sourceSignature);
+ if (signaturePredicate && contextualPredicate && signaturePredicate.kind === contextualPredicate.kind &&
+ (signaturePredicate.kind === 0 /* This */ || signaturePredicate.parameterIndex === contextualPredicate.parameterIndex)) {
+ inferTypes(context.inferences, contextualPredicate.type, signaturePredicate.type, 8 /* ReturnType */);
+ }
}
return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
}
- function inferJsxTypeArguments(node, signature, excludeArgument, context) {
+ function inferJsxTypeArguments(node, signature, checkMode, context) {
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context);
+ var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
inferTypes(context.inferences, checkAttrType, paramType);
return getInferredTypes(context);
}
- function inferTypeArguments(node, signature, args, excludeArgument, context) {
+ function inferTypeArguments(node, signature, args, checkMode, context) {
// Clear out all the inference results from the last time inferTypeArguments was called on this context
for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) {
var inference = _a[_i];
@@ -49561,7 +49708,7 @@ var ts;
}
}
if (ts.isJsxOpeningLikeElement(node)) {
- return inferJsxTypeArguments(node, signature, excludeArgument, context);
+ return inferJsxTypeArguments(node, signature, checkMode, context);
}
// If a contextual type is available, infer from that type to the return type of the call expression. For
// example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression
@@ -49605,10 +49752,7 @@ var ts;
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- // For context sensitive arguments we pass the identityMapper, which is a signal to treat all
- // context sensitive function expressions as wildcards
- var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context;
- var argType = checkExpressionWithContextualType(arg, paramType, mapper);
+ var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
inferTypes(context.inferences, argType, paramType);
}
}
@@ -49632,7 +49776,7 @@ var ts;
// and the argument are ...x forms.
return arg.kind === 215 /* SyntheticExpression */ ?
createArrayType(arg.type) :
- getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context));
+ getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
}
}
var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType;
@@ -49640,7 +49784,7 @@ var ts;
var types = [];
var spreadIndex = -1;
for (var i = index; i < argCount; i++) {
- var argType = checkExpressionWithContextualType(args[i], contextualType, context);
+ var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
if (spreadIndex < 0 && isSpreadArgument(args[i])) {
spreadIndex = i - index;
}
@@ -49690,19 +49834,18 @@ var ts;
* @param node a JSX opening-like element we are trying to figure its call signature
* @param signature a candidate signature we are trying whether it is a call signature
* @param relation a relationship to check parameter and argument type
- * @param excludeArgument
*/
- function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors) {
// Stateless function components can have maximum of three arguments: "props", "context", and "updater".
// However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
// can be specified by users through attributes property.
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined);
+ var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined, checkMode);
return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes);
}
- function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignature(node, args, signature, relation, checkMode, reportErrors) {
if (ts.isJsxOpeningLikeElement(node)) {
- return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors);
+ return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors);
}
var thisType = getThisTypeOfSignature(signature);
if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) {
@@ -49724,11 +49867,11 @@ var ts;
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined);
- // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter),
+ var argType = checkExpressionWithContextualType(arg, paramType, /*contextualMapper*/ undefined, checkMode);
+ // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
// we obtain the regular type of any object literal arguments because we may not have inferred complete
// parameter types yet and therefore excess property checks may yield false positives (see #17041).
- var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType;
+ var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) {
return false;
}
@@ -49933,7 +50076,7 @@ var ts;
}
return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
}
- function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) {
+ function resolveCall(node, signatures, candidatesOutArray, checkMode, fallbackError) {
var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */;
var isDecorator = node.kind === 152 /* Decorator */;
var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
@@ -49969,7 +50112,7 @@ var ts;
// For a decorator, no arguments are susceptible to contextual typing due to the fact
// decorators are applied to a declaration by the emitter, and not to an expression.
var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
- var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined;
+ var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
// The following variables are captured and modified by calls to chooseOverload.
// If overload resolution or type argument inference fails, we want to report the
// best error possible. The best error is one which says that an argument was not
@@ -49997,7 +50140,7 @@ var ts;
var result;
// If we are in signature help, a trailing comma indicates that we intend to provide another argument,
// so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
- var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma;
+ var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma;
// Section 4.12.1:
// if the candidate list contains one or more signatures for which the type of each argument
// expression is a subtype of each corresponding parameter type, the return type of the first
@@ -50023,12 +50166,7 @@ var ts;
// skip the checkApplicableSignature check.
if (reportErrors) {
if (candidateForArgumentError) {
- // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...]
- // The importance of excludeArgument is to prevent us from typing function expression parameters
- // in arguments too early. If possible, we'd like to only type them once we know the correct
- // overload. However, this matters for the case where the call is correct. When the call is
- // an error, we don't need to exclude any arguments, although it would cause no harm to do so.
- checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true);
+ checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, 0 /* Normal */, /*reportErrors*/ true);
}
else if (candidateForArgumentArityError) {
diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
@@ -50060,7 +50198,7 @@ var ts;
if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
return undefined;
}
- if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false)) {
candidateForArgumentError = candidate;
return undefined;
}
@@ -50084,9 +50222,10 @@ var ts;
}
else {
inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
+ typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
+ argCheckMode |= inferenceContext.flags & 8 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
}
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// If the original signature has a generic rest type, instantiation may produce a
// signature with different arity and we need to perform another arity check.
if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -50097,21 +50236,21 @@ var ts;
else {
checkCandidate = candidate;
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
}
continue;
}
- if (excludeArgument) {
+ if (argCheckMode) {
// If one or more context sensitive arguments were excluded, we start including
// them now (and keeping do so for any subsequent candidates) and perform a second
// round of type inference and applicability checking for this particular candidate.
- excludeArgument = undefined;
+ argCheckMode = 0 /* Normal */;
if (inferenceContext) {
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// If the original signature has a generic rest type, instantiation may produce a
// signature with different arity and we need to perform another arity check.
if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -50119,7 +50258,7 @@ var ts;
continue;
}
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
@@ -50133,20 +50272,6 @@ var ts;
return undefined;
}
}
- function getExcludeArgument(args) {
- var excludeArgument;
- // We do not need to call `getEffectiveArgumentCount` here as it only
- // applies when calculating the number of arguments for a decorator.
- for (var i = 0; i < args.length; i++) {
- if (isContextSensitive(args[i])) {
- if (!excludeArgument) {
- excludeArgument = new Array(args.length);
- }
- excludeArgument[i] = true;
- }
- }
- return excludeArgument;
- }
// No signature was applicable. We have already reported the errors for the invalid signature.
// If this is a type resolution session, e.g. Language Service, try to get better information than anySignature.
function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
@@ -50235,7 +50360,7 @@ var ts;
}
function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext);
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
return createSignatureInstantiation(candidate, typeArgumentTypes);
}
function getLongestCandidateIndex(candidates, argsCount) {
@@ -50254,7 +50379,7 @@ var ts;
}
return maxParamsIndex;
}
- function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveCallExpression(node, candidatesOutArray, checkMode) {
if (node.expression.kind === 98 /* SuperKeyword */) {
var superType = checkSuperExpression(node.expression);
if (isTypeAny(superType)) {
@@ -50270,7 +50395,7 @@ var ts;
var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
if (baseTypeNode) {
var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
- return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, baseConstructors, candidatesOutArray, checkMode);
}
}
return resolveUntypedCall(node);
@@ -50320,12 +50445,31 @@ var ts;
}
return resolveErrorCall(node);
}
+ // When a call to a generic function is an argument to an outer call to a generic function for which
+ // inference is in process, we have a choice to make. If the inner call relies on inferences made from
+ // its contextual type to its return type, deferring the inner call processing allows the best possible
+ // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
+ // the inner call, the inner call should be processed early. There's no sure way to know which choice is
+ // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
+ // If no type arguments are specified in the inner call and at least one call signature is generic and
+ // returns a function type, we choose to defer processing. This narrowly permits function composition
+ // operators to flow inferences through return types, but otherwise processes calls right away. We
+ // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
+ // propagated out and eventually turned into silentNeverType (a type that is assignable to anything and
+ // from which we never make inferences).
+ if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
+ skippedGenericFunction(node, checkMode);
+ return resolvingSignature;
+ }
// If the function is explicitly marked with `@class`, then it must be constructed.
if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
+ }
+ function isGenericFunctionReturningFunction(signature) {
+ return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
}
/**
* TS 1.0 spec: 4.12
@@ -50337,7 +50481,7 @@ var ts;
return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
!numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
}
- function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveNewExpression(node, candidatesOutArray, checkMode) {
if (node.arguments && languageVersion < 1 /* ES5 */) {
var spreadIndex = getSpreadArgumentIndex(node.arguments);
if (spreadIndex >= 0) {
@@ -50385,7 +50529,7 @@ var ts;
error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
return resolveErrorCall(node);
}
- return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, constructSignatures, candidatesOutArray, checkMode);
}
// If expressionType's apparent type is an object type with no construct signatures but
// one or more call signatures, the expression is processed as a function call. A compile-time
@@ -50393,7 +50537,7 @@ var ts;
// operation is Any. It is an error to have a Void this type.
var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
if (callSignatures.length) {
- var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode);
if (!noImplicitAny) {
if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
@@ -50490,7 +50634,7 @@ var ts;
addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead));
}
}
- function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
var tagType = checkExpression(node.tag);
var apparentType = getApparentType(tagType);
if (apparentType === errorType) {
@@ -50506,7 +50650,7 @@ var ts;
invocationError(node, apparentType, 0 /* Call */);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
}
/**
* Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
@@ -50531,7 +50675,7 @@ var ts;
/**
* Resolves a decorator as if it were a call expression.
*/
- function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveDecorator(node, candidatesOutArray, checkMode) {
var funcType = checkExpression(node.expression);
var apparentType = getApparentType(funcType);
if (apparentType === errorType) {
@@ -50556,7 +50700,7 @@ var ts;
invocationErrorRecovery(apparentType, 0 /* Call */, diag);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode, headMessage);
}
function createSignatureForJSXIntrinsic(node, result) {
var namespace = getJsxNamespaceAt(node);
@@ -50575,11 +50719,11 @@ var ts;
/*hasRestparameter*/ false,
/*hasLiteralTypes*/ false);
}
- function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
if (isJsxIntrinsicIdentifier(node.tagName)) {
var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
var fakeSignature = createSignatureForJSXIntrinsic(node, result);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes);
+ checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
return fakeSignature;
}
var exprTypes = checkExpression(node.tagName);
@@ -50596,7 +50740,7 @@ var ts;
error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
return resolveErrorCall(node);
}
- return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, signatures, candidatesOutArray, checkMode);
}
/**
* Sometimes, we have a decorator that could accept zero arguments,
@@ -50610,19 +50754,19 @@ var ts;
signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
});
}
- function resolveSignature(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveSignature(node, candidatesOutArray, checkMode) {
switch (node.kind) {
case 191 /* CallExpression */:
- return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveCallExpression(node, candidatesOutArray, checkMode);
case 192 /* NewExpression */:
- return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveNewExpression(node, candidatesOutArray, checkMode);
case 193 /* TaggedTemplateExpression */:
- return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
case 152 /* Decorator */:
- return resolveDecorator(node, candidatesOutArray, isForSignatureHelp);
+ return resolveDecorator(node, candidatesOutArray, checkMode);
case 262 /* JsxOpeningElement */:
case 261 /* JsxSelfClosingElement */:
- return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp);
+ return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
}
throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
}
@@ -50633,8 +50777,7 @@ var ts;
* the function will fill it up with appropriate candidate signatures
* @return a signature of the call-like expression or undefined if one can't be found
*/
- function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) {
- if (isForSignatureHelp === void 0) { isForSignatureHelp = false; }
+ function getResolvedSignature(node, candidatesOutArray, checkMode) {
var links = getNodeLinks(node);
// If getResolvedSignature has already been called, we will have cached the resolvedSignature.
// However, it is possible that either candidatesOutArray was not passed in the first time,
@@ -50645,11 +50788,15 @@ var ts;
return cached;
}
links.resolvedSignature = resolvingSignature;
- var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp);
- // If signature resolution originated in control flow type analysis (for example to compute the
- // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
- // types from the control flow analysis.
- links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
+ // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
+ // resolution should be deferred.
+ if (result !== resolvingSignature) {
+ // If signature resolution originated in control flow type analysis (for example to compute the
+ // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
+ // types from the control flow analysis.
+ links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ }
return result;
}
/**
@@ -50725,10 +50872,15 @@ var ts;
* @param node The call/new expression to be checked.
* @returns On success, the expression's signature's return type. On failure, anyType.
*/
- function checkCallExpression(node) {
+ function checkCallExpression(node, checkMode) {
if (!checkGrammarTypeArguments(node, node.typeArguments))
checkGrammarArguments(node.arguments);
- var signature = getResolvedSignature(node);
+ var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
+ if (signature === resolvingSignature) {
+ // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
+ // returns a function type. We defer checking and return anyFunctionType.
+ return silentNeverType;
+ }
if (node.expression.kind === 98 /* SuperKeyword */) {
return voidType;
}
@@ -50972,7 +51124,7 @@ var ts;
if (isTupleType(restType)) {
var associatedNames = restType.target.associatedNames;
var index = pos - paramCount;
- return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index;
+ return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
}
return restParameter.escapedName;
}
@@ -51180,7 +51332,7 @@ var ts;
var functionFlags = ts.getFunctionFlags(func);
var type;
if (func.body.kind !== 218 /* Block */) {
- type = checkExpressionCached(func.body, checkMode);
+ type = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -51358,7 +51510,7 @@ var ts;
ts.forEachReturnStatement(func.body, function (returnStatement) {
var expr = returnStatement.expression;
if (expr) {
- var type = checkExpressionCached(expr, checkMode);
+ var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -51451,7 +51603,7 @@ var ts;
ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
checkNodeDeferred(node);
// The identityMapper object is used to indicate that function expressions are wildcards
- if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) {
+ if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
// Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) {
var links_1 = getNodeLinks(node);
@@ -51488,7 +51640,7 @@ var ts;
var signature = getSignaturesOfType(type, 0 /* Call */)[0];
if (isContextSensitive(node)) {
var contextualMapper = getContextualMapper(node);
- if (checkMode === 2 /* Inferential */) {
+ if (checkMode && checkMode & 2 /* Inferential */) {
inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper);
}
var instantiatedContextualSignature = contextualMapper === identityMapper ?
@@ -52410,15 +52562,13 @@ var ts;
}
return node;
}
- function checkExpressionWithContextualType(node, contextualType, contextualMapper) {
+ function checkExpressionWithContextualType(node, contextualType, contextualMapper, checkMode) {
var context = getContextNode(node);
var saveContextualType = context.contextualType;
var saveContextualMapper = context.contextualMapper;
context.contextualType = contextualType;
context.contextualMapper = contextualMapper;
- var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ :
- contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */;
- var type = checkExpression(node, checkMode);
+ var type = checkExpression(node, checkMode | 1 /* Contextual */ | (contextualMapper ? 2 /* Inferential */ : 0));
// We strip literal freshness when an appropriate contextual type is present such that contextually typed
// literals always preserve their literal types (otherwise they might widen during type inference). An alternative
// here would be to not mark contextually typed literals as fresh in the first place.
@@ -52431,7 +52581,7 @@ var ts;
function checkExpressionCached(node, checkMode) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- if (checkMode) {
+ if (checkMode && checkMode !== 0 /* Normal */) {
return checkExpression(node, checkMode);
}
// When computing a type that we're going to cache, we need to ignore any ongoing control flow
@@ -52528,20 +52678,122 @@ var ts;
return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
}
function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
- if (checkMode === 2 /* Inferential */) {
+ if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
var signature = getSingleCallSignature(type);
if (signature && signature.typeParameters) {
+ if (checkMode & 8 /* SkipGenericFunctions */) {
+ skippedGenericFunction(node, checkMode);
+ return anyFunctionType;
+ }
var contextualType = getApparentTypeOfContextualType(node);
if (contextualType) {
var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType));
if (contextualSignature && !contextualSignature.typeParameters) {
- return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node)));
+ var context = getContextualMapper(node);
+ // We have an expression that is an argument of a generic function for which we are performing
+ // type argument inference. The expression is of a function type with a single generic call
+ // signature and a contextual function type with a single non-generic call signature. Now check
+ // if the outer function returns a function type with a single non-generic call signature and
+ // if some of the outer function type parameters have no inferences so far. If so, we can
+ // potentially add inferred type parameters to the outer function return type.
+ var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature));
+ if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
+ // Instantiate the expression type with its own type parameters as type arguments. This
+ // ensures that the type parameters are not erased to type any during type inference such
+ // that they can be inferred as actual types.
+ var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
+ var strippedType = getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters));
+ // Infer from the stripped expression type to the contextual type starting with an empty
+ // set of inference candidates.
+ var inferences = ts.map(context.typeParameters, createInferenceInfo);
+ inferTypes(inferences, strippedType, contextualType);
+ // If we produced some inference candidates and if the type parameters for which we produced
+ // candidates do not already have existing inferences, we adopt the new inference candidates and
+ // add the type parameters of the expression type to the set of inferred type parameters for
+ // the outer function return type.
+ if (ts.some(inferences, hasInferenceCandidates) && !hasOverlappingInferences(context.inferences, inferences)) {
+ mergeInferences(context.inferences, inferences);
+ context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
+ return strippedType;
+ }
+ }
+ return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
}
}
}
}
return type;
}
+ function skippedGenericFunction(node, checkMode) {
+ if (checkMode & 2 /* Inferential */) {
+ // We have skipped a generic function during inferential typing. Obtain the inference context and
+ // indicate this has occurred such that we know a second pass of inference is be needed.
+ var context = getContextualMapper(node);
+ context.flags |= 8 /* SkippedGenericFunction */;
+ }
+ }
+ function hasInferenceCandidates(info) {
+ return !!(info.candidates || info.contraCandidates);
+ }
+ function hasOverlappingInferences(a, b) {
+ for (var i = 0; i < a.length; i++) {
+ if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
+ return true;
+ }
+ }
+ return false;
+ }
+ function mergeInferences(target, source) {
+ for (var i = 0; i < target.length; i++) {
+ if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
+ target[i] = source[i];
+ }
+ }
+ }
+ function getUniqueTypeParameters(context, typeParameters) {
+ var result = [];
+ var oldTypeParameters;
+ var newTypeParameters;
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var tp = typeParameters_2[_i];
+ var name = tp.symbol.escapedName;
+ if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
+ var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
+ var symbol = createSymbol(262144 /* TypeParameter */, newName);
+ var newTypeParameter = createTypeParameter(symbol);
+ newTypeParameter.target = tp;
+ oldTypeParameters = ts.append(oldTypeParameters, tp);
+ newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
+ result.push(newTypeParameter);
+ }
+ else {
+ result.push(tp);
+ }
+ }
+ if (newTypeParameters) {
+ var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
+ for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
+ var tp = newTypeParameters_1[_a];
+ tp.mapper = mapper;
+ }
+ }
+ return result;
+ }
+ function hasTypeParameterByName(typeParameters, name) {
+ return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
+ }
+ function getUniqueTypeParameterName(typeParameters, baseName) {
+ var len = baseName.length;
+ while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
+ len--;
+ var s = baseName.slice(0, len);
+ for (var index = 1; true; index++) {
+ var augmentedName = (s + index);
+ if (!hasTypeParameterByName(typeParameters, augmentedName)) {
+ return augmentedName;
+ }
+ }
+ }
/**
* Returns the type of an expression. Unlike checkExpression, this function is simply concerned
* with computing the type and may not fully check all contained sub-expressions for errors.
@@ -52581,7 +52833,7 @@ var ts;
}
var saveContextualType = node.contextualType;
node.contextualType = anyType;
- var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */);
+ var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
node.contextualType = saveContextualType;
return type;
}
@@ -52673,7 +52925,7 @@ var ts;
}
/* falls through */
case 192 /* NewExpression */:
- return checkCallExpression(node);
+ return checkCallExpression(node, checkMode);
case 193 /* TaggedTemplateExpression */:
return checkTaggedTemplateExpression(node);
case 195 /* ParenthesizedExpression */:
@@ -52932,7 +53184,7 @@ var ts;
checkAsyncFunctionReturnType(node, returnTypeNode);
}
}
- if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) {
+ if (node.kind !== 162 /* IndexSignature */ && node.kind !== 294 /* JSDocFunctionType */) {
registerForUnusedIdentifiersCheck(node);
}
}
@@ -53688,8 +53940,8 @@ var ts;
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
// A jsdoc typedef and callback are, by definition, type aliases
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return 2 /* ExportType */;
case 244 /* ModuleDeclaration */:
return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
@@ -53698,7 +53950,7 @@ var ts;
case 240 /* ClassDeclaration */:
case 243 /* EnumDeclaration */:
return 2 /* ExportType */ | 1 /* ExportValue */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
case 254 /* ExportAssignment */:
// Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
@@ -54339,7 +54591,7 @@ var ts;
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 244 /* ModuleDeclaration */:
case 218 /* Block */:
case 246 /* CaseBlock */:
@@ -54432,8 +54684,8 @@ var ts;
return;
var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
var seenParentsWithEveryUnused = new ts.NodeSet();
- for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
- var typeParameter = typeParameters_2[_i];
+ for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
+ var typeParameter = typeParameters_3[_i];
if (!isTypeParameterUnused(typeParameter))
continue;
var name = ts.idText(typeParameter.name);
@@ -54686,7 +54938,7 @@ var ts;
}
// In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
var parent = getDeclarationContainer(node);
- if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
+ if (parent.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
// If the declaration happens to be in external module, report error that require and exports are reserved keywords
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
@@ -54701,7 +54953,7 @@ var ts;
}
// In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
var parent = getDeclarationContainer(node);
- if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
+ if (parent.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
// If the declaration happens to be in external module, report error that Promise is a reserved identifier.
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
@@ -54758,7 +55010,7 @@ var ts;
(container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) ||
container.kind === 245 /* ModuleBlock */ ||
container.kind === 244 /* ModuleDeclaration */ ||
- container.kind === 279 /* SourceFile */);
+ container.kind === 284 /* SourceFile */);
// here we know that function scoped variable is shadowed by block scoped one
// if they are defined in the same scope - binder has already reported redeclaration error
// otherwise if variable has an initializer - show error that initialization will fail
@@ -56608,7 +56860,7 @@ var ts;
return false;
}
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule) {
error(moduleName, node.kind === 255 /* ExportDeclaration */ ?
ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
@@ -56739,7 +56991,7 @@ var ts;
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ &&
!node.moduleSpecifier && node.flags & 4194304 /* Ambient */;
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
}
}
@@ -56756,7 +57008,7 @@ var ts;
}
}
function checkGrammarModuleElementContext(node, errorMessage) {
- var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
+ var isInAppropriateContext = node.parent.kind === 284 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
if (!isInAppropriateContext) {
grammarErrorOnFirstToken(node, errorMessage);
}
@@ -56785,7 +57037,7 @@ var ts;
// If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
return;
}
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
if (node.isExportEquals) {
error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
@@ -56955,32 +57207,32 @@ var ts;
return checkInferType(node);
case 183 /* ImportType */:
return checkImportType(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return checkJSDocAugmentsTag(node);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return checkJSDocTypeAliasTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return checkJSDocTemplateTag(node);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return checkJSDocTypeTag(node);
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
return checkJSDocParameterTag(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
checkJSDocFunctionType(node);
// falls through
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
- case 292 /* JSDocTypeLiteral */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
+ case 297 /* JSDocTypeLiteral */:
checkJSDocTypeIsInJsFile(node);
ts.forEachChild(node, checkSourceElement);
return;
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
checkJSDocVariadicType(node);
return;
- case 283 /* JSDocTypeExpression */:
+ case 288 /* JSDocTypeExpression */:
return checkSourceElement(node.type);
case 180 /* IndexedAccessType */:
return checkIndexedAccessType(node);
@@ -57288,7 +57540,7 @@ var ts;
copySymbols(location.locals, meaning);
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
// falls through
@@ -57507,10 +57759,10 @@ var ts;
return entityNameSymbol;
}
}
- if (entityName.parent.kind === 299 /* JSDocParameterTag */) {
+ if (entityName.parent.kind === 304 /* JSDocParameterTag */) {
return ts.getParameterSymbolFromJSDoc(entityName.parent);
}
- if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) {
+ if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 308 /* JSDocTemplateTag */) {
ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true.
var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
return typeParameter && typeParameter.symbol;
@@ -57552,7 +57804,7 @@ var ts;
return undefined;
}
function getSymbolAtLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
}
var parent = node.parent;
@@ -57894,7 +58146,7 @@ var ts;
}
var parentSymbol_1 = getParentOfSymbol(symbol);
if (parentSymbol_1) {
- if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) {
+ if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 284 /* SourceFile */) {
var symbolFile = parentSymbol_1.valueDeclaration;
var referenceFile = ts.getSourceFileOfNode(node);
// If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
@@ -58009,7 +58261,7 @@ var ts;
}
function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
- if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
+ if (node === undefined || node.parent.kind !== 284 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
// parent is not source file or it is not reference to internal module
return false;
}
@@ -58438,7 +58690,7 @@ var ts;
break;
}
}
- if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
+ if (current.valueDeclaration && current.valueDeclaration.kind === 284 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
return false;
}
// check that at least one declaration of top level symbol originates from type declaration file
@@ -58471,7 +58723,7 @@ var ts;
if (!moduleSymbol) {
return undefined;
}
- return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */);
+ return ts.getDeclarationOfKind(moduleSymbol, 284 /* SourceFile */);
}
function initializeTypeChecker() {
// Bind all source files and propagate errors
@@ -58703,7 +58955,7 @@ var ts;
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
}
else if (flags & 128 /* Abstract */) {
@@ -58726,7 +58978,7 @@ var ts;
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
}
else if (node.kind === 151 /* Parameter */) {
@@ -58771,7 +59023,7 @@ var ts;
flags |= 1 /* Export */;
break;
case 80 /* DefaultKeyword */:
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
}
@@ -58894,7 +59146,7 @@ var ts;
case 151 /* Parameter */:
return false;
default:
- if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return false;
}
switch (node.kind) {
@@ -59817,7 +60069,7 @@ var ts;
// to prevent noisiness. So use a bit on the block to indicate if
// this has already been reported, and don't report if it has.
//
- if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
var links_2 = getNodeLinks(node.parent);
// Check if the containing block ever report this error
if (!links_2.hasReportedStatementInAmbientContext) {
@@ -61871,14 +62123,14 @@ var ts;
// JSDoc
/* @internal */
function createJSDocTypeExpression(type) {
- var node = createSynthesizedNode(283 /* JSDocTypeExpression */);
+ var node = createSynthesizedNode(288 /* JSDocTypeExpression */);
node.type = type;
return node;
}
ts.createJSDocTypeExpression = createJSDocTypeExpression;
/* @internal */
function createJSDocTypeTag(typeExpression, comment) {
- var tag = createJSDocTag(302 /* JSDocTypeTag */, "type");
+ var tag = createJSDocTag(307 /* JSDocTypeTag */, "type");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61886,7 +62138,7 @@ var ts;
ts.createJSDocTypeTag = createJSDocTypeTag;
/* @internal */
function createJSDocReturnTag(typeExpression, comment) {
- var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns");
+ var tag = createJSDocTag(305 /* JSDocReturnTag */, "returns");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61894,7 +62146,7 @@ var ts;
ts.createJSDocReturnTag = createJSDocReturnTag;
/* @internal */
function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
- var tag = createJSDocTag(299 /* JSDocParameterTag */, "param");
+ var tag = createJSDocTag(304 /* JSDocParameterTag */, "param");
tag.typeExpression = typeExpression;
tag.name = name;
tag.isBracketed = isBracketed;
@@ -61904,7 +62156,7 @@ var ts;
ts.createJSDocParamTag = createJSDocParamTag;
/* @internal */
function createJSDocComment(comment, tags) {
- var node = createSynthesizedNode(291 /* JSDocComment */);
+ var node = createSynthesizedNode(296 /* JSDocComment */);
node.comment = comment;
node.tags = tags;
return node;
@@ -62163,7 +62415,7 @@ var ts;
(typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
(libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
(hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
- var updated = createSynthesizedNode(279 /* SourceFile */);
+ var updated = createSynthesizedNode(284 /* SourceFile */);
updated.flags |= node.flags;
updated.statements = createNodeArray(statements);
updated.endOfFileToken = node.endOfFileToken;
@@ -62247,7 +62499,7 @@ var ts;
* @param original The original statement.
*/
function createNotEmittedStatement(original) {
- var node = createSynthesizedNode(307 /* NotEmittedStatement */);
+ var node = createSynthesizedNode(312 /* NotEmittedStatement */);
node.original = original;
setTextRange(node, original);
return node;
@@ -62259,7 +62511,7 @@ var ts;
*/
/* @internal */
function createEndOfDeclarationMarker(original) {
- var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */);
+ var node = createSynthesizedNode(316 /* EndOfDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -62271,7 +62523,7 @@ var ts;
*/
/* @internal */
function createMergeDeclarationMarker(original) {
- var node = createSynthesizedNode(310 /* MergeDeclarationMarker */);
+ var node = createSynthesizedNode(315 /* MergeDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -62286,7 +62538,7 @@ var ts;
* @param location The location for the expression. Defaults to the positions from "original" if provided.
*/
function createPartiallyEmittedExpression(expression, original) {
- var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */);
+ var node = createSynthesizedNode(313 /* PartiallyEmittedExpression */);
node.expression = expression;
node.original = original;
setTextRange(node, original);
@@ -62302,7 +62554,7 @@ var ts;
ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
function flattenCommaElements(node) {
if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
- if (node.kind === 309 /* CommaListExpression */) {
+ if (node.kind === 314 /* CommaListExpression */) {
return node.elements;
}
if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
@@ -62312,7 +62564,7 @@ var ts;
return node;
}
function createCommaList(elements) {
- var node = createSynthesizedNode(309 /* CommaListExpression */);
+ var node = createSynthesizedNode(314 /* CommaListExpression */);
node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
return node;
}
@@ -62325,33 +62577,197 @@ var ts;
ts.updateCommaList = updateCommaList;
function createBundle(sourceFiles, prepends) {
if (prepends === void 0) { prepends = ts.emptyArray; }
- var node = ts.createNode(280 /* Bundle */);
+ var node = ts.createNode(285 /* Bundle */);
node.prepends = prepends;
node.sourceFiles = sourceFiles;
return node;
}
ts.createBundle = createBundle;
- function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, map) {
- var node = ts.createNode(281 /* UnparsedSource */);
+ var allUnscopedEmitHelpers;
+ function getAllUnscopedEmitHelpers() {
+ return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
+ ts.valuesHelper,
+ ts.readHelper,
+ ts.spreadHelper,
+ ts.restHelper,
+ ts.decorateHelper,
+ ts.metadataHelper,
+ ts.paramHelper,
+ ts.awaiterHelper,
+ ts.assignHelper,
+ ts.awaitHelper,
+ ts.asyncGeneratorHelper,
+ ts.asyncDelegator,
+ ts.asyncValues,
+ ts.extendsHelper,
+ ts.templateObjectHelper,
+ ts.generatorHelper,
+ ts.importStarHelper,
+ ts.importDefaultHelper
+ ], function (helper) { return helper.name; }));
+ }
+ function createUnparsedSource() {
+ var node = ts.createNode(286 /* UnparsedSource */);
+ node.prologues = ts.emptyArray;
+ node.referencedFiles = ts.emptyArray;
+ node.libReferenceDirectives = ts.emptyArray;
+ node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
+ return node;
+ }
+ function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
+ var node = createUnparsedSource();
+ var stripInternal;
+ var bundleFileInfo;
if (!ts.isString(textOrInputFiles)) {
ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
- node.fileName = mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath;
+ node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
Object.defineProperties(node, {
text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
});
+ if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
+ node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
+ ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
+ stripInternal = mapTextOrStripInternal;
+ bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
+ if (node.oldFileOfCurrentEmit) {
+ parseOldFileOfCurrentEmit(node, ts.Debug.assertDefined(bundleFileInfo));
+ return node;
+ }
+ }
}
else {
+ node.fileName = "";
node.text = textOrInputFiles;
node.sourceMapPath = mapPathOrType;
- node.sourceMapText = map;
+ node.sourceMapText = mapTextOrStripInternal;
}
+ ts.Debug.assert(!node.oldFileOfCurrentEmit);
+ parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
return node;
}
ts.createUnparsedSourceFile = createUnparsedSourceFile;
- function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapText) {
- var node = ts.createNode(282 /* InputFiles */);
+ function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
+ var prologues;
+ var helpers;
+ var referencedFiles;
+ var typeReferenceDirectives;
+ var libReferenceDirectives;
+ var texts;
+ for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "prologue" /* Prologue */:
+ (prologues || (prologues = [])).push(createUnparsedNode(section, node));
+ break;
+ case "emitHelpers" /* EmitHelpers */:
+ (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ node.hasNoDefaultLib = true;
+ break;
+ case "reference" /* Reference */:
+ (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "type" /* Type */:
+ (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
+ break;
+ case "lib" /* Lib */:
+ (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "prepend" /* Prepend */:
+ var prependNode = createUnparsedNode(section, node);
+ var prependTexts = void 0;
+ for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
+ var text = _c[_b];
+ if (!stripInternal || text.kind !== "internal" /* Internal */) {
+ (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
+ }
+ }
+ prependNode.texts = prependTexts || ts.emptyArray;
+ (texts || (texts = [])).push(prependNode);
+ break;
+ case "internal" /* Internal */:
+ if (stripInternal)
+ break;
+ // falls through
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.prologues = prologues || ts.emptyArray;
+ node.helpers = helpers;
+ node.referencedFiles = referencedFiles || ts.emptyArray;
+ node.typeReferenceDirectives = typeReferenceDirectives;
+ node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
+ node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
+ }
+ function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
+ ts.Debug.assert(!!node.oldFileOfCurrentEmit);
+ var texts;
+ var syntheticReferences;
+ for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "internal" /* Internal */:
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
+ break;
+ // Ignore
+ case "prologue" /* Prologue */:
+ case "emitHelpers" /* EmitHelpers */:
+ case "prepend" /* Prepend */:
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.texts = texts || ts.emptyArray;
+ node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
+ node.syntheticReferences = syntheticReferences;
+ return node;
+ }
+ function mapBundleFileSectionKindToSyntaxKind(kind) {
+ switch (kind) {
+ case "prologue" /* Prologue */: return 279 /* UnparsedPrologue */;
+ case "prepend" /* Prepend */: return 280 /* UnparsedPrepend */;
+ case "internal" /* Internal */: return 282 /* UnparsedInternalText */;
+ case "text" /* Text */: return 281 /* UnparsedText */;
+ case "emitHelpers" /* EmitHelpers */:
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
+ default:
+ return ts.Debug.assertNever(kind);
+ }
+ }
+ function createUnparsedNode(section, parent) {
+ var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ return node;
+ }
+ function createUnparsedSyntheticReference(section, parent) {
+ var node = ts.createNode(283 /* UnparsedSyntheticReference */, section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ node.section = section;
+ return node;
+ }
+ function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
+ var node = ts.createNode(287 /* InputFiles */);
if (!ts.isString(javascriptTextOrReadFileText)) {
var cache_1 = ts.createMap();
var textGetter_1 = function (path) {
@@ -62368,15 +62784,25 @@ var ts;
var result = textGetter_1(path);
return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
};
+ var buildInfo_1;
+ var getAndCacheBuildInfo_1 = function (getText) {
+ if (buildInfo_1 === undefined) {
+ var result = getText();
+ buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
+ }
+ return buildInfo_1 || undefined;
+ };
node.javascriptPath = declarationTextOrJavascriptPath;
node.javascriptMapPath = javascriptMapPath;
node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
node.declarationMapPath = declarationMapPath;
+ node.buildInfoPath = declarationMapTextOrBuildInfoPath;
Object.defineProperties(node, {
javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
- declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } } // TODO:: if there is inline sourceMap in dtsFile, use that
+ declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
+ buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
});
}
else {
@@ -62385,7 +62811,12 @@ var ts;
node.javascriptMapText = javascriptMapTextOrDeclarationPath;
node.declarationText = declarationTextOrJavascriptPath;
node.declarationMapPath = declarationMapPath;
- node.declarationMapText = declarationMapText;
+ node.declarationMapText = declarationMapTextOrBuildInfoPath;
+ node.javascriptPath = javascriptPath;
+ node.declarationPath = declarationPath,
+ node.buildInfoPath = buildInfoPath;
+ node.buildInfo = buildInfo;
+ node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
}
return node;
}
@@ -62523,7 +62954,7 @@ var ts;
// To avoid holding onto transformation artifacts, we keep track of any
// parse tree node we are annotating. This allows us to clean them up after
// all transformations have completed.
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return node.emitNode = { annotatedNodes: [node] };
}
var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
@@ -62969,38 +63400,38 @@ var ts;
return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
}
ts.getHelperName = getHelperName;
- var valuesHelper = {
+ ts.valuesHelper = {
name: "typescript:values",
scoped: false,
text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };"
};
function createValuesHelper(context, expression, location) {
- context.requestEmitHelper(valuesHelper);
+ context.requestEmitHelper(ts.valuesHelper);
return ts.setTextRange(ts.createCall(getHelperName("__values"),
/*typeArguments*/ undefined, [expression]), location);
}
ts.createValuesHelper = createValuesHelper;
- var readHelper = {
+ ts.readHelper = {
name: "typescript:read",
scoped: false,
text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };"
};
function createReadHelper(context, iteratorRecord, count, location) {
- context.requestEmitHelper(readHelper);
+ context.requestEmitHelper(ts.readHelper);
return ts.setTextRange(ts.createCall(getHelperName("__read"),
/*typeArguments*/ undefined, count !== undefined
? [iteratorRecord, ts.createLiteral(count)]
: [iteratorRecord]), location);
}
ts.createReadHelper = createReadHelper;
- var spreadHelper = {
+ ts.spreadHelper = {
name: "typescript:spread",
scoped: false,
text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };"
};
function createSpreadHelper(context, argumentList, location) {
- context.requestEmitHelper(readHelper);
- context.requestEmitHelper(spreadHelper);
+ context.requestEmitHelper(ts.readHelper);
+ context.requestEmitHelper(ts.spreadHelper);
return ts.setTextRange(ts.createCall(getHelperName("__spread"),
/*typeArguments*/ undefined, argumentList), location);
}
@@ -63846,7 +64277,7 @@ var ts;
case 190 /* ElementAccessExpression */:
case 189 /* PropertyAccessExpression */:
case 213 /* NonNullExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
node = node.expression;
continue;
}
@@ -63862,7 +64293,7 @@ var ts;
ts.parenthesizeConciseBody = parenthesizeConciseBody;
function isCommaSequence(node) {
return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
- node.kind === 309 /* CommaListExpression */;
+ node.kind === 314 /* CommaListExpression */;
}
ts.isCommaSequence = isCommaSequence;
var OuterExpressionKinds;
@@ -63881,7 +64312,7 @@ var ts;
case 212 /* AsExpression */:
case 213 /* NonNullExpression */:
return (kinds & 2 /* Assertions */) !== 0;
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0;
}
return false;
@@ -63918,7 +64349,7 @@ var ts;
case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
- case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
+ case 313 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
}
}
/**
@@ -64710,12 +65141,12 @@ var ts;
case 278 /* EnumMember */:
return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
default:
// No need to visit nodes with no children.
@@ -64771,7 +65202,7 @@ var ts;
case 220 /* EmptyStatement */:
case 210 /* OmittedExpression */:
case 236 /* DebuggerStatement */:
- case 307 /* NotEmittedStatement */:
+ case 312 /* NotEmittedStatement */:
// No need to visit nodes with no children.
break;
// Names
@@ -65148,14 +65579,14 @@ var ts;
result = reduceNode(node.initializer, cbNode, result);
break;
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
result = reduceNodes(node.statements, cbNodes, result);
break;
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
result = reduceNodes(node.elements, cbNodes, result);
break;
default:
@@ -65436,7 +65867,7 @@ var ts;
}
exit();
}
- function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) {
+ function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
var _a;
ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
@@ -65446,6 +65877,14 @@ var ts;
var nameIndexToNewNameIndexMap;
var mappingIterator = decodeMappings(map.mappings);
for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) {
+ if (end && (raw.generatedLine > end.line ||
+ (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
+ break;
+ }
+ if (start && (raw.generatedLine < start.line ||
+ (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
+ continue;
+ }
// Then reencode all the updated mappings into the overall map
var newSourceIndex = void 0;
var newSourceLine = void 0;
@@ -65474,8 +65913,10 @@ var ts;
}
}
}
- var newGeneratedLine = raw.generatedLine + generatedLine;
- var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter;
+ var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
+ var newGeneratedLine = rawGeneratedLine + generatedLine;
+ var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
+ var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
}
exit();
@@ -65958,7 +66399,7 @@ var ts;
function chainBundle(transformSourceFile) {
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
+ return node.kind === 284 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
}
function transformBundle(node) {
return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
@@ -66619,7 +67060,7 @@ var ts;
function makeAssignmentElement(name) {
return name;
}
- var restHelper = {
+ ts.restHelper = {
name: "typescript:rest",
scoped: false,
text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };"
@@ -66628,7 +67069,7 @@ var ts;
* `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
*/
function createRestCall(context, value, elements, computedTempVariables, location) {
- context.requestEmitHelper(restHelper);
+ context.requestEmitHelper(ts.restHelper);
var propertyNames = [];
var computedTempVariableOffset = 0;
for (var i = 0; i < elements.length - 1; i++) {
@@ -66729,14 +67170,14 @@ var ts;
var pendingExpressions;
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* Bundle */) {
return transformBundle(node);
}
return transformSourceFile(node);
}
function transformBundle(node) {
return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
- if (prepend.kind === 282 /* InputFiles */) {
+ if (prepend.kind === 287 /* InputFiles */) {
return ts.createUnparsedSourceFile(prepend, "js");
}
return prepend;
@@ -66785,7 +67226,7 @@ var ts;
*/
function onBeforeVisitNode(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 245 /* ModuleBlock */:
case 218 /* Block */:
@@ -69016,7 +69457,7 @@ var ts;
// enums in any other scope are emitted as a `let` declaration.
var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
- ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
+ ], currentLexicalScope.kind === 284 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
ts.setOriginalNode(statement, node);
recordEmittedDeclarationInScope(node);
if (isFirstEmittedDeclarationInScope(node)) {
@@ -69581,7 +70022,7 @@ var ts;
// If we are nested within a namespace declaration, we may need to qualifiy
// an identifier that is exported from a merged namespace.
var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
- if (container && container.kind !== 279 /* SourceFile */) {
+ if (container && container.kind !== 284 /* SourceFile */) {
var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) ||
(applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */);
if (substitute) {
@@ -69632,39 +70073,39 @@ var ts;
argumentsArray.push(descriptor);
}
}
- context.requestEmitHelper(decorateHelper);
+ context.requestEmitHelper(ts.decorateHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"),
/*typeArguments*/ undefined, argumentsArray), location);
}
- var decorateHelper = {
+ ts.decorateHelper = {
name: "typescript:decorate",
scoped: false,
priority: 2,
text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };"
};
function createMetadataHelper(context, metadataKey, metadataValue) {
- context.requestEmitHelper(metadataHelper);
+ context.requestEmitHelper(ts.metadataHelper);
return ts.createCall(ts.getHelperName("__metadata"),
/*typeArguments*/ undefined, [
ts.createLiteral(metadataKey),
metadataValue
]);
}
- var metadataHelper = {
+ ts.metadataHelper = {
name: "typescript:metadata",
scoped: false,
priority: 3,
text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };"
};
function createParamHelper(context, expression, parameterOffset, location) {
- context.requestEmitHelper(paramHelper);
+ context.requestEmitHelper(ts.paramHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__param"),
/*typeArguments*/ undefined, [
ts.createLiteral(parameterOffset),
expression
]), location);
}
- var paramHelper = {
+ ts.paramHelper = {
name: "typescript:param",
scoped: false,
priority: 4,
@@ -70215,14 +70656,14 @@ var ts;
], 2 /* Const */));
}
ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
- var awaiterHelper = {
+ ts.awaiterHelper = {
name: "typescript:awaiter",
scoped: false,
priority: 5,
text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };"
};
function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) {
- context.requestEmitHelper(awaiterHelper);
+ context.requestEmitHelper(ts.awaiterHelper);
var generatorFunc = ts.createFunctionExpression(
/*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */),
/*name*/ undefined,
@@ -70854,7 +71295,7 @@ var ts;
}
}
ts.transformES2018 = transformES2018;
- var assignHelper = {
+ ts.assignHelper = {
name: "typescript:assign",
scoped: false,
priority: 1,
@@ -70865,28 +71306,28 @@ var ts;
return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"),
/*typeArguments*/ undefined, attributesSegments);
}
- context.requestEmitHelper(assignHelper);
+ context.requestEmitHelper(ts.assignHelper);
return ts.createCall(ts.getHelperName("__assign"),
/*typeArguments*/ undefined, attributesSegments);
}
ts.createAssignHelper = createAssignHelper;
- var awaitHelper = {
+ ts.awaitHelper = {
name: "typescript:await",
scoped: false,
text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
};
function createAwaitHelper(context, expression) {
- context.requestEmitHelper(awaitHelper);
+ context.requestEmitHelper(ts.awaitHelper);
return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]);
}
- var asyncGeneratorHelper = {
+ ts.asyncGeneratorHelper = {
name: "typescript:asyncGenerator",
scoped: false,
text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
};
function createAsyncGeneratorHelper(context, generatorFunc) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncGeneratorHelper);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncGeneratorHelper);
// Mark this node as originally an async function
(generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */;
return ts.createCall(ts.getHelperName("__asyncGenerator"),
@@ -70896,24 +71337,24 @@ var ts;
generatorFunc
]);
}
- var asyncDelegator = {
+ ts.asyncDelegator = {
name: "typescript:asyncDelegator",
scoped: false,
text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };"
};
function createAsyncDelegatorHelper(context, expression, location) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncDelegator);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncDelegator);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"),
/*typeArguments*/ undefined, [expression]), location);
}
- var asyncValues = {
+ ts.asyncValues = {
name: "typescript:asyncValues",
scoped: false,
text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };"
};
function createAsyncValuesHelper(context, expression, location) {
- context.requestEmitHelper(asyncValues);
+ context.requestEmitHelper(ts.asyncValues);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"),
/*typeArguments*/ undefined, [expression]), location);
}
@@ -74725,7 +75166,7 @@ var ts;
}
ts.transformES2015 = transformES2015;
function createExtendsHelper(context, name) {
- context.requestEmitHelper(extendsHelper);
+ context.requestEmitHelper(ts.extendsHelper);
return ts.createCall(ts.getHelperName("__extends"),
/*typeArguments*/ undefined, [
name,
@@ -74733,20 +75174,20 @@ var ts;
]);
}
function createTemplateObjectHelper(context, cooked, raw) {
- context.requestEmitHelper(templateObjectHelper);
+ context.requestEmitHelper(ts.templateObjectHelper);
return ts.createCall(ts.getHelperName("__makeTemplateObject"),
/*typeArguments*/ undefined, [
cooked,
raw
]);
}
- var extendsHelper = {
+ ts.extendsHelper = {
name: "typescript:extends",
scoped: false,
priority: 0,
text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();"
};
- var templateObjectHelper = {
+ ts.templateObjectHelper = {
name: "typescript:makeTemplateObject",
scoped: false,
priority: 0,
@@ -77440,7 +77881,7 @@ var ts;
}
ts.transformGenerators = transformGenerators;
function createGeneratorHelper(context, body) {
- context.requestEmitHelper(generatorHelper);
+ context.requestEmitHelper(ts.generatorHelper);
return ts.createCall(ts.getHelperName("__generator"),
/*typeArguments*/ undefined, [ts.createThis(), body]);
}
@@ -77503,7 +77944,7 @@ var ts;
// entering a finally block.
//
// For examples of how these are used, see the comments in ./transformers/generators.ts
- var generatorHelper = {
+ ts.generatorHelper = {
name: "typescript:generator",
scoped: false,
priority: 6,
@@ -77536,7 +77977,7 @@ var ts;
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* SourceFile */); // Restore state when substituting nodes in a file.
var moduleInfoMap = []; // The ExternalModuleInfo for each file.
var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
var currentSourceFile; // The current file.
@@ -77878,9 +78319,9 @@ var ts;
return visitFunctionDeclaration(node);
case 240 /* ClassDeclaration */:
return visitClassDeclaration(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
@@ -78038,7 +78479,7 @@ var ts;
}
var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]);
}
return promise;
@@ -78052,7 +78493,7 @@ var ts;
var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
}
var func;
@@ -78086,11 +78527,11 @@ var ts;
return innerExpr;
}
if (ts.getImportNeedsImportStarHelper(node)) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
}
if (ts.getImportNeedsImportDefaultHelper(node)) {
- context.requestEmitHelper(importDefaultHelper);
+ context.requestEmitHelper(ts.importDefaultHelper);
return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
}
return innerExpr;
@@ -78659,7 +79100,7 @@ var ts;
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
currentSourceFile = node;
currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
noSubstitution = [];
@@ -78747,7 +79188,7 @@ var ts;
}
if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)),
/*location*/ node);
}
@@ -78873,13 +79314,13 @@ var ts;
text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
};
// emit helper for `import * as Name from "foo"`
- var importStarHelper = {
+ ts.importStarHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
};
// emit helper for `import Name from "foo"`
- var importDefaultHelper = {
+ ts.importDefaultHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
@@ -78902,7 +79343,7 @@ var ts;
context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols.
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* SourceFile */); // Restore state when substituting nodes in a file.
var moduleInfoMap = []; // The ExternalModuleInfo for each file.
var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
var exportFunctionsMap = []; // The export function associated with a source file.
@@ -79472,7 +79913,7 @@ var ts;
function shouldHoistVariableDeclarationList(node) {
// hoist only non-block scoped declarations or block scoped declarations parented by source file
return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
- && (enclosingBlockScopedContainer.kind === 279 /* SourceFile */
+ && (enclosingBlockScopedContainer.kind === 284 /* SourceFile */
|| (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
}
/**
@@ -79815,9 +80256,9 @@ var ts;
return visitCatchClause(node);
case 218 /* Block */:
return visitBlock(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return destructuringAndImportCallVisitor(node);
@@ -80065,7 +80506,7 @@ var ts;
}
else if (ts.isIdentifier(node)) {
var container = resolver.getReferencedExportContainer(node);
- return container !== undefined && container.kind === 279 /* SourceFile */;
+ return container !== undefined && container.kind === 284 /* SourceFile */;
}
else {
return false;
@@ -80098,7 +80539,7 @@ var ts;
* @param emitCallback A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
var id = ts.getOriginalNodeId(node);
currentSourceFile = node;
moduleInfo = moduleInfoMap[id];
@@ -80307,7 +80748,7 @@ var ts;
|| resolver.getReferencedValueDeclaration(name);
if (valueDeclaration) {
var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
}
exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
@@ -80346,7 +80787,7 @@ var ts;
var previousOnSubstituteNode = context.onSubstituteNode;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
- context.enableEmitNotification(279 /* SourceFile */);
+ context.enableEmitNotification(284 /* SourceFile */);
context.enableSubstitution(72 /* Identifier */);
var currentSourceFile;
return ts.chainBundle(transformSourceFile);
@@ -80776,6 +81217,9 @@ var ts;
case 241 /* InterfaceDeclaration */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
break;
+ case 181 /* MappedType */:
+ diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
+ break;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
@@ -80859,6 +81303,15 @@ var ts;
return result.diagnostics;
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
+ function isInternalDeclaration(node, currentSourceFile) {
+ var parseTreeNode = ts.getParseTreeNode(node);
+ var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
+ return !!ts.forEach(leadingCommentRanges, function (range) {
+ var comment = currentSourceFile.text.substring(range.pos, range.end);
+ return ts.stringContains(comment, "@internal");
+ });
+ }
+ ts.isInternalDeclaration = isInternalDeclaration;
var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
2048 /* WriteClassExpressionAsTypeLiteral */ |
4096 /* UseTypeOfFunction */ |
@@ -80987,10 +81440,10 @@ var ts;
}
}
function transformRoot(node) {
- if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
+ if (node.kind === 284 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
}
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* Bundle */) {
isBundledEmit = true;
refs = ts.createMap();
libs = ts.createMap();
@@ -81020,9 +81473,15 @@ var ts;
var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
}), ts.mapDefined(node.prepends, function (prepend) {
- if (prepend.kind === 282 /* InputFiles */) {
- return ts.createUnparsedSourceFile(prepend, "dts");
+ if (prepend.kind === 287 /* InputFiles */) {
+ var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
+ hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
+ collectReferences(sourceFile, refs);
+ recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
+ collectLibs(sourceFile, libs);
+ return sourceFile;
}
+ return prepend;
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
@@ -81114,7 +81573,7 @@ var ts;
}
}
function collectReferences(sourceFile, ret) {
- if (noResolve || ts.isSourceFileJS(sourceFile))
+ if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
return ret;
ts.forEach(sourceFile.referencedFiles, function (f) {
var elem = ts.tryResolveScriptReference(host, sourceFile, f);
@@ -81842,18 +82301,8 @@ var ts;
}
errorNameNode = undefined;
}
- function hasInternalAnnotation(range) {
- var comment = currentSourceFile.text.substring(range.pos, range.end);
- return ts.stringContains(comment, "@internal");
- }
function shouldStripInternal(node) {
- if (stripInternal && node) {
- var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile);
- if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) {
- return true;
- }
- }
- return false;
+ return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
}
function isScopeMarker(node) {
return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
@@ -81875,7 +82324,7 @@ var ts;
function ensureModifierFlags(node, privateDeclaration) {
var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
- var parentIsFile = node.parent.kind === 279 /* SourceFile */;
+ var parentIsFile = node.parent.kind === 284 /* SourceFile */;
if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */);
additions = 0 /* None */;
@@ -82092,7 +82541,7 @@ var ts;
* @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
*/
function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
- var enabledSyntaxKindFeatures = new Array(312 /* Count */);
+ var enabledSyntaxKindFeatures = new Array(317 /* Count */);
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
@@ -82352,10 +82801,14 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- var infoExtension = ".tsbundleinfo";
var brackets = createBracketsMap();
var syntheticParent = { pos: -1, end: -1 };
/*@internal*/
+ function isBuildInfoFile(file) {
+ return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
+ }
+ ts.isBuildInfoFile = isBuildInfoFile;
+ /*@internal*/
/**
* Iterates over the source files that are expected to have an emit output.
*
@@ -82365,13 +82818,14 @@ var ts;
* If an array, the full list of source files to emit.
* Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
*/
- function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) {
+ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles, onlyBuildInfo, includeBuildInfo) {
if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; }
var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
- if (sourceFiles.length) {
- var bundle = ts.createBundle(sourceFiles, host.getPrependNodes());
+ var prepends = host.getPrependNodes();
+ if (sourceFiles.length || prepends.length) {
+ var bundle = ts.createBundle(sourceFiles, prepends);
var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
if (result) {
return result;
@@ -82379,31 +82833,61 @@ var ts;
}
}
else {
- for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
- var sourceFile = sourceFiles_1[_a];
- var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
- if (result) {
- return result;
+ if (!onlyBuildInfo) {
+ for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
+ var sourceFile = sourceFiles_1[_a];
+ var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
+ if (result) {
+ return result;
+ }
}
}
+ if (includeBuildInfo) {
+ var buildInfoPath = getOutputPathForBuildInfo(host.getCompilerOptions());
+ if (buildInfoPath)
+ return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
+ }
}
}
ts.forEachEmittedFile = forEachEmittedFile;
/*@internal*/
+ function getOutputPathForBuildInfo(options) {
+ var configFile = options.configFilePath;
+ if (!configFile || !ts.isIncrementalCompilation(options))
+ return undefined;
+ if (options.tsBuildInfoFile)
+ return options.tsBuildInfoFile;
+ var outPath = options.outFile || options.out;
+ var buildInfoExtensionLess;
+ if (outPath) {
+ buildInfoExtensionLess = ts.removeFileExtension(outPath);
+ }
+ else {
+ var configFileExtensionLess = ts.removeFileExtension(configFile);
+ buildInfoExtensionLess = options.outDir ?
+ options.rootDir ?
+ ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
+ ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
+ configFileExtensionLess;
+ }
+ return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
+ }
+ ts.getOutputPathForBuildInfo = getOutputPathForBuildInfo;
+ /*@internal*/
function getOutputPathsForBundle(options, forceDtsPaths) {
var outPath = options.outFile || options.out;
var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath };
+ var buildInfoPath = getOutputPathForBuildInfo(options);
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
}
ts.getOutputPathsForBundle = getOutputPathsForBundle;
/*@internal*/
function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
var options = host.getCompilerOptions();
- if (sourceFile.kind === 280 /* Bundle */) {
+ if (sourceFile.kind === 285 /* Bundle */) {
return getOutputPathsForBundle(options, forceDtsPaths);
}
else {
@@ -82417,19 +82901,13 @@ var ts;
var isJs = ts.isSourceFileJS(sourceFile);
var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined };
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
}
}
ts.getOutputPathsFor = getOutputPathsFor;
function getSourceMapFilePath(jsFilePath, options) {
return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
}
- function createDefaultBundleInfo() {
- return {
- originalOffset: -1,
- totalLength: -1
- };
- }
// JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
// So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
// For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
@@ -82454,7 +82932,7 @@ var ts;
ts.getOutputExtension = getOutputExtension;
/*@internal*/
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) {
+ function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers, onlyBuildInfo) {
var compilerOptions = host.getCompilerOptions();
var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
@@ -82462,12 +82940,12 @@ var ts;
var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
var writer = ts.createTextWriter(newLine);
var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit;
- var bundleInfo = createDefaultBundleInfo();
+ var bundleBuildInfo;
var emitSkipped = false;
var exportedModulesFromDeclarationEmit;
// Emit each output file
enter();
- forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles);
+ forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles, onlyBuildInfo, !targetSourceFile);
exit();
return {
emitSkipped: emitSkipped,
@@ -82477,9 +82955,16 @@ var ts;
exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
};
function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
- var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath;
- emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
+ var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
+ bundleBuildInfo = {
+ commonSourceDirectory: host.getCommonSourceDirectory(),
+ sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return file.fileName; })
+ };
+ }
+ emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
+ emitBuildInfo(bundleBuildInfo, buildInfoPath);
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
if (jsFilePath) {
@@ -82488,8 +82973,8 @@ var ts;
if (sourceMapFilePath) {
emittedFilesList.push(sourceMapFilePath);
}
- if (bundleInfoPath) {
- emittedFilesList.push(bundleInfoPath);
+ if (buildInfoPath) {
+ emittedFilesList.push(buildInfoPath);
}
}
if (declarationFilePath) {
@@ -82500,8 +82985,21 @@ var ts;
}
}
}
- function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) {
- if (emitOnlyDtsFiles || !jsFilePath) {
+ function emitBuildInfo(bundle, buildInfoPath) {
+ // Write build information if applicable
+ if (!buildInfoPath || targetSourceFile || emitSkipped)
+ return;
+ var program = host.getProgramBuildInfo();
+ if (!bundle && !program)
+ return;
+ if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
+ emitSkipped = true;
+ return;
+ }
+ ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: ts.version }), /*writeByteOrderMark*/ false);
+ }
+ function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) {
+ if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
return;
}
// Make sure not to write js file and source map file if any of them cannot be written
@@ -82521,6 +83019,7 @@ var ts;
inlineSourceMap: compilerOptions.inlineSourceMap,
inlineSources: compilerOptions.inlineSources,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
+ writeBundleFileInfo: !!bundleBuildInfo
};
// Create a printer to print the nodes
var printer = createPrinter(printerOptions, {
@@ -82531,12 +83030,14 @@ var ts;
substituteNode: transform.substituteNode,
});
ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
- printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions);
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
// Clean up emit nodes on parse tree
transform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.js = printer.bundleFileInfo;
}
function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) {
- if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
+ if (!sourceFileOrBundle || !(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
return;
}
var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
@@ -82565,6 +83066,8 @@ var ts;
inlineSourceMap: compilerOptions.inlineSourceMap,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
onlyPrintJsDocStyle: true,
+ writeBundleFileInfo: !!bundleBuildInfo,
+ recordInternalSection: !!bundleBuildInfo
};
var declarationPrinter = createPrinter(printerOptions, {
// resolver hooks
@@ -82577,18 +83080,20 @@ var ts;
emitSkipped = emitSkipped || declBlocked;
if (!declBlocked || emitOnlyDtsFiles) {
ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
- printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, {
+ printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
sourceMap: compilerOptions.declarationMap,
sourceRoot: compilerOptions.sourceRoot,
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
});
- if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) {
+ if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 284 /* SourceFile */) {
var sourceFile = declarationTransform.transformed[0];
exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
}
}
declarationTransform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
}
function collectLinkedAliases(node) {
if (ts.isExportAssignment(node)) {
@@ -82603,16 +83108,16 @@ var ts;
}
ts.forEachChild(node, collectLinkedAliases);
}
- function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) {
- var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined;
- var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined;
+ function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
+ var bundle = sourceFileOrBundle.kind === 285 /* Bundle */ ? sourceFileOrBundle : undefined;
+ var sourceFile = sourceFileOrBundle.kind === 284 /* SourceFile */ ? sourceFileOrBundle : undefined;
var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
var sourceMapGenerator;
if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
}
if (bundle) {
- printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator);
+ printer.writeBundle(bundle, writer, sourceMapGenerator);
}
else {
printer.writeFile(sourceFile, writer, sourceMapGenerator);
@@ -82641,18 +83146,12 @@ var ts;
}
// Write the output file
ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
- // Write bundled offset information if applicable
- if (bundleInfoPath) {
- bundleInfo.totalLength = writer.getTextPos();
- ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false);
- }
// Reset state
writer.clear();
- bundleInfo = createDefaultBundleInfo();
}
function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
- && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
+ && (sourceFileOrBundle.kind !== 284 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
}
function getSourceRoot(mapOptions) {
// Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
@@ -82709,6 +83208,166 @@ var ts;
}
}
ts.emitFiles = emitFiles;
+ /*@internal*/
+ function getBuildInfoText(buildInfo) {
+ return JSON.stringify(buildInfo, undefined, 2);
+ }
+ ts.getBuildInfoText = getBuildInfoText;
+ /*@internal*/
+ function getBuildInfo(buildInfoText) {
+ return JSON.parse(buildInfoText);
+ }
+ ts.getBuildInfo = getBuildInfo;
+ /*@internal*/
+ ts.notImplementedResolver = {
+ hasGlobalName: ts.notImplemented,
+ getReferencedExportContainer: ts.notImplemented,
+ getReferencedImportDeclaration: ts.notImplemented,
+ getReferencedDeclarationWithCollidingName: ts.notImplemented,
+ isDeclarationWithCollidingName: ts.notImplemented,
+ isValueAliasDeclaration: ts.notImplemented,
+ isReferencedAliasDeclaration: ts.notImplemented,
+ isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
+ getNodeCheckFlags: ts.notImplemented,
+ isDeclarationVisible: ts.notImplemented,
+ isLateBound: function (_node) { return false; },
+ collectLinkedAliases: ts.notImplemented,
+ isImplementationOfOverload: ts.notImplemented,
+ isRequiredInitializedParameter: ts.notImplemented,
+ isOptionalUninitializedParameterProperty: ts.notImplemented,
+ isExpandoFunctionDeclaration: ts.notImplemented,
+ getPropertiesOfContainerFunction: ts.notImplemented,
+ createTypeOfDeclaration: ts.notImplemented,
+ createReturnTypeOfSignatureDeclaration: ts.notImplemented,
+ createTypeOfExpression: ts.notImplemented,
+ createLiteralConstValue: ts.notImplemented,
+ isSymbolAccessible: ts.notImplemented,
+ isEntityNameVisible: ts.notImplemented,
+ // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
+ getConstantValue: ts.notImplemented,
+ getReferencedValueDeclaration: ts.notImplemented,
+ getTypeReferenceSerializationKind: ts.notImplemented,
+ isOptionalParameter: ts.notImplemented,
+ moduleExportsSomeValue: ts.notImplemented,
+ isArgumentsLocalBinding: ts.notImplemented,
+ getExternalModuleFileFromDeclaration: ts.notImplemented,
+ getTypeReferenceDirectivesForEntityName: ts.notImplemented,
+ getTypeReferenceDirectivesForSymbol: ts.notImplemented,
+ isLiteralConstDeclaration: ts.notImplemented,
+ getJsxFactoryEntity: ts.notImplemented,
+ getAllAccessorDeclarations: ts.notImplemented,
+ getSymbolOfExternalModuleSpecifier: ts.notImplemented,
+ isBindingCapturedByNode: ts.notImplemented,
+ };
+ function createSourceFilesFromBundleBuildInfo(bundle) {
+ var sourceFiles = bundle.sourceFiles.map(function (fileName) {
+ var sourceFile = ts.createNode(284 /* SourceFile */, 0, 0);
+ sourceFile.fileName = fileName;
+ sourceFile.text = "";
+ sourceFile.statements = ts.createNodeArray();
+ return sourceFile;
+ });
+ var jsBundle = ts.Debug.assertDefined(bundle.js);
+ ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
+ var sourceFile = sourceFiles[prologueInfo.file];
+ sourceFile.text = prologueInfo.text;
+ sourceFile.end = prologueInfo.text.length;
+ sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
+ var statement = ts.createNode(221 /* ExpressionStatement */, directive.pos, directive.end);
+ statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
+ statement.expression.text = directive.expression.text;
+ return statement;
+ }));
+ });
+ return sourceFiles;
+ }
+ /*@internal*/
+ function emitUsingBuildInfo(config, host, getCommandLine) {
+ var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
+ var buildInfoText = host.readFile(ts.Debug.assertDefined(buildInfoPath));
+ if (!buildInfoText)
+ return buildInfoPath;
+ var jsFileText = host.readFile(ts.Debug.assertDefined(jsFilePath));
+ if (!jsFileText)
+ return jsFilePath;
+ var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
+ // error if no source map or for now if inline sourcemap
+ if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
+ return sourceMapFilePath || "inline sourcemap decoding";
+ // read declaration text
+ var declarationText = declarationFilePath && host.readFile(declarationFilePath);
+ if (declarationFilePath && !declarationText)
+ return declarationFilePath;
+ var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
+ // error if no source map or for now if inline sourcemap
+ if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
+ return declarationMapPath || "inline sourcemap decoding";
+ var buildInfo = getBuildInfo(buildInfoText);
+ if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
+ return buildInfoPath;
+ var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo,
+ /*onlyOwnText*/ true);
+ var outputFiles = [];
+ var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
+ var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle);
+ var emitHost = {
+ getPrependNodes: ts.memoize(function () { return prependNodes.concat([ownPrependInput]); }),
+ getCanonicalFileName: host.getCanonicalFileName,
+ getCommonSourceDirectory: function () { return buildInfo.bundle.commonSourceDirectory; },
+ getCompilerOptions: function () { return config.options; },
+ getCurrentDirectory: function () { return host.getCurrentDirectory(); },
+ getNewLine: function () { return host.getNewLine(); },
+ getSourceFile: function () { return undefined; },
+ getSourceFileByPath: function () { return undefined; },
+ getSourceFiles: function () { return sourceFilesForJsEmit; },
+ getLibFileFromReference: ts.notImplemented,
+ isSourceFileFromExternalLibrary: ts.returnFalse,
+ writeFile: function (name, text, writeByteOrderMark) {
+ switch (name) {
+ case jsFilePath:
+ if (jsFileText === text)
+ return;
+ break;
+ case sourceMapFilePath:
+ if (sourceMapText === text)
+ return;
+ break;
+ case buildInfoPath:
+ var newBuildInfo = getBuildInfo(text);
+ newBuildInfo.program = buildInfo.program;
+ // Update sourceFileInfo
+ var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
+ newBuildInfo.bundle.js.sources = js.sources;
+ if (dts) {
+ newBuildInfo.bundle.dts.sources = dts.sources;
+ }
+ newBuildInfo.bundle.sourceFiles = sourceFiles;
+ outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
+ return;
+ case declarationFilePath:
+ if (declarationText === text)
+ return;
+ break;
+ case declarationMapPath:
+ if (declarationMapText === text)
+ return;
+ break;
+ default:
+ ts.Debug.fail("Unexpected path: " + name);
+ }
+ outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
+ },
+ isEmitBlocked: ts.returnFalse,
+ readFile: function (f) { return host.readFile(f); },
+ fileExists: function (f) { return host.fileExists(f); },
+ directoryExists: host.directoryExists && (function (f) { return host.directoryExists(f); }),
+ useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
+ getProgramBuildInfo: function () { return undefined; }
+ };
+ emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, /*emitOnlyDtsFiles*/ false, ts.getTransformers(config.options));
+ return outputFiles;
+ }
+ ts.emitUsingBuildInfo = emitUsingBuildInfo;
var PipelinePhase;
(function (PipelinePhase) {
PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
@@ -82737,6 +83396,10 @@ var ts;
var ownWriter; // Reusable `EmitTextWriter` for basic printing.
var write = writeBase;
var isOwnFileEmit;
+ var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
+ var recordInternalSection = printerOptions.recordInternalSection;
+ var sourceFileTextPos = 0;
+ var sourceFileTextKind = "text" /* Text */;
// Source Maps
var sourceMapsDisabled = true;
var sourceMapGenerator;
@@ -82762,7 +83425,8 @@ var ts;
writeNode: writeNode,
writeList: writeList,
writeFile: writeFile,
- writeBundle: writeBundle
+ writeBundle: writeBundle,
+ bundleFileInfo: bundleFileInfo
};
function printNode(hint, node, sourceFile) {
switch (hint) {
@@ -82777,9 +83441,9 @@ var ts;
break;
}
switch (node.kind) {
- case 279 /* SourceFile */: return printFile(node);
- case 280 /* Bundle */: return printBundle(node);
- case 281 /* UnparsedSource */: return printUnparsedSource(node);
+ case 284 /* SourceFile */: return printFile(node);
+ case 285 /* Bundle */: return printBundle(node);
+ case 286 /* UnparsedSource */: return printUnparsedSource(node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
@@ -82789,7 +83453,7 @@ var ts;
return endPrint();
}
function printBundle(bundle) {
- writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined);
+ writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
return endPrint();
}
function printFile(sourceFile) {
@@ -82817,7 +83481,49 @@ var ts;
reset();
writer = previousWriter;
}
- function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) {
+ function getTextPosWithWriteLine() {
+ return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
+ }
+ function updateOrPushBundleFileTextLike(pos, end, kind) {
+ var last = ts.lastOrUndefined(bundleFileInfo.sections);
+ if (last && last.kind === kind) {
+ last.end = end;
+ }
+ else {
+ bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
+ }
+ }
+ function recordBundleFileInternalSectionStart(node) {
+ if (recordInternalSection &&
+ bundleFileInfo &&
+ currentSourceFile &&
+ (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
+ ts.isInternalDeclaration(node, currentSourceFile) &&
+ sourceFileTextKind !== "internal" /* Internal */) {
+ var prevSourceFileTextKind = sourceFileTextKind;
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = "internal" /* Internal */;
+ return prevSourceFileTextKind;
+ }
+ return undefined;
+ }
+ function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
+ if (prevSourceFileTextKind) {
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = prevSourceFileTextKind;
+ }
+ }
+ function recordBundleFileTextLikeSection(end) {
+ if (sourceFileTextPos < end) {
+ updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
+ return true;
+ }
+ return false;
+ }
+ function writeBundle(bundle, output, sourceMapGenerator) {
+ var _a;
isOwnFileEmit = false;
var previousWriter = writer;
setWriter(output, sourceMapGenerator);
@@ -82825,18 +83531,49 @@ var ts;
emitPrologueDirectivesIfNeeded(bundle);
emitHelpers(bundle);
emitSyntheticTripleSlashReferencesIfNeeded(bundle);
- for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) {
- var prepend = _b[_a];
+ for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
+ var prepend = _c[_b];
writeLine();
+ var pos = writer.getTextPos();
+ var savedSections = bundleFileInfo && bundleFileInfo.sections;
+ if (savedSections)
+ bundleFileInfo.sections = [];
print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
+ if (bundleFileInfo) {
+ var newSections = bundleFileInfo.sections;
+ bundleFileInfo.sections = savedSections;
+ if (prepend.oldFileOfCurrentEmit)
+ (_a = bundleFileInfo.sections).push.apply(_a, newSections);
+ else {
+ newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prepend" /* Prepend */, data: prepend.fileName, texts: newSections });
+ }
+ }
}
- if (bundleInfo) {
- bundleInfo.originalOffset = writer.getTextPos();
- }
- for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) {
- var sourceFile = _d[_c];
+ sourceFileTextPos = getTextPosWithWriteLine();
+ for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
+ var sourceFile = _e[_d];
print(0 /* SourceFile */, sourceFile, sourceFile);
}
+ if (bundleFileInfo && bundle.sourceFiles.length) {
+ var end = writer.getTextPos();
+ if (recordBundleFileTextLikeSection(end)) {
+ // Store prologues
+ var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
+ if (prologues) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.prologues = prologues;
+ }
+ // Store helpes
+ var helpers = getHelpersFromBundledSourceFiles(bundle);
+ if (helpers) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.helpers = helpers;
+ }
+ }
+ }
reset();
writer = previousWriter;
}
@@ -82906,8 +83643,10 @@ var ts;
function emit(node) {
if (node === undefined)
return;
+ var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
var pipelinePhase = getPipelinePhase(0 /* Notification */, node);
pipelinePhase(4 /* Unspecified */, node);
+ recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
}
function emitIdentifierName(node) {
if (node === undefined)
@@ -82934,12 +83673,12 @@ var ts;
}
// falls through
case 2 /* Comments */:
- if (!commentsDisabled && node.kind !== 279 /* SourceFile */) {
+ if (!commentsDisabled && node.kind !== 284 /* SourceFile */) {
return pipelineEmitWithComments;
}
// falls through
case 3 /* SourceMaps */:
- if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) {
+ if (!sourceMapsDisabled && node.kind !== 284 /* SourceFile */ && !ts.isInJsonFile(node)) {
return pipelineEmitWithSourceMap;
}
// falls through
@@ -82976,8 +83715,16 @@ var ts;
case 16 /* TemplateMiddle */:
case 17 /* TemplateTail */:
return emitLiteral(node);
- case 281 /* UnparsedSource */:
- return emitUnparsedSource(node);
+ case 286 /* UnparsedSource */:
+ case 280 /* UnparsedPrepend */:
+ return emitUnparsedSourceOrPrepend(node);
+ case 279 /* UnparsedPrologue */:
+ return writeUnparsedNode(node);
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return emitUnparsedTextLike(node);
+ case 283 /* UnparsedSyntheticReference */:
+ return emitUnparsedSyntheticReference(node);
// Identifiers
case 72 /* Identifier */:
return emitIdentifier(node);
@@ -83021,7 +83768,7 @@ var ts;
return emitTypeReference(node);
case 165 /* FunctionType */:
return emitFunctionType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return emitJSDocFunctionType(node);
case 166 /* ConstructorType */:
return emitConstructorType(node);
@@ -83059,20 +83806,20 @@ var ts;
return emitLiteralType(node);
case 183 /* ImportType */:
return emitImportTypeNode(node);
- case 284 /* JSDocAllType */:
+ case 289 /* JSDocAllType */:
writePunctuation("*");
return;
- case 285 /* JSDocUnknownType */:
+ case 290 /* JSDocUnknownType */:
writePunctuation("?");
return;
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return emitJSDocNullableType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return emitJSDocNonNullableType(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return emitJSDocOptionalType(node);
case 172 /* RestType */:
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return emitRestOrJSDocVariadicType(node);
// Binding patterns
case 184 /* ObjectBindingPattern */:
@@ -83210,30 +83957,30 @@ var ts;
case 278 /* EnumMember */:
return emitEnumMember(node);
// JSDoc nodes (only used in codefixes currently)
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return emitJSDocPropertyLikeTag(node);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return emitJSDocSimpleTypedTag(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return emitJSDocAugmentsTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return emitJSDocTemplateTag(node);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return emitJSDocTypedefTag(node);
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return emitJSDocCallbackTag(node);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return emitJSDocSignature(node);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return emitJSDocTypeLiteral(node);
- case 296 /* JSDocClassTag */:
- case 294 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
return emitJSDocSimpleTag(node);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return emitJSDoc(node);
// Transformation nodes (ignored)
}
@@ -83332,9 +84079,9 @@ var ts;
case 264 /* JsxFragment */:
return emitJsxFragment(node);
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return emitPartiallyEmittedExpression(node);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return emitCommaList(node);
}
}
@@ -83350,22 +84097,45 @@ var ts;
var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node);
pipelinePhase(hint, substituteNode(hint, node));
}
+ function getHelpersFromBundledSourceFiles(bundle) {
+ var result;
+ if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
+ return undefined;
+ }
+ var bundledHelpers = ts.createMap();
+ for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
+ var sourceFile = _b[_a];
+ var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
+ var helpers = getSortedEmitHelpers(sourceFile);
+ if (!helpers)
+ continue;
+ for (var _c = 0, helpers_3 = helpers; _c < helpers_3.length; _c++) {
+ var helper = helpers_3[_c];
+ if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
+ bundledHelpers.set(helper.name, true);
+ (result || (result = [])).push(helper.name);
+ }
+ }
+ }
+ return result;
+ }
function emitHelpers(node) {
var helpersEmitted = false;
- var bundle = node.kind === 280 /* Bundle */ ? node : undefined;
+ var bundle = node.kind === 285 /* Bundle */ ? node : undefined;
if (bundle && moduleKind === ts.ModuleKind.None) {
return;
}
- var numNodes = bundle ? bundle.sourceFiles.length : 1;
+ var numPrepends = bundle ? bundle.prepends.length : 0;
+ var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
for (var i = 0; i < numNodes; i++) {
- var currentNode = bundle ? bundle.sourceFiles[i] : node;
- var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile;
- var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined;
- var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit;
- var helpers = ts.getEmitHelpers(currentNode);
+ var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
+ var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
+ var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined);
+ var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
+ var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
if (helpers) {
- for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) {
- var helper = _b[_a];
+ for (var _a = 0, helpers_4 = helpers; _a < helpers_4.length; _a++) {
+ var helper = helpers_4[_a];
if (!helper.scoped) {
// Skip the helper if it can be skipped and the noEmitHelpers compiler
// option is set, or if it can be imported and the importHelpers compiler
@@ -83385,18 +84155,25 @@ var ts;
// Skip the helper if it is scoped and we are emitting bundled helpers
continue;
}
+ var pos = getTextPosWithWriteLine();
if (typeof helper.text === "string") {
writeLines(helper.text);
}
else {
writeLines(helper.text(makeFileLevelOptimisticUniqueName));
}
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
helpersEmitted = true;
}
}
}
return helpersEmitted;
}
+ function getSortedEmitHelpers(node) {
+ var helpers = ts.getEmitHelpers(node);
+ return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
+ }
//
// Literals/Pseudo-literals
//
@@ -83423,8 +84200,42 @@ var ts;
}
}
// SyntaxKind.UnparsedSource
- function emitUnparsedSource(unparsed) {
- writer.rawWrite(unparsed.text);
+ // SyntaxKind.UnparsedPrepend
+ function emitUnparsedSourceOrPrepend(unparsed) {
+ for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
+ var text = _b[_a];
+ writeLine();
+ emit(text);
+ }
+ }
+ // SyntaxKind.UnparsedPrologue
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ // SyntaxKind.UnparsedSyntheticReference
+ function writeUnparsedNode(unparsed) {
+ writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
+ }
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ function emitUnparsedTextLike(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 281 /* UnparsedText */ ?
+ "text" /* Text */ :
+ "internal" /* Internal */);
+ }
+ }
+ // SyntaxKind.UnparsedSyntheticReference
+ function emitUnparsedSyntheticReference(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ var section = ts.clone(unparsed.section);
+ section.pos = pos;
+ section.end = writer.getTextPos();
+ bundleFileInfo.sections.push(section);
+ }
}
//
// Identifiers
@@ -83479,7 +84290,7 @@ var ts;
emit(node.dotDotDotToken);
emitNodeWithWriter(node.name, writeParameter);
emit(node.questionToken);
- if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) {
+ if (node.parent && node.parent.kind === 294 /* JSDocFunctionType */ && !node.name) {
emit(node.type);
}
else {
@@ -84359,7 +85170,7 @@ var ts;
}
function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
// Emit all the prologue directives (like "use strict").
- var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true);
+ var statementOffset = emitPrologueDirectives(body.statements);
var pos = writer.getTextPos();
emitHelpers(body);
if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
@@ -84764,7 +85575,7 @@ var ts;
}
}
if (node.tags) {
- if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) {
+ if (node.tags.length === 1 && node.tags[0].kind === 307 /* JSDocTypeTag */ && !node.comment) {
writeSpace();
emit(node.tags[0]);
}
@@ -84798,7 +85609,7 @@ var ts;
function emitJSDocTypedefTag(tag) {
emitJSDocTagName(tag.tagName);
if (tag.typeExpression) {
- if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
emitJSDocTypeExpression(tag.typeExpression);
}
else {
@@ -84817,7 +85628,7 @@ var ts;
emit(tag.fullName);
}
emitJSDocComment(tag.comment);
- if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) {
+ if (tag.typeExpression && tag.typeExpression.kind === 297 /* JSDocTypeLiteral */) {
emitJSDocTypeLiteral(tag.typeExpression);
}
}
@@ -84904,6 +85715,16 @@ var ts;
}
function emitSyntheticTripleSlashReferencesIfNeeded(node) {
emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
+ for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
+ for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
+ var ref = _d[_c];
+ emit(ref);
+ writeLine();
+ }
+ }
+ }
}
function emitTripleSlashDirectivesIfNeeded(node) {
if (node.isDeclarationFile)
@@ -84911,7 +85732,10 @@ var ts;
}
function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
if (hasNoDefaultLib) {
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
writeLine();
}
if (currentSourceFile && currentSourceFile.moduleName) {
@@ -84932,17 +85756,26 @@ var ts;
}
for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
var directive = files_1[_c];
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
writeLine();
}
for (var _d = 0, types_19 = types; _d < types_19.length; _d++) {
var directive = types_19[_d];
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
writeLine();
}
for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
var directive = libs_1[_e];
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
writeLine();
}
}
@@ -84967,16 +85800,22 @@ var ts;
* Emits any prologue directives at the start of a Statement list, returning the
* number of prologue directives written to the output.
*/
- function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) {
+ function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
+ var needsToSetSourceFile = !!sourceFile;
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (ts.isPrologueDirective(statement)) {
var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
if (shouldEmitPrologueDirective) {
- if (startWithNewLine || i > 0) {
- writeLine();
+ if (needsToSetSourceFile) {
+ needsToSetSourceFile = false;
+ setSourceFile(sourceFile);
}
+ writeLine();
+ var pos = writer.getTextPos();
emit(statement);
+ if (recordBundleFileSection && bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
if (seenPrologueDirectives) {
seenPrologueDirectives.set(statement.expression.text, true);
}
@@ -84989,23 +85828,70 @@ var ts;
}
return statements.length;
}
+ function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
+ for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
+ var prologue = prologues_1[_a];
+ if (!seenPrologueDirectives.has(prologue.data)) {
+ writeLine();
+ var pos = writer.getTextPos();
+ emit(prologue);
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
+ if (seenPrologueDirectives) {
+ seenPrologueDirectives.set(prologue.data, true);
+ }
+ }
+ }
+ }
function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
if (ts.isSourceFile(sourceFileOrBundle)) {
- setSourceFile(sourceFileOrBundle);
- emitPrologueDirectives(sourceFileOrBundle.statements);
+ emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
}
else {
var seenPrologueDirectives = ts.createMap();
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
- setSourceFile(sourceFile);
- emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives);
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
+ emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
}
setSourceFile(undefined);
}
}
+ function getPrologueDirectivesFromBundledSourceFiles(bundle) {
+ var seenPrologueDirectives = ts.createMap();
+ var prologues;
+ for (var index = 0; index < bundle.sourceFiles.length; index++) {
+ var sourceFile = bundle.sourceFiles[index];
+ var directives = void 0;
+ var end = 0;
+ for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
+ var statement = _b[_a];
+ if (!ts.isPrologueDirective(statement))
+ break;
+ if (seenPrologueDirectives.has(statement.expression.text))
+ continue;
+ seenPrologueDirectives.set(statement.expression.text, true);
+ (directives || (directives = [])).push({
+ pos: statement.pos,
+ end: statement.end,
+ expression: {
+ pos: statement.expression.pos,
+ end: statement.expression.end,
+ text: statement.expression.text
+ }
+ });
+ end = end < statement.end ? statement.end : end;
+ }
+ if (directives)
+ (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
+ }
+ return prologues;
+ }
function emitShebangIfNeeded(sourceFileOrBundle) {
- if (ts.isSourceFile(sourceFileOrBundle)) {
+ if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
var shebang = ts.getShebang(sourceFileOrBundle.text);
if (shebang) {
writeComment(shebang);
@@ -85014,11 +85900,18 @@ var ts;
}
}
else {
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ ts.Debug.assertNode(prepend, ts.isUnparsedSource);
+ if (emitShebangIfNeeded(prepend)) {
+ return true;
+ }
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
// Emit only the first encountered shebang
if (emitShebangIfNeeded(sourceFile)) {
- break;
+ return true;
}
}
}
@@ -85221,6 +86114,7 @@ var ts;
}
// Emit each child.
var previousSibling = void 0;
+ var previousSourceFileTextKind = void 0;
var shouldDecreaseIndentAfterEmit = false;
for (var i = 0; i < count; i++) {
var child = children[start + i];
@@ -85241,6 +86135,7 @@ var ts;
emitLeadingCommentsOfPosition(previousSibling.end);
}
writeDelimiter(format);
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write either a line terminator or whitespace to separate the elements.
if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) {
// If a synthesized node in a single-line list starts on a new
@@ -85257,6 +86152,7 @@ var ts;
}
}
// Emit this child.
+ previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
if (shouldEmitInterveningComments) {
if (emitTrailingCommentsOfPosition) {
var commentRange = ts.getCommentRange(child);
@@ -85291,6 +86187,7 @@ var ts;
if (format & 128 /* Indented */) {
decreaseIndent();
}
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write the closing line terminator or closing whitespace.
if (shouldWriteClosingLineTerminator(parentNode, children, format)) {
writeLine();
@@ -85392,7 +86289,6 @@ var ts;
if (line.length) {
writeLine();
write(line);
- writer.rawWrite(newLine);
}
}
}
@@ -85906,7 +86802,7 @@ var ts;
hasWrittenComment = false;
var emitFlags = ts.getEmitFlags(node);
var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
- var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */;
+ var isEmittedNode = node.kind !== 312 /* NotEmittedStatement */;
// We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
// It is expensive to walk entire tree just to set one kind of node to have no comments.
var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
@@ -86166,19 +87062,28 @@ var ts;
return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
}
// Source Maps
+ function getParsedSourceMap(node) {
+ if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
+ node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
+ }
+ return node.parsedSourceMap || undefined;
+ }
function pipelineEmitWithSourceMap(hint, node) {
var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node);
- if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) {
- var parsed = ts.tryParseRawSourceMap(node.sourceMapText);
- if (parsed) {
- sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath);
+ if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
+ pipelinePhase(hint, node);
+ }
+ else if (ts.isUnparsedNode(node)) {
+ var parsed = getParsedSourceMap(node.parent);
+ if (parsed && sourceMapGenerator) {
+ sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
}
pipelinePhase(hint, node);
}
else {
var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
var emitFlags = ts.getEmitFlags(node);
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 16 /* NoLeadingSourceMap */) === 0
&& pos >= 0) {
emitSourcePos(source, skipSourceTrivia(source, pos));
@@ -86191,7 +87096,7 @@ var ts;
else {
pipelinePhase(hint, node);
}
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 32 /* NoTrailingSourceMap */) === 0
&& end >= 0) {
emitSourcePos(source, end);
@@ -86839,7 +87744,8 @@ var ts;
var value = readFileCache.get(key);
if (value !== undefined)
return value !== false ? value : undefined; // could be .d.ts from output
- if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) {
+ // Cache json or buildInfo
+ if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
return originalReadFile.call(host, fileName);
}
return setReadFileCache(key, fileName);
@@ -86870,7 +87776,7 @@ var ts;
var key = toPath(fileName);
fileExistsCache.delete(key);
var value = readFileCache.get(key);
- if (value && value !== data) {
+ if (value !== undefined && value !== data) {
readFileCache.delete(key);
sourceFileCache.delete(key);
}
@@ -87425,7 +88331,8 @@ var ts;
getProjectReferenceRedirect: getProjectReferenceRedirect,
getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
- forEachResolvedProjectReference: forEachResolvedProjectReference
+ forEachResolvedProjectReference: forEachResolvedProjectReference,
+ emitBuildInfo: emitBuildInfo
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -87852,7 +88759,20 @@ var ts;
return false;
// Before falling back to the host
return host.fileExists(f);
- } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } });
+ } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); } });
+ }
+ function emitBuildInfo(writeFileCallback) {
+ ts.Debug.assert(!options.out && !options.outFile);
+ ts.performance.mark("beforeEmit");
+ var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback),
+ /*targetSourceFile*/ undefined,
+ /*emitOnlyDtsFiles*/ false,
+ /*transformers*/ undefined,
+ /*declaraitonTransformers*/ undefined,
+ /*onlyBuildInfo*/ true);
+ ts.performance.mark("afterEmit");
+ ts.performance.measure("Emit", "beforeEmit", "afterEmit");
+ return emitResult;
}
function getResolvedProjectReferences() {
return resolvedProjectReferences;
@@ -87861,28 +88781,11 @@ var ts;
return projectReferences;
}
function getPrependNodes() {
- if (!projectReferences) {
- return ts.emptyArray;
- }
- var nodes = [];
- for (var i = 0; i < projectReferences.length; i++) {
- var ref = projectReferences[i];
- var resolvedRefOpts = resolvedProjectReferences[i].commandLine;
- if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
- var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
- // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
- if (!out)
- continue;
- var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
- var node = ts.createInputFiles(function (fileName) {
- var path = toPath(fileName);
- var sourceFile = getSourceFileByPath(path);
- return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
- }, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath);
- nodes.push(node);
- }
- }
- return nodes;
+ return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
+ var path = toPath(fileName);
+ var sourceFile = getSourceFileByPath(path);
+ return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
+ });
}
function isSourceFileFromExternalLibrary(file) {
return !!sourceFilesFoundSearchingNodeModules.get(file.path);
@@ -87954,8 +88857,7 @@ var ts;
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
ts.performance.mark("beforeEmit");
var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers);
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217
- emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -88957,6 +89859,14 @@ var ts;
if (options.declaration === false) {
createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
}
+ if (options.incremental === false) {
+ createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
+ }
+ }
+ if (options.tsBuildInfoFile) {
+ if (!ts.isIncrementalCompilation(options)) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
+ }
}
verifyProjectReferences();
// List of collected files is complete; validate exhautiveness if this is a project with a file list
@@ -89151,6 +90061,7 @@ var ts;
}
}
function verifyProjectReferences() {
+ var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getOutputPathForBuildInfo(options) : undefined;
forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
var parentFile = parent && parent.sourceFile;
@@ -89177,6 +90088,10 @@ var ts;
createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
}
}
+ if (!parent && buildInfoPath && buildInfoPath === ts.getOutputPathForBuildInfo(options)) {
+ createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
+ hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
+ }
});
}
function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
@@ -89326,6 +90241,27 @@ var ts;
};
}
ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
+ /* @internal */
+ function createPrependNodes(projectReferences, getCommandLine, readFile) {
+ if (!projectReferences)
+ return ts.emptyArray;
+ var nodes;
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = getCommandLine(ref, i);
+ if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
+ var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
+ // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
+ if (!out)
+ continue;
+ var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
+ (nodes || (nodes = [])).push(node);
+ }
+ }
+ return nodes || ts.emptyArray;
+ }
+ ts.createPrependNodes = createPrependNodes;
function resolveProjectReferencePath(hostOrRef, ref) {
var passedInRef = ref ? ref : hostOrRef;
return ts.resolveConfigFileProjectName(passedInRef.path);
@@ -89869,11 +90805,14 @@ var ts;
var affectedSignatures = oldState.currentAffectedFilesSignatures;
ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
}
+ var changedFilesSet = oldState.changedFilesSet;
if (canCopySemanticDiagnostics) {
- ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
+ ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
}
// Copy old state's changed files set
- ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet);
+ if (changedFilesSet) {
+ ts.copyEntries(changedFilesSet, state.changedFilesSet);
+ }
if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit;
state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
@@ -89911,7 +90850,7 @@ var ts;
// Unchanged file copy diagnostics
var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
if (diagnostics) {
- state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics);
+ state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics);
if (!state.semanticDiagnosticsFromOldState) {
state.semanticDiagnosticsFromOldState = ts.createMap();
}
@@ -89919,8 +90858,45 @@ var ts;
}
}
});
+ if (oldCompilerOptions &&
+ (oldCompilerOptions.outDir !== compilerOptions.outDir ||
+ oldCompilerOptions.declarationDir !== compilerOptions.declarationDir ||
+ (oldCompilerOptions.outFile || oldCompilerOptions.out) !== (compilerOptions.outFile || compilerOptions.out))) {
+ // Add all files to affectedFilesPendingEmit since emit changed
+ state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, newProgram.getSourceFiles().map(function (f) { return f.path; }));
+ if (state.affectedFilesPendingEmitIndex === undefined) {
+ state.affectedFilesPendingEmitIndex = 0;
+ }
+ ts.Debug.assert(state.seenAffectedFiles === undefined);
+ state.seenAffectedFiles = ts.createMap();
+ }
return state;
}
+ function convertToDiagnostics(diagnostics, newProgram) {
+ if (!diagnostics.length)
+ return ts.emptyArray;
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToDiagnosticRelatedInformation(diagnostic, newProgram) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && newProgram.getSourceFileByPath(file), messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToDiagnosticMessageChain(messageText, newProgram) });
+ }
+ function convertToDiagnosticMessageChain(diagnostic, newProgram) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToDiagnosticMessageChain(diagnostic.next, newProgram) });
+ }
/**
* Releases program and other related not needed properties
*/
@@ -90140,8 +91116,11 @@ var ts;
* This is called after completing operation on the next affected file.
* The operations here are postponed to ensure that cancellation during the iteration is handled correctly
*/
- function doneWithAffectedFile(state, affected, isPendingEmit) {
- if (affected === state.program) {
+ function doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit) {
+ if (isBuildInfoEmit) {
+ state.emittedBuildInfo = true;
+ }
+ else if (affected === state.program) {
state.changedFilesSet.clear();
state.programEmitComplete = true;
}
@@ -90158,8 +91137,8 @@ var ts;
/**
* Returns the result with affected file
*/
- function toAffectedFileResult(state, result, affected, isPendingEmit) {
- doneWithAffectedFile(state, affected, isPendingEmit);
+ function toAffectedFileResult(state, result, affected, isPendingEmit, isBuildInfoEmit) {
+ doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit);
return { result: result, affected: affected };
}
/**
@@ -90182,6 +91161,77 @@ var ts;
}
return diagnostics;
}
+ /**
+ * Gets the program information to be emitted in buildInfo so that we can use it to create new program
+ */
+ function getProgramBuildInfo(state) {
+ if (state.compilerOptions.outFile || state.compilerOptions.out)
+ return undefined;
+ var fileInfos = {};
+ state.fileInfos.forEach(function (value, key) {
+ var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
+ fileInfos[key] = signature === undefined ? value : { version: value.version, signature: signature };
+ });
+ var result = { fileInfos: fileInfos, options: state.compilerOptions };
+ if (state.referencedMap) {
+ var referencedMap_1 = {};
+ state.referencedMap.forEach(function (value, key) {
+ referencedMap_1[key] = ts.arrayFrom(value.keys());
+ });
+ result.referencedMap = referencedMap_1;
+ }
+ if (state.exportedModulesMap) {
+ var exportedModulesMap_1 = {};
+ state.exportedModulesMap.forEach(function (value, key) {
+ var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
+ // Not in temporary cache, use existing value
+ if (newValue === undefined)
+ exportedModulesMap_1[key] = ts.arrayFrom(value.keys());
+ // Value in cache and has updated value map, use that
+ else if (newValue)
+ exportedModulesMap_1[key] = ts.arrayFrom(newValue.keys());
+ });
+ result.exportedModulesMap = exportedModulesMap_1;
+ }
+ if (state.semanticDiagnosticsPerFile) {
+ var semanticDiagnosticsPerFile_1 = [];
+ // Currently not recording actual errors since those mean no emit for tsc --build
+ state.semanticDiagnosticsPerFile.forEach(function (value, key) { return semanticDiagnosticsPerFile_1.push(value.length ?
+ [
+ key,
+ state.hasReusableDiagnostic ?
+ value :
+ convertToReusableDiagnostics(value)
+ ] :
+ key); });
+ result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile_1;
+ }
+ return result;
+ }
+ function convertToReusableDiagnostics(diagnostics) {
+ ts.Debug.assert(!!diagnostics.length);
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToReusableDiagnosticRelatedInformation(diagnostic);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToReusableDiagnosticRelatedInformation(diagnostic) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && file.path, messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToReusableDiagnosticMessageChain(messageText) });
+ }
+ function convertToReusableDiagnosticMessageChain(diagnostic) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToReusableDiagnosticMessageChain(diagnostic.next) });
+ }
var BuilderProgramKind;
(function (BuilderProgramKind) {
BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
@@ -90238,6 +91288,7 @@ var ts;
var computeHash = host.createHash || ts.generateDjb2Hash;
var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
var backupState;
+ newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state); };
// To ensure that we arent storing any references to old program or new program without state
newProgram = undefined; // TODO: GH#18217
oldProgram = undefined;
@@ -90281,7 +91332,16 @@ var ts;
if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
affected = getNextAffectedFilePendingEmit(state);
if (!affected) {
- return undefined;
+ if (state.emittedBuildInfo) {
+ return undefined;
+ }
+ var affected_1 = ts.Debug.assertDefined(state.program);
+ return toAffectedFileResult(state,
+ // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
+ // Otherwise just affected file
+ affected_1.emitBuildInfo(writeFile || host.writeFile, cancellationToken), affected_1,
+ /*isPendingEmitFile*/ false,
+ /*isBuildInfoEmit*/ true);
}
isPendingEmitFile = true;
}
@@ -90414,6 +91474,53 @@ var ts;
}
}
ts.createBuilderProgram = createBuilderProgram;
+ function getMapOfReferencedSet(mapLike) {
+ if (!mapLike)
+ return undefined;
+ var map = ts.createMap();
+ // Copies keys/values from template. Note that for..in will not throw if
+ // template is undefined, and instead will just exit the loop.
+ for (var key in mapLike) {
+ if (ts.hasProperty(mapLike, key)) {
+ map.set(key, ts.arrayToSet(mapLike[key]));
+ }
+ }
+ return map;
+ }
+ function createBuildProgramUsingProgramBuildInfo(program) {
+ var fileInfos = ts.createMapFromTemplate(program.fileInfos);
+ var state = {
+ fileInfos: fileInfos,
+ compilerOptions: program.options,
+ referencedMap: getMapOfReferencedSet(program.referencedMap),
+ exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap),
+ semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return ts.isString(value) ? value : value[0]; }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }),
+ hasReusableDiagnostic: true
+ };
+ return {
+ getState: function () { return state; },
+ backupState: ts.noop,
+ restoreState: ts.noop,
+ getProgram: ts.notImplemented,
+ getProgramOrUndefined: function () { return undefined; },
+ releaseProgram: ts.noop,
+ getCompilerOptions: function () { return state.compilerOptions; },
+ getSourceFile: ts.notImplemented,
+ getSourceFiles: ts.notImplemented,
+ getOptionsDiagnostics: ts.notImplemented,
+ getGlobalDiagnostics: ts.notImplemented,
+ getConfigFileParsingDiagnostics: ts.notImplemented,
+ getSyntacticDiagnostics: ts.notImplemented,
+ getDeclarationDiagnostics: ts.notImplemented,
+ getSemanticDiagnostics: ts.notImplemented,
+ emit: ts.notImplemented,
+ getAllDependencies: ts.notImplemented,
+ getCurrentDirectory: ts.notImplemented,
+ emitNextAffectedFile: ts.notImplemented,
+ getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
+ };
+ }
+ ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
return {
getState: ts.notImplemented,
@@ -90433,7 +91540,7 @@ var ts;
getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
getAllDependencies: ts.notImplemented,
- getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); }
+ getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
};
function getProgram() {
return ts.Debug.assertDefined(state.program);
@@ -90459,10 +91566,10 @@ var ts;
/*@internal*/
var ts;
(function (ts) {
- function isPathInNodeModulesStartingWithDot(path) {
- return ts.stringContains(path, "/node_modules/.");
+ function isPathIgnored(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); });
}
- ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot;
+ ts.isPathIgnored = isPathIgnored;
ts.maxNumberOfFilesToIterateForInvalidation = 256;
function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
var filesWithChangedSetOfUnresolvedImports;
@@ -90984,7 +92091,7 @@ var ts;
}
else {
// If something to do with folder/file starting with "." in node_modules folder, skip it
- if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (isPathIgnored(fileOrDirectoryPath))
return false;
// Some file or directory in the watching directory is created
// Return early if it does not have any of the watching extension or not the custom failed lookup path
@@ -91461,6 +92568,8 @@ var ts;
case ".jsx" /* Jsx */:
case ".json" /* Json */:
return ext;
+ case ".tsbuildinfo" /* TsBuildInfo */:
+ return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
default:
return ts.Debug.assertNever(ext);
}
@@ -91742,7 +92851,7 @@ var ts;
writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; },
createHash: ts.maybeBind(system, system.createHash),
- createProgram: createProgram
+ createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
};
}
ts.createProgramHost = createProgramHost;
@@ -91752,7 +92861,7 @@ var ts;
function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
var writeFileName = function (s) { return system.write(s + system.newLine); };
- var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram);
+ var result = createProgramHost(system, createProgram);
ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
result.afterProgramCreate = function (builderProgram) {
var compilerOptions = builderProgram.getCompilerOptions();
@@ -92181,7 +93290,7 @@ var ts;
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
nextSourceFileVersion(fileOrDirectoryPath);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
// If the the added or created file or directory is not supported file name, ignore the file
// But when watched directory is added/removed, we need to reload the file list
@@ -92235,16 +93344,23 @@ var ts;
* This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
*/
UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
- UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream";
- UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate";
- UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked";
- UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream";
+ /**
+ * The project appears out of date because its upstream inputs are newer than its outputs,
+ * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
+ * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
+ */
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
+ UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
+ UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
+ UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
+ UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
+ UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
/**
* Projects with no outputs (i.e. "solution" files)
*/
- UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly";
+ UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
})(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
function createFileMap(toPath) {
// tslint:disable-next-line:no-null-keyword
@@ -92325,24 +93441,18 @@ var ts;
}
return outputs;
}
- function getOutFileOutputs(project) {
- var out = project.options.outFile || project.options.out;
- if (!out) {
- return ts.Debug.fail("outFile must be set");
- }
+ function getOutFileOutputs(project, ignoreBuildInfo) {
+ ts.Debug.assert(!!project.options.outFile || !!project.options.out, "outFile must be set");
+ var _a = ts.getOutputPathsForBundle(project.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
var outputs = [];
- outputs.push(out);
- if (project.options.sourceMap) {
- outputs.push(out + ".map");
- }
- if (ts.getEmitDeclarations(project.options)) {
- var dts = ts.changeExtension(out, ".d.ts" /* Dts */);
- outputs.push(dts);
- if (project.options.declarationMap) {
- outputs.push(dts + ".map");
- }
- }
- return outputs;
+ var addOutput = function (path) { return path && (outputs || (outputs = [])).push(path); };
+ addOutput(jsFilePath);
+ addOutput(sourceMapFilePath);
+ addOutput(declarationFilePath);
+ addOutput(declarationMapPath);
+ if (!ignoreBuildInfo)
+ addOutput(buildInfoPath);
+ return outputs || ts.emptyArray;
}
function rootDirOfOptions(opts, configFileName) {
return opts.rootDir || ts.getDirectoryPath(configFileName);
@@ -92375,14 +93485,14 @@ var ts;
}
function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
host.reportErrorSummary = reportErrorSummary;
return host;
}
ts.createSolutionBuilderHost = createSolutionBuilderHost;
function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
var watchHost = ts.createWatchHost(system, reportWatchStatus);
ts.copyProperties(host, watchHost);
return host;
@@ -92416,7 +93526,18 @@ var ts;
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; });
var originalGetSourceFile = compilerHost.getSourceFile;
var computeHash = host.createHash || ts.generateDjb2Hash;
- updateGetSourceFile();
+ compilerHost.getSourceFile = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
+ if (result) {
+ result.version = computeHash.call(host, result.text);
+ }
+ return result;
+ };
+ var buildInfoChecked = createFileMap(toPath);
// Watch state
var builderPrograms = createFileMap(toPath);
var diagnostics = createFileMap(toPath);
@@ -92454,6 +93575,7 @@ var ts;
projectStatus.clear();
missingRoots.clear();
globalDependencyGraph = undefined;
+ buildInfoChecked.clear();
diagnostics.clear();
projectPendingBuild.clear();
projectErrorsReported.clear();
@@ -92468,29 +93590,6 @@ var ts;
ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); });
ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher);
builderPrograms.clear();
- updateGetSourceFile();
- }
- function updateGetSourceFile() {
- if (options.watch) {
- if (compilerHost.getSourceFile === originalGetSourceFile) {
- compilerHost.getSourceFile = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
- if (result && options.watch) {
- result.version = computeHash.call(host, result.text);
- }
- return result;
- };
- }
- }
- else {
- if (compilerHost.getSourceFile !== originalGetSourceFile) {
- compilerHost.getSourceFile = originalGetSourceFile;
- }
- }
}
function isParsedCommandLine(entry) {
return !!entry.options;
@@ -92722,25 +93821,28 @@ var ts;
upstreamProjectName: ref.path
};
}
- // If the upstream project's newest file is older than our oldest output, we
- // can't be out of date because of it
- if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
- continue;
- }
- // If the upstream project has only change .d.ts files, and we've built
- // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
- if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
- pseudoUpToDate = true;
- upstreamChangedProject = ref.path;
- continue;
+ // Check oldest output file name only if there is no missing output file name
+ if (!missingOutputFileName) {
+ // If the upstream project's newest file is older than our oldest output, we
+ // can't be out of date because of it
+ if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
+ continue;
+ }
+ // If the upstream project has only change .d.ts files, and we've built
+ // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
+ if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
+ pseudoUpToDate = true;
+ upstreamChangedProject = ref.path;
+ continue;
+ }
+ // We have an output older than an upstream output - we are out of date
+ ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
+ return {
+ type: UpToDateStatusType.OutOfDateWithUpstream,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerProjectName: ref.path
+ };
}
- // We have an output older than an upstream output - we are out of date
- ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
- return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: oldestOutputFileName,
- newerProjectName: ref.path
- };
}
}
if (missingOutputFileName !== undefined) {
@@ -92756,9 +93858,23 @@ var ts;
newerInputFileName: newestInputFileName
};
}
+ if (!buildInfoChecked.hasKey(project.options.configFilePath)) {
+ buildInfoChecked.setValue(project.options.configFilePath, true);
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath) {
+ var value = readFileWithCache(buildInfoPath);
+ var buildInfo = value && ts.getBuildInfo(value);
+ if (buildInfo && buildInfo.version !== ts.version) {
+ return {
+ type: UpToDateStatusType.TsVersionOutputOfDate,
+ version: buildInfo.version
+ };
+ }
+ }
+ }
if (usesPrepend && pseudoUpToDate) {
return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
+ type: UpToDateStatusType.OutOfDateWithPrepend,
outOfDateOutputFileName: oldestOutputFileName,
newerProjectName: upstreamChangedProject
};
@@ -92892,7 +94008,9 @@ var ts;
updateOutputTimestamps(proj);
return;
}
- var buildResult = buildSingleProject(resolved);
+ var buildResult = status.type === UpToDateStatusType.OutOfDateWithPrepend ?
+ updateBundle(resolved) : // Fake that files have been built by manipulating prepend and existing output
+ buildSingleProject(resolved); // Actual build
if (buildResult & BuildResultFlags.AnyErrors)
return;
var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue;
@@ -92908,17 +94026,26 @@ var ts;
// If declaration output is changed, build the project
// otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
var status_1 = projectStatus.getValue(project);
- if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
- if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) {
+ if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
+ if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes || status_1.type === UpToDateStatusType.OutOfDateWithPrepend)) {
projectStatus.setValue(project, {
type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: status_1.oldestOutputFileName,
+ outOfDateOutputFileName: status_1.type === UpToDateStatusType.OutOfDateWithPrepend ? status_1.outOfDateOutputFileName : status_1.oldestOutputFileName,
newerProjectName: resolved
});
}
}
else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) {
- status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
+ if (prepend) {
+ projectStatus.setValue(project, {
+ type: UpToDateStatusType.OutOfDateWithPrepend,
+ outOfDateOutputFileName: status_1.oldestOutputFileName,
+ newerProjectName: resolved
+ });
+ }
+ else {
+ status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
+ }
}
addProjToQueue(project);
}
@@ -92975,8 +94102,7 @@ var ts;
}
if (options.verbose)
reportStatus(ts.Diagnostics.Building_project_0, proj);
- var resultFlags = BuildResultFlags.None;
- resultFlags |= BuildResultFlags.DeclarationOutputUnchanged;
+ var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
var configFile = parseConfigFile(proj);
if (!configFile) {
// Failed to read the config file
@@ -92992,8 +94118,7 @@ var ts;
}
// TODO: handle resolve module name to cache result in project reference redirect
projectCompilerOptions = configFile.options;
- var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences);
- projectCompilerOptions = baseCompilerOptions;
+ var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, getOldProgram(proj, configFile), configFile.errors, configFile.projectReferences);
// Don't emit anything in the presence of syntactic errors or options diagnostics
var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
@@ -93054,12 +94179,14 @@ var ts;
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
}
}
@@ -93072,9 +94199,67 @@ var ts;
builderPrograms.setValue(proj, program);
}
}
+ function getOldProgram(proj, parsed) {
+ var value = builderPrograms.getValue(proj);
+ if (value)
+ return value;
+ var buildInfoPath = ts.getOutputPathForBuildInfo(parsed.options);
+ if (!buildInfoPath)
+ return undefined;
+ var content = readFileWithCache(buildInfoPath);
+ if (!content)
+ return undefined;
+ var buildInfo = ts.getBuildInfo(content);
+ if (buildInfo.version !== ts.version)
+ return undefined;
+ return buildInfo.program && ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program);
+ }
+ function updateBundle(proj) {
+ if (options.dry) {
+ reportStatus(ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, proj);
+ return BuildResultFlags.Success;
+ }
+ if (options.verbose)
+ reportStatus(ts.Diagnostics.Updating_output_of_project_0, proj);
+ // Update js, and source map
+ var config = ts.Debug.assertDefined(parseConfigFile(proj));
+ projectCompilerOptions = config.options;
+ var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) { return parseConfigFile(resolveProjectName(ref.path)); });
+ if (ts.isString(outputFiles)) {
+ reportStatus(ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, proj, relName(outputFiles));
+ return buildSingleProject(proj);
+ }
+ // Actual Emit
+ ts.Debug.assert(!!outputFiles.length);
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ var emittedOutputs = createFileMap(toPath);
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
+ emittedOutputs.setValue(name, true);
+ ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
+ });
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
+ reportAndStoreErrors(proj, emitDiagnostics);
+ projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Emit errors" });
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged | BuildResultFlags.EmitErrors;
+ }
+ // Update timestamps for dts
+ var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(config, minimumDate, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
+ oldestOutputFileName: outputFiles[0].name
+ };
+ diagnostics.removeKey(proj);
+ projectStatus.setValue(proj, status);
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged;
+ }
function updateOutputTimestamps(proj) {
if (options.dry) {
- return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath);
+ return reportStatus(ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
}
var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime });
@@ -93201,7 +94386,9 @@ var ts;
// Do nothing
continue;
}
- var buildResult = buildSingleProject(next);
+ var buildResult = status.type === UpToDateStatusType.OutOfDateWithPrepend && !options.force ?
+ updateBundle(next) : // Fake that files have been built by manipulating prepend and existing output
+ buildSingleProject(next); // Actual build
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
@@ -93263,6 +94450,9 @@ var ts;
var inputFile = _a[_i];
outputs.push.apply(outputs, getOutputFileNames(inputFile, project));
}
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath)
+ outputs.push(buildInfoPath);
return outputs;
}
}
@@ -93294,6 +94484,8 @@ var ts;
}
// Don't report anything for "up to date because it was already built" -- too verbose
break;
+ case UpToDateStatusType.OutOfDateWithPrepend:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(configFileName), relName(status.newerProjectName));
case UpToDateStatusType.UpToDateWithUpstreamTypes:
return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName));
case UpToDateStatusType.UpstreamOutOfDate:
@@ -93302,6 +94494,8 @@ var ts;
return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName));
case UpToDateStatusType.Unbuildable:
return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason);
+ case UpToDateStatusType.TsVersionOutputOfDate:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(configFileName), status.version, ts.version);
case UpToDateStatusType.ContainerOnly:
// Don't report status on "solution" projects
case UpToDateStatusType.ComputingUpstream:
@@ -93700,8 +94894,8 @@ var ts;
if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
continue;
}
- var result_7 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
- var packageJson = result_7.config;
+ var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
+ var packageJson = result_1.config;
// npm 3's package.json contains a "_requiredBy" field
// we should include all the top level module names for npm 2, and only module names whose
// "_requiredBy" field starts with "#" or equals "/" for npm 3.
@@ -94108,7 +95302,7 @@ var ts;
case 242 /* TypeAliasDeclaration */:
case 168 /* TypeLiteral */:
return 2 /* Type */;
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
// If it has no name node, it shares the name with the value declaration below it.
return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */;
case 278 /* EnumMember */:
@@ -94133,14 +95327,14 @@ var ts;
case 255 /* ExportDeclaration */:
return 7 /* All */;
// An external module can be a Value
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 4 /* Namespace */ | 1 /* Value */;
}
return 7 /* All */;
}
ts.getMeaningFromDeclaration = getMeaningFromDeclaration;
function getMeaningFromLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return 1 /* Value */;
}
else if (node.parent.kind === 254 /* ExportAssignment */ || node.parent.kind === 259 /* ExternalModuleReference */) {
@@ -94346,7 +95540,7 @@ var ts;
return undefined;
}
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
case 239 /* FunctionDeclaration */:
@@ -94364,7 +95558,7 @@ var ts;
ts.getContainerNode = getContainerNode;
function getNodeKind(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */;
case 244 /* ModuleDeclaration */:
return "module" /* moduleElement */;
@@ -94373,8 +95567,8 @@ var ts;
return "class" /* classElement */;
case 241 /* InterfaceDeclaration */: return "interface" /* interfaceElement */;
case 242 /* TypeAliasDeclaration */:
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
return "type" /* typeElement */;
case 243 /* EnumDeclaration */: return "enum" /* enumElement */;
case 237 /* VariableDeclaration */:
@@ -94791,8 +95985,8 @@ var ts;
isWhiteSpaceOnlyJsxText(child);
if (lookInPreviousChild) {
// actual start of the node is past the position - previous token should be at the end of previous child
- var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
- return candidate_2 && findRightmostToken(candidate_2, sourceFile);
+ var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
+ return candidate_1 && findRightmostToken(candidate_1, sourceFile);
}
else {
// candidate should be in this node
@@ -94800,7 +95994,7 @@ var ts;
}
}
}
- ts.Debug.assert(startNode !== undefined || n.kind === 279 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
+ ts.Debug.assert(startNode !== undefined || n.kind === 284 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
// Here we know that none of child token nodes embrace the position,
// the only known case is when position is at the end of the file.
// Try to find the rightmost token in the file without filtering.
@@ -95647,6 +96841,17 @@ var ts;
return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName));
}
ts.getScriptKind = getScriptKind;
+ function getSymbolTarget(symbol) {
+ var next = symbol;
+ while (isTransientSymbol(next) && next.target) {
+ next = next.target;
+ }
+ return next;
+ }
+ ts.getSymbolTarget = getSymbolTarget;
+ function isTransientSymbol(symbol) {
+ return (symbol.flags & 33554432 /* Transient */) !== 0;
+ }
function getUniqueSymbolId(symbol, checker) {
return ts.getSymbolId(ts.skipAlias(symbol, checker));
}
@@ -95705,14 +96910,14 @@ var ts;
ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext);
if (visited === node) {
// This only happens for leaf nodes - internal nodes always see their children change.
- var clone_8 = ts.getSynthesizedClone(node);
- if (ts.isStringLiteral(clone_8)) {
- clone_8.textSourceNode = node;
+ var clone_1 = ts.getSynthesizedClone(node);
+ if (ts.isStringLiteral(clone_1)) {
+ clone_1.textSourceNode = node;
}
- else if (ts.isNumericLiteral(clone_8)) {
- clone_8.numericLiteralFlags = node.numericLiteralFlags;
+ else if (ts.isNumericLiteral(clone_1)) {
+ clone_1.numericLiteralFlags = node.numericLiteralFlags;
}
- return ts.setTextRange(clone_8, node);
+ return ts.setTextRange(clone_1, node);
}
// PERF: As an optimization, rather than calling getSynthesizedClone, we'll update
// the new node created by visitEachChild with the extra changes getSynthesizedClone
@@ -95798,8 +97003,27 @@ var ts;
return lastPos;
}
ts.getRenameLocation = getRenameLocation;
- function copyComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
- ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) {
+ function copyLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
+ }
+ ts.copyLeadingComments = copyLeadingComments;
+ function copyTrailingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticTrailingComment));
+ }
+ ts.copyTrailingComments = copyTrailingComments;
+ /**
+ * This function copies the trailing comments for the token that comes before `sourceNode`, as leading comments of `targetNode`.
+ * This is useful because sometimes a comment that refers to `sourceNode` will be a leading comment for `sourceNode`, according to the
+ * notion of trivia ownership, and instead will be a trailing comment for the token before `sourceNode`, e.g.:
+ * `function foo(\* not leading comment for a *\ a: string) {}`
+ * The comment refers to `a` but belongs to the `(` token, but we might want to copy it.
+ */
+ function copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
+ }
+ ts.copyTrailingAsLeadingComments = copyTrailingAsLeadingComments;
+ function getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, cb) {
+ return function (pos, end, kind, htnl) {
if (kind === 3 /* MultiLineCommentTrivia */) {
// Remove leading /*
pos += 2;
@@ -95810,10 +97034,9 @@ var ts;
// Remove leading //
pos += 2;
}
- ts.addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
- });
+ cb(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
+ };
}
- ts.copyComments = copyComments;
function indexInTextChange(change, name) {
if (ts.startsWith(change, name))
return 0;
@@ -95894,6 +97117,30 @@ var ts;
return checker.getTypeAtLocation(caseClause.parent.parent.expression);
}
ts.getSwitchedType = getSwitchedType;
+ function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
+ var checker = program.getTypeChecker();
+ var typeIsAccessible = true;
+ var notAccessible = function () { typeIsAccessible = false; };
+ var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
+ trackSymbol: function (symbol, declaration, meaning) {
+ // TODO: GH#18217
+ typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
+ },
+ reportInaccessibleThisError: notAccessible,
+ reportPrivateInBaseOfClassExpression: notAccessible,
+ reportInaccessibleUniqueSymbolError: notAccessible,
+ moduleResolverHost: {
+ readFile: host.readFile,
+ fileExists: host.fileExists,
+ directoryExists: host.directoryExists,
+ getSourceFiles: program.getSourceFiles,
+ getCurrentDirectory: program.getCurrentDirectory,
+ getCommonSourceDirectory: program.getCommonSourceDirectory,
+ }
+ });
+ return typeIsAccessible ? res : undefined;
+ }
+ ts.getTypeNodeIfAccessible = getTypeNodeIfAccessible;
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -96137,7 +97384,7 @@ var ts;
var lastEnd = 0;
for (var i = 0; i < dense.length; i += 3) {
var start = dense[i];
- var length_5 = dense[i + 1];
+ var length_1 = dense[i + 1];
var type = dense[i + 2];
// Make a whitespace entry between the last item and this one.
if (lastEnd >= 0) {
@@ -96146,8 +97393,8 @@ var ts;
entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace });
}
}
- entries.push({ length: length_5, classification: convertClassification(type) });
- lastEnd = start + length_5;
+ entries.push({ length: length_1, classification: convertClassification(type) });
+ lastEnd = start + length_1;
}
var whitespaceLength = text.length - lastEnd;
if (whitespaceLength > 0) {
@@ -96545,18 +97792,18 @@ var ts;
pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param"
pos = tag.tagName.end;
switch (tag.kind) {
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
processJSDocParameterTag(tag);
break;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
processJSDocTemplateTag(tag);
pos = tag.end;
break;
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
- case 300 /* JSDocReturnTag */:
+ case 305 /* JSDocReturnTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
@@ -96860,6 +98107,7 @@ var ts;
case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */;
case ".ts" /* Ts */: return ".ts" /* tsModifier */;
case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */;
+ case ".tsbuildinfo" /* TsBuildInfo */: return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported.");
case undefined: return "" /* none */;
default:
return ts.Debug.assertNever(extension);
@@ -97090,8 +98338,8 @@ var ts;
* both foo.ts and foo.tsx become foo
*/
var foundFiles = ts.createMap(); // maps file to its extension
- for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
- var filePath = files_3[_i];
+ for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
+ var filePath = files_1[_i];
filePath = ts.normalizePath(filePath);
if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) {
continue;
@@ -97136,7 +98384,7 @@ var ts;
continue;
var patterns = paths[path];
if (patterns) {
- var _loop_11 = function (name, kind, extension) {
+ var _loop_1 = function (name, kind, extension) {
// Path mappings may provide a duplicate way to get to something we've already added, so don't add again.
if (!result.some(function (entry) { return entry.name === name; })) {
result.push(nameAndKind(name, kind, extension));
@@ -97144,7 +98392,7 @@ var ts;
};
for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) {
var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension;
- _loop_11(name, kind, extension);
+ _loop_1(name, kind, extension);
}
}
}
@@ -97179,7 +98427,7 @@ var ts;
// (But do if we didn't find anything, e.g. 'package.json' missing.)
var foundGlobal = false;
if (fragmentDirectory === undefined) {
- var _loop_12 = function (moduleName) {
+ var _loop_2 = function (moduleName) {
if (!result.some(function (entry) { return entry.name === moduleName; })) {
foundGlobal = true;
result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined));
@@ -97187,7 +98435,7 @@ var ts;
};
for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) {
var moduleName = _c[_b];
- _loop_12(moduleName);
+ _loop_2(moduleName);
}
}
if (!foundGlobal) {
@@ -97301,8 +98549,8 @@ var ts;
// Check for typings specified in compiler options
var seen = ts.createMap();
var typeRoots = tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray;
- for (var _i = 0, typeRoots_2 = typeRoots; _i < typeRoots_2.length; _i++) {
- var root = typeRoots_2[_i];
+ for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
+ var root = typeRoots_1[_i];
getCompletionEntriesFromDirectories(root);
}
// Also get all @types typings installed in visible node_modules directories
@@ -97664,8 +98912,8 @@ var ts;
// Based on the order we add things we will always see locals first, then globals, then module exports.
// So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name.
var uniques = ts.createMap();
- for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) {
- var symbol = symbols_3[_i];
+ for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
+ var symbol = symbols_1[_i];
var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined;
var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences);
if (!entry) {
@@ -97884,7 +99132,7 @@ var ts;
return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker));
}
function isModuleSymbol(symbol) {
- return symbol.declarations.some(function (d) { return d.kind === 279 /* SourceFile */; });
+ return symbol.declarations.some(function (d) { return d.kind === 284 /* SourceFile */; });
}
function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) {
var typeChecker = program.getTypeChecker();
@@ -97935,11 +99183,11 @@ var ts;
if (tag.tagName.pos <= position && position <= tag.tagName.end) {
return { kind: 1 /* JsDocTagName */ };
}
- if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
currentToken = ts.getTokenAtPosition(sourceFile, position);
if (!currentToken ||
(!ts.isDeclarationName(currentToken) &&
- (currentToken.parent.kind !== 305 /* JSDocPropertyTag */ ||
+ (currentToken.parent.kind !== 310 /* JSDocPropertyTag */ ||
currentToken.parent.name !== currentToken))) {
// Use as type location if inside tag's type expression
insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
@@ -97965,9 +99213,9 @@ var ts;
// Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS|
// Skip this partial identifier and adjust the contextToken to the token that precedes it.
if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) {
- var start_3 = ts.timestamp();
+ var start_1 = ts.timestamp();
contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217
- log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_3));
+ log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1));
}
// Find the node where completion is requested on.
// Also determine whether we are trying to complete with members of that node
@@ -98110,11 +99358,11 @@ var ts;
return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer };
function isTagWithTypeExpression(tag) {
switch (tag.kind) {
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 304 /* JSDocTypedefTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 309 /* JSDocTypedefTag */:
return true;
default:
return false;
@@ -98154,7 +99402,7 @@ var ts;
}
}
// If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods).
- if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 279 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) {
+ if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 284 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) {
addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node));
}
return;
@@ -98287,7 +99535,7 @@ var ts;
var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */;
symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined");
// Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
- if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 279 /* SourceFile */) {
+ if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 284 /* SourceFile */) {
var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false);
if (thisType) {
for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) {
@@ -98320,7 +99568,7 @@ var ts;
}
function isSnippetScope(scopeNode) {
switch (scopeNode.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 206 /* TemplateExpression */:
case 270 /* JsxExpression */:
case 218 /* Block */:
@@ -99152,7 +100400,7 @@ var ts;
function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) {
// class c { method() { } | method2() { } }
switch (location.kind) {
- case 306 /* SyntaxList */:
+ case 311 /* SyntaxList */:
return ts.tryCast(location.parent, ts.isObjectTypeDeclaration);
case 1 /* EndOfFileToken */:
var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration);
@@ -99337,7 +100585,7 @@ var ts;
var child = throwStatement;
while (child.parent) {
var parent = child.parent;
- if (ts.isFunctionBlock(parent) || parent.kind === 279 /* SourceFile */) {
+ if (ts.isFunctionBlock(parent) || parent.kind === 284 /* SourceFile */) {
return parent;
}
// A throw-statement is only owned by a try-statement if the try-statement has
@@ -99395,7 +100643,7 @@ var ts;
var container = declaration.parent;
switch (container.kind) {
case 245 /* ModuleBlock */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 218 /* Block */:
case 271 /* CaseClause */:
case 272 /* DefaultClause */:
@@ -99893,7 +101141,7 @@ var ts;
}
else if (!isAvailableThroughGlobal) {
var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration);
- ts.Debug.assert(sourceFileLike.kind === 279 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */);
+ ts.Debug.assert(sourceFileLike.kind === 284 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */);
if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) {
addIndirectUsers(sourceFileLike);
}
@@ -100059,10 +101307,10 @@ var ts;
function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
var refs = [];
var checker = program.getTypeChecker();
- for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
- var referencingFile = sourceFiles_3[_i];
+ for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
+ var referencingFile = sourceFiles_1[_i];
var searchSourceFile = searchModuleSymbol.valueDeclaration;
- if (searchSourceFile.kind === 279 /* SourceFile */) {
+ if (searchSourceFile.kind === 284 /* SourceFile */) {
for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
var ref = _b[_a];
if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) {
@@ -100090,8 +101338,8 @@ var ts;
/** Returns a map from a module symbol Id to all import statements that directly reference the module. */
function getDirectImportsMap(sourceFiles, checker, cancellationToken) {
var map = ts.createMap();
- for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
- var sourceFile = sourceFiles_4[_i];
+ for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
+ var sourceFile = sourceFiles_2[_i];
if (cancellationToken)
cancellationToken.throwIfCancellationRequested();
forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
@@ -100110,7 +101358,7 @@ var ts;
}
/** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */
function forEachPossibleImportOrExportStatement(sourceFileLike, action) {
- return ts.forEach(sourceFileLike.kind === 279 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
+ return ts.forEach(sourceFileLike.kind === 284 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action));
});
}
@@ -100334,7 +101582,7 @@ var ts;
return node.getSourceFile();
}
var parent = node.parent;
- if (parent.kind === 279 /* SourceFile */) {
+ if (parent.kind === 284 /* SourceFile */) {
return parent;
}
ts.Debug.assert(parent.kind === 245 /* ModuleBlock */);
@@ -100396,16 +101644,16 @@ var ts;
}
FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition;
function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return undefined;
}
var checker = program.getTypeChecker();
// If invoked directly on a shorthand property assignment, then return
// the declaration of the symbol being assigned (not the symbol being assigned to).
if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) {
- var result_8 = [];
- FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_8.push(nodeEntry(node)); });
- return result_8;
+ var result_1 = [];
+ FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_1.push(nodeEntry(node)); });
+ return result_1;
}
else if (node.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
// References to and accesses on the super keyword only have one possible implementation, so no
@@ -100437,27 +101685,27 @@ var ts;
case 0 /* Symbol */: {
var symbol = def.symbol;
var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
- var name_4 = displayParts_1.map(function (p) { return p.text; }).join("");
- return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 };
+ var name_1 = displayParts_1.map(function (p) { return p.text; }).join("");
+ return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_1, kind: kind_1, displayParts: displayParts_1 };
}
case 1 /* Label */: {
- var node_3 = def.node;
- return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] };
+ var node_1 = def.node;
+ return { node: node_1, name: node_1.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_1.text, ts.SymbolDisplayPartKind.text)] };
}
case 2 /* Keyword */: {
- var node_4 = def.node;
- var name_5 = ts.tokenToString(node_4.kind);
- return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] };
+ var node_2 = def.node;
+ var name_2 = ts.tokenToString(node_2.kind);
+ return { node: node_2, name: name_2, kind: "keyword" /* keyword */, displayParts: [{ text: name_2, kind: "keyword" /* keyword */ }] };
}
case 3 /* This */: {
- var node_5 = def.node;
- var symbol = checker.getSymbolAtLocation(node_5);
- var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")];
- return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
+ var node_3 = def.node;
+ var symbol = checker.getSymbolAtLocation(node_3);
+ var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_3.getSourceFile(), ts.getContainerNode(node_3), node_3).displayParts || [ts.textPart("this")];
+ return { node: node_3, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
}
case 4 /* String */: {
- var node_6 = def.node;
- return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] };
+ var node_4 = def.node;
+ return { node: node_4, name: node_4.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_4), ts.SymbolDisplayPartKind.stringLiteral)] };
}
default:
return ts.Debug.assertNever(def);
@@ -100616,8 +101864,8 @@ var ts;
case 248 /* ImportEqualsDeclaration */:
case 253 /* ImportSpecifier */:
case 241 /* InterfaceDeclaration */:
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
case 267 /* JsxAttribute */:
case 244 /* ModuleDeclaration */:
case 247 /* NamespaceExportDeclaration */:
@@ -100642,8 +101890,8 @@ var ts;
return !!decl.initializer || ts.isCatchClause(decl.parent);
case 155 /* MethodSignature */:
case 153 /* PropertySignature */:
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
return false;
default:
return ts.Debug.failBadSyntaxKind(decl);
@@ -100735,7 +101983,7 @@ var ts;
result = references;
continue;
}
- var _loop_13 = function (entry) {
+ var _loop_3 = function (entry) {
if (!entry.definition || entry.definition.type !== 0 /* Symbol */) {
result.push(entry);
return "continue";
@@ -100767,7 +102015,7 @@ var ts;
};
for (var _b = 0, references_1 = references; _b < references_1.length; _b++) {
var entry = references_1[_b];
- _loop_13(entry);
+ _loop_3(entry);
}
}
return result;
@@ -100803,7 +102051,7 @@ var ts;
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
switch (decl.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.)
break;
case 244 /* ModuleDeclaration */:
@@ -101027,8 +102275,8 @@ var ts;
var sourceId = ts.getNodeId(sourceFile);
var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = ts.createMap());
var anyNewSymbols = false;
- for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) {
- var sym = symbols_4[_i];
+ for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
+ var sym = symbols_2[_i];
anyNewSymbols = ts.addToSeen(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols;
}
return anyNewSymbols;
@@ -101167,14 +102415,14 @@ var ts;
return undefined;
}
var scope;
- for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) {
- var declaration = declarations_11[_i];
+ for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
+ var declaration = declarations_1[_i];
var container = ts.getContainerNode(declaration);
if (scope && scope !== container) {
// Different declarations have different containers, bail out
return undefined;
}
- if (!container || container.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
+ if (!container || container.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
// This is a global variable and not an external module, any declaration defined
// within this scope is visible outside the file
return undefined;
@@ -101219,8 +102467,8 @@ var ts;
if (!signature.name || !ts.isIdentifier(signature.name))
return;
var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name));
- for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
- var sourceFile = sourceFiles_5[_i];
+ for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
+ var sourceFile = sourceFiles_3[_i];
for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) {
var name = _b[_a];
if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText)
@@ -101733,7 +102981,7 @@ var ts;
staticFlag &= ts.getModifierFlags(searchSpaceNode);
searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) {
return undefined;
}
@@ -101746,7 +102994,7 @@ var ts;
default:
return undefined;
}
- var references = ts.flatMap(searchSpaceNode.kind === 279 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
+ var references = ts.flatMap(searchSpaceNode.kind === 284 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) {
if (!ts.isThis(node)) {
@@ -101765,8 +103013,8 @@ var ts;
// Make sure the container belongs to the same class
// and has the appropriate static modifier from the original container.
return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag;
- case 279 /* SourceFile */:
- return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
+ case 284 /* SourceFile */:
+ return container.kind === 284 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
}
});
}).map(function (n) { return FindAllReferences.nodeEntry(n); });
@@ -101922,8 +103170,8 @@ var ts;
// To achieve that we will keep iterating until the result stabilizes.
// Remember the last meaning
lastIterationMeaning = meaning;
- for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) {
- var declaration = declarations_12[_i];
+ for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
+ var declaration = declarations_2[_i];
var declarationMeaning = ts.getMeaningFromDeclaration(declaration);
if (declarationMeaning & meaning) {
meaning |= declarationMeaning;
@@ -102072,8 +103320,8 @@ var ts;
// Type annotation needed due to #7294
var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer];
var foundExactMatch = false;
- for (var _i = 0, elements_5 = elements; _i < elements_5.length; _i++) {
- var element = elements_5[_i];
+ for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
+ var element = elements_1[_i];
foundExactMatch = tryUpdateString(element) || foundExactMatch;
}
return foundExactMatch;
@@ -102095,7 +103343,7 @@ var ts;
}
function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) {
var allFiles = program.getSourceFiles();
- var _loop_14 = function (sourceFile) {
+ var _loop_4 = function (sourceFile) {
var newFromOld = oldToNew(sourceFile.path);
var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path;
var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath);
@@ -102127,7 +103375,7 @@ var ts;
};
for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) {
var sourceFile = allFiles_1[_i];
- _loop_14(sourceFile);
+ _loop_4(sourceFile);
}
}
function combineNormal(pathA, pathB) {
@@ -102157,9 +103405,9 @@ var ts;
return undefined;
// First try resolved module
if (resolved.resolvedModule) {
- var result_9 = tryChange(resolved.resolvedModule.resolvedFileName);
- if (result_9)
- return result_9;
+ var result_2 = tryChange(resolved.resolvedModule.resolvedFileName);
+ if (result_2)
+ return result_2;
}
// Then failed lookups except package.json since we dont want to touch them (only included ts/js files)
var result = ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson);
@@ -102269,10 +103517,10 @@ var ts;
// bar(({pr/*goto*/op1})=>{});
if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) &&
(node === (parent.propertyName || parent.name))) {
- var name_6 = ts.getNameFromPropertyName(node);
+ var name_3 = ts.getNameFromPropertyName(node);
var type = typeChecker.getTypeAtLocation(parent.parent);
- return name_6 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) {
- var prop = t.getProperty(name_6);
+ return name_3 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) {
+ var prop = t.getProperty(name_3);
return prop && getDefinitionFromSymbol(typeChecker, prop, node);
});
}
@@ -102620,11 +103868,11 @@ var ts;
JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
function getCommentHavingNodes(declaration) {
switch (declaration.kind) {
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return [declaration];
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
return [declaration, declaration.parent];
default:
return ts.getJSDocCommentsAndTags(declaration);
@@ -102645,16 +103893,16 @@ var ts;
function getCommentText(tag) {
var comment = tag.comment;
switch (tag.kind) {
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return withNode(tag.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return withList(tag.typeParameters);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return withNode(tag.typeExpression);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
var name = tag.name;
return name ? withNode(name) : comment;
default:
@@ -102865,7 +104113,7 @@ var ts;
: undefined;
return { commentOwner: commentOwner, parameters: parameters_1 };
}
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return "quit";
case 244 /* ModuleDeclaration */:
// If in walking up the tree, we hit a a nested namespace declaration,
@@ -102917,7 +104165,7 @@ var ts;
if (!patternMatcher)
return ts.emptyArray;
var rawItems = [];
- var _loop_15 = function (sourceFile) {
+ var _loop_5 = function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
if (excludeDtsFiles && sourceFile.isDeclarationFile) {
return "continue";
@@ -102927,9 +104175,9 @@ var ts;
});
};
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
- for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
- var sourceFile = sourceFiles_6[_i];
- _loop_15(sourceFile);
+ for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
+ var sourceFile = sourceFiles_4[_i];
+ _loop_5(sourceFile);
}
rawItems.sort(compareNavigateToItems);
return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem);
@@ -102942,8 +104190,8 @@ var ts;
if (!match) {
return; // continue to next named declarations
}
- for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) {
- var declaration = declarations_13[_i];
+ for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
+ var declaration = declarations_3[_i];
if (!shouldKeepItem(declaration, checker))
continue;
if (patternMatcher.patternContainsDots) {
@@ -103425,7 +104673,7 @@ var ts;
}
}
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
var sourceFile = node;
return ts.isExternalModule(sourceFile)
? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\""
@@ -103477,10 +104725,10 @@ var ts;
case 243 /* EnumDeclaration */:
case 241 /* InterfaceDeclaration */:
case 244 /* ModuleDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 242 /* TypeAliasDeclaration */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return true;
case 157 /* Constructor */:
case 156 /* MethodDeclaration */:
@@ -103501,7 +104749,7 @@ var ts;
}
switch (navigationBarNodeKind(item.parent)) {
case 245 /* ModuleBlock */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
return true;
@@ -103586,7 +104834,7 @@ var ts;
return !member.name || member.name.kind === 149 /* ComputedPropertyName */;
}
function getNodeSpan(node) {
- return node.kind === 279 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
+ return node.kind === 284 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
}
function getModifiers(node) {
if (node.parent && node.parent.kind === 237 /* VariableDeclaration */) {
@@ -103707,8 +104955,8 @@ var ts;
else {
// Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: false,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include,
suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
});
}
@@ -104046,8 +105294,8 @@ var ts;
var lastSingleLineCommentEnd = -1;
var singleLineCommentCount = 0;
var sourceText = sourceFile.getFullText();
- for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) {
- var _a = comments_2[_i], kind = _a.kind, pos = _a.pos, end = _a.end;
+ for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
+ var _a = comments_1[_i], kind = _a.kind, pos = _a.pos, end = _a.end;
cancellationToken.throwIfCancellationRequested();
switch (kind) {
case 2 /* SingleLineCommentTrivia */:
@@ -104457,15 +105705,15 @@ var ts;
// Assumes 'value' is already lowercase.
function indexOfIgnoringCase(str, value) {
var n = str.length - value.length;
- var _loop_16 = function (start) {
+ var _loop_6 = function (start) {
if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) {
return { value: start };
}
};
for (var start = 0; start <= n; start++) {
- var state_4 = _loop_16(start);
- if (typeof state_4 === "object")
- return state_4.value;
+ var state_1 = _loop_6(start);
+ if (typeof state_1 === "object")
+ return state_1.value;
}
return -1;
}
@@ -105476,7 +106724,7 @@ var ts;
return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
}
function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) {
- var _loop_17 = function (n) {
+ var _loop_7 = function (n) {
// If the node is not a subspan of its parent, this is a big problem.
// There have been crashes that might be caused by this violation.
ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); });
@@ -105486,9 +106734,9 @@ var ts;
}
};
for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) {
- var state_5 = _loop_17(n);
- if (typeof state_5 === "object")
- return state_5.value;
+ var state_2 = _loop_7(n);
+ if (typeof state_2 === "object")
+ return state_2.value;
}
return undefined;
}
@@ -105766,8 +107014,8 @@ var ts;
var name = importNameForConvertToDefaultImport(importNode);
if (!name)
continue;
- var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
- var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName);
+ var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
+ var resolvedFile = module && program.getSourceFile(module.resolvedFileName);
if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
}
@@ -105782,8 +107030,8 @@ var ts;
case 196 /* FunctionExpression */:
var decl = ts.getDeclarationOfExpando(node);
if (decl) {
- var symbol_2 = decl.symbol;
- if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) {
+ var symbol_1 = decl.symbol;
+ if (symbol_1 && (symbol_1.exports && symbol_1.exports.size || symbol_1.members && symbol_1.members.size)) {
diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration));
break;
}
@@ -106404,7 +107652,7 @@ var ts;
// For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo`
// there documentation comments might be attached to the right hand side symbol of their declarations.
// The pattern of such special property access is that the parent symbol is the symbol of the file.
- if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 279 /* SourceFile */; })) {
+ if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 284 /* SourceFile */; })) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
if (!declaration.parent || declaration.parent.kind !== 204 /* BinaryExpression */) {
@@ -106529,7 +107777,7 @@ var ts;
// If the parent is not sourceFile or module block it is local variable
for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) {
// Reached source file or module block
- if (parent.kind === 279 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) {
+ if (parent.kind === 284 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) {
return false;
}
}
@@ -106643,7 +107891,7 @@ var ts;
return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; });
});
options = ts.cloneCompilerOptions(options);
- var _loop_18 = function (opt) {
+ var _loop_8 = function (opt) {
if (!ts.hasProperty(options, opt.name)) {
return "continue";
}
@@ -106662,7 +107910,7 @@ var ts;
};
for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) {
var opt = commandLineOptionsStringToEnum_1[_i];
- _loop_18(opt);
+ _loop_8(opt);
}
return options;
}
@@ -107854,7 +109102,7 @@ var ts;
case 244 /* ModuleDeclaration */:
var body = parent.body;
return !!body && body.kind === 245 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 218 /* Block */:
case 245 /* ModuleBlock */:
return ts.rangeContainsRange(parent.statements, node);
@@ -108973,7 +110221,7 @@ var ts;
// - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually
// - parent and child are not on the same line
var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) &&
- (parent.kind === 279 /* SourceFile */ || !parentAndChildShareLine);
+ (parent.kind === 284 /* SourceFile */ || !parentAndChildShareLine);
if (!useActualIndentation) {
return -1 /* Unknown */;
}
@@ -109061,7 +110309,7 @@ var ts;
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return getList(node.typeParameters);
case 192 /* NewExpression */:
case 191 /* CallExpression */:
@@ -109310,11 +110558,23 @@ var ts;
ts.Debug.assert(typeof end === "number");
n.__end = end;
}
- var Position;
- (function (Position) {
- Position[Position["FullStart"] = 0] = "FullStart";
- Position[Position["Start"] = 1] = "Start";
- })(Position = textChanges_3.Position || (textChanges_3.Position = {}));
+ var LeadingTriviaOption;
+ (function (LeadingTriviaOption) {
+ /** Exclude all leading trivia (use getStart()) */
+ LeadingTriviaOption[LeadingTriviaOption["Exclude"] = 0] = "Exclude";
+ /** Include leading trivia and,
+ * if there are no line breaks between the node and the previous token,
+ * include all trivia between the node and the previous token
+ */
+ LeadingTriviaOption[LeadingTriviaOption["IncludeAll"] = 1] = "IncludeAll";
+ })(LeadingTriviaOption = textChanges_3.LeadingTriviaOption || (textChanges_3.LeadingTriviaOption = {}));
+ var TrailingTriviaOption;
+ (function (TrailingTriviaOption) {
+ /** Exclude all trailing trivia (use getEnd()) */
+ TrailingTriviaOption[TrailingTriviaOption["Exclude"] = 0] = "Exclude";
+ /** Include trailing trivia */
+ TrailingTriviaOption[TrailingTriviaOption["Include"] = 1] = "Include";
+ })(TrailingTriviaOption = textChanges_3.TrailingTriviaOption || (textChanges_3.TrailingTriviaOption = {}));
function skipWhitespacesAndLineBreaks(text, start) {
return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
@@ -109330,9 +110590,9 @@ var ts;
}
return false;
}
- textChanges_3.useNonAdjustedPositions = {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: true,
+ var useNonAdjustedPositions = {
+ leadingTriviaOption: LeadingTriviaOption.Exclude,
+ trailingTriviaOption: TrailingTriviaOption.Exclude,
};
var ChangeKind;
(function (ChangeKind) {
@@ -109342,10 +110602,11 @@ var ts;
ChangeKind[ChangeKind["Text"] = 3] = "Text";
})(ChangeKind || (ChangeKind = {}));
function getAdjustedRange(sourceFile, startNode, endNode, options) {
- return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) };
+ return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) };
}
- function getAdjustedStartPosition(sourceFile, node, options, position) {
- if (options.useNonAdjustedStartPosition) {
+ function getAdjustedStartPosition(sourceFile, node, options) {
+ var leadingTriviaOption = options.leadingTriviaOption;
+ if (leadingTriviaOption === LeadingTriviaOption.Exclude) {
return node.getStart(sourceFile);
}
var fullStart = node.getFullStart();
@@ -109363,7 +110624,7 @@ var ts;
// fullstart
// when b is replaced - we usually want to keep the leading trvia
// when b is deleted - we delete it
- return position === Position.Start ? start : fullStart;
+ return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start;
}
// get start position of the line following the line that contains fullstart position
// (but only if the fullstart isn't the very beginning of the file)
@@ -109375,11 +110636,12 @@ var ts;
}
function getAdjustedEndPosition(sourceFile, node, options) {
var end = node.end;
- if (options.useNonAdjustedEndPosition || ts.isExpression(node)) {
+ var trailingTriviaOption = options.trailingTriviaOption;
+ if (trailingTriviaOption === TrailingTriviaOption.Exclude || (ts.isExpression(node) && trailingTriviaOption !== TrailingTriviaOption.Include)) {
return end;
}
var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
- return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))
+ return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)))
? newEnd
: end;
}
@@ -109424,15 +110686,15 @@ var ts;
this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) });
};
ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
- var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
+ var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
@@ -109440,11 +110702,11 @@ var ts;
this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode });
};
ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
};
ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options);
};
ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) {
@@ -109452,14 +110714,14 @@ var ts;
this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes });
};
ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
};
ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) {
- this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text);
+ this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text);
};
ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
};
ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
@@ -109487,7 +110749,7 @@ var ts;
};
ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) {
if (blankLineBetween === void 0) { blankLineBetween = false; }
- this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
+ this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
};
ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) {
var pos = before.getStart(sourceFile);
@@ -109594,7 +110856,7 @@ var ts;
this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true));
};
ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) {
- var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start);
+ var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {});
this.insertNodeAt(sourceFile, pos, newNode, {
prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter,
suffix: this.newLineCharacter
@@ -109834,7 +111096,7 @@ var ts;
ChangeTracker.prototype.finishDeleteDeclarations = function () {
var _this = this;
var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
- var _loop_19 = function (sourceFile, node) {
+ var _loop_9 = function (sourceFile, node) {
if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) {
if (ts.isArray(node)) {
this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node));
@@ -109847,7 +111109,7 @@ var ts;
var this_1 = this;
for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) {
var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node;
- _loop_19(sourceFile, node);
+ _loop_9(sourceFile, node);
}
deletedNodesInLists.forEach(function (node) {
var sourceFile = node.getSourceFile();
@@ -109884,7 +111146,7 @@ var ts;
textChanges_3.ChangeTracker = ChangeTracker;
// find first non-whitespace position in the leading trivia of the node
function startPositionToDeleteNodeInList(sourceFile, node) {
- return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
+ return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
function getClassOrObjectBraceEnds(cls, sourceFile) {
return [ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile).end];
@@ -109904,14 +111166,14 @@ var ts;
// order changes by start position
// If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa.
var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); });
- var _loop_20 = function (i) {
+ var _loop_10 = function (i) {
ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () {
return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range);
});
};
// verify that change intervals do not overlap, except possibly at end points.
for (var i = 0; i < normalized.length - 1; i++) {
- _loop_20(i);
+ _loop_10(i);
}
var textChanges = normalized.map(function (c) {
return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
@@ -110221,7 +111483,7 @@ var ts;
case 249 /* ImportDeclaration */:
deleteNode(changes, sourceFile, node,
// For first import, leave header comment in place
- node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined);
+ node === sourceFile.imports[0].parent ? { leadingTriviaOption: LeadingTriviaOption.Exclude } : undefined);
break;
case 186 /* BindingElement */:
var pattern = node.parent;
@@ -110259,7 +111521,7 @@ var ts;
deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
}
else {
- deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined);
+ deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { trailingTriviaOption: TrailingTriviaOption.Exclude } : undefined);
}
}
}
@@ -110330,8 +111592,8 @@ var ts;
/** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */
// Exported for tests only! (TODO: improve tests to not need this)
function deleteNode(changes, sourceFile, node, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, node, options);
var endPosition = getAdjustedEndPosition(sourceFile, node, options);
changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
}
@@ -110624,18 +111886,18 @@ var ts;
}
function transformJSDocType(node) {
switch (node.kind) {
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return transformJSDocOptionalType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return transformJSDocType(node.type);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return transformJSDocNullableType(node);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return transformJSDocVariadicType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return transformJSDocFunctionType(node);
case 164 /* TypeReference */:
return transformJSDocTypeReference(node);
@@ -110659,7 +111921,7 @@ var ts;
}
function transformJSDocParameter(node) {
var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 290 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
+ var isRest = node.type.kind === 295 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
var name = node.name || (isRest ? "rest" : "arg" + index);
var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken;
return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
@@ -110815,7 +112077,7 @@ var ts;
}
if (ts.isPropertyAccessExpression(parent)) {
var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken);
- var typeNode = getTypeNodeIfAccessible(type, parent, program, host);
+ var typeNode = ts.getTypeNodeIfAccessible(type, parent, program, host);
if (typeNode) {
// Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags
var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ "");
@@ -110919,7 +112181,7 @@ var ts;
}
}
function annotate(changes, sourceFile, declaration, type, program, host) {
- var typeNode = getTypeNodeIfAccessible(type, declaration, program, host);
+ var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host);
if (typeNode) {
if (ts.isInJSFile(sourceFile) && declaration.kind !== 153 /* PropertySignature */) {
var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration;
@@ -110945,7 +112207,7 @@ var ts;
// only infer parameters that have (1) no type and (2) an accessible inferred type
if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name))
return;
- var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host);
+ var typeNode = inference.type && ts.getTypeNodeIfAccessible(inference.type, param, program, host);
var name = ts.getSynthesizedClone(param.name);
ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), "");
@@ -110978,40 +112240,17 @@ var ts;
return undefined;
}
switch (oldTag.kind) {
- case 299 /* JSDocParameterTag */: {
+ case 304 /* JSDocParameterTag */: {
var oldParam = oldTag;
var newParam = newTag;
return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText
? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment)
: undefined;
}
- case 300 /* JSDocReturnTag */:
+ case 305 /* JSDocReturnTag */:
return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment);
}
}
- function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
- var checker = program.getTypeChecker();
- var typeIsAccessible = true;
- var notAccessible = function () { typeIsAccessible = false; };
- var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
- trackSymbol: function (symbol, declaration, meaning) {
- // TODO: GH#18217
- typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
- },
- reportInaccessibleThisError: notAccessible,
- reportPrivateInBaseOfClassExpression: notAccessible,
- reportInaccessibleUniqueSymbolError: notAccessible,
- moduleResolverHost: {
- readFile: host.readFile,
- fileExists: host.fileExists,
- directoryExists: host.directoryExists,
- getSourceFiles: program.getSourceFiles,
- getCurrentDirectory: program.getCurrentDirectory,
- getCommonSourceDirectory: program.getCommonSourceDirectory,
- }
- });
- return typeIsAccessible ? res : undefined;
- }
function getReferences(token, program, cancellationToken) {
// Position shouldn't matter since token is not a SourceFile.
return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) {
@@ -111310,8 +112549,8 @@ var ts;
}
function removeLowPriorityInferences(inferences, priorities) {
var toRemove = [];
- for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
- var i = inferences_2[_i];
+ for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
+ var i = inferences_1[_i];
for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) {
var _b = priorities_1[_a], high = _b.high, low = _b.low;
if (high(i)) {
@@ -111403,8 +112642,8 @@ var ts;
types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); }));
if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) {
var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217
- var types_20 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); });
- types_20.push(checker.createPromiseType(types_20.length ? checker.getUnionType(types_20, 2 /* Subtype */) : checker.getAnyType()));
+ var types_1 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); });
+ types_1.push(checker.createPromiseType(types_1.length ? checker.getUnionType(types_1, 2 /* Subtype */) : checker.getAnyType()));
}
else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) {
types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)));
@@ -111413,7 +112652,7 @@ var ts;
types.push(checker.createArrayType(recur(usageContext.numberIndexContext)));
}
else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) {
- var members_6 = ts.createUnderscoreEscapedMap();
+ var members_1 = ts.createUnderscoreEscapedMap();
var callSignatures = [];
var constructSignatures = [];
var stringIndexInfo = void 0;
@@ -111421,7 +112660,7 @@ var ts;
usageContext.properties.forEach(function (context, name) {
var symbol = checker.createSymbol(4 /* Property */, name);
symbol.type = recur(context);
- members_6.set(name, symbol);
+ members_1.set(name, symbol);
});
}
if (usageContext.callContexts) {
@@ -111439,7 +112678,7 @@ var ts;
if (usageContext.stringIndexContext) {
stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false);
}
- types.push(checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217
+ types.push(checker.createAnonymousType(/*symbol*/ undefined, members_1, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217
}
return types;
function recur(innerContext) {
@@ -111524,7 +112763,7 @@ var ts;
precedingNode = ctorDeclaration.parent.parent;
newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
if (ctorDeclaration.parent.declarations.length === 1) {
- ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
+ ts.copyLeadingComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
changes.delete(sourceFile, precedingNode);
}
else {
@@ -111535,7 +112774,7 @@ var ts;
if (!newClassDeclaration) {
return undefined;
}
- ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile);
+ ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile);
// Because the preceding node could be touched, we need to insert nodes before delete nodes.
changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
function createClassElementsFromSymbol(symbol) {
@@ -111588,7 +112827,7 @@ var ts;
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 121 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
- ts.copyComments(assignmentBinaryExpression, method, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
case 197 /* ArrowFunction */: {
@@ -111606,7 +112845,7 @@ var ts;
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 121 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
- ts.copyComments(assignmentBinaryExpression, method, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
default: {
@@ -111616,7 +112855,7 @@ var ts;
}
var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
/*type*/ undefined, assignmentBinaryExpression.right);
- ts.copyComments(assignmentBinaryExpression.parent, prop, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile);
return prop;
}
}
@@ -111708,7 +112947,7 @@ var ts;
var newNodes = transformExpression(node, transformer, node);
changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes);
}
- var _loop_21 = function (statement) {
+ var _loop_11 = function (statement) {
ts.forEachChild(statement, function visit(node) {
if (ts.isCallExpression(node)) {
startTransformation(node, statement);
@@ -111720,7 +112959,7 @@ var ts;
};
for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) {
var statement = returnStatements_1[_i];
- _loop_21(statement);
+ _loop_11(statement);
}
}
function getReturnStatementsWithPromiseHandlers(body) {
@@ -112045,8 +113284,8 @@ var ts;
if (innerCbBody.length > 0) {
return innerCbBody;
}
- var type_6 = transformer.checker.getTypeAtLocation(func);
- var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType();
+ var type_1 = transformer.checker.getTypeAtLocation(func);
+ var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType();
var rightHandSide = ts.getSynthesizedDeepClone(funcBody);
var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide;
if (!shouldReturn) {
@@ -113372,7 +114611,7 @@ var ts;
});
typeDeclToMembers.forEach(function (infos, classDeclaration) {
var supers = getAllSupers(classDeclaration, checker);
- var _loop_22 = function (info) {
+ var _loop_12 = function (info) {
// If some superclass added this property, don't add it again.
if (supers.some(function (superClassOrInterface) {
var superInfos = typeDeclToMembers.get(superClassOrInterface);
@@ -113399,7 +114638,7 @@ var ts;
};
for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
var info = infos_1[_i];
- _loop_22(info);
+ _loop_12(info);
}
});
}));
@@ -114365,7 +115604,7 @@ var ts;
var typeNode = info.typeNode, type = info.type;
var original = typeNode.getText(sourceFile);
var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)];
- if (typeNode.kind === 286 /* JSDocNullableType */) {
+ if (typeNode.kind === 291 /* JSDocNullableType */) {
// for nullable types, suggest the flow-compatible `T | null | undefined`
// in addition to the jsdoc/closure-compatible `T | null`
actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
@@ -114385,7 +115624,7 @@ var ts;
if (!info)
return;
var typeNode = info.typeNode, type = info.type;
- var fixedType = typeNode.kind === 286 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
+ var fixedType = typeNode.kind === 291 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
doChange(changes, sourceFile, typeNode, fixedType, checker);
});
}
@@ -114634,8 +115873,8 @@ var ts;
outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences));
break;
}
- for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) {
- var signature = signatures_7[_i];
+ for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
+ var signature = signatures_1[_i];
// Need to ensure nodes are fresh each time so they can have different positions.
outputMethod(signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false));
}
@@ -114718,8 +115957,8 @@ var ts;
var maxArgsSignature = signatures[0];
var minArgumentCount = signatures[0].minArgumentCount;
var someSigHasRestParameter = false;
- for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
- var sig = signatures_8[_i];
+ for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
+ var sig = signatures_2[_i];
minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount);
if (sig.hasRestParameter) {
someSigHasRestParameter = true;
@@ -114878,8 +116117,8 @@ var ts;
ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport));
}
if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) {
- var sourceFile_3 = context.sourceFile;
- var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_3, expr, ts.createPropertyAccess(expr, "default"), {}); });
+ var sourceFile_1 = context.sourceFile;
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_1, expr, ts.createPropertyAccess(expr, "default"), {}); });
fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member));
}
return fixes;
@@ -115017,6 +116256,7 @@ var ts;
return ts.textChanges.getNewFileText(toStatements(valueInfo, outputKind), 3 /* TS */, formatSettings.newLineCharacter || "\n", ts.formatting.getFormatContext(formatSettings));
}
ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText;
+ /* @internal */
var OutputKind;
(function (OutputKind) {
OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals";
@@ -115158,9 +116398,9 @@ var ts;
forEachOwnNodeOfFunction(fnAst, function (node) {
if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) &&
ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 100 /* ThisKeyword */) {
- var name_7 = node.left.name.text;
- if (!ts.isJsPrivate(name_7)) {
- ts.getOrUpdate(members, name_7, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_7, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); });
+ var name_4 = node.left.name.text;
+ if (!ts.isJsPrivate(name_4)) {
+ ts.getOrUpdate(members, name_4, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_4, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); });
}
}
});
@@ -115675,7 +116915,7 @@ var ts;
});
var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName;
var neededNamedImports = [];
- var _loop_23 = function (element) {
+ var _loop_13 = function (element) {
var propertyName = (element.propertyName || element.name).text;
ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) {
var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName);
@@ -115694,7 +116934,7 @@ var ts;
};
for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) {
var element = _a[_i];
- _loop_23(element);
+ _loop_13(element);
}
changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName)));
if (neededNamedImports.length) {
@@ -116184,7 +117424,7 @@ var ts;
// * Module/namespace or source file
if (isScope(current)) {
scopes.push(current);
- if (current.kind === 279 /* SourceFile */) {
+ if (current.kind === 284 /* SourceFile */) {
return scopes;
}
}
@@ -116749,8 +117989,8 @@ var ts;
ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one.
var prevMember;
var allProperties = true;
- for (var _i = 0, members_7 = members; _i < members_7.length; _i++) {
- var member = members_7[_i];
+ for (var _i = 0, members_2 = members; _i < members_2.length; _i++) {
+ var member = members_2[_i];
if (member.pos > maxPos) {
return prevMember || members[0];
}
@@ -116924,7 +118164,7 @@ var ts;
: ts.getEnclosingBlockScopeContainer(scopes[0]);
ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
- var _loop_24 = function (i) {
+ var _loop_14 = function (i) {
var scopeUsages = usagesPerScope[i];
// Special case: in the innermost scope, all usages are available.
// (The computed value reflects the value at the top-level of the scope, but the
@@ -116964,7 +118204,7 @@ var ts;
}
};
for (var i = 0; i < scopes.length; i++) {
- _loop_24(i);
+ _loop_14(i);
}
return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
function isInGenericContext(node) {
@@ -117198,7 +118438,7 @@ var ts;
function isBlockLike(node) {
switch (node.kind) {
case 218 /* Block */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 245 /* ModuleBlock */:
case 271 /* CaseClause */:
return true;
@@ -117515,10 +118755,10 @@ var ts;
}
function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) {
var checker = program.getTypeChecker();
- var _loop_25 = function (sourceFile) {
+ var _loop_15 = function (sourceFile) {
if (sourceFile === oldFile)
return "continue";
- var _loop_26 = function (statement) {
+ var _loop_16 = function (statement) {
forEachImportInStatement(statement, function (importNode) {
if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol)
return;
@@ -117540,12 +118780,12 @@ var ts;
};
for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
var statement = _a[_i];
- _loop_26(statement);
+ _loop_16(statement);
}
};
for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
var sourceFile = _a[_i];
- _loop_25(sourceFile);
+ _loop_15(sourceFile);
}
}
function getNamespaceLikeImport(node) {
@@ -117660,9 +118900,9 @@ var ts;
if (isTopLevelDeclarationStatement(statement) &&
!isExported(sourceFile, statement, useEs6Exports) &&
forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) {
- var exports_2 = addExport(statement, useEs6Exports);
- if (exports_2)
- return exports_2;
+ var exports = addExport(statement, useEs6Exports);
+ if (exports)
+ return exports;
}
return statement;
});
@@ -118137,13 +119377,13 @@ var ts;
var returnStatement_1 = ts.createReturn(expression);
body = ts.createBlock([returnStatement_1], /* multiLine */ true);
ts.suppressLeadingAndTrailingTrivia(body);
- ts.copyComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
+ ts.copyLeadingComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
}
else if (actionName === removeBracesActionName && returnStatement) {
var actualExpression = expression || ts.createVoidZero();
body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression;
ts.suppressLeadingAndTrailingTrivia(body);
- ts.copyComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
+ ts.copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
}
else {
ts.Debug.fail("invalid action");
@@ -118182,6 +119422,410 @@ var ts;
})(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var refactor;
+ (function (refactor) {
+ var convertToNamedParameters;
+ (function (convertToNamedParameters) {
+ var refactorName = "Convert to named parameters";
+ var minimumParameterLength = 2;
+ refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
+ function getAvailableActions(context) {
+ var file = context.file, startPosition = context.startPosition;
+ var isJSFile = ts.isSourceFileJS(file);
+ if (isJSFile)
+ return ts.emptyArray; // TODO: GH#30113
+ var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker());
+ if (!functionDeclaration)
+ return ts.emptyArray;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_named_parameters);
+ return [{
+ name: refactorName,
+ description: description,
+ actions: [{
+ name: refactorName,
+ description: description
+ }]
+ }];
+ }
+ function getEditsForAction(context, actionName) {
+ ts.Debug.assert(actionName === refactorName);
+ var file = context.file, startPosition = context.startPosition, program = context.program, cancellationToken = context.cancellationToken, host = context.host;
+ var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker());
+ if (!functionDeclaration || !cancellationToken)
+ return undefined;
+ var groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken);
+ if (groupedReferences.valid) {
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(file, program, host, t, functionDeclaration, groupedReferences); });
+ return { renameFilename: undefined, renameLocation: undefined, edits: edits };
+ }
+ return { edits: [] }; // TODO: GH#30113
+ }
+ function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) {
+ var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); });
+ changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ",
+ // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter
+ indentation: 0,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include
+ });
+ var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); });
+ for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) {
+ var call = functionCalls_1[_i];
+ if (call.arguments && call.arguments.length) {
+ var newArgument = ts.getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true);
+ changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include });
+ }
+ }
+ }
+ function getGroupedReferences(functionDeclaration, program, cancellationToken) {
+ var functionNames = getFunctionNames(functionDeclaration);
+ var classNames = ts.isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : [];
+ var names = ts.deduplicate(functionNames.concat(classNames), ts.equateValues);
+ var checker = program.getTypeChecker();
+ var references = ts.flatMap(names, /*mapfn*/ function (/*mapfn*/ name) { return ts.FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken); });
+ var groupedReferences = groupReferences(references);
+ if (!ts.every(groupedReferences.declarations, function (decl) { return ts.contains(names, decl); })) {
+ groupedReferences.valid = false;
+ }
+ return groupedReferences;
+ function groupReferences(referenceEntries) {
+ var classReferences = { accessExpressions: [], typeUsages: [] };
+ var groupedReferences = { functionCalls: [], declarations: [], classReferences: classReferences, valid: true };
+ var functionSymbols = ts.map(functionNames, checker.getSymbolAtLocation);
+ var classSymbols = ts.map(classNames, checker.getSymbolAtLocation);
+ var isConstructor = ts.isConstructorDeclaration(functionDeclaration);
+ for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) {
+ var entry = referenceEntries_1[_i];
+ if (entry.kind !== 1 /* Node */) {
+ groupedReferences.valid = false;
+ continue;
+ }
+ if (ts.contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ var call = entryToFunctionCall(entry);
+ if (call) {
+ groupedReferences.functionCalls.push(call);
+ continue;
+ }
+ }
+ // if the refactored function is a constructor, we must also check if the references to its class are valid
+ if (isConstructor && ts.contains(classSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ var accessExpression = entryToAccessExpression(entry);
+ if (accessExpression) {
+ classReferences.accessExpressions.push(accessExpression);
+ continue;
+ }
+ // Only class declarations are allowed to be used as a type (in a heritage clause),
+ // otherwise `findAllReferences` might not be able to track constructor calls.
+ if (ts.isClassDeclaration(functionDeclaration.parent)) {
+ var type = entryToType(entry);
+ if (type) {
+ classReferences.typeUsages.push(type);
+ continue;
+ }
+ }
+ }
+ groupedReferences.valid = false;
+ }
+ return groupedReferences;
+ }
+ }
+ function symbolComparer(a, b) {
+ return ts.getSymbolTarget(a) === ts.getSymbolTarget(b);
+ }
+ function entryToDeclaration(entry) {
+ if (ts.isDeclaration(entry.node.parent)) {
+ return entry.node;
+ }
+ return undefined;
+ }
+ function entryToFunctionCall(entry) {
+ if (entry.node.parent) {
+ var functionReference = entry.node;
+ var parent = functionReference.parent;
+ switch (parent.kind) {
+ // Function call (foo(...) or super(...))
+ case 191 /* CallExpression */:
+ var callExpression = ts.tryCast(parent, ts.isCallExpression);
+ if (callExpression && callExpression.expression === functionReference) {
+ return callExpression;
+ }
+ break;
+ // Constructor call (new Foo(...))
+ case 192 /* NewExpression */:
+ var newExpression = ts.tryCast(parent, ts.isNewExpression);
+ if (newExpression && newExpression.expression === functionReference) {
+ return newExpression;
+ }
+ break;
+ // Method call (x.foo(...))
+ case 189 /* PropertyAccessExpression */:
+ var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
+ if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) {
+ var callExpression_1 = ts.tryCast(propertyAccessExpression.parent, ts.isCallExpression);
+ if (callExpression_1 && callExpression_1.expression === propertyAccessExpression) {
+ return callExpression_1;
+ }
+ }
+ break;
+ // Method call (x["foo"](...))
+ case 190 /* ElementAccessExpression */:
+ var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
+ if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) {
+ var callExpression_2 = ts.tryCast(elementAccessExpression.parent, ts.isCallExpression);
+ if (callExpression_2 && callExpression_2.expression === elementAccessExpression) {
+ return callExpression_2;
+ }
+ }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function entryToAccessExpression(entry) {
+ if (entry.node.parent) {
+ var reference = entry.node;
+ var parent = reference.parent;
+ switch (parent.kind) {
+ // `C.foo`
+ case 189 /* PropertyAccessExpression */:
+ var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
+ if (propertyAccessExpression && propertyAccessExpression.expression === reference) {
+ return propertyAccessExpression;
+ }
+ break;
+ // `C["foo"]`
+ case 190 /* ElementAccessExpression */:
+ var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
+ if (elementAccessExpression && elementAccessExpression.expression === reference) {
+ return elementAccessExpression;
+ }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function entryToType(entry) {
+ var reference = entry.node;
+ if (ts.getMeaningFromLocation(reference) === 2 /* Type */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) {
+ return reference;
+ }
+ return undefined;
+ }
+ function getFunctionDeclarationAtPosition(file, startPosition, checker) {
+ var node = ts.getTouchingToken(file, startPosition);
+ var functionDeclaration = ts.getContainingFunction(node);
+ if (functionDeclaration
+ && isValidFunctionDeclaration(functionDeclaration, checker)
+ && ts.rangeContainsRange(functionDeclaration, node)
+ && !(functionDeclaration.body && ts.rangeContainsRange(functionDeclaration.body, node)))
+ return functionDeclaration;
+ return undefined;
+ }
+ function isValidFunctionDeclaration(functionDeclaration, checker) {
+ if (!isValidParameterNodeArray(functionDeclaration.parameters))
+ return false;
+ switch (functionDeclaration.kind) {
+ case 239 /* FunctionDeclaration */:
+ case 156 /* MethodDeclaration */:
+ return !!functionDeclaration.name && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration);
+ case 157 /* Constructor */:
+ if (ts.isClassDeclaration(functionDeclaration.parent)) {
+ return !!functionDeclaration.body && !!functionDeclaration.parent.name && !checker.isImplementationOfOverload(functionDeclaration);
+ }
+ else {
+ return isValidVariableDeclaration(functionDeclaration.parent.parent) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration);
+ }
+ case 196 /* FunctionExpression */:
+ case 197 /* ArrowFunction */:
+ return isValidVariableDeclaration(functionDeclaration.parent);
+ }
+ return false;
+ }
+ function isValidParameterNodeArray(parameters) {
+ return getRefactorableParametersLength(parameters) >= minimumParameterLength && ts.every(parameters, isValidParameterDeclaration);
+ }
+ function isValidParameterDeclaration(paramDeclaration) {
+ return !paramDeclaration.modifiers && !paramDeclaration.decorators && ts.isIdentifier(paramDeclaration.name);
+ }
+ function isValidVariableDeclaration(node) {
+ return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113
+ }
+ function hasThisParameter(parameters) {
+ return parameters.length > 0 && ts.isThis(parameters[0].name);
+ }
+ function getRefactorableParametersLength(parameters) {
+ if (hasThisParameter(parameters)) {
+ return parameters.length - 1;
+ }
+ return parameters.length;
+ }
+ function getRefactorableParameters(parameters) {
+ if (hasThisParameter(parameters)) {
+ parameters = ts.createNodeArray(parameters.slice(1), parameters.hasTrailingComma);
+ }
+ return parameters;
+ }
+ function createNewArgument(functionDeclaration, functionArguments) {
+ var parameters = getRefactorableParameters(functionDeclaration.parameters);
+ var hasRestParameter = ts.isRestParameter(ts.last(parameters));
+ var nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments;
+ var properties = ts.map(nonRestArguments, function (arg, i) {
+ var property = ts.createPropertyAssignment(getParameterName(parameters[i]), arg);
+ ts.suppressLeadingAndTrailingTrivia(property.initializer);
+ copyComments(arg, property);
+ return property;
+ });
+ if (hasRestParameter && functionArguments.length >= parameters.length) {
+ var restArguments = functionArguments.slice(parameters.length - 1);
+ var restProperty = ts.createPropertyAssignment(getParameterName(ts.last(parameters)), ts.createArrayLiteral(restArguments));
+ properties.push(restProperty);
+ }
+ var objectLiteral = ts.createObjectLiteral(properties, /*multiLine*/ false);
+ return objectLiteral;
+ }
+ function createNewParameters(functionDeclaration, program, host) {
+ var refactorableParameters = getRefactorableParameters(functionDeclaration.parameters);
+ var bindingElements = ts.map(refactorableParameters, createBindingElementFromParameterDeclaration);
+ var objectParameterName = ts.createObjectBindingPattern(bindingElements);
+ var objectParameterType = createParameterTypeNode(refactorableParameters);
+ var checker = program.getTypeChecker();
+ var objectInitializer;
+ // If every parameter in the original function was optional, add an empty object initializer to the new object parameter
+ if (ts.every(refactorableParameters, checker.isOptionalParameter)) {
+ objectInitializer = ts.createObjectLiteral();
+ }
+ var objectParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, objectParameterName,
+ /*questionToken*/ undefined, objectParameterType, objectInitializer);
+ if (hasThisParameter(functionDeclaration.parameters)) {
+ var thisParameter = functionDeclaration.parameters[0];
+ var newThisParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, thisParameter.name,
+ /*questionToken*/ undefined, thisParameter.type);
+ ts.suppressLeadingAndTrailingTrivia(newThisParameter.name);
+ copyComments(thisParameter.name, newThisParameter.name);
+ if (thisParameter.type) {
+ ts.suppressLeadingAndTrailingTrivia(newThisParameter.type);
+ copyComments(thisParameter.type, newThisParameter.type);
+ }
+ return ts.createNodeArray([newThisParameter, objectParameter]);
+ }
+ return ts.createNodeArray([objectParameter]);
+ function createParameterTypeNode(parameters) {
+ var members = ts.map(parameters, createPropertySignatureFromParameterDeclaration);
+ var typeNode = ts.addEmitFlags(ts.createTypeLiteralNode(members), 1 /* SingleLine */);
+ return typeNode;
+ }
+ function createPropertySignatureFromParameterDeclaration(parameterDeclaration) {
+ var parameterType = parameterDeclaration.type;
+ if (!parameterType && (parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration))) {
+ parameterType = getTypeNode(parameterDeclaration);
+ }
+ var propertySignature = ts.createPropertySignature(
+ /*modifiers*/ undefined, getParameterName(parameterDeclaration), parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration) ? ts.createToken(56 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType,
+ /*initializer*/ undefined);
+ ts.suppressLeadingAndTrailingTrivia(propertySignature);
+ copyComments(parameterDeclaration.name, propertySignature.name);
+ if (parameterDeclaration.type && propertySignature.type) {
+ copyComments(parameterDeclaration.type, propertySignature.type);
+ }
+ return propertySignature;
+ }
+ function getTypeNode(node) {
+ var checker = program.getTypeChecker();
+ var type = checker.getTypeAtLocation(node);
+ return ts.getTypeNodeIfAccessible(type, node, program, host);
+ }
+ }
+ function createBindingElementFromParameterDeclaration(parameterDeclaration) {
+ var element = ts.createBindingElement(
+ /*dotDotDotToken*/ undefined,
+ /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer);
+ ts.suppressLeadingAndTrailingTrivia(element);
+ if (parameterDeclaration.initializer && element.initializer) {
+ copyComments(parameterDeclaration.initializer, element.initializer);
+ }
+ return element;
+ }
+ function copyComments(sourceNode, targetNode) {
+ var sourceFile = sourceNode.getSourceFile();
+ var text = sourceFile.text;
+ if (hasLeadingLineBreak(sourceNode, text)) {
+ ts.copyLeadingComments(sourceNode, targetNode, sourceFile);
+ }
+ else {
+ ts.copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile);
+ }
+ ts.copyTrailingComments(sourceNode, targetNode, sourceFile);
+ }
+ function hasLeadingLineBreak(node, text) {
+ var start = node.getFullStart();
+ var end = node.getStart();
+ for (var i = start; i < end; i++) {
+ if (text.charCodeAt(i) === 10 /* lineFeed */)
+ return true;
+ }
+ return false;
+ }
+ function getParameterName(paramDeclaration) {
+ return ts.getTextOfIdentifierOrLiteral(paramDeclaration.name);
+ }
+ function getClassNames(constructorDeclaration) {
+ switch (constructorDeclaration.parent.kind) {
+ case 240 /* ClassDeclaration */:
+ var classDeclaration = constructorDeclaration.parent;
+ return [classDeclaration.name];
+ case 209 /* ClassExpression */:
+ var classExpression = constructorDeclaration.parent;
+ var variableDeclaration = constructorDeclaration.parent.parent;
+ var className = classExpression.name;
+ if (className)
+ return [className, variableDeclaration.name];
+ return [variableDeclaration.name];
+ }
+ }
+ function getFunctionNames(functionDeclaration) {
+ switch (functionDeclaration.kind) {
+ case 239 /* FunctionDeclaration */:
+ case 156 /* MethodDeclaration */:
+ return [functionDeclaration.name];
+ case 157 /* Constructor */:
+ var ctrKeyword = ts.findChildOfKind(functionDeclaration, 124 /* ConstructorKeyword */, functionDeclaration.getSourceFile());
+ if (functionDeclaration.parent.kind === 209 /* ClassExpression */) {
+ var variableDeclaration = functionDeclaration.parent.parent;
+ return [variableDeclaration.name, ctrKeyword];
+ }
+ return [ctrKeyword];
+ case 197 /* ArrowFunction */:
+ return [functionDeclaration.parent.name];
+ case 196 /* FunctionExpression */:
+ if (functionDeclaration.name)
+ return [functionDeclaration.name, functionDeclaration.parent.name];
+ return [functionDeclaration.parent.name];
+ default:
+ return ts.Debug.assertNever(functionDeclaration);
+ }
+ }
+ })(convertToNamedParameters = refactor.convertToNamedParameters || (refactor.convertToNamedParameters = {}));
+ })(refactor = ts.refactor || (ts.refactor = {}));
+})(ts || (ts = {}));
var ts;
(function (ts) {
/** The version of the language service API */
@@ -118262,7 +119906,7 @@ var ts;
if (!children.length) {
return undefined;
}
- var child = ts.find(children, function (kid) { return kid.kind < 283 /* FirstJSDocNode */ || kid.kind > 305 /* LastJSDocNode */; });
+ var child = ts.find(children, function (kid) { return kid.kind < 288 /* FirstJSDocNode */ || kid.kind > 310 /* LastJSDocNode */; });
return child.kind < 148 /* FirstNode */ ?
child :
child.getFirstToken(sourceFile);
@@ -118332,11 +119976,11 @@ var ts;
}
}
function createSyntaxList(nodes, parent) {
- var list = createNode(306 /* SyntaxList */, nodes.pos, nodes.end, parent);
+ var list = createNode(311 /* SyntaxList */, nodes.pos, nodes.end, parent);
list._children = [];
var pos = nodes.pos;
- for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) {
- var node = nodes_7[_i];
+ for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
+ var node = nodes_1[_i];
addSyntheticNodes(list._children, pos, node.pos, parent);
list._children.push(node);
pos = node.end;
@@ -118580,8 +120224,8 @@ var ts;
return ts.emptyArray;
var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations);
if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) {
- for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) {
- var declaration = declarations_14[_i];
+ for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
+ var declaration = declarations_4[_i];
var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217
// TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs
if (inheritedDocs)
@@ -119333,14 +120977,14 @@ var ts;
var typeChecker = program.getTypeChecker();
var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker);
if (!symbol || typeChecker.isUnknownSymbol(symbol)) {
- var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined;
- return type_7 && {
+ var type_2 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined;
+ return type_2 && {
kind: "" /* unknown */,
kindModifiers: "" /* none */,
textSpan: ts.createTextSpanFromNode(node, sourceFile),
- displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }),
- documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined,
- tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined
+ displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_2, ts.getContainerNode(node)); }),
+ documentation: type_2.symbol ? type_2.symbol.getDocumentationComment(typeChecker) : undefined,
+ tags: type_2.symbol ? type_2.symbol.getJsDocTags() : undefined
};
}
var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) {
@@ -121749,6 +123393,7 @@ var ts;
CommandTypes["SynchronizeProjectList"] = "synchronizeProjectList";
/* @internal */
CommandTypes["ApplyChangedToOpenFiles"] = "applyChangedToOpenFiles";
+ CommandTypes["UpdateOpen"] = "updateOpen";
/* @internal */
CommandTypes["EncodedSemanticClassificationsFull"] = "encodedSemanticClassifications-full";
/* @internal */
@@ -122466,8 +124111,8 @@ var ts;
dts: 0, dtsSize: 0,
deferred: 0, deferredSize: 0,
};
- for (var _i = 0, infos_2 = infos; _i < infos_2.length; _i++) {
- var info = infos_2[_i];
+ for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
+ var info = infos_1[_i];
var fileSize = includeSizes ? info.getTelemetryFileSize() : 0;
switch (info.scriptKind) {
case 1 /* JS */:
@@ -123259,8 +124904,8 @@ var ts;
var sourceFiles = this.program.getSourceFiles();
var strBuilder = "\tFiles (" + sourceFiles.length + ")\n";
if (writeProjectFileNames) {
- for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) {
- var file = sourceFiles_7[_i];
+ for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
+ var file = sourceFiles_1[_i];
strBuilder += "\t" + file.fileName + "\n";
}
}
@@ -123355,7 +125000,7 @@ var ts;
// ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/
var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations);
if (this.projectService.globalPlugins) {
- var _loop_27 = function (globalPluginName) {
+ var _loop_1 = function (globalPluginName) {
// Skip empty names from odd commandline parses
if (!globalPluginName)
return "continue";
@@ -123363,14 +125008,14 @@ var ts;
if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; }))
return "continue";
// Provide global: true so plugins can detect why they can't find their config
- this_2.projectService.logger.info("Loading global plugin " + globalPluginName);
- this_2.enablePlugin({ name: globalPluginName, global: true }, searchPaths, pluginConfigOverrides);
+ this_1.projectService.logger.info("Loading global plugin " + globalPluginName);
+ this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths, pluginConfigOverrides);
};
- var this_2 = this;
+ var this_1 = this;
// Enable global plugins with synthetic configuration entries
for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) {
var globalPluginName = _a[_i];
- _loop_27(globalPluginName);
+ _loop_1(globalPluginName);
}
}
};
@@ -124442,7 +126087,7 @@ var ts;
return this.watchFactory.watchDirectory(this.host, directory, function (fileOrDirectory) {
var fileOrDirectoryPath = _this.toPath(fileOrDirectory);
project.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
var configFilename = project.getConfigFilePath();
// If the the added or created file or directory is not supported file name, ignore the file
@@ -124542,7 +126187,7 @@ var ts;
}
project.updateGraph();
if (!this.useSingleInferredProject && !project.projectRootPath) {
- var _loop_28 = function (inferredProject) {
+ var _loop_2 = function (inferredProject) {
if (inferredProject === project || inferredProject.isOrphan()) {
return "continue";
}
@@ -124563,17 +126208,27 @@ var ts;
// Note that we need to create a copy of the array since the list of project can change
for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) {
var inferredProject = _a[_i];
- _loop_28(inferredProject);
+ _loop_2(inferredProject);
}
}
return project;
};
+ ProjectService.prototype.assignOrphanScriptInfosToInferredProject = function () {
+ var _this = this;
+ // collect orphaned files and assign them to inferred project just like we treat open of a file
+ this.openFiles.forEach(function (projectRootPath, path) {
+ var info = _this.getScriptInfoForPath(path);
+ // collect all orphaned script infos from open files
+ if (info.isOrphan()) {
+ _this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
+ }
+ });
+ };
/**
* Remove this file from the set of open, non-configured files.
* @param info The file that has been closed or newly configured
*/
- ProjectService.prototype.closeOpenFile = function (info) {
- var _this = this;
+ ProjectService.prototype.closeOpenFile = function (info, skipAssignOrphanScriptInfosToInferredProject) {
// Closing file should trigger re-reading the file content from disk. This is
// because the user may chose to discard the buffer content before saving
// to the disk, and the server's version of the file can be out of sync.
@@ -124612,15 +126267,8 @@ var ts;
}
}
this.openFiles.delete(info.path);
- if (ensureProjectsForOpenFiles) {
- // collect orphaned files and assign them to inferred project just like we treat open of a file
- this.openFiles.forEach(function (projectRootPath, path) {
- var info = _this.getScriptInfoForPath(path);
- // collect all orphaned script infos from open files
- if (info.isOrphan()) {
- _this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
- }
- });
+ if (!skipAssignOrphanScriptInfosToInferredProject && ensureProjectsForOpenFiles) {
+ this.assignOrphanScriptInfosToInferredProject();
}
// Cleanup script infos that arent part of any project (eg. those could be closed script infos not referenced by any project)
// is postponed to next file open so that if file from same project is opened,
@@ -124633,6 +126281,7 @@ var ts;
else {
this.handleDeletedFile(info);
}
+ return ensureProjectsForOpenFiles;
};
ProjectService.prototype.deleteScriptInfo = function (info) {
this.filenameToScriptInfo.delete(info.path);
@@ -124937,8 +126586,8 @@ var ts;
this.projectToSizeMap.set(name, 0);
this.projectToSizeMap.forEach(function (val) { return (availableSpace -= (val || 0)); });
var totalNonTsFileSize = 0;
- for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) {
- var f = fileNames_2[_i];
+ for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
+ var f = fileNames_1[_i];
var fileName = propertyReader.getFileName(f);
if (ts.hasTSFileExtension(fileName)) {
continue;
@@ -125103,8 +126752,8 @@ var ts;
ProjectService.prototype.updateNonInferredProjectFiles = function (project, files, propertyReader) {
var projectRootFilesMap = project.getRootFilesMap();
var newRootScriptInfoMap = ts.createMap();
- for (var _i = 0, files_4 = files; _i < files_4.length; _i++) {
- var f = files_4[_i];
+ for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
+ var f = files_1[_i];
var newRootFile = propertyReader.getFileName(f);
var normalizedPath = server.toNormalizedPath(newRootFile);
var isDynamic = server.isDynamicFileName(normalizedPath);
@@ -125322,7 +126971,7 @@ var ts;
return projects;
function combineProjects(toAddInfo) {
if (toAddInfo !== info) {
- var _loop_29 = function (project) {
+ var _loop_3 = function (project) {
// Add the projects only if they can use symLink targets and not already in the list
if (project.languageServiceEnabled &&
!project.isOrphan() &&
@@ -125339,7 +126988,7 @@ var ts;
};
for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) {
var project = _a[_i];
- _loop_29(project);
+ _loop_3(project);
}
}
}
@@ -125373,7 +127022,7 @@ var ts;
var watchDir = dir + "/node_modules";
var watcher = this.watchFactory.watchDirectory(this.host, watchDir, function (fileOrDirectory) {
var fileOrDirectoryPath = _this.toPath(fileOrDirectory);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
// Has extension
ts.Debug.assert(result.refCount > 0);
@@ -125842,18 +127491,21 @@ var ts;
return proj.containsScriptInfo(info);
});
};
- ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
- var configFileName;
- var configFileErrors;
+ ProjectService.prototype.getOrCreateOpenScriptInfo = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); // TODO: GH#18217
this.openFiles.set(info.path, projectRootPath);
+ return info;
+ };
+ ProjectService.prototype.assignProjectToOpenedScriptInfo = function (info) {
+ var configFileName;
+ var configFileErrors;
var project = this.findExternalProjectContainingOpenScriptInfo(info);
if (!project && !this.syntaxOnly) { // Checking syntaxOnly is an optimization
configFileName = this.getConfigFileNameForFile(info);
if (configFileName) {
project = this.findConfiguredProjectByProjectName(configFileName);
if (!project) {
- project = this.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + fileName + " to open");
+ project = this.createLoadAndUpdateConfiguredProject(configFileName, "Creating possible configured project for " + info.fileName + " to open");
// Send the event only if the project got created as part of this open request and info is part of the project
if (info.isOrphan()) {
// Since the file isnt part of configured project, do not send config file info
@@ -125861,7 +127513,7 @@ var ts;
}
else {
configFileErrors = project.getAllProjectErrors();
- this.sendConfigFileDiagEvent(project, fileName);
+ this.sendConfigFileDiagEvent(project, info.fileName);
}
}
else {
@@ -125880,9 +127532,13 @@ var ts;
// At this point if file is part of any any configured or external project, then it would be present in the containing projects
// So if it still doesnt have any containing projects, it needs to be part of inferred project
if (info.isOrphan()) {
- this.assignOrphanScriptInfoToInferredProject(info, projectRootPath);
+ ts.Debug.assert(this.openFiles.has(info.path));
+ this.assignOrphanScriptInfoToInferredProject(info, this.openFiles.get(info.path));
}
ts.Debug.assert(!info.isOrphan());
+ return { configFileName: configFileName, configFileErrors: configFileErrors };
+ };
+ ProjectService.prototype.cleanupAfterOpeningFile = function () {
// This was postponed from closeOpenFile to after opening next file,
// so that we can reuse the project if we need to right away
this.removeOrphanConfiguredProjects();
@@ -125900,8 +127556,13 @@ var ts;
// the file from that old project is reopened because of opening file from here.
this.removeOrphanScriptInfos();
this.printProjects();
+ };
+ ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) {
+ var info = this.getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath);
+ var result = this.assignProjectToOpenedScriptInfo(info);
+ this.cleanupAfterOpeningFile();
this.telemetryOnOpenFile(info);
- return { configFileName: configFileName, configFileErrors: configFileErrors };
+ return result;
};
ProjectService.prototype.removeOrphanConfiguredProjects = function () {
var _this = this;
@@ -125997,25 +127658,22 @@ var ts;
var info = { checkJs: !!project.getSourceFile(scriptInfo.path).checkJsDirective };
this.eventHandler({ eventName: server.OpenFileInfoTelemetryEvent, data: { info: info } });
};
- /**
- * Close file whose contents is managed by the client
- * @param filename is absolute pathname
- */
- ProjectService.prototype.closeClientFile = function (uncheckedFileName) {
+ ProjectService.prototype.closeClientFile = function (uncheckedFileName, skipAssignOrphanScriptInfosToInferredProject) {
var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName));
- if (info) {
- this.closeOpenFile(info);
+ var result = info ? this.closeOpenFile(info, skipAssignOrphanScriptInfosToInferredProject) : false;
+ if (!skipAssignOrphanScriptInfosToInferredProject) {
+ this.printProjects();
}
- this.printProjects();
+ return result;
};
ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) {
- var _loop_30 = function (proj) {
+ var _loop_4 = function (proj) {
var knownProject = ts.find(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName(); });
result.push(proj.getChangesSinceVersion(knownProject && knownProject.version));
};
for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) {
var proj = currentProjects_1[_i];
- _loop_30(proj);
+ _loop_4(proj);
}
};
/* @internal */
@@ -126028,35 +127686,59 @@ var ts;
};
/* @internal */
ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) {
+ var _this = this;
+ var openScriptInfos;
+ var assignOrphanScriptInfosToInferredProject = false;
if (openFiles) {
- for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) {
- var file = openFiles_1[_i];
+ while (true) {
+ var _a = openFiles.next(), file = _a.value, done = _a.done;
+ if (done)
+ break;
var scriptInfo = this.getScriptInfo(file.fileName);
ts.Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen(), "Script should not exist and not be open already");
- var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName);
- this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent); // TODO: GH#18217
+ // Create script infos so we have the new content for all the open files before we do any updates to projects
+ var info = this.getOrCreateOpenScriptInfo(scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName), file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent, file.projectRootPath ? server.toNormalizedPath(file.projectRootPath) : undefined);
+ (openScriptInfos || (openScriptInfos = [])).push(info);
}
}
if (changedFiles) {
- for (var _a = 0, changedFiles_2 = changedFiles; _a < changedFiles_2.length; _a++) {
- var file = changedFiles_2[_a];
+ while (true) {
+ var _b = changedFiles.next(), file = _b.value, done = _b.done;
+ if (done)
+ break;
var scriptInfo = this.getScriptInfo(file.fileName);
ts.Debug.assert(!!scriptInfo);
+ // Make edits to script infos and marks containing project as dirty
this.applyChangesToFile(scriptInfo, file.changes);
}
}
if (closedFiles) {
- for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) {
- var file = closedFiles_1[_b];
- this.closeClientFile(file);
+ for (var _i = 0, closedFiles_1 = closedFiles; _i < closedFiles_1.length; _i++) {
+ var file = closedFiles_1[_i];
+ // Close files, but dont assign projects to orphan open script infos, that part comes later
+ assignOrphanScriptInfosToInferredProject = this.closeClientFile(file, /*skipAssignOrphanScriptInfosToInferredProject*/ true) || assignOrphanScriptInfosToInferredProject;
}
}
+ // All the script infos now exist, so ok to go update projects for open files
+ if (openScriptInfos) {
+ openScriptInfos.forEach(function (info) { return _this.assignProjectToOpenedScriptInfo(info); });
+ }
+ // While closing files there could be open files that needed assigning new inferred projects, do it now
+ if (assignOrphanScriptInfosToInferredProject) {
+ this.assignOrphanScriptInfosToInferredProject();
+ }
+ // Cleanup projects
+ this.cleanupAfterOpeningFile();
+ // Telemetry
+ ts.forEach(openScriptInfos, function (info) { return _this.telemetryOnOpenFile(info); });
+ this.printProjects();
};
/* @internal */
ProjectService.prototype.applyChangesToFile = function (scriptInfo, changes) {
- // apply changes in reverse order
- for (var i = changes.length - 1; i >= 0; i--) {
- var change = changes[i];
+ while (true) {
+ var _a = changes.next(), change = _a.value, done = _a.done;
+ if (done)
+ break;
scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText);
}
};
@@ -126125,12 +127807,12 @@ var ts;
var excludeRules = [];
var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); });
var excludedFiles = [];
- var _loop_31 = function (name) {
- var rule = this_3.safelist[name];
+ var _loop_5 = function (name) {
+ var rule = this_2.safelist[name];
for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) {
var root = normalizedNames_1[_i];
if (rule.match.test(root)) {
- this_3.logger.info("Excluding files based on rule " + name + " matching file '" + root + "'");
+ this_2.logger.info("Excluding files based on rule " + name + " matching file '" + root + "'");
// If the file matches, collect its types packages and exclude rules
if (rule.types) {
for (var _a = 0, _b = rule.types; _a < _b.length; _a++) {
@@ -126143,7 +127825,7 @@ var ts;
}
}
if (rule.exclude) {
- var _loop_33 = function (exclude) {
+ var _loop_7 = function (exclude) {
var processedRule = root.replace(rule.match, function () {
var groups = [];
for (var _i = 0; _i < arguments.length; _i++) {
@@ -126170,7 +127852,7 @@ var ts;
};
for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) {
var exclude = _d[_c];
- _loop_33(exclude);
+ _loop_7(exclude);
}
}
else {
@@ -126183,14 +127865,14 @@ var ts;
}
}
};
- var this_3 = this;
+ var this_2 = this;
for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) {
var name = _a[_i];
- _loop_31(name);
+ _loop_5(name);
}
var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); });
var filesToKeep = [];
- var _loop_32 = function (i) {
+ var _loop_6 = function (i) {
if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) {
excludedFiles.push(normalizedNames[i]);
}
@@ -126201,9 +127883,9 @@ var ts;
if (ts.fileExtensionIs(baseName, "js")) {
var inferredTypingName = ts.removeFileExtension(baseName);
var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName);
- var typeName = this_4.legacySafelist.get(cleanedTypingName);
+ var typeName = this_3.legacySafelist.get(cleanedTypingName);
if (typeName !== undefined) {
- this_4.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist");
+ this_3.logger.info("Excluded '" + normalizedNames[i] + "' because it matched " + cleanedTypingName + " from the legacy safelist");
excludedFiles.push(normalizedNames[i]);
// *exclude* it from the project...
exclude = true;
@@ -126226,9 +127908,9 @@ var ts;
}
}
};
- var this_4 = this;
+ var this_3 = this;
for (var i = 0; i < proj.rootFiles.length; i++) {
- _loop_32(i);
+ _loop_6(i);
}
proj.rootFiles = filesToKeep;
return excludedFiles;
@@ -126633,7 +128315,7 @@ var ts;
var outputs = [];
combineProjectOutputWorker(projects, defaultProject, initialLocation, function (_a, getMappedLocation) {
var project = _a.project, location = _a.location;
- var _loop_34 = function (outputReferencedSymbol) {
+ var _loop_8 = function (outputReferencedSymbol) {
var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition));
var definition = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : __assign({}, outputReferencedSymbol.definition, { textSpan: ts.createTextSpan(mappedDefinitionFile.pos, outputReferencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName });
var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, definition); });
@@ -126651,7 +128333,7 @@ var ts;
};
for (var _i = 0, _b = project.getLanguageService().findReferences(location.fileName, location.pos) || server.emptyArray; _i < _b.length; _i++) {
var outputReferencedSymbol = _b[_i];
- _loop_34(outputReferencedSymbol);
+ _loop_8(outputReferencedSymbol);
}
}, function () { return getDefinitionLocation(defaultProject, initialLocation); });
return outputs.filter(function (o) { return o.references.length !== 0; });
@@ -126783,9 +128465,31 @@ var ts;
});
return _this.requiredResponse(converted);
},
+ _a[server.CommandNames.UpdateOpen] = function (request) {
+ _this.changeSeq++;
+ _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles && ts.mapIterator(ts.arrayIterator(request.arguments.openFiles), function (file) { return ({
+ fileName: file.file,
+ content: file.fileContent,
+ scriptKind: file.scriptKindName,
+ projectRootPath: file.projectRootPath
+ }); }), request.arguments.changedFiles && ts.mapIterator(ts.arrayIterator(request.arguments.changedFiles), function (file) { return ({
+ fileName: file.fileName,
+ changes: ts.mapDefinedIterator(ts.arrayReverseIterator(file.textChanges), function (change) {
+ var scriptInfo = ts.Debug.assertDefined(_this.projectService.getScriptInfo(file.fileName));
+ var start = scriptInfo.lineOffsetToPosition(change.start.line, change.start.offset);
+ var end = scriptInfo.lineOffsetToPosition(change.end.line, change.end.offset);
+ return start >= 0 ? { span: { start: start, length: end - start }, newText: change.newText } : undefined;
+ })
+ }); }), request.arguments.closedFiles);
+ return _this.requiredResponse(/*response*/ true);
+ },
_a[server.CommandNames.ApplyChangedToOpenFiles] = function (request) {
_this.changeSeq++;
- _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); // TODO: GH#18217
+ _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles && ts.arrayIterator(request.arguments.openFiles), request.arguments.changedFiles && ts.mapIterator(ts.arrayIterator(request.arguments.changedFiles), function (file) { return ({
+ fileName: file.fileName,
+ // apply changes in reverse order
+ changes: ts.arrayReverseIterator(file.changes)
+ }); }), request.arguments.closedFiles);
// TODO: report errors
return _this.requiredResponse(/*response*/ true);
},
@@ -127678,11 +129382,11 @@ var ts;
for (var _i = 0, locations_1 = locations; _i < locations_1.length; _i++) {
var _a = locations_1[_i];
var fileName = _a.fileName, textSpan = _a.textSpan, _ = _a.originalTextSpan, _1 = _a.originalFileName, prefixSuffixText = __rest(_a, ["fileName", "textSpan", "originalTextSpan", "originalFileName"]);
- var group_2 = map.get(fileName);
- if (!group_2)
- map.set(fileName, group_2 = { file: fileName, locs: [] });
+ var group_1 = map.get(fileName);
+ if (!group_1)
+ map.set(fileName, group_1 = { file: fileName, locs: [] });
var scriptInfo = ts.Debug.assertDefined(this.projectService.getScriptInfo(fileName));
- group_2.locs.push(__assign({}, this.toLocationTextSpan(textSpan, scriptInfo), prefixSuffixText));
+ group_1.locs.push(__assign({}, this.toLocationTextSpan(textSpan, scriptInfo), prefixSuffixText));
}
return ts.arrayFrom(map.values());
};
@@ -127699,7 +129403,7 @@ var ts;
var symbolDisplayString = nameInfo ? ts.displayPartsToString(nameInfo.displayParts) : "";
var nameSpan = nameInfo && nameInfo.textSpan;
var symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0;
- var symbolName_3 = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)) : "";
+ var symbolName_1 = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)) : "";
var refs = ts.flatMap(references, function (referencedSymbol) {
return referencedSymbol.references.map(function (_a) {
var fileName = _a.fileName, textSpan = _a.textSpan, isWriteAccess = _a.isWriteAccess, isDefinition = _a.isDefinition;
@@ -127710,7 +129414,7 @@ var ts;
return __assign({}, toFileSpan(fileName, textSpan, scriptInfo), { lineText: lineText, isWriteAccess: isWriteAccess, isDefinition: isDefinition });
});
});
- var result = { refs: refs, symbolName: symbolName_3, symbolStartOffset: symbolStartOffset, symbolDisplayString: symbolDisplayString };
+ var result = { refs: refs, symbolName: symbolName_1, symbolStartOffset: symbolStartOffset, symbolDisplayString: symbolDisplayString };
return result;
}
else {
@@ -127922,10 +129626,10 @@ var ts;
var prefix = args.prefix || "";
var entries = ts.mapDefined(completions.entries, function (entry) {
if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) {
- var name = entry.name, kind_2 = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended;
+ var name = entry.name, kind_1 = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended;
var convertedSpan = replacementSpan ? _this.toLocationTextSpan(replacementSpan, scriptInfo) : undefined;
// Use `hasAction || undefined` to avoid serializing `false`.
- return { name: name, kind: kind_2, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended };
+ return { name: name, kind: kind_1, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended };
}
}).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); });
if (kind === "completions" /* Completions */) {
@@ -128030,10 +129734,10 @@ var ts;
var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset);
if (start >= 0) {
this.changeSeq++;
- this.projectService.applyChangesToFile(scriptInfo, [{
- span: { start: start, length: end - start },
- newText: args.insertString // TODO: GH#18217
- }]);
+ this.projectService.applyChangesToFile(scriptInfo, ts.singleIterator({
+ span: { start: start, length: end - start },
+ newText: args.insertString // TODO: GH#18217
+ }));
}
};
Session.prototype.reload = function (args, reqSeq) {
@@ -128504,14 +130208,14 @@ var ts;
}
server.getLocationInNewDocument = getLocationInNewDocument;
function applyEdits(text, textFilename, edits) {
- for (var _i = 0, edits_2 = edits; _i < edits_2.length; _i++) {
- var _a = edits_2[_i], fileName = _a.fileName, textChanges_4 = _a.textChanges;
+ for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
+ var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges;
if (fileName !== textFilename) {
continue;
}
- for (var i = textChanges_4.length - 1; i >= 0; i--) {
- var _b = textChanges_4[i], newText = _b.newText, _c = _b.span, start = _c.start, length_6 = _c.length;
- text = text.slice(0, start) + newText + text.slice(start + length_6);
+ for (var i = textChanges_1.length - 1; i >= 0; i--) {
+ var _b = textChanges_1[i], newText = _b.newText, _c = _b.span, start = _c.start, length_1 = _c.length;
+ text = text.slice(0, start) + newText + text.slice(start + length_1);
}
}
return text;
diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts
index 40e16bf55bdfb..d7b494960537c 100644
--- a/lib/typescript.d.ts
+++ b/lib/typescript.d.ts
@@ -355,40 +355,45 @@ declare namespace ts {
ShorthandPropertyAssignment = 276,
SpreadAssignment = 277,
EnumMember = 278,
- SourceFile = 279,
- Bundle = 280,
- UnparsedSource = 281,
- InputFiles = 282,
- JSDocTypeExpression = 283,
- JSDocAllType = 284,
- JSDocUnknownType = 285,
- JSDocNullableType = 286,
- JSDocNonNullableType = 287,
- JSDocOptionalType = 288,
- JSDocFunctionType = 289,
- JSDocVariadicType = 290,
- JSDocComment = 291,
- JSDocTypeLiteral = 292,
- JSDocSignature = 293,
- JSDocTag = 294,
- JSDocAugmentsTag = 295,
- JSDocClassTag = 296,
- JSDocCallbackTag = 297,
- JSDocEnumTag = 298,
- JSDocParameterTag = 299,
- JSDocReturnTag = 300,
- JSDocThisTag = 301,
- JSDocTypeTag = 302,
- JSDocTemplateTag = 303,
- JSDocTypedefTag = 304,
- JSDocPropertyTag = 305,
- SyntaxList = 306,
- NotEmittedStatement = 307,
- PartiallyEmittedExpression = 308,
- CommaListExpression = 309,
- MergeDeclarationMarker = 310,
- EndOfDeclarationMarker = 311,
- Count = 312,
+ UnparsedPrologue = 279,
+ UnparsedPrepend = 280,
+ UnparsedText = 281,
+ UnparsedInternalText = 282,
+ UnparsedSyntheticReference = 283,
+ SourceFile = 284,
+ Bundle = 285,
+ UnparsedSource = 286,
+ InputFiles = 287,
+ JSDocTypeExpression = 288,
+ JSDocAllType = 289,
+ JSDocUnknownType = 290,
+ JSDocNullableType = 291,
+ JSDocNonNullableType = 292,
+ JSDocOptionalType = 293,
+ JSDocFunctionType = 294,
+ JSDocVariadicType = 295,
+ JSDocComment = 296,
+ JSDocTypeLiteral = 297,
+ JSDocSignature = 298,
+ JSDocTag = 299,
+ JSDocAugmentsTag = 300,
+ JSDocClassTag = 301,
+ JSDocCallbackTag = 302,
+ JSDocEnumTag = 303,
+ JSDocParameterTag = 304,
+ JSDocReturnTag = 305,
+ JSDocThisTag = 306,
+ JSDocTypeTag = 307,
+ JSDocTemplateTag = 308,
+ JSDocTypedefTag = 309,
+ JSDocPropertyTag = 310,
+ SyntaxList = 311,
+ NotEmittedStatement = 312,
+ PartiallyEmittedExpression = 313,
+ CommaListExpression = 314,
+ MergeDeclarationMarker = 315,
+ EndOfDeclarationMarker = 316,
+ Count = 317,
FirstAssignment = 59,
LastAssignment = 71,
FirstCompoundAssignment = 60,
@@ -414,10 +419,10 @@ declare namespace ts {
FirstBinaryOperator = 28,
LastBinaryOperator = 71,
FirstNode = 148,
- FirstJSDocNode = 283,
- LastJSDocNode = 305,
- FirstJSDocTagNode = 294,
- LastJSDocTagNode = 305
+ FirstJSDocNode = 288,
+ LastJSDocNode = 310,
+ FirstJSDocTagNode = 299,
+ LastJSDocTagNode = 310,
}
enum NodeFlags {
None = 0,
@@ -446,7 +451,7 @@ declare namespace ts {
ReachabilityCheckFlags = 384,
ReachabilityAndEmitFlags = 1408,
ContextFlags = 12679168,
- TypeExcludesFlags = 20480
+ TypeExcludesFlags = 20480,
}
enum ModifierFlags {
None = 0,
@@ -1003,7 +1008,7 @@ declare namespace ts {
Octal = 32,
HexSpecifier = 64,
BinarySpecifier = 128,
- OctalSpecifier = 256
+ OctalSpecifier = 256,
}
interface NumericLiteral extends LiteralExpression {
kind: SyntaxKind.NumericLiteral;
@@ -1745,10 +1750,44 @@ declare namespace ts {
}
interface UnparsedSource extends Node {
kind: SyntaxKind.UnparsedSource;
- fileName?: string;
+ fileName: string;
text: string;
+ prologues: ReadonlyArray;
+ helpers: ReadonlyArray | undefined;
+ referencedFiles: ReadonlyArray;
+ typeReferenceDirectives: ReadonlyArray | undefined;
+ libReferenceDirectives: ReadonlyArray;
+ hasNoDefaultLib?: boolean;
sourceMapPath?: string;
sourceMapText?: string;
+ syntheticReferences?: ReadonlyArray;
+ texts: ReadonlyArray;
+ }
+ type UnparsedSourceText = UnparsedPrepend | UnparsedTextLike;
+ type UnparsedNode = UnparsedPrologue | UnparsedSourceText | UnparsedSyntheticReference;
+ interface UnparsedSection extends Node {
+ kind: SyntaxKind;
+ data?: string;
+ parent: UnparsedSource;
+ }
+ interface UnparsedPrologue extends UnparsedSection {
+ kind: SyntaxKind.UnparsedPrologue;
+ data: string;
+ parent: UnparsedSource;
+ }
+ interface UnparsedPrepend extends UnparsedSection {
+ kind: SyntaxKind.UnparsedPrepend;
+ data: string;
+ parent: UnparsedSource;
+ texts: ReadonlyArray;
+ }
+ interface UnparsedTextLike extends UnparsedSection {
+ kind: SyntaxKind.UnparsedText | SyntaxKind.UnparsedInternalText;
+ parent: UnparsedSource;
+ }
+ interface UnparsedSyntheticReference extends UnparsedSection {
+ kind: SyntaxKind.UnparsedSyntheticReference;
+ parent: UnparsedSource;
}
interface JsonSourceFile extends SourceFile {
statements: NodeArray;
@@ -2022,7 +2061,7 @@ declare namespace ts {
WriteTypeParametersOrArguments = 1,
UseOnlyExternalAliasing = 2,
AllowAnyNodeKind = 4,
- UseAliasDefinedOutsideCurrentScope = 8
+ UseAliasDefinedOutsideCurrentScope = 8,
}
enum TypePredicateKind {
This = 0,
@@ -2100,7 +2139,7 @@ declare namespace ts {
ExportHasLocal = 944,
BlockScoped = 418,
PropertyOrAccessor = 98308,
- ClassMember = 106500
+ ClassMember = 106500,
}
interface Symbol {
flags: SymbolFlags;
@@ -2208,7 +2247,7 @@ declare namespace ts {
Instantiable = 63176704,
StructuredOrInstantiable = 66846720,
Narrowable = 133970943,
- NotUnionOrUnit = 67637251
+ NotUnionOrUnit = 67637251,
}
type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
interface Type {
@@ -2255,7 +2294,7 @@ declare namespace ts {
MarkerType = 8192,
JSLiteral = 16384,
FreshLiteral = 32768,
- ClassOrInterface = 3
+ ClassOrInterface = 3,
}
interface ObjectType extends Type {
objectFlags: ObjectFlags;
@@ -2503,6 +2542,8 @@ declare namespace ts {
reactNamespace?: string;
jsxFactory?: string;
composite?: boolean;
+ incremental?: boolean;
+ tsBuildInfoFile?: string;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
@@ -2679,7 +2720,8 @@ declare namespace ts {
Dts = ".d.ts",
Js = ".js",
Jsx = ".jsx",
- Json = ".json"
+ Json = ".json",
+ TsBuildInfo = ".tsbuildinfo"
}
interface ResolvedModuleWithFailedLookupLocations {
readonly resolvedModule: ResolvedModuleFull | undefined;
@@ -2752,7 +2794,7 @@ declare namespace ts {
NoHoisting = 2097152,
HasEndOfDeclarationMarker = 4194304,
Iterator = 8388608,
- NoAsciiEscaping = 16777216
+ NoAsciiEscaping = 16777216,
}
interface EmitHelper {
readonly name: string;
@@ -2760,6 +2802,10 @@ declare namespace ts {
readonly text: string | ((node: EmitHelperUniqueNameCallback) => string);
readonly priority?: number;
}
+ interface UnscopedEmitHelper extends EmitHelper {
+ readonly scoped: false;
+ readonly text: string;
+ }
type EmitHelperUniqueNameCallback = (name: string) => string;
enum EmitHint {
SourceFile = 0,
@@ -3459,6 +3505,9 @@ declare namespace ts {
function isSourceFile(node: Node): node is SourceFile;
function isBundle(node: Node): node is Bundle;
function isUnparsedSource(node: Node): node is UnparsedSource;
+ function isUnparsedPrepend(node: Node): node is UnparsedPrepend;
+ function isUnparsedTextLike(node: Node): node is UnparsedTextLike;
+ function isUnparsedNode(node: Node): node is UnparsedNode;
function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression;
function isJSDocAllType(node: JSDocAllType): node is JSDocAllType;
function isJSDocUnknownType(node: Node): node is JSDocUnknownType;
@@ -3994,10 +4043,10 @@ declare namespace ts {
function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression;
function createBundle(sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle;
function createUnparsedSourceFile(text: string): UnparsedSource;
- function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts"): UnparsedSource;
+ function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts", stripInternal?: boolean): UnparsedSource;
function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource;
function createInputFiles(javascriptText: string, declarationText: string): InputFiles;
- function createInputFiles(readFileText: (path: string) => string | undefined, javascriptPath: string, javascriptMapPath: string | undefined, declarationPath: string, declarationMapPath: string | undefined): InputFiles;
+ function createInputFiles(readFileText: (path: string) => string | undefined, javascriptPath: string, javascriptMapPath: string | undefined, declarationPath: string, declarationMapPath: string | undefined, buildInfoPath: string | undefined): InputFiles;
function createInputFiles(javascriptText: string, declarationText: string, javascriptMapPath: string | undefined, javascriptMapText: string | undefined, declarationMapPath: string | undefined, declarationMapText: string | undefined): InputFiles;
function updateBundle(node: Bundle, sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray): CallExpression;
diff --git a/lib/typescript.js b/lib/typescript.js
index 04665d089e1a5..4774041a6d731 100644
--- a/lib/typescript.js
+++ b/lib/typescript.js
@@ -812,7 +812,7 @@ var ts;
}
/**
* Deduplicates an unsorted array.
- * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates.
+ * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates.
* @param comparer An optional `Comparer` used to sort entries before comparison, though the
* result will remain in the original order in `array`.
*/
@@ -1028,6 +1028,21 @@ var ts;
} };
}
ts.arrayIterator = arrayIterator;
+ function arrayReverseIterator(array) {
+ var i = array.length;
+ return {
+ next: function () {
+ if (i === 0) {
+ return { value: undefined, done: true };
+ }
+ else {
+ i--;
+ return { value: array[i], done: false };
+ }
+ }
+ };
+ }
+ ts.arrayReverseIterator = arrayReverseIterator;
/**
* Stable sort of an array. Elements equal to each other maintain their relative position in the array.
*/
@@ -2867,47 +2882,53 @@ var ts;
SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment";
// Enum
SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember";
+ // Unparsed
+ SyntaxKind[SyntaxKind["UnparsedPrologue"] = 279] = "UnparsedPrologue";
+ SyntaxKind[SyntaxKind["UnparsedPrepend"] = 280] = "UnparsedPrepend";
+ SyntaxKind[SyntaxKind["UnparsedText"] = 281] = "UnparsedText";
+ SyntaxKind[SyntaxKind["UnparsedInternalText"] = 282] = "UnparsedInternalText";
+ SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 283] = "UnparsedSyntheticReference";
// Top-level nodes
- SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile";
- SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle";
- SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource";
- SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles";
+ SyntaxKind[SyntaxKind["SourceFile"] = 284] = "SourceFile";
+ SyntaxKind[SyntaxKind["Bundle"] = 285] = "Bundle";
+ SyntaxKind[SyntaxKind["UnparsedSource"] = 286] = "UnparsedSource";
+ SyntaxKind[SyntaxKind["InputFiles"] = 287] = "InputFiles";
// JSDoc nodes
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression";
+ SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 288] = "JSDocTypeExpression";
// The * type
- SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType";
+ SyntaxKind[SyntaxKind["JSDocAllType"] = 289] = "JSDocAllType";
// The ? type
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature";
- SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag";
- SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag";
- SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag";
+ SyntaxKind[SyntaxKind["JSDocUnknownType"] = 290] = "JSDocUnknownType";
+ SyntaxKind[SyntaxKind["JSDocNullableType"] = 291] = "JSDocNullableType";
+ SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 292] = "JSDocNonNullableType";
+ SyntaxKind[SyntaxKind["JSDocOptionalType"] = 293] = "JSDocOptionalType";
+ SyntaxKind[SyntaxKind["JSDocFunctionType"] = 294] = "JSDocFunctionType";
+ SyntaxKind[SyntaxKind["JSDocVariadicType"] = 295] = "JSDocVariadicType";
+ SyntaxKind[SyntaxKind["JSDocComment"] = 296] = "JSDocComment";
+ SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 297] = "JSDocTypeLiteral";
+ SyntaxKind[SyntaxKind["JSDocSignature"] = 298] = "JSDocSignature";
+ SyntaxKind[SyntaxKind["JSDocTag"] = 299] = "JSDocTag";
+ SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 300] = "JSDocAugmentsTag";
+ SyntaxKind[SyntaxKind["JSDocClassTag"] = 301] = "JSDocClassTag";
+ SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 302] = "JSDocCallbackTag";
+ SyntaxKind[SyntaxKind["JSDocEnumTag"] = 303] = "JSDocEnumTag";
+ SyntaxKind[SyntaxKind["JSDocParameterTag"] = 304] = "JSDocParameterTag";
+ SyntaxKind[SyntaxKind["JSDocReturnTag"] = 305] = "JSDocReturnTag";
+ SyntaxKind[SyntaxKind["JSDocThisTag"] = 306] = "JSDocThisTag";
+ SyntaxKind[SyntaxKind["JSDocTypeTag"] = 307] = "JSDocTypeTag";
+ SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 308] = "JSDocTemplateTag";
+ SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 309] = "JSDocTypedefTag";
+ SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 310] = "JSDocPropertyTag";
// Synthesized list
- SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList";
+ SyntaxKind[SyntaxKind["SyntaxList"] = 311] = "SyntaxList";
// Transformation nodes
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker";
+ SyntaxKind[SyntaxKind["NotEmittedStatement"] = 312] = "NotEmittedStatement";
+ SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 313] = "PartiallyEmittedExpression";
+ SyntaxKind[SyntaxKind["CommaListExpression"] = 314] = "CommaListExpression";
+ SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 315] = "MergeDeclarationMarker";
+ SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 316] = "EndOfDeclarationMarker";
// Enum value count
- SyntaxKind[SyntaxKind["Count"] = 312] = "Count";
+ SyntaxKind[SyntaxKind["Count"] = 317] = "Count";
// Markers
SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment";
SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment";
@@ -2934,10 +2955,10 @@ var ts;
SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator";
SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator";
SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode";
+ SyntaxKind[SyntaxKind["FirstJSDocNode"] = 288] = "FirstJSDocNode";
+ SyntaxKind[SyntaxKind["LastJSDocNode"] = 310] = "LastJSDocNode";
+ SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 299] = "FirstJSDocTagNode";
+ SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 310] = "LastJSDocTagNode";
/* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword";
/* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword";
})(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
@@ -3555,6 +3576,7 @@ var ts;
InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
InferenceFlags[InferenceFlags["NoFixing"] = 4] = "NoFixing";
+ InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 8] = "SkippedGenericFunction";
})(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
/**
* Ternary values are defined such that
@@ -3814,6 +3836,7 @@ var ts;
Extension["Js"] = ".js";
Extension["Jsx"] = ".jsx";
Extension["Json"] = ".json";
+ Extension["TsBuildInfo"] = ".tsbuildinfo";
})(Extension = ts.Extension || (ts.Extension = {}));
/* @internal */
var TransformFlags;
@@ -3971,6 +3994,20 @@ var ts;
EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
})(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
+ /*@internal*/
+ var BundleFileSectionKind;
+ (function (BundleFileSectionKind) {
+ BundleFileSectionKind["Prologue"] = "prologue";
+ BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
+ BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
+ BundleFileSectionKind["Reference"] = "reference";
+ BundleFileSectionKind["Type"] = "type";
+ BundleFileSectionKind["Lib"] = "lib";
+ BundleFileSectionKind["Prepend"] = "prepend";
+ BundleFileSectionKind["Text"] = "text";
+ BundleFileSectionKind["Internal"] = "internal";
+ // comments?
+ })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
var ListFormat;
(function (ListFormat) {
ListFormat[ListFormat["None"] = 0] = "None";
@@ -4378,6 +4415,8 @@ var ts;
: FileWatcherEventKind.Changed;
}
ts.getFileWatcherEventKind = getFileWatcherEventKind;
+ /*@internal*/
+ ts.ignoredPaths = ["/node_modules/.", "/.git"];
/**
* Watch the directory recursively using host provided method to watch child directories
* that means if this is recursive watcher, watch the children directories as well
@@ -4402,6 +4441,8 @@ var ts;
else {
directoryWatcher = {
watcher: host.watchDirectory(dirName, function (fileName) {
+ if (isIgnoredPath(fileName))
+ return;
// Call the actual callback
callbackCache.forEach(function (callbacks, rootDirName) {
if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
@@ -4451,7 +4492,7 @@ var ts;
var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
// Filter our the symbolic link directories since those arent included in recursive watch
// which is same behaviour when recursive: true is passed to fs.watch
- return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
+ return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
}) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
return newChildWatches || ts.emptyArray;
/**
@@ -4468,6 +4509,16 @@ var ts;
(newChildWatches || (newChildWatches = [])).push(childWatcher);
}
}
+ function isIgnoredPath(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
+ }
+ function isInPath(path, searchPath) {
+ if (ts.stringContains(path, searchPath))
+ return true;
+ if (host.useCaseSensitiveFileNames)
+ return false;
+ return ts.stringContains(toCanonicalFilePath(path), searchPath);
+ }
}
ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher;
function getNodeMajorVersion() {
@@ -5833,6 +5884,7 @@ var ts;
Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."),
Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."),
+ Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."),
The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."),
Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."),
File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),
@@ -6100,6 +6152,16 @@ var ts;
Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."),
Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."),
Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."),
+ Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"),
+ Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
+ A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"),
+ A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"),
+ Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"),
+ Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"),
+ Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
+ Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."),
+ Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"),
+ Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"),
The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"),
The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."),
The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."),
@@ -6316,6 +6378,7 @@ var ts;
Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"),
+ Convert_to_named_parameters: diag(95075, ts.DiagnosticCategory.Message, "Convert_to_named_parameters_95075", "Convert to named parameters"),
};
})(ts || (ts = {}));
var ts;
@@ -6803,16 +6866,20 @@ var ts;
return pos;
}
var shebangTriviaRegex = /^#!.*/;
+ /*@internal*/
function isShebangTrivia(text, pos) {
// Shebangs check must only be done at the start of the file
ts.Debug.assert(pos === 0);
return shebangTriviaRegex.test(text);
}
+ ts.isShebangTrivia = isShebangTrivia;
+ /*@internal*/
function scanShebangTrivia(text, pos) {
var shebang = shebangTriviaRegex.exec(text)[0];
pos = pos + shebang.length;
return pos;
}
+ ts.scanShebangTrivia = scanShebangTrivia;
/**
* Invokes a callback for each comment range following the provided position.
*
@@ -8522,7 +8589,7 @@ var ts;
}
}
function getSourceFileOfNode(node) {
- while (node && node.kind !== 279 /* SourceFile */) {
+ while (node && node.kind !== 284 /* SourceFile */) {
node = node.parent;
}
return node;
@@ -8668,7 +8735,7 @@ var ts;
// the syntax list itself considers them as normal trivia. Therefore if we simply skip
// trivia for the list, we may have skipped the JSDocComment as well. So we should process its
// first child to determine the actual position of its first token.
- if (node.kind === 306 /* SyntaxList */ && node._children.length > 0) {
+ if (node.kind === 311 /* SyntaxList */ && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -8687,7 +8754,7 @@ var ts;
}
ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
function isJSDocTypeExpressionOrChild(node) {
- return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
+ return node.kind === 288 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
}
function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
if (includeTrivia === void 0) { includeTrivia = false; }
@@ -8814,7 +8881,7 @@ var ts;
return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body);
}
function isBlockScopedContainerTopLevel(node) {
- return node.kind === 279 /* SourceFile */ ||
+ return node.kind === 284 /* SourceFile */ ||
node.kind === 244 /* ModuleDeclaration */ ||
ts.isFunctionLike(node);
}
@@ -8832,7 +8899,7 @@ var ts;
// - defined in the top level scope and source file is an external module
// - defined inside ambient module declaration located in the top level scope and source file not an external module
switch (node.parent.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node.parent);
case 245 /* ModuleBlock */:
return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
@@ -8850,7 +8917,7 @@ var ts;
ts.isEffectiveExternalModule = isEffectiveExternalModule;
function isBlockScope(node, parentNode) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 274 /* CatchClause */:
case 244 /* ModuleDeclaration */:
@@ -8875,9 +8942,9 @@ var ts;
ts.isBlockScope = isBlockScope;
function isDeclarationWithTypeParameters(node) {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
- case 293 /* JSDocSignature */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 298 /* JSDocSignature */:
return true;
default:
ts.assertType(node);
@@ -8893,12 +8960,12 @@ var ts;
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 240 /* ClassDeclaration */:
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
@@ -9043,7 +9110,7 @@ var ts;
function getErrorSpanForNode(sourceFile, node) {
var errorNode = node;
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
if (pos_1 === sourceFile.text.length) {
// file is empty - return span for the beginning of the file
@@ -9218,7 +9285,7 @@ var ts;
return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
case 150 /* TypeParameter */:
return node === parent.constraint;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return node === parent.constraint;
case 154 /* PropertyDeclaration */:
case 153 /* PropertySignature */:
@@ -9478,7 +9545,7 @@ var ts;
}
ts.getContainingClass = getContainingClass;
function getThisContainer(node, includeArrowFunctions) {
- ts.Debug.assert(node.kind !== 279 /* SourceFile */);
+ ts.Debug.assert(node.kind !== 284 /* SourceFile */);
while (true) {
node = node.parent;
if (!node) {
@@ -9532,7 +9599,7 @@ var ts;
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 243 /* EnumDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return node;
}
}
@@ -10240,7 +10307,7 @@ var ts;
}
ts.isJSDocConstructSignature = isJSDocConstructSignature;
function isJSDocTypeAlias(node) {
- return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 309 /* JSDocTypedefTag */ || node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocTypeAlias = isJSDocTypeAlias;
function isTypeAlias(node) {
@@ -10384,7 +10451,7 @@ var ts;
ts.hasRestParameter = hasRestParameter;
function isRestParameter(node) {
var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
- return node.dotDotDotToken !== undefined || !!type && type.kind === 290 /* JSDocVariadicType */;
+ return node.dotDotDotToken !== undefined || !!type && type.kind === 295 /* JSDocVariadicType */;
}
ts.isRestParameter = isRestParameter;
var AssignmentKind;
@@ -10869,7 +10936,7 @@ var ts;
|| kind === 158 /* GetAccessor */
|| kind === 159 /* SetAccessor */
|| kind === 244 /* ModuleDeclaration */
- || kind === 279 /* SourceFile */;
+ || kind === 284 /* SourceFile */;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(range) {
@@ -10946,7 +11013,7 @@ var ts;
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return 0;
case 208 /* SpreadElement */:
return 1;
@@ -11264,6 +11331,9 @@ var ts;
lineStart = true;
}
}
+ function getTextPosWithWriteLine() {
+ return lineStart ? output.length : (output.length + newLine.length);
+ }
reset();
return {
write: write,
@@ -11292,7 +11362,8 @@ var ts;
writeStringLiteral: write,
writeSymbol: function (s, _) { return write(s); },
writeTrailingSemicolon: write,
- writeComment: write
+ writeComment: write,
+ getTextPosWithWriteLine: getTextPosWithWriteLine
};
}
ts.createTextWriter = createTextWriter;
@@ -11583,7 +11654,7 @@ var ts;
ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
/** template tags are only available when a typedef isn't already using them */
function isNonTypeAliasTemplate(tag) {
- return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
+ return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 296 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
}
/**
* Gets the effective type annotation of the value parameter of a set accessor. If the node
@@ -12555,19 +12626,29 @@ var ts;
|| kind === 96 /* NullKeyword */
|| kind === 132 /* NeverKeyword */
|| kind === 211 /* ExpressionWithTypeArguments */
- || kind === 284 /* JSDocAllType */
- || kind === 285 /* JSDocUnknownType */
- || kind === 286 /* JSDocNullableType */
- || kind === 287 /* JSDocNonNullableType */
- || kind === 288 /* JSDocOptionalType */
- || kind === 289 /* JSDocFunctionType */
- || kind === 290 /* JSDocVariadicType */;
+ || kind === 289 /* JSDocAllType */
+ || kind === 290 /* JSDocUnknownType */
+ || kind === 291 /* JSDocNullableType */
+ || kind === 292 /* JSDocNonNullableType */
+ || kind === 293 /* JSDocOptionalType */
+ || kind === 294 /* JSDocFunctionType */
+ || kind === 295 /* JSDocVariadicType */;
}
ts.isTypeNodeKind = isTypeNodeKind;
function isAccessExpression(node) {
return node.kind === 189 /* PropertyAccessExpression */ || node.kind === 190 /* ElementAccessExpression */;
}
ts.isAccessExpression = isAccessExpression;
+ function isBundleFileTextLike(section) {
+ switch (section.kind) {
+ case "text" /* Text */:
+ case "internal" /* Internal */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isBundleFileTextLike = isBundleFileTextLike;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
@@ -13029,8 +13110,8 @@ var ts;
switch (declaration.kind) {
case 72 /* Identifier */:
return declaration;
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */: {
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */: {
var name = declaration.name;
if (name.kind === 148 /* QualifiedName */) {
return name.right;
@@ -13054,7 +13135,7 @@ var ts;
return undefined;
}
}
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return getNameOfJSDocTypedef(declaration);
case 254 /* ExportAssignment */: {
var expression = declaration.expression;
@@ -13258,7 +13339,7 @@ var ts;
return ts.emptyArray;
}
if (ts.isJSDocTypeAlias(node)) {
- ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */);
+ ts.Debug.assert(node.parent.kind === 296 /* JSDocComment */);
return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
}
if (node.typeParameters) {
@@ -13530,7 +13611,7 @@ var ts;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 308 /* PartiallyEmittedExpression */) {
+ while (node.kind === 313 /* PartiallyEmittedExpression */) {
node = node.expression;
}
return node;
@@ -13877,108 +13958,128 @@ var ts;
ts.isEnumMember = isEnumMember;
// Top-level nodes
function isSourceFile(node) {
- return node.kind === 279 /* SourceFile */;
+ return node.kind === 284 /* SourceFile */;
}
ts.isSourceFile = isSourceFile;
function isBundle(node) {
- return node.kind === 280 /* Bundle */;
+ return node.kind === 285 /* Bundle */;
}
ts.isBundle = isBundle;
function isUnparsedSource(node) {
- return node.kind === 281 /* UnparsedSource */;
+ return node.kind === 286 /* UnparsedSource */;
}
ts.isUnparsedSource = isUnparsedSource;
+ function isUnparsedPrepend(node) {
+ return node.kind === 280 /* UnparsedPrepend */;
+ }
+ ts.isUnparsedPrepend = isUnparsedPrepend;
+ function isUnparsedTextLike(node) {
+ switch (node.kind) {
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isUnparsedTextLike = isUnparsedTextLike;
+ function isUnparsedNode(node) {
+ return isUnparsedTextLike(node) ||
+ node.kind === 279 /* UnparsedPrologue */ ||
+ node.kind === 283 /* UnparsedSyntheticReference */;
+ }
+ ts.isUnparsedNode = isUnparsedNode;
// JSDoc
function isJSDocTypeExpression(node) {
- return node.kind === 283 /* JSDocTypeExpression */;
+ return node.kind === 288 /* JSDocTypeExpression */;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 284 /* JSDocAllType */;
+ return node.kind === 289 /* JSDocAllType */;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 285 /* JSDocUnknownType */;
+ return node.kind === 290 /* JSDocUnknownType */;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 286 /* JSDocNullableType */;
+ return node.kind === 291 /* JSDocNullableType */;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 287 /* JSDocNonNullableType */;
+ return node.kind === 292 /* JSDocNonNullableType */;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 288 /* JSDocOptionalType */;
+ return node.kind === 293 /* JSDocOptionalType */;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 289 /* JSDocFunctionType */;
+ return node.kind === 294 /* JSDocFunctionType */;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 290 /* JSDocVariadicType */;
+ return node.kind === 295 /* JSDocVariadicType */;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 291 /* JSDocComment */;
+ return node.kind === 296 /* JSDocComment */;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 295 /* JSDocAugmentsTag */;
+ return node.kind === 300 /* JSDocAugmentsTag */;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 296 /* JSDocClassTag */;
+ return node.kind === 301 /* JSDocClassTag */;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocEnumTag(node) {
- return node.kind === 298 /* JSDocEnumTag */;
+ return node.kind === 303 /* JSDocEnumTag */;
}
ts.isJSDocEnumTag = isJSDocEnumTag;
function isJSDocThisTag(node) {
- return node.kind === 301 /* JSDocThisTag */;
+ return node.kind === 306 /* JSDocThisTag */;
}
ts.isJSDocThisTag = isJSDocThisTag;
function isJSDocParameterTag(node) {
- return node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 300 /* JSDocReturnTag */;
+ return node.kind === 305 /* JSDocReturnTag */;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 302 /* JSDocTypeTag */;
+ return node.kind === 307 /* JSDocTypeTag */;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 303 /* JSDocTemplateTag */;
+ return node.kind === 308 /* JSDocTemplateTag */;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 304 /* JSDocTypedefTag */;
+ return node.kind === 309 /* JSDocTypedefTag */;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */;
+ return node.kind === 310 /* JSDocPropertyTag */;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 310 /* JSDocPropertyTag */ || node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 292 /* JSDocTypeLiteral */;
+ return node.kind === 297 /* JSDocTypeLiteral */;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
function isJSDocCallbackTag(node) {
- return node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocCallbackTag = isJSDocCallbackTag;
function isJSDocSignature(node) {
- return node.kind === 293 /* JSDocSignature */;
+ return node.kind === 298 /* JSDocSignature */;
}
ts.isJSDocSignature = isJSDocSignature;
})(ts || (ts = {}));
@@ -13989,7 +14090,7 @@ var ts;
(function (ts) {
/* @internal */
function isSyntaxList(n) {
- return n.kind === 306 /* SyntaxList */;
+ return n.kind === 311 /* SyntaxList */;
}
ts.isSyntaxList = isSyntaxList;
/* @internal */
@@ -14141,11 +14242,11 @@ var ts;
switch (kind) {
case 155 /* MethodSignature */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 166 /* ConstructorType */:
return true;
default:
@@ -14436,8 +14537,8 @@ var ts;
case 208 /* SpreadElement */:
case 212 /* AsExpression */:
case 210 /* OmittedExpression */:
- case 309 /* CommaListExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 314 /* CommaListExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -14451,12 +14552,12 @@ var ts;
ts.isAssertionExpression = isAssertionExpression;
/* @internal */
function isPartiallyEmittedExpression(node) {
- return node.kind === 308 /* PartiallyEmittedExpression */;
+ return node.kind === 313 /* PartiallyEmittedExpression */;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
/* @internal */
function isNotEmittedStatement(node) {
- return node.kind === 307 /* NotEmittedStatement */;
+ return node.kind === 312 /* NotEmittedStatement */;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
/* @internal */
@@ -14567,9 +14668,9 @@ var ts;
|| kind === 242 /* TypeAliasDeclaration */
|| kind === 150 /* TypeParameter */
|| kind === 237 /* VariableDeclaration */
- || kind === 304 /* JSDocTypedefTag */
- || kind === 297 /* JSDocCallbackTag */
- || kind === 305 /* JSDocPropertyTag */;
+ || kind === 309 /* JSDocTypedefTag */
+ || kind === 302 /* JSDocCallbackTag */
+ || kind === 310 /* JSDocPropertyTag */;
}
function isDeclarationStatementKind(kind) {
return kind === 239 /* FunctionDeclaration */
@@ -14604,14 +14705,14 @@ var ts;
|| kind === 219 /* VariableStatement */
|| kind === 224 /* WhileStatement */
|| kind === 231 /* WithStatement */
- || kind === 307 /* NotEmittedStatement */
- || kind === 311 /* EndOfDeclarationMarker */
- || kind === 310 /* MergeDeclarationMarker */;
+ || kind === 312 /* NotEmittedStatement */
+ || kind === 316 /* EndOfDeclarationMarker */
+ || kind === 315 /* MergeDeclarationMarker */;
}
/* @internal */
function isDeclaration(node) {
if (node.kind === 150 /* TypeParameter */) {
- return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node);
+ return (node.parent && node.parent.kind !== 308 /* JSDocTemplateTag */) || ts.isInJSFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -14706,18 +14807,18 @@ var ts;
/** True if node is of some JSDoc syntax kind. */
/* @internal */
function isJSDocNode(node) {
- return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */;
+ return node.kind >= 288 /* FirstJSDocNode */ && node.kind <= 310 /* LastJSDocNode */;
}
ts.isJSDocNode = isJSDocNode;
/** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node) {
- return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
+ return node.kind === 296 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
}
ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
// TODO: determine what this does before making it public.
/* @internal */
function isJSDocTag(node) {
- return node.kind >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */;
+ return node.kind >= 299 /* FirstJSDocTagNode */ && node.kind <= 310 /* LastJSDocTagNode */;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -15034,6 +15135,10 @@ var ts;
return !!(compilerOptions.declaration || compilerOptions.composite);
}
ts.getEmitDeclarations = getEmitDeclarations;
+ function isIncrementalCompilation(options) {
+ return !!(options.incremental || options.composite);
+ }
+ ts.isIncrementalCompilation = isIncrementalCompilation;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
}
@@ -16318,7 +16423,7 @@ var ts;
var SourceFileConstructor;
// tslint:enable variable-name
function createNode(kind, pos, end) {
- if (kind === 279 /* SourceFile */) {
+ if (kind === 284 /* SourceFile */) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 72 /* Identifier */) {
@@ -16569,7 +16674,7 @@ var ts;
case 218 /* Block */:
case 245 /* ModuleBlock */:
return visitNodes(cbNode, cbNodes, node.statements);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return visitNodes(cbNode, cbNodes, node.statements) ||
visitNode(cbNode, node.endOfFileToken);
case 219 /* VariableStatement */:
@@ -16718,7 +16823,7 @@ var ts;
return visitNode(cbNode, node.expression);
case 258 /* MissingDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return visitNodes(cbNode, cbNodes, node.elements);
case 260 /* JsxElement */:
return visitNode(cbNode, node.openingElement) ||
@@ -16747,60 +16852,60 @@ var ts;
return visitNode(cbNode, node.tagName);
case 171 /* OptionalType */:
case 172 /* RestType */:
- case 283 /* JSDocTypeExpression */:
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 288 /* JSDocOptionalType */:
- case 290 /* JSDocVariadicType */:
+ case 288 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 293 /* JSDocOptionalType */:
+ case 295 /* JSDocVariadicType */:
return visitNode(cbNode, node.type);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return visitNodes(cbNode, cbNodes, node.tags);
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return visitNode(cbNode, node.tagName) ||
(node.isNameFirst
? visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression)
: visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name));
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.constraint) ||
visitNodes(cbNode, cbNodes, node.typeParameters);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return visitNode(cbNode, node.tagName) ||
(node.typeExpression &&
- node.typeExpression.kind === 283 /* JSDocTypeExpression */
+ node.typeExpression.kind === 288 /* JSDocTypeExpression */
? visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName)
: visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression));
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.typeExpression);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return ts.forEach(node.jsDocPropertyTags, cbNode);
- case 294 /* JSDocTag */:
- case 296 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
return visitNode(cbNode, node.tagName);
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
}
@@ -17174,7 +17279,7 @@ var ts;
function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
// code from createNode is inlined here so createNode won't have to deal with special case of creating source files
// this is quite rare comparing to other nodes and createNode should be as fast as possible
- var sourceFile = new SourceFileConstructor(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
+ var sourceFile = new SourceFileConstructor(284 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
@@ -18374,9 +18479,9 @@ var ts;
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(284 /* JSDocAllType */);
+ var result = createNode(289 /* JSDocAllType */);
if (postFixEquals) {
- return createPostfixType(288 /* JSDocOptionalType */, result);
+ return createPostfixType(293 /* JSDocOptionalType */, result);
}
else {
nextToken();
@@ -18384,7 +18489,7 @@ var ts;
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(287 /* JSDocNonNullableType */);
+ var result = createNode(292 /* JSDocNonNullableType */);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -18408,18 +18513,18 @@ var ts;
token() === 30 /* GreaterThanToken */ ||
token() === 59 /* EqualsToken */ ||
token() === 50 /* BarToken */) {
- var result = createNode(285 /* JSDocUnknownType */, pos);
+ var result = createNode(290 /* JSDocUnknownType */, pos);
return finishNode(result);
}
else {
- var result = createNode(286 /* JSDocNullableType */, pos);
+ var result = createNode(291 /* JSDocNullableType */, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(289 /* JSDocFunctionType */);
+ var result = createNodeWithJSDoc(294 /* JSDocFunctionType */);
nextToken();
fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
return finishNode(result);
@@ -18443,12 +18548,12 @@ var ts;
var type = parseTypeOrTypePredicate();
scanner.setInJSDocType(false);
if (dotdotdot) {
- var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos);
+ var variadic = createNode(295 /* JSDocVariadicType */, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 59 /* EqualsToken */) {
- return createPostfixType(288 /* JSDocOptionalType */, type);
+ return createPostfixType(293 /* JSDocOptionalType */, type);
}
return type;
}
@@ -18820,7 +18925,7 @@ var ts;
return finishNode(node);
}
var type = parseType();
- if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) {
+ if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 291 /* JSDocNullableType */ && type.pos === type.type.pos) {
type.kind = 171 /* OptionalType */;
}
return type;
@@ -19007,14 +19112,14 @@ var ts;
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 52 /* ExclamationToken */:
- type = createPostfixType(287 /* JSDocNonNullableType */, type);
+ type = createPostfixType(292 /* JSDocNonNullableType */, type);
break;
case 56 /* QuestionToken */:
// If not in JSDoc and next token is start of a type we have a conditional type
if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
return type;
}
- type = createPostfixType(286 /* JSDocNullableType */, type);
+ type = createPostfixType(291 /* JSDocNullableType */, type);
break;
case 22 /* OpenBracketToken */:
parseExpected(22 /* OpenBracketToken */);
@@ -21951,7 +22056,7 @@ var ts;
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
// Parses out a JSDoc type expression.
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(283 /* JSDocTypeExpression */);
+ var result = createNode(288 /* JSDocTypeExpression */);
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -22114,7 +22219,7 @@ var ts;
}
}
function createJSDocComment() {
- var result = createNode(291 /* JSDocComment */, start);
+ var result = createNode(296 /* JSDocComment */, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
@@ -22281,7 +22386,7 @@ var ts;
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(start, tagName) {
- var result = createNode(294 /* JSDocTag */, start);
+ var result = createNode(299 /* JSDocTag */, start);
result.tagName = tagName;
return finishNode(result);
}
@@ -22340,8 +22445,8 @@ var ts;
typeExpression = tryParseTypeExpression();
}
var result = target === 1 /* Property */ ?
- createNode(305 /* JSDocPropertyTag */, start) :
- createNode(299 /* JSDocParameterTag */, start);
+ createNode(310 /* JSDocPropertyTag */, start) :
+ createNode(304 /* JSDocParameterTag */, start);
var comment = parseTagComments(indent + scanner.getStartPos() - start);
var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
if (nestedTypeLiteral) {
@@ -22358,18 +22463,18 @@ var ts;
}
function parseNestedTypeLiteral(typeExpression, name, target, indent) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(288 /* JSDocTypeExpression */, scanner.getTokenPos());
var child = void 0;
var jsdocTypeLiteral = void 0;
var start_2 = scanner.getStartPos();
var children = void 0;
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
- if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) {
+ if (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 169 /* ArrayType */) {
jsdocTypeLiteral.isArrayType = true;
@@ -22380,25 +22485,25 @@ var ts;
}
}
function parseReturnTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 305 /* JSDocReturnTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(300 /* JSDocReturnTag */, start);
+ var result = createNode(305 /* JSDocReturnTag */, start);
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 307 /* JSDocTypeTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(302 /* JSDocTypeTag */, start);
+ var result = createNode(307 /* JSDocTypeTag */, start);
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
return finishNode(result);
}
function parseAugmentsTag(start, tagName) {
- var result = createNode(295 /* JSDocAugmentsTag */, start);
+ var result = createNode(300 /* JSDocAugmentsTag */, start);
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
return finishNode(result);
@@ -22425,19 +22530,19 @@ var ts;
return node;
}
function parseClassTag(start, tagName) {
- var tag = createNode(296 /* JSDocClassTag */, start);
+ var tag = createNode(301 /* JSDocClassTag */, start);
tag.tagName = tagName;
return finishNode(tag);
}
function parseThisTag(start, tagName) {
- var tag = createNode(301 /* JSDocThisTag */, start);
+ var tag = createNode(306 /* JSDocThisTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
return finishNode(tag);
}
function parseEnumTag(start, tagName) {
- var tag = createNode(298 /* JSDocEnumTag */, start);
+ var tag = createNode(303 /* JSDocEnumTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
@@ -22446,7 +22551,7 @@ var ts;
function parseTypedefTag(start, tagName, indent) {
var typeExpression = tryParseTypeExpression();
skipWhitespaceOrAsterisk();
- var typedefTag = createNode(304 /* JSDocTypedefTag */, start);
+ var typedefTag = createNode(309 /* JSDocTypedefTag */, start);
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace();
typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
@@ -22460,9 +22565,9 @@ var ts;
var childTypeTag = void 0;
while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start);
}
- if (child.kind === 302 /* JSDocTypeTag */) {
+ if (child.kind === 307 /* JSDocTypeTag */) {
if (childTypeTag) {
break;
}
@@ -22508,14 +22613,14 @@ var ts;
return typeNameOrNamespaceName;
}
function parseCallbackTag(start, tagName, indent) {
- var callbackTag = createNode(297 /* JSDocCallbackTag */, start);
+ var callbackTag = createNode(302 /* JSDocCallbackTag */, start);
callbackTag.tagName = tagName;
callbackTag.fullName = parseJSDocTypeNameWithNamespace();
callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
skipWhitespace();
callbackTag.comment = parseTagComments(indent);
var child;
- var jsdocSignature = createNode(293 /* JSDocSignature */, start);
+ var jsdocSignature = createNode(298 /* JSDocSignature */, start);
jsdocSignature.parameters = [];
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
@@ -22523,7 +22628,7 @@ var ts;
var returnTag = tryParse(function () {
if (parseOptionalJsdoc(58 /* AtToken */)) {
var tag = parseTag(indent);
- if (tag && tag.kind === 300 /* JSDocReturnTag */) {
+ if (tag && tag.kind === 305 /* JSDocReturnTag */) {
return tag;
}
}
@@ -22568,7 +22673,7 @@ var ts;
case 58 /* AtToken */:
if (canParseTag) {
var child = tryParseChildTag(target, indent);
- if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) &&
+ if (child && (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) &&
target !== 4 /* CallbackParameter */ &&
name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
@@ -22638,7 +22743,7 @@ var ts;
skipWhitespace();
typeParameters.push(typeParameter);
} while (parseOptionalJsdoc(27 /* CommaToken */));
- var result = createNode(303 /* JSDocTemplateTag */, start);
+ var result = createNode(308 /* JSDocTemplateTag */, start);
result.tagName = tagName;
result.constraint = constraint;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -23724,6 +23829,22 @@ var ts;
category: ts.Diagnostics.Basic_Options,
description: ts.Diagnostics.Enable_project_compilation,
},
+ {
+ name: "incremental",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_incremental_compilation,
+ },
+ {
+ name: "tsBuildInfoFile",
+ type: "string",
+ isFilePath: true,
+ paramType: ts.Diagnostics.FILE,
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
+ },
{
name: "removeComments",
type: "boolean",
@@ -27442,7 +27563,7 @@ var ts;
return "__constructor" /* Constructor */;
case 165 /* FunctionType */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return "__call" /* Call */;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
@@ -27451,7 +27572,7 @@ var ts;
return "__index" /* Index */;
case 255 /* ExportDeclaration */:
return "__export" /* ExportStar */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// json file should behave as
// module.exports = ...
return "export=" /* ExportEquals */;
@@ -27462,12 +27583,12 @@ var ts;
}
ts.Debug.fail("Unknown binary declaration kind");
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
case 151 /* Parameter */:
// Parameters with names are handled at the top of this function. Parameters
// without names can only come from JSDocFunctionTypes.
- ts.Debug.assert(node.parent.kind === 289 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
+ ts.Debug.assert(node.parent.kind === 294 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
var functionType = node.parent;
var index = functionType.parameters.indexOf(node);
return "arg" + index;
@@ -27706,7 +27827,7 @@ var ts;
if (hasExplicitReturn)
node.flags |= 256 /* HasExplicitReturn */;
}
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
node.flags |= emitFlags;
}
if (currentReturnTarget) {
@@ -27850,12 +27971,12 @@ var ts;
case 191 /* CallExpression */:
bindCallExpressionFlow(node);
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
bindJSDocTypeAlias(node);
break;
// In source files and blocks, bind functions first to match hoisting that occurs at runtime
- case 279 /* SourceFile */: {
+ case 284 /* SourceFile */: {
bindEachFunctionsFirst(node.statements);
bind(node.endOfFileToken);
break;
@@ -28542,7 +28663,7 @@ var ts;
case 243 /* EnumDeclaration */:
case 188 /* ObjectLiteralExpression */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 268 /* JsxAttributes */:
return 1 /* IsContainer */;
case 241 /* InterfaceDeclaration */:
@@ -28551,7 +28672,7 @@ var ts;
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
return 1 /* IsContainer */ | 32 /* HasLocals */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
case 156 /* MethodDeclaration */:
if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
@@ -28564,8 +28685,8 @@ var ts;
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
- case 289 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
case 165 /* FunctionType */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
@@ -28619,7 +28740,7 @@ var ts;
// handlers to take care of declaring these child members.
case 244 /* ModuleDeclaration */:
return declareModuleMember(node, symbolFlags, symbolExcludes);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return declareSourceFileMember(node, symbolFlags, symbolExcludes);
case 209 /* ClassExpression */:
case 240 /* ClassDeclaration */:
@@ -28627,7 +28748,7 @@ var ts;
case 243 /* EnumDeclaration */:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 188 /* ObjectLiteralExpression */:
case 241 /* InterfaceDeclaration */:
case 268 /* JsxAttributes */:
@@ -28641,7 +28762,7 @@ var ts;
case 166 /* ConstructorType */:
case 160 /* CallSignature */:
case 161 /* ConstructSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 162 /* IndexSignature */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
@@ -28651,9 +28772,9 @@ var ts;
case 239 /* FunctionDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
- case 289 /* JSDocFunctionType */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 294 /* JSDocFunctionType */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
// All the children of these container types are never visible through another
@@ -28676,8 +28797,8 @@ var ts;
: declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
function hasExportDeclarations(node) {
- var body = node.kind === 279 /* SourceFile */ ? node : node.body;
- if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
+ var body = node.kind === 284 /* SourceFile */ ? node : node.body;
+ if (body && (body.kind === 284 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
var stat = _a[_i];
if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) {
@@ -28811,7 +28932,7 @@ var ts;
case 244 /* ModuleDeclaration */:
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalOrCommonJsModule(container)) {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
@@ -28949,7 +29070,7 @@ var ts;
function checkStrictModeFunctionDeclaration(node) {
if (languageVersion < 2 /* ES2015 */) {
// Report error if function is not top level function declaration
- if (blockScopeContainer.kind !== 279 /* SourceFile */ &&
+ if (blockScopeContainer.kind !== 284 /* SourceFile */ &&
blockScopeContainer.kind !== 244 /* ModuleDeclaration */ &&
!ts.isFunctionLike(blockScopeContainer)) {
// We check first if the name is inside class declaration or class expression; if so give explicit message
@@ -29224,12 +29345,12 @@ var ts;
case 159 /* SetAccessor */:
return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */);
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
case 166 /* ConstructorType */:
return bindFunctionOrConstructorType(node);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 181 /* MappedType */:
return bindAnonymousTypeWorker(node);
case 188 /* ObjectLiteralExpression */:
@@ -29288,7 +29409,7 @@ var ts;
return bindExportDeclaration(node);
case 254 /* ExportAssignment */:
return bindExportAssignment(node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
updateStrictModeStatementList(node.statements);
return bindSourceFileIfExternalModule();
case 218 /* Block */:
@@ -29298,22 +29419,22 @@ var ts;
// falls through
case 245 /* ModuleBlock */:
return updateStrictModeStatementList(node.statements);
- case 299 /* JSDocParameterTag */:
- if (node.parent.kind === 293 /* JSDocSignature */) {
+ case 304 /* JSDocParameterTag */:
+ if (node.parent.kind === 298 /* JSDocSignature */) {
return bindParameter(node);
}
- if (node.parent.kind !== 292 /* JSDocTypeLiteral */) {
+ if (node.parent.kind !== 297 /* JSDocTypeLiteral */) {
break;
}
// falls through
- case 305 /* JSDocPropertyTag */:
+ case 310 /* JSDocPropertyTag */:
var propTag = node;
- var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ?
+ var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 293 /* JSDocOptionalType */ ?
4 /* Property */ | 16777216 /* Optional */ :
4 /* Property */;
return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
}
}
@@ -29485,7 +29606,7 @@ var ts;
var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
if (thisContainer.commonJsModuleIndicator) {
declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
@@ -29502,7 +29623,7 @@ var ts;
if (node.expression.kind === 100 /* ThisKeyword */) {
bindThisPropertyAssignment(node);
}
- else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) {
+ else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 284 /* SourceFile */) {
if (ts.isPrototypeAccess(node.expression)) {
bindPrototypePropertyAssignment(node, node.parent);
}
@@ -29539,7 +29660,7 @@ var ts;
}
function bindObjectDefinePropertyAssignment(node) {
var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
- var isToplevel = node.parent.parent.kind === 279 /* SourceFile */;
+ var isToplevel = node.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false);
bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
}
@@ -29606,8 +29727,8 @@ var ts;
function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) {
var namespaceSymbol = lookupSymbolForPropertyAccess(name);
var isToplevel = ts.isBinaryExpression(propertyAccess.parent)
- ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */
- : propertyAccess.parent.parent.kind === 279 /* SourceFile */;
+ ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 284 /* SourceFile */
+ : propertyAccess.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty);
bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
}
@@ -29745,7 +29866,7 @@ var ts;
}
}
function bindParameter(node) {
- if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) {
+ if (node.kind === 304 /* JSDocParameterTag */ && container.kind !== 298 /* JSDocSignature */) {
return;
}
if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) {
@@ -30488,7 +30609,7 @@ var ts;
break;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
// These nodes are TypeScript syntax.
transformFlags |= 3 /* AssertTypeScript */;
excludeFlags = 536872257 /* OuterExpressionExcludes */;
@@ -30689,7 +30810,7 @@ var ts;
transformFlags |= 192 /* AssertES2015 */;
}
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) {
transformFlags |= 192 /* AssertES2015 */;
}
@@ -30769,7 +30890,7 @@ var ts;
return 637666625 /* BindingPatternExcludes */;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
case 195 /* ParenthesizedExpression */:
case 98 /* SuperKeyword */:
return 536872257 /* OuterExpressionExcludes */;
@@ -31180,10 +31301,10 @@ var ts;
isContextSensitive: isContextSensitive,
getFullyQualifiedName: getFullyQualifiedName,
getResolvedSignature: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 0 /* Normal */);
},
getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16 /* IsForSignatureHelp */);
},
getConstantValue: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
@@ -31310,10 +31431,10 @@ var ts;
},
getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
};
- function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) {
+ function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
apparentArgumentCount = argumentCount;
- var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined;
+ var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
apparentArgumentCount = undefined;
return res;
}
@@ -31588,9 +31709,11 @@ var ts;
var CheckMode;
(function (CheckMode) {
CheckMode[CheckMode["Normal"] = 0] = "Normal";
- CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive";
+ CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
- CheckMode[CheckMode["Contextual"] = 3] = "Contextual";
+ CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
+ CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
+ CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
})(CheckMode || (CheckMode = {}));
var CallbackCheck;
(function (CallbackCheck) {
@@ -31946,7 +32069,7 @@ var ts;
return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 });
}
function isGlobalSourceFile(node) {
- return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
+ return node.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
}
function getSymbol(symbols, name, meaning) {
if (meaning) {
@@ -32120,7 +32243,7 @@ var ts;
// - parameters are only in the scope of function body
// This restriction does not apply to JSDoc comment types because they are parented
// at a higher level than type parameters would normally be
- if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) {
+ if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 296 /* JSDocComment */) {
useResult = result.flags & 262144 /* TypeParameter */
// type parameters are visible in parameter list, return type and type parameter list
? lastLocation === location.type ||
@@ -32162,14 +32285,14 @@ var ts;
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
isInExternalModule = true;
// falls through
case 244 /* ModuleDeclaration */:
var moduleExports = getSymbolOfNode(location).exports;
- if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) {
+ if (location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location)) {
// It's an external module. First see if the module has an export default and if the local
// name of that export default matches.
if (result = moduleExports.get("default" /* Default */)) {
@@ -32341,8 +32464,8 @@ var ts;
location = location.parent;
}
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
// js type aliases do not resolve names from their host, so skip past it
location = ts.getJSDocHost(location);
break;
@@ -32361,7 +32484,7 @@ var ts;
}
if (!result) {
if (lastLocation) {
- ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */);
+ ts.Debug.assert(lastLocation.kind === 284 /* SourceFile */);
if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
return lastLocation.symbol;
}
@@ -33217,7 +33340,7 @@ var ts;
function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) {
var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
if (!dontResolveAlias && symbol) {
- if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) {
+ if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 284 /* SourceFile */)) {
var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
? "allowSyntheticDefaultImports"
: "esModuleInterop";
@@ -33568,7 +33691,7 @@ var ts;
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
@@ -33808,10 +33931,10 @@ var ts;
return node && getSymbolOfNode(node);
}
function hasExternalModuleSymbol(declaration) {
- return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isAmbientModule(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
- return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
var aliasesToMakeVisible;
@@ -34268,7 +34391,7 @@ var ts;
var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
(symbol.parent || // is exported function symbol
ts.forEach(symbol.declarations, function (declaration) {
- return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
+ return declaration.parent.kind === 284 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
}));
if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
// typeof is allowed only for static/non local functions
@@ -34634,7 +34757,7 @@ var ts;
var savedContextFlags = context.flags;
context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
- type.symbol.declarations[0] &&
+ type.symbol.declarations && type.symbol.declarations[0] &&
ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
typeParameterShadowsNameInScope(type, context);
var name = shouldUseGeneratedName
@@ -34653,7 +34776,7 @@ var ts;
function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */);
if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) {
- parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */);
+ parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 304 /* JSDocParameterTag */);
}
var parameterType = getTypeOfSymbol(parameterSymbol);
if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
@@ -34811,7 +34934,7 @@ var ts;
return top;
}
function getSpecifierForModuleSymbol(symbol, context) {
- var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */);
+ var file = ts.getDeclarationOfKind(symbol, 284 /* SourceFile */);
if (file && file.moduleName !== undefined) {
// Use the amd name if it is available
return file.moduleName;
@@ -35064,7 +35187,7 @@ var ts;
ts.isExternalModuleAugmentation(node.parent.parent);
}
function isDefaultBindingContext(location) {
- return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location);
+ return location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location);
}
function getNameOfSymbolFromNameType(symbol, context) {
var nameType = symbol.nameType;
@@ -35141,8 +35264,8 @@ var ts;
return false;
function determineIfDeclarationIsVisible() {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
// Top-level jsdoc type aliases are considered exported
// First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file
return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
@@ -35169,7 +35292,7 @@ var ts;
var parent = getDeclarationContainer(node);
// If the node is not exported or it is not ambient module element (except import declaration)
if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
- !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
+ !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 284 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
return isGlobalSourceFile(parent);
}
// Exported members/ambient module elements (exception import declaration) are visible if parent is visible
@@ -35211,7 +35334,7 @@ var ts;
// Type parameters are always visible
case 150 /* TypeParameter */:
// Source file and namespace export are always visible
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 247 /* NamespaceExportDeclaration */:
return true;
// Export assignments do not create name bindings outside the module
@@ -36321,15 +36444,15 @@ var ts;
case 155 /* MethodSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 308 /* JSDocTemplateTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 181 /* MappedType */:
case 175 /* ConditionalType */:
var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
@@ -38321,10 +38444,10 @@ var ts;
function isJSDocOptionalParameter(node) {
return ts.isInJSFile(node) && (
// node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
- node.type && node.type.kind === 288 /* JSDocOptionalType */
+ node.type && node.type.kind === 293 /* JSDocOptionalType */
|| ts.getJSDocParameterTags(node).some(function (_a) {
var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}));
}
function tryFindAmbientModule(moduleName, withAugmentations) {
@@ -38358,7 +38481,7 @@ var ts;
return false;
}
var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}
function createIdentifierTypePredicate(parameterName, parameterIndex, type) {
return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
@@ -38689,8 +38812,21 @@ var ts;
}
return undefined;
}
- function getSignatureInstantiation(signature, typeArguments, isJavascript) {
- return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ if (inferredTypeParameters) {
+ var returnSignature = getSingleCallSignature(getReturnTypeOfSignature(instantiatedSignature));
+ if (returnSignature) {
+ var newReturnSignature = cloneSignature(returnSignature);
+ newReturnSignature.typeParameters = inferredTypeParameters;
+ newReturnSignature.target = returnSignature.target;
+ newReturnSignature.mapper = returnSignature.mapper;
+ var newInstantiatedSignature = cloneSignature(instantiatedSignature);
+ newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
+ return newInstantiatedSignature;
+ }
+ }
+ return instantiatedSignature;
}
function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
@@ -39062,7 +39198,7 @@ var ts;
}
function getTypeReferenceTypeWorker(node, symbol, typeArguments) {
if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
- if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
+ if (symbol.valueDeclaration && symbol.valueDeclaration.parent && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
var jsdocType = getJSDocTypeReference(node, symbol, typeArguments);
if (jsdocType) {
return jsdocType;
@@ -39098,7 +39234,7 @@ var ts;
}
function getConstrainedTypeVariable(typeVariable, node) {
var constraints;
- while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) {
+ while (node && !ts.isStatement(node) && node.kind !== 296 /* JSDocComment */) {
var parent = node.parent;
if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) {
var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType);
@@ -40671,8 +40807,8 @@ var ts;
function getTypeFromTypeNode(node) {
switch (node.kind) {
case 120 /* AnyKeyword */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return anyType;
case 143 /* UnknownKeyword */:
return unknownType;
@@ -40719,23 +40855,23 @@ var ts;
return getTypeFromUnionTypeNode(node);
case 174 /* IntersectionType */:
return getTypeFromIntersectionTypeNode(node);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return getTypeFromJSDocNullableTypeNode(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return addOptionality(getTypeFromTypeNode(node.type));
case 177 /* ParenthesizedType */:
case 172 /* RestType */:
- case 287 /* JSDocNonNullableType */:
- case 283 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 288 /* JSDocTypeExpression */:
return getTypeFromTypeNode(node.type);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return getTypeFromJSDocVariadicType(node);
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 297 /* JSDocTypeLiteral */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
case 179 /* TypeOperator */:
return getTypeFromTypeOperatorNode(node);
@@ -41673,7 +41809,7 @@ var ts;
return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation);
}
// recreate a tuple from the elements, if possible
- var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true);
+ var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
if (isTupleLikeType(tupleizedType)) {
return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation);
}
@@ -44096,7 +44232,7 @@ var ts;
return;
}
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
return;
case 239 /* FunctionDeclaration */:
@@ -46377,7 +46513,7 @@ var ts;
return ts.findAncestor(node.parent, function (node) {
return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
node.kind === 245 /* ModuleBlock */ ||
- node.kind === 279 /* SourceFile */ ||
+ node.kind === 284 /* SourceFile */ ||
node.kind === 154 /* PropertyDeclaration */;
});
}
@@ -46498,7 +46634,7 @@ var ts;
// to the constructor in the initializer, we will need to substitute that
// binding with an alias as the class name is not in scope.
var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
- while (container.kind !== 279 /* SourceFile */) {
+ while (container.kind !== 284 /* SourceFile */) {
if (container.parent === declaration) {
if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
@@ -46921,7 +47057,7 @@ var ts;
}
function getTypeForThisExpressionFromJSDoc(node) {
var jsdocType = ts.getJSDocType(node);
- if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) {
+ if (jsdocType && jsdocType.kind === 294 /* JSDocFunctionType */) {
var jsDocFunctionType = jsdocType;
if (jsDocFunctionType.parameters.length > 0 &&
jsDocFunctionType.parameters[0].name &&
@@ -49523,23 +49659,34 @@ var ts;
// Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) {
var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
- var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature;
+ // We clone the contextualMapper to avoid fixing. For example, when the source signature is (x: T) => T[] and
+ // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
+ // for T but leave it possible to later infer '[any]' back to A.
+ var restType = getEffectiveRestType(contextualSignature);
+ var mapper = contextualMapper && restType && restType.flags & 262144 /* TypeParameter */ ? cloneTypeMapper(contextualMapper) : contextualMapper;
+ var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
forEachMatchingParameterType(sourceSignature, signature, function (source, target) {
// Type parameters from outer context referenced by source type are fixed by instantiation of the source type
inferTypes(context.inferences, source, target);
});
if (!contextualMapper) {
inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */);
+ var signaturePredicate = getTypePredicateOfSignature(signature);
+ var contextualPredicate = getTypePredicateOfSignature(sourceSignature);
+ if (signaturePredicate && contextualPredicate && signaturePredicate.kind === contextualPredicate.kind &&
+ (signaturePredicate.kind === 0 /* This */ || signaturePredicate.parameterIndex === contextualPredicate.parameterIndex)) {
+ inferTypes(context.inferences, contextualPredicate.type, signaturePredicate.type, 8 /* ReturnType */);
+ }
}
return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
}
- function inferJsxTypeArguments(node, signature, excludeArgument, context) {
+ function inferJsxTypeArguments(node, signature, checkMode, context) {
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context);
+ var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
inferTypes(context.inferences, checkAttrType, paramType);
return getInferredTypes(context);
}
- function inferTypeArguments(node, signature, args, excludeArgument, context) {
+ function inferTypeArguments(node, signature, args, checkMode, context) {
// Clear out all the inference results from the last time inferTypeArguments was called on this context
for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) {
var inference = _a[_i];
@@ -49552,7 +49699,7 @@ var ts;
}
}
if (ts.isJsxOpeningLikeElement(node)) {
- return inferJsxTypeArguments(node, signature, excludeArgument, context);
+ return inferJsxTypeArguments(node, signature, checkMode, context);
}
// If a contextual type is available, infer from that type to the return type of the call expression. For
// example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression
@@ -49596,10 +49743,7 @@ var ts;
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- // For context sensitive arguments we pass the identityMapper, which is a signal to treat all
- // context sensitive function expressions as wildcards
- var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context;
- var argType = checkExpressionWithContextualType(arg, paramType, mapper);
+ var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
inferTypes(context.inferences, argType, paramType);
}
}
@@ -49623,7 +49767,7 @@ var ts;
// and the argument are ...x forms.
return arg.kind === 215 /* SyntheticExpression */ ?
createArrayType(arg.type) :
- getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context));
+ getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
}
}
var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType;
@@ -49631,7 +49775,7 @@ var ts;
var types = [];
var spreadIndex = -1;
for (var i = index; i < argCount; i++) {
- var argType = checkExpressionWithContextualType(args[i], contextualType, context);
+ var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
if (spreadIndex < 0 && isSpreadArgument(args[i])) {
spreadIndex = i - index;
}
@@ -49681,19 +49825,18 @@ var ts;
* @param node a JSX opening-like element we are trying to figure its call signature
* @param signature a candidate signature we are trying whether it is a call signature
* @param relation a relationship to check parameter and argument type
- * @param excludeArgument
*/
- function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors) {
// Stateless function components can have maximum of three arguments: "props", "context", and "updater".
// However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
// can be specified by users through attributes property.
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined);
+ var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined, checkMode);
return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes);
}
- function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignature(node, args, signature, relation, checkMode, reportErrors) {
if (ts.isJsxOpeningLikeElement(node)) {
- return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors);
+ return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors);
}
var thisType = getThisTypeOfSignature(signature);
if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) {
@@ -49715,11 +49858,11 @@ var ts;
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined);
- // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter),
+ var argType = checkExpressionWithContextualType(arg, paramType, /*contextualMapper*/ undefined, checkMode);
+ // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
// we obtain the regular type of any object literal arguments because we may not have inferred complete
// parameter types yet and therefore excess property checks may yield false positives (see #17041).
- var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType;
+ var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) {
return false;
}
@@ -49924,7 +50067,7 @@ var ts;
}
return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
}
- function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) {
+ function resolveCall(node, signatures, candidatesOutArray, checkMode, fallbackError) {
var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */;
var isDecorator = node.kind === 152 /* Decorator */;
var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
@@ -49960,7 +50103,7 @@ var ts;
// For a decorator, no arguments are susceptible to contextual typing due to the fact
// decorators are applied to a declaration by the emitter, and not to an expression.
var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
- var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined;
+ var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
// The following variables are captured and modified by calls to chooseOverload.
// If overload resolution or type argument inference fails, we want to report the
// best error possible. The best error is one which says that an argument was not
@@ -49988,7 +50131,7 @@ var ts;
var result;
// If we are in signature help, a trailing comma indicates that we intend to provide another argument,
// so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
- var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma;
+ var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma;
// Section 4.12.1:
// if the candidate list contains one or more signatures for which the type of each argument
// expression is a subtype of each corresponding parameter type, the return type of the first
@@ -50014,12 +50157,7 @@ var ts;
// skip the checkApplicableSignature check.
if (reportErrors) {
if (candidateForArgumentError) {
- // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...]
- // The importance of excludeArgument is to prevent us from typing function expression parameters
- // in arguments too early. If possible, we'd like to only type them once we know the correct
- // overload. However, this matters for the case where the call is correct. When the call is
- // an error, we don't need to exclude any arguments, although it would cause no harm to do so.
- checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true);
+ checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, 0 /* Normal */, /*reportErrors*/ true);
}
else if (candidateForArgumentArityError) {
diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
@@ -50051,7 +50189,7 @@ var ts;
if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
return undefined;
}
- if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false)) {
candidateForArgumentError = candidate;
return undefined;
}
@@ -50075,9 +50213,10 @@ var ts;
}
else {
inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
+ typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
+ argCheckMode |= inferenceContext.flags & 8 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
}
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// If the original signature has a generic rest type, instantiation may produce a
// signature with different arity and we need to perform another arity check.
if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -50088,21 +50227,21 @@ var ts;
else {
checkCandidate = candidate;
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
}
continue;
}
- if (excludeArgument) {
+ if (argCheckMode) {
// If one or more context sensitive arguments were excluded, we start including
// them now (and keeping do so for any subsequent candidates) and perform a second
// round of type inference and applicability checking for this particular candidate.
- excludeArgument = undefined;
+ argCheckMode = 0 /* Normal */;
if (inferenceContext) {
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// If the original signature has a generic rest type, instantiation may produce a
// signature with different arity and we need to perform another arity check.
if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -50110,7 +50249,7 @@ var ts;
continue;
}
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
@@ -50124,20 +50263,6 @@ var ts;
return undefined;
}
}
- function getExcludeArgument(args) {
- var excludeArgument;
- // We do not need to call `getEffectiveArgumentCount` here as it only
- // applies when calculating the number of arguments for a decorator.
- for (var i = 0; i < args.length; i++) {
- if (isContextSensitive(args[i])) {
- if (!excludeArgument) {
- excludeArgument = new Array(args.length);
- }
- excludeArgument[i] = true;
- }
- }
- return excludeArgument;
- }
// No signature was applicable. We have already reported the errors for the invalid signature.
// If this is a type resolution session, e.g. Language Service, try to get better information than anySignature.
function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
@@ -50226,7 +50351,7 @@ var ts;
}
function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext);
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
return createSignatureInstantiation(candidate, typeArgumentTypes);
}
function getLongestCandidateIndex(candidates, argsCount) {
@@ -50245,7 +50370,7 @@ var ts;
}
return maxParamsIndex;
}
- function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveCallExpression(node, candidatesOutArray, checkMode) {
if (node.expression.kind === 98 /* SuperKeyword */) {
var superType = checkSuperExpression(node.expression);
if (isTypeAny(superType)) {
@@ -50261,7 +50386,7 @@ var ts;
var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
if (baseTypeNode) {
var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
- return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, baseConstructors, candidatesOutArray, checkMode);
}
}
return resolveUntypedCall(node);
@@ -50311,12 +50436,31 @@ var ts;
}
return resolveErrorCall(node);
}
+ // When a call to a generic function is an argument to an outer call to a generic function for which
+ // inference is in process, we have a choice to make. If the inner call relies on inferences made from
+ // its contextual type to its return type, deferring the inner call processing allows the best possible
+ // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
+ // the inner call, the inner call should be processed early. There's no sure way to know which choice is
+ // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
+ // If no type arguments are specified in the inner call and at least one call signature is generic and
+ // returns a function type, we choose to defer processing. This narrowly permits function composition
+ // operators to flow inferences through return types, but otherwise processes calls right away. We
+ // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
+ // propagated out and eventually turned into silentNeverType (a type that is assignable to anything and
+ // from which we never make inferences).
+ if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
+ skippedGenericFunction(node, checkMode);
+ return resolvingSignature;
+ }
// If the function is explicitly marked with `@class`, then it must be constructed.
if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
+ }
+ function isGenericFunctionReturningFunction(signature) {
+ return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
}
/**
* TS 1.0 spec: 4.12
@@ -50328,7 +50472,7 @@ var ts;
return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
!numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
}
- function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveNewExpression(node, candidatesOutArray, checkMode) {
if (node.arguments && languageVersion < 1 /* ES5 */) {
var spreadIndex = getSpreadArgumentIndex(node.arguments);
if (spreadIndex >= 0) {
@@ -50376,7 +50520,7 @@ var ts;
error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
return resolveErrorCall(node);
}
- return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, constructSignatures, candidatesOutArray, checkMode);
}
// If expressionType's apparent type is an object type with no construct signatures but
// one or more call signatures, the expression is processed as a function call. A compile-time
@@ -50384,7 +50528,7 @@ var ts;
// operation is Any. It is an error to have a Void this type.
var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
if (callSignatures.length) {
- var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode);
if (!noImplicitAny) {
if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
@@ -50481,7 +50625,7 @@ var ts;
addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead));
}
}
- function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
var tagType = checkExpression(node.tag);
var apparentType = getApparentType(tagType);
if (apparentType === errorType) {
@@ -50497,7 +50641,7 @@ var ts;
invocationError(node, apparentType, 0 /* Call */);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
}
/**
* Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
@@ -50522,7 +50666,7 @@ var ts;
/**
* Resolves a decorator as if it were a call expression.
*/
- function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveDecorator(node, candidatesOutArray, checkMode) {
var funcType = checkExpression(node.expression);
var apparentType = getApparentType(funcType);
if (apparentType === errorType) {
@@ -50547,7 +50691,7 @@ var ts;
invocationErrorRecovery(apparentType, 0 /* Call */, diag);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode, headMessage);
}
function createSignatureForJSXIntrinsic(node, result) {
var namespace = getJsxNamespaceAt(node);
@@ -50566,11 +50710,11 @@ var ts;
/*hasRestparameter*/ false,
/*hasLiteralTypes*/ false);
}
- function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
if (isJsxIntrinsicIdentifier(node.tagName)) {
var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
var fakeSignature = createSignatureForJSXIntrinsic(node, result);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes);
+ checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
return fakeSignature;
}
var exprTypes = checkExpression(node.tagName);
@@ -50587,7 +50731,7 @@ var ts;
error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
return resolveErrorCall(node);
}
- return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, signatures, candidatesOutArray, checkMode);
}
/**
* Sometimes, we have a decorator that could accept zero arguments,
@@ -50601,19 +50745,19 @@ var ts;
signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
});
}
- function resolveSignature(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveSignature(node, candidatesOutArray, checkMode) {
switch (node.kind) {
case 191 /* CallExpression */:
- return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveCallExpression(node, candidatesOutArray, checkMode);
case 192 /* NewExpression */:
- return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveNewExpression(node, candidatesOutArray, checkMode);
case 193 /* TaggedTemplateExpression */:
- return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
case 152 /* Decorator */:
- return resolveDecorator(node, candidatesOutArray, isForSignatureHelp);
+ return resolveDecorator(node, candidatesOutArray, checkMode);
case 262 /* JsxOpeningElement */:
case 261 /* JsxSelfClosingElement */:
- return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp);
+ return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
}
throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
}
@@ -50624,8 +50768,7 @@ var ts;
* the function will fill it up with appropriate candidate signatures
* @return a signature of the call-like expression or undefined if one can't be found
*/
- function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) {
- if (isForSignatureHelp === void 0) { isForSignatureHelp = false; }
+ function getResolvedSignature(node, candidatesOutArray, checkMode) {
var links = getNodeLinks(node);
// If getResolvedSignature has already been called, we will have cached the resolvedSignature.
// However, it is possible that either candidatesOutArray was not passed in the first time,
@@ -50636,11 +50779,15 @@ var ts;
return cached;
}
links.resolvedSignature = resolvingSignature;
- var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp);
- // If signature resolution originated in control flow type analysis (for example to compute the
- // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
- // types from the control flow analysis.
- links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
+ // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
+ // resolution should be deferred.
+ if (result !== resolvingSignature) {
+ // If signature resolution originated in control flow type analysis (for example to compute the
+ // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
+ // types from the control flow analysis.
+ links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ }
return result;
}
/**
@@ -50716,10 +50863,15 @@ var ts;
* @param node The call/new expression to be checked.
* @returns On success, the expression's signature's return type. On failure, anyType.
*/
- function checkCallExpression(node) {
+ function checkCallExpression(node, checkMode) {
if (!checkGrammarTypeArguments(node, node.typeArguments))
checkGrammarArguments(node.arguments);
- var signature = getResolvedSignature(node);
+ var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
+ if (signature === resolvingSignature) {
+ // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
+ // returns a function type. We defer checking and return anyFunctionType.
+ return silentNeverType;
+ }
if (node.expression.kind === 98 /* SuperKeyword */) {
return voidType;
}
@@ -50963,7 +51115,7 @@ var ts;
if (isTupleType(restType)) {
var associatedNames = restType.target.associatedNames;
var index = pos - paramCount;
- return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index;
+ return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
}
return restParameter.escapedName;
}
@@ -51171,7 +51323,7 @@ var ts;
var functionFlags = ts.getFunctionFlags(func);
var type;
if (func.body.kind !== 218 /* Block */) {
- type = checkExpressionCached(func.body, checkMode);
+ type = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -51349,7 +51501,7 @@ var ts;
ts.forEachReturnStatement(func.body, function (returnStatement) {
var expr = returnStatement.expression;
if (expr) {
- var type = checkExpressionCached(expr, checkMode);
+ var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -51442,7 +51594,7 @@ var ts;
ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
checkNodeDeferred(node);
// The identityMapper object is used to indicate that function expressions are wildcards
- if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) {
+ if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
// Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) {
var links_1 = getNodeLinks(node);
@@ -51479,7 +51631,7 @@ var ts;
var signature = getSignaturesOfType(type, 0 /* Call */)[0];
if (isContextSensitive(node)) {
var contextualMapper = getContextualMapper(node);
- if (checkMode === 2 /* Inferential */) {
+ if (checkMode && checkMode & 2 /* Inferential */) {
inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper);
}
var instantiatedContextualSignature = contextualMapper === identityMapper ?
@@ -52401,15 +52553,13 @@ var ts;
}
return node;
}
- function checkExpressionWithContextualType(node, contextualType, contextualMapper) {
+ function checkExpressionWithContextualType(node, contextualType, contextualMapper, checkMode) {
var context = getContextNode(node);
var saveContextualType = context.contextualType;
var saveContextualMapper = context.contextualMapper;
context.contextualType = contextualType;
context.contextualMapper = contextualMapper;
- var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ :
- contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */;
- var type = checkExpression(node, checkMode);
+ var type = checkExpression(node, checkMode | 1 /* Contextual */ | (contextualMapper ? 2 /* Inferential */ : 0));
// We strip literal freshness when an appropriate contextual type is present such that contextually typed
// literals always preserve their literal types (otherwise they might widen during type inference). An alternative
// here would be to not mark contextually typed literals as fresh in the first place.
@@ -52422,7 +52572,7 @@ var ts;
function checkExpressionCached(node, checkMode) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- if (checkMode) {
+ if (checkMode && checkMode !== 0 /* Normal */) {
return checkExpression(node, checkMode);
}
// When computing a type that we're going to cache, we need to ignore any ongoing control flow
@@ -52519,20 +52669,122 @@ var ts;
return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
}
function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
- if (checkMode === 2 /* Inferential */) {
+ if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
var signature = getSingleCallSignature(type);
if (signature && signature.typeParameters) {
+ if (checkMode & 8 /* SkipGenericFunctions */) {
+ skippedGenericFunction(node, checkMode);
+ return anyFunctionType;
+ }
var contextualType = getApparentTypeOfContextualType(node);
if (contextualType) {
var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType));
if (contextualSignature && !contextualSignature.typeParameters) {
- return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node)));
+ var context = getContextualMapper(node);
+ // We have an expression that is an argument of a generic function for which we are performing
+ // type argument inference. The expression is of a function type with a single generic call
+ // signature and a contextual function type with a single non-generic call signature. Now check
+ // if the outer function returns a function type with a single non-generic call signature and
+ // if some of the outer function type parameters have no inferences so far. If so, we can
+ // potentially add inferred type parameters to the outer function return type.
+ var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature));
+ if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
+ // Instantiate the expression type with its own type parameters as type arguments. This
+ // ensures that the type parameters are not erased to type any during type inference such
+ // that they can be inferred as actual types.
+ var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
+ var strippedType = getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters));
+ // Infer from the stripped expression type to the contextual type starting with an empty
+ // set of inference candidates.
+ var inferences = ts.map(context.typeParameters, createInferenceInfo);
+ inferTypes(inferences, strippedType, contextualType);
+ // If we produced some inference candidates and if the type parameters for which we produced
+ // candidates do not already have existing inferences, we adopt the new inference candidates and
+ // add the type parameters of the expression type to the set of inferred type parameters for
+ // the outer function return type.
+ if (ts.some(inferences, hasInferenceCandidates) && !hasOverlappingInferences(context.inferences, inferences)) {
+ mergeInferences(context.inferences, inferences);
+ context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
+ return strippedType;
+ }
+ }
+ return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
}
}
}
}
return type;
}
+ function skippedGenericFunction(node, checkMode) {
+ if (checkMode & 2 /* Inferential */) {
+ // We have skipped a generic function during inferential typing. Obtain the inference context and
+ // indicate this has occurred such that we know a second pass of inference is be needed.
+ var context = getContextualMapper(node);
+ context.flags |= 8 /* SkippedGenericFunction */;
+ }
+ }
+ function hasInferenceCandidates(info) {
+ return !!(info.candidates || info.contraCandidates);
+ }
+ function hasOverlappingInferences(a, b) {
+ for (var i = 0; i < a.length; i++) {
+ if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
+ return true;
+ }
+ }
+ return false;
+ }
+ function mergeInferences(target, source) {
+ for (var i = 0; i < target.length; i++) {
+ if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
+ target[i] = source[i];
+ }
+ }
+ }
+ function getUniqueTypeParameters(context, typeParameters) {
+ var result = [];
+ var oldTypeParameters;
+ var newTypeParameters;
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var tp = typeParameters_2[_i];
+ var name = tp.symbol.escapedName;
+ if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
+ var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
+ var symbol = createSymbol(262144 /* TypeParameter */, newName);
+ var newTypeParameter = createTypeParameter(symbol);
+ newTypeParameter.target = tp;
+ oldTypeParameters = ts.append(oldTypeParameters, tp);
+ newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
+ result.push(newTypeParameter);
+ }
+ else {
+ result.push(tp);
+ }
+ }
+ if (newTypeParameters) {
+ var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
+ for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
+ var tp = newTypeParameters_1[_a];
+ tp.mapper = mapper;
+ }
+ }
+ return result;
+ }
+ function hasTypeParameterByName(typeParameters, name) {
+ return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
+ }
+ function getUniqueTypeParameterName(typeParameters, baseName) {
+ var len = baseName.length;
+ while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
+ len--;
+ var s = baseName.slice(0, len);
+ for (var index = 1; true; index++) {
+ var augmentedName = (s + index);
+ if (!hasTypeParameterByName(typeParameters, augmentedName)) {
+ return augmentedName;
+ }
+ }
+ }
/**
* Returns the type of an expression. Unlike checkExpression, this function is simply concerned
* with computing the type and may not fully check all contained sub-expressions for errors.
@@ -52572,7 +52824,7 @@ var ts;
}
var saveContextualType = node.contextualType;
node.contextualType = anyType;
- var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */);
+ var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
node.contextualType = saveContextualType;
return type;
}
@@ -52664,7 +52916,7 @@ var ts;
}
/* falls through */
case 192 /* NewExpression */:
- return checkCallExpression(node);
+ return checkCallExpression(node, checkMode);
case 193 /* TaggedTemplateExpression */:
return checkTaggedTemplateExpression(node);
case 195 /* ParenthesizedExpression */:
@@ -52923,7 +53175,7 @@ var ts;
checkAsyncFunctionReturnType(node, returnTypeNode);
}
}
- if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) {
+ if (node.kind !== 162 /* IndexSignature */ && node.kind !== 294 /* JSDocFunctionType */) {
registerForUnusedIdentifiersCheck(node);
}
}
@@ -53679,8 +53931,8 @@ var ts;
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
// A jsdoc typedef and callback are, by definition, type aliases
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return 2 /* ExportType */;
case 244 /* ModuleDeclaration */:
return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
@@ -53689,7 +53941,7 @@ var ts;
case 240 /* ClassDeclaration */:
case 243 /* EnumDeclaration */:
return 2 /* ExportType */ | 1 /* ExportValue */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
case 254 /* ExportAssignment */:
// Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
@@ -54330,7 +54582,7 @@ var ts;
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 244 /* ModuleDeclaration */:
case 218 /* Block */:
case 246 /* CaseBlock */:
@@ -54423,8 +54675,8 @@ var ts;
return;
var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
var seenParentsWithEveryUnused = new ts.NodeSet();
- for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
- var typeParameter = typeParameters_2[_i];
+ for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
+ var typeParameter = typeParameters_3[_i];
if (!isTypeParameterUnused(typeParameter))
continue;
var name = ts.idText(typeParameter.name);
@@ -54677,7 +54929,7 @@ var ts;
}
// In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
var parent = getDeclarationContainer(node);
- if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
+ if (parent.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
// If the declaration happens to be in external module, report error that require and exports are reserved keywords
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
@@ -54692,7 +54944,7 @@ var ts;
}
// In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
var parent = getDeclarationContainer(node);
- if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
+ if (parent.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
// If the declaration happens to be in external module, report error that Promise is a reserved identifier.
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
@@ -54749,7 +55001,7 @@ var ts;
(container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) ||
container.kind === 245 /* ModuleBlock */ ||
container.kind === 244 /* ModuleDeclaration */ ||
- container.kind === 279 /* SourceFile */);
+ container.kind === 284 /* SourceFile */);
// here we know that function scoped variable is shadowed by block scoped one
// if they are defined in the same scope - binder has already reported redeclaration error
// otherwise if variable has an initializer - show error that initialization will fail
@@ -56599,7 +56851,7 @@ var ts;
return false;
}
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule) {
error(moduleName, node.kind === 255 /* ExportDeclaration */ ?
ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
@@ -56730,7 +56982,7 @@ var ts;
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ &&
!node.moduleSpecifier && node.flags & 4194304 /* Ambient */;
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
}
}
@@ -56747,7 +56999,7 @@ var ts;
}
}
function checkGrammarModuleElementContext(node, errorMessage) {
- var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
+ var isInAppropriateContext = node.parent.kind === 284 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
if (!isInAppropriateContext) {
grammarErrorOnFirstToken(node, errorMessage);
}
@@ -56776,7 +57028,7 @@ var ts;
// If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
return;
}
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
if (node.isExportEquals) {
error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
@@ -56946,32 +57198,32 @@ var ts;
return checkInferType(node);
case 183 /* ImportType */:
return checkImportType(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return checkJSDocAugmentsTag(node);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return checkJSDocTypeAliasTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return checkJSDocTemplateTag(node);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return checkJSDocTypeTag(node);
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
return checkJSDocParameterTag(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
checkJSDocFunctionType(node);
// falls through
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
- case 292 /* JSDocTypeLiteral */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
+ case 297 /* JSDocTypeLiteral */:
checkJSDocTypeIsInJsFile(node);
ts.forEachChild(node, checkSourceElement);
return;
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
checkJSDocVariadicType(node);
return;
- case 283 /* JSDocTypeExpression */:
+ case 288 /* JSDocTypeExpression */:
return checkSourceElement(node.type);
case 180 /* IndexedAccessType */:
return checkIndexedAccessType(node);
@@ -57279,7 +57531,7 @@ var ts;
copySymbols(location.locals, meaning);
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
// falls through
@@ -57498,10 +57750,10 @@ var ts;
return entityNameSymbol;
}
}
- if (entityName.parent.kind === 299 /* JSDocParameterTag */) {
+ if (entityName.parent.kind === 304 /* JSDocParameterTag */) {
return ts.getParameterSymbolFromJSDoc(entityName.parent);
}
- if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) {
+ if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 308 /* JSDocTemplateTag */) {
ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true.
var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
return typeParameter && typeParameter.symbol;
@@ -57543,7 +57795,7 @@ var ts;
return undefined;
}
function getSymbolAtLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
}
var parent = node.parent;
@@ -57885,7 +58137,7 @@ var ts;
}
var parentSymbol_1 = getParentOfSymbol(symbol);
if (parentSymbol_1) {
- if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) {
+ if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 284 /* SourceFile */) {
var symbolFile = parentSymbol_1.valueDeclaration;
var referenceFile = ts.getSourceFileOfNode(node);
// If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
@@ -58000,7 +58252,7 @@ var ts;
}
function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
- if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
+ if (node === undefined || node.parent.kind !== 284 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
// parent is not source file or it is not reference to internal module
return false;
}
@@ -58429,7 +58681,7 @@ var ts;
break;
}
}
- if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
+ if (current.valueDeclaration && current.valueDeclaration.kind === 284 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
return false;
}
// check that at least one declaration of top level symbol originates from type declaration file
@@ -58462,7 +58714,7 @@ var ts;
if (!moduleSymbol) {
return undefined;
}
- return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */);
+ return ts.getDeclarationOfKind(moduleSymbol, 284 /* SourceFile */);
}
function initializeTypeChecker() {
// Bind all source files and propagate errors
@@ -58694,7 +58946,7 @@ var ts;
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
}
else if (flags & 128 /* Abstract */) {
@@ -58717,7 +58969,7 @@ var ts;
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
}
else if (node.kind === 151 /* Parameter */) {
@@ -58762,7 +59014,7 @@ var ts;
flags |= 1 /* Export */;
break;
case 80 /* DefaultKeyword */:
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
}
@@ -58885,7 +59137,7 @@ var ts;
case 151 /* Parameter */:
return false;
default:
- if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return false;
}
switch (node.kind) {
@@ -59808,7 +60060,7 @@ var ts;
// to prevent noisiness. So use a bit on the block to indicate if
// this has already been reported, and don't report if it has.
//
- if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
var links_2 = getNodeLinks(node.parent);
// Check if the containing block ever report this error
if (!links_2.hasReportedStatementInAmbientContext) {
@@ -61862,14 +62114,14 @@ var ts;
// JSDoc
/* @internal */
function createJSDocTypeExpression(type) {
- var node = createSynthesizedNode(283 /* JSDocTypeExpression */);
+ var node = createSynthesizedNode(288 /* JSDocTypeExpression */);
node.type = type;
return node;
}
ts.createJSDocTypeExpression = createJSDocTypeExpression;
/* @internal */
function createJSDocTypeTag(typeExpression, comment) {
- var tag = createJSDocTag(302 /* JSDocTypeTag */, "type");
+ var tag = createJSDocTag(307 /* JSDocTypeTag */, "type");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61877,7 +62129,7 @@ var ts;
ts.createJSDocTypeTag = createJSDocTypeTag;
/* @internal */
function createJSDocReturnTag(typeExpression, comment) {
- var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns");
+ var tag = createJSDocTag(305 /* JSDocReturnTag */, "returns");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61885,7 +62137,7 @@ var ts;
ts.createJSDocReturnTag = createJSDocReturnTag;
/* @internal */
function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
- var tag = createJSDocTag(299 /* JSDocParameterTag */, "param");
+ var tag = createJSDocTag(304 /* JSDocParameterTag */, "param");
tag.typeExpression = typeExpression;
tag.name = name;
tag.isBracketed = isBracketed;
@@ -61895,7 +62147,7 @@ var ts;
ts.createJSDocParamTag = createJSDocParamTag;
/* @internal */
function createJSDocComment(comment, tags) {
- var node = createSynthesizedNode(291 /* JSDocComment */);
+ var node = createSynthesizedNode(296 /* JSDocComment */);
node.comment = comment;
node.tags = tags;
return node;
@@ -62154,7 +62406,7 @@ var ts;
(typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
(libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
(hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
- var updated = createSynthesizedNode(279 /* SourceFile */);
+ var updated = createSynthesizedNode(284 /* SourceFile */);
updated.flags |= node.flags;
updated.statements = createNodeArray(statements);
updated.endOfFileToken = node.endOfFileToken;
@@ -62238,7 +62490,7 @@ var ts;
* @param original The original statement.
*/
function createNotEmittedStatement(original) {
- var node = createSynthesizedNode(307 /* NotEmittedStatement */);
+ var node = createSynthesizedNode(312 /* NotEmittedStatement */);
node.original = original;
setTextRange(node, original);
return node;
@@ -62250,7 +62502,7 @@ var ts;
*/
/* @internal */
function createEndOfDeclarationMarker(original) {
- var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */);
+ var node = createSynthesizedNode(316 /* EndOfDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -62262,7 +62514,7 @@ var ts;
*/
/* @internal */
function createMergeDeclarationMarker(original) {
- var node = createSynthesizedNode(310 /* MergeDeclarationMarker */);
+ var node = createSynthesizedNode(315 /* MergeDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -62277,7 +62529,7 @@ var ts;
* @param location The location for the expression. Defaults to the positions from "original" if provided.
*/
function createPartiallyEmittedExpression(expression, original) {
- var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */);
+ var node = createSynthesizedNode(313 /* PartiallyEmittedExpression */);
node.expression = expression;
node.original = original;
setTextRange(node, original);
@@ -62293,7 +62545,7 @@ var ts;
ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
function flattenCommaElements(node) {
if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
- if (node.kind === 309 /* CommaListExpression */) {
+ if (node.kind === 314 /* CommaListExpression */) {
return node.elements;
}
if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
@@ -62303,7 +62555,7 @@ var ts;
return node;
}
function createCommaList(elements) {
- var node = createSynthesizedNode(309 /* CommaListExpression */);
+ var node = createSynthesizedNode(314 /* CommaListExpression */);
node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
return node;
}
@@ -62316,33 +62568,197 @@ var ts;
ts.updateCommaList = updateCommaList;
function createBundle(sourceFiles, prepends) {
if (prepends === void 0) { prepends = ts.emptyArray; }
- var node = ts.createNode(280 /* Bundle */);
+ var node = ts.createNode(285 /* Bundle */);
node.prepends = prepends;
node.sourceFiles = sourceFiles;
return node;
}
ts.createBundle = createBundle;
- function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, map) {
- var node = ts.createNode(281 /* UnparsedSource */);
+ var allUnscopedEmitHelpers;
+ function getAllUnscopedEmitHelpers() {
+ return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
+ ts.valuesHelper,
+ ts.readHelper,
+ ts.spreadHelper,
+ ts.restHelper,
+ ts.decorateHelper,
+ ts.metadataHelper,
+ ts.paramHelper,
+ ts.awaiterHelper,
+ ts.assignHelper,
+ ts.awaitHelper,
+ ts.asyncGeneratorHelper,
+ ts.asyncDelegator,
+ ts.asyncValues,
+ ts.extendsHelper,
+ ts.templateObjectHelper,
+ ts.generatorHelper,
+ ts.importStarHelper,
+ ts.importDefaultHelper
+ ], function (helper) { return helper.name; }));
+ }
+ function createUnparsedSource() {
+ var node = ts.createNode(286 /* UnparsedSource */);
+ node.prologues = ts.emptyArray;
+ node.referencedFiles = ts.emptyArray;
+ node.libReferenceDirectives = ts.emptyArray;
+ node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
+ return node;
+ }
+ function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
+ var node = createUnparsedSource();
+ var stripInternal;
+ var bundleFileInfo;
if (!ts.isString(textOrInputFiles)) {
ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
- node.fileName = mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath;
+ node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
Object.defineProperties(node, {
text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
});
+ if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
+ node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
+ ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
+ stripInternal = mapTextOrStripInternal;
+ bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
+ if (node.oldFileOfCurrentEmit) {
+ parseOldFileOfCurrentEmit(node, ts.Debug.assertDefined(bundleFileInfo));
+ return node;
+ }
+ }
}
else {
+ node.fileName = "";
node.text = textOrInputFiles;
node.sourceMapPath = mapPathOrType;
- node.sourceMapText = map;
+ node.sourceMapText = mapTextOrStripInternal;
}
+ ts.Debug.assert(!node.oldFileOfCurrentEmit);
+ parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
return node;
}
ts.createUnparsedSourceFile = createUnparsedSourceFile;
- function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapText) {
- var node = ts.createNode(282 /* InputFiles */);
+ function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
+ var prologues;
+ var helpers;
+ var referencedFiles;
+ var typeReferenceDirectives;
+ var libReferenceDirectives;
+ var texts;
+ for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "prologue" /* Prologue */:
+ (prologues || (prologues = [])).push(createUnparsedNode(section, node));
+ break;
+ case "emitHelpers" /* EmitHelpers */:
+ (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ node.hasNoDefaultLib = true;
+ break;
+ case "reference" /* Reference */:
+ (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "type" /* Type */:
+ (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
+ break;
+ case "lib" /* Lib */:
+ (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "prepend" /* Prepend */:
+ var prependNode = createUnparsedNode(section, node);
+ var prependTexts = void 0;
+ for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
+ var text = _c[_b];
+ if (!stripInternal || text.kind !== "internal" /* Internal */) {
+ (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
+ }
+ }
+ prependNode.texts = prependTexts || ts.emptyArray;
+ (texts || (texts = [])).push(prependNode);
+ break;
+ case "internal" /* Internal */:
+ if (stripInternal)
+ break;
+ // falls through
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.prologues = prologues || ts.emptyArray;
+ node.helpers = helpers;
+ node.referencedFiles = referencedFiles || ts.emptyArray;
+ node.typeReferenceDirectives = typeReferenceDirectives;
+ node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
+ node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
+ }
+ function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
+ ts.Debug.assert(!!node.oldFileOfCurrentEmit);
+ var texts;
+ var syntheticReferences;
+ for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "internal" /* Internal */:
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
+ break;
+ // Ignore
+ case "prologue" /* Prologue */:
+ case "emitHelpers" /* EmitHelpers */:
+ case "prepend" /* Prepend */:
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.texts = texts || ts.emptyArray;
+ node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
+ node.syntheticReferences = syntheticReferences;
+ return node;
+ }
+ function mapBundleFileSectionKindToSyntaxKind(kind) {
+ switch (kind) {
+ case "prologue" /* Prologue */: return 279 /* UnparsedPrologue */;
+ case "prepend" /* Prepend */: return 280 /* UnparsedPrepend */;
+ case "internal" /* Internal */: return 282 /* UnparsedInternalText */;
+ case "text" /* Text */: return 281 /* UnparsedText */;
+ case "emitHelpers" /* EmitHelpers */:
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
+ default:
+ return ts.Debug.assertNever(kind);
+ }
+ }
+ function createUnparsedNode(section, parent) {
+ var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ return node;
+ }
+ function createUnparsedSyntheticReference(section, parent) {
+ var node = ts.createNode(283 /* UnparsedSyntheticReference */, section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ node.section = section;
+ return node;
+ }
+ function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
+ var node = ts.createNode(287 /* InputFiles */);
if (!ts.isString(javascriptTextOrReadFileText)) {
var cache_1 = ts.createMap();
var textGetter_1 = function (path) {
@@ -62359,15 +62775,25 @@ var ts;
var result = textGetter_1(path);
return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
};
+ var buildInfo_1;
+ var getAndCacheBuildInfo_1 = function (getText) {
+ if (buildInfo_1 === undefined) {
+ var result = getText();
+ buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
+ }
+ return buildInfo_1 || undefined;
+ };
node.javascriptPath = declarationTextOrJavascriptPath;
node.javascriptMapPath = javascriptMapPath;
node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
node.declarationMapPath = declarationMapPath;
+ node.buildInfoPath = declarationMapTextOrBuildInfoPath;
Object.defineProperties(node, {
javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
- declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } } // TODO:: if there is inline sourceMap in dtsFile, use that
+ declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
+ buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
});
}
else {
@@ -62376,7 +62802,12 @@ var ts;
node.javascriptMapText = javascriptMapTextOrDeclarationPath;
node.declarationText = declarationTextOrJavascriptPath;
node.declarationMapPath = declarationMapPath;
- node.declarationMapText = declarationMapText;
+ node.declarationMapText = declarationMapTextOrBuildInfoPath;
+ node.javascriptPath = javascriptPath;
+ node.declarationPath = declarationPath,
+ node.buildInfoPath = buildInfoPath;
+ node.buildInfo = buildInfo;
+ node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
}
return node;
}
@@ -62514,7 +62945,7 @@ var ts;
// To avoid holding onto transformation artifacts, we keep track of any
// parse tree node we are annotating. This allows us to clean them up after
// all transformations have completed.
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return node.emitNode = { annotatedNodes: [node] };
}
var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
@@ -62960,38 +63391,38 @@ var ts;
return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
}
ts.getHelperName = getHelperName;
- var valuesHelper = {
+ ts.valuesHelper = {
name: "typescript:values",
scoped: false,
text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };"
};
function createValuesHelper(context, expression, location) {
- context.requestEmitHelper(valuesHelper);
+ context.requestEmitHelper(ts.valuesHelper);
return ts.setTextRange(ts.createCall(getHelperName("__values"),
/*typeArguments*/ undefined, [expression]), location);
}
ts.createValuesHelper = createValuesHelper;
- var readHelper = {
+ ts.readHelper = {
name: "typescript:read",
scoped: false,
text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };"
};
function createReadHelper(context, iteratorRecord, count, location) {
- context.requestEmitHelper(readHelper);
+ context.requestEmitHelper(ts.readHelper);
return ts.setTextRange(ts.createCall(getHelperName("__read"),
/*typeArguments*/ undefined, count !== undefined
? [iteratorRecord, ts.createLiteral(count)]
: [iteratorRecord]), location);
}
ts.createReadHelper = createReadHelper;
- var spreadHelper = {
+ ts.spreadHelper = {
name: "typescript:spread",
scoped: false,
text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };"
};
function createSpreadHelper(context, argumentList, location) {
- context.requestEmitHelper(readHelper);
- context.requestEmitHelper(spreadHelper);
+ context.requestEmitHelper(ts.readHelper);
+ context.requestEmitHelper(ts.spreadHelper);
return ts.setTextRange(ts.createCall(getHelperName("__spread"),
/*typeArguments*/ undefined, argumentList), location);
}
@@ -63837,7 +64268,7 @@ var ts;
case 190 /* ElementAccessExpression */:
case 189 /* PropertyAccessExpression */:
case 213 /* NonNullExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
node = node.expression;
continue;
}
@@ -63853,7 +64284,7 @@ var ts;
ts.parenthesizeConciseBody = parenthesizeConciseBody;
function isCommaSequence(node) {
return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
- node.kind === 309 /* CommaListExpression */;
+ node.kind === 314 /* CommaListExpression */;
}
ts.isCommaSequence = isCommaSequence;
var OuterExpressionKinds;
@@ -63872,7 +64303,7 @@ var ts;
case 212 /* AsExpression */:
case 213 /* NonNullExpression */:
return (kinds & 2 /* Assertions */) !== 0;
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0;
}
return false;
@@ -63909,7 +64340,7 @@ var ts;
case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
- case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
+ case 313 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
}
}
/**
@@ -64701,12 +65132,12 @@ var ts;
case 278 /* EnumMember */:
return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
default:
// No need to visit nodes with no children.
@@ -64762,7 +65193,7 @@ var ts;
case 220 /* EmptyStatement */:
case 210 /* OmittedExpression */:
case 236 /* DebuggerStatement */:
- case 307 /* NotEmittedStatement */:
+ case 312 /* NotEmittedStatement */:
// No need to visit nodes with no children.
break;
// Names
@@ -65139,14 +65570,14 @@ var ts;
result = reduceNode(node.initializer, cbNode, result);
break;
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
result = reduceNodes(node.statements, cbNodes, result);
break;
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
result = reduceNodes(node.elements, cbNodes, result);
break;
default:
@@ -65427,7 +65858,7 @@ var ts;
}
exit();
}
- function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) {
+ function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
var _a;
ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
@@ -65437,6 +65868,14 @@ var ts;
var nameIndexToNewNameIndexMap;
var mappingIterator = decodeMappings(map.mappings);
for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) {
+ if (end && (raw.generatedLine > end.line ||
+ (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
+ break;
+ }
+ if (start && (raw.generatedLine < start.line ||
+ (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
+ continue;
+ }
// Then reencode all the updated mappings into the overall map
var newSourceIndex = void 0;
var newSourceLine = void 0;
@@ -65465,8 +65904,10 @@ var ts;
}
}
}
- var newGeneratedLine = raw.generatedLine + generatedLine;
- var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter;
+ var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
+ var newGeneratedLine = rawGeneratedLine + generatedLine;
+ var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
+ var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
}
exit();
@@ -65949,7 +66390,7 @@ var ts;
function chainBundle(transformSourceFile) {
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
+ return node.kind === 284 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
}
function transformBundle(node) {
return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
@@ -66610,7 +67051,7 @@ var ts;
function makeAssignmentElement(name) {
return name;
}
- var restHelper = {
+ ts.restHelper = {
name: "typescript:rest",
scoped: false,
text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };"
@@ -66619,7 +67060,7 @@ var ts;
* `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
*/
function createRestCall(context, value, elements, computedTempVariables, location) {
- context.requestEmitHelper(restHelper);
+ context.requestEmitHelper(ts.restHelper);
var propertyNames = [];
var computedTempVariableOffset = 0;
for (var i = 0; i < elements.length - 1; i++) {
@@ -66720,14 +67161,14 @@ var ts;
var pendingExpressions;
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* Bundle */) {
return transformBundle(node);
}
return transformSourceFile(node);
}
function transformBundle(node) {
return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
- if (prepend.kind === 282 /* InputFiles */) {
+ if (prepend.kind === 287 /* InputFiles */) {
return ts.createUnparsedSourceFile(prepend, "js");
}
return prepend;
@@ -66776,7 +67217,7 @@ var ts;
*/
function onBeforeVisitNode(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 245 /* ModuleBlock */:
case 218 /* Block */:
@@ -69007,7 +69448,7 @@ var ts;
// enums in any other scope are emitted as a `let` declaration.
var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
- ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
+ ], currentLexicalScope.kind === 284 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
ts.setOriginalNode(statement, node);
recordEmittedDeclarationInScope(node);
if (isFirstEmittedDeclarationInScope(node)) {
@@ -69572,7 +70013,7 @@ var ts;
// If we are nested within a namespace declaration, we may need to qualifiy
// an identifier that is exported from a merged namespace.
var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
- if (container && container.kind !== 279 /* SourceFile */) {
+ if (container && container.kind !== 284 /* SourceFile */) {
var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) ||
(applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */);
if (substitute) {
@@ -69623,39 +70064,39 @@ var ts;
argumentsArray.push(descriptor);
}
}
- context.requestEmitHelper(decorateHelper);
+ context.requestEmitHelper(ts.decorateHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"),
/*typeArguments*/ undefined, argumentsArray), location);
}
- var decorateHelper = {
+ ts.decorateHelper = {
name: "typescript:decorate",
scoped: false,
priority: 2,
text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };"
};
function createMetadataHelper(context, metadataKey, metadataValue) {
- context.requestEmitHelper(metadataHelper);
+ context.requestEmitHelper(ts.metadataHelper);
return ts.createCall(ts.getHelperName("__metadata"),
/*typeArguments*/ undefined, [
ts.createLiteral(metadataKey),
metadataValue
]);
}
- var metadataHelper = {
+ ts.metadataHelper = {
name: "typescript:metadata",
scoped: false,
priority: 3,
text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };"
};
function createParamHelper(context, expression, parameterOffset, location) {
- context.requestEmitHelper(paramHelper);
+ context.requestEmitHelper(ts.paramHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__param"),
/*typeArguments*/ undefined, [
ts.createLiteral(parameterOffset),
expression
]), location);
}
- var paramHelper = {
+ ts.paramHelper = {
name: "typescript:param",
scoped: false,
priority: 4,
@@ -70206,14 +70647,14 @@ var ts;
], 2 /* Const */));
}
ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
- var awaiterHelper = {
+ ts.awaiterHelper = {
name: "typescript:awaiter",
scoped: false,
priority: 5,
text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };"
};
function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) {
- context.requestEmitHelper(awaiterHelper);
+ context.requestEmitHelper(ts.awaiterHelper);
var generatorFunc = ts.createFunctionExpression(
/*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */),
/*name*/ undefined,
@@ -70845,7 +71286,7 @@ var ts;
}
}
ts.transformES2018 = transformES2018;
- var assignHelper = {
+ ts.assignHelper = {
name: "typescript:assign",
scoped: false,
priority: 1,
@@ -70856,28 +71297,28 @@ var ts;
return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"),
/*typeArguments*/ undefined, attributesSegments);
}
- context.requestEmitHelper(assignHelper);
+ context.requestEmitHelper(ts.assignHelper);
return ts.createCall(ts.getHelperName("__assign"),
/*typeArguments*/ undefined, attributesSegments);
}
ts.createAssignHelper = createAssignHelper;
- var awaitHelper = {
+ ts.awaitHelper = {
name: "typescript:await",
scoped: false,
text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
};
function createAwaitHelper(context, expression) {
- context.requestEmitHelper(awaitHelper);
+ context.requestEmitHelper(ts.awaitHelper);
return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]);
}
- var asyncGeneratorHelper = {
+ ts.asyncGeneratorHelper = {
name: "typescript:asyncGenerator",
scoped: false,
text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
};
function createAsyncGeneratorHelper(context, generatorFunc) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncGeneratorHelper);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncGeneratorHelper);
// Mark this node as originally an async function
(generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */;
return ts.createCall(ts.getHelperName("__asyncGenerator"),
@@ -70887,24 +71328,24 @@ var ts;
generatorFunc
]);
}
- var asyncDelegator = {
+ ts.asyncDelegator = {
name: "typescript:asyncDelegator",
scoped: false,
text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };"
};
function createAsyncDelegatorHelper(context, expression, location) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncDelegator);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncDelegator);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"),
/*typeArguments*/ undefined, [expression]), location);
}
- var asyncValues = {
+ ts.asyncValues = {
name: "typescript:asyncValues",
scoped: false,
text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };"
};
function createAsyncValuesHelper(context, expression, location) {
- context.requestEmitHelper(asyncValues);
+ context.requestEmitHelper(ts.asyncValues);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"),
/*typeArguments*/ undefined, [expression]), location);
}
@@ -74716,7 +75157,7 @@ var ts;
}
ts.transformES2015 = transformES2015;
function createExtendsHelper(context, name) {
- context.requestEmitHelper(extendsHelper);
+ context.requestEmitHelper(ts.extendsHelper);
return ts.createCall(ts.getHelperName("__extends"),
/*typeArguments*/ undefined, [
name,
@@ -74724,20 +75165,20 @@ var ts;
]);
}
function createTemplateObjectHelper(context, cooked, raw) {
- context.requestEmitHelper(templateObjectHelper);
+ context.requestEmitHelper(ts.templateObjectHelper);
return ts.createCall(ts.getHelperName("__makeTemplateObject"),
/*typeArguments*/ undefined, [
cooked,
raw
]);
}
- var extendsHelper = {
+ ts.extendsHelper = {
name: "typescript:extends",
scoped: false,
priority: 0,
text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();"
};
- var templateObjectHelper = {
+ ts.templateObjectHelper = {
name: "typescript:makeTemplateObject",
scoped: false,
priority: 0,
@@ -77431,7 +77872,7 @@ var ts;
}
ts.transformGenerators = transformGenerators;
function createGeneratorHelper(context, body) {
- context.requestEmitHelper(generatorHelper);
+ context.requestEmitHelper(ts.generatorHelper);
return ts.createCall(ts.getHelperName("__generator"),
/*typeArguments*/ undefined, [ts.createThis(), body]);
}
@@ -77494,7 +77935,7 @@ var ts;
// entering a finally block.
//
// For examples of how these are used, see the comments in ./transformers/generators.ts
- var generatorHelper = {
+ ts.generatorHelper = {
name: "typescript:generator",
scoped: false,
priority: 6,
@@ -77527,7 +77968,7 @@ var ts;
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* SourceFile */); // Restore state when substituting nodes in a file.
var moduleInfoMap = []; // The ExternalModuleInfo for each file.
var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
var currentSourceFile; // The current file.
@@ -77869,9 +78310,9 @@ var ts;
return visitFunctionDeclaration(node);
case 240 /* ClassDeclaration */:
return visitClassDeclaration(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
@@ -78029,7 +78470,7 @@ var ts;
}
var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]);
}
return promise;
@@ -78043,7 +78484,7 @@ var ts;
var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
}
var func;
@@ -78077,11 +78518,11 @@ var ts;
return innerExpr;
}
if (ts.getImportNeedsImportStarHelper(node)) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
}
if (ts.getImportNeedsImportDefaultHelper(node)) {
- context.requestEmitHelper(importDefaultHelper);
+ context.requestEmitHelper(ts.importDefaultHelper);
return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
}
return innerExpr;
@@ -78650,7 +79091,7 @@ var ts;
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
currentSourceFile = node;
currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
noSubstitution = [];
@@ -78738,7 +79179,7 @@ var ts;
}
if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)),
/*location*/ node);
}
@@ -78864,13 +79305,13 @@ var ts;
text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
};
// emit helper for `import * as Name from "foo"`
- var importStarHelper = {
+ ts.importStarHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
};
// emit helper for `import Name from "foo"`
- var importDefaultHelper = {
+ ts.importDefaultHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
@@ -78893,7 +79334,7 @@ var ts;
context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols.
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* SourceFile */); // Restore state when substituting nodes in a file.
var moduleInfoMap = []; // The ExternalModuleInfo for each file.
var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
var exportFunctionsMap = []; // The export function associated with a source file.
@@ -79463,7 +79904,7 @@ var ts;
function shouldHoistVariableDeclarationList(node) {
// hoist only non-block scoped declarations or block scoped declarations parented by source file
return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
- && (enclosingBlockScopedContainer.kind === 279 /* SourceFile */
+ && (enclosingBlockScopedContainer.kind === 284 /* SourceFile */
|| (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
}
/**
@@ -79806,9 +80247,9 @@ var ts;
return visitCatchClause(node);
case 218 /* Block */:
return visitBlock(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return destructuringAndImportCallVisitor(node);
@@ -80056,7 +80497,7 @@ var ts;
}
else if (ts.isIdentifier(node)) {
var container = resolver.getReferencedExportContainer(node);
- return container !== undefined && container.kind === 279 /* SourceFile */;
+ return container !== undefined && container.kind === 284 /* SourceFile */;
}
else {
return false;
@@ -80089,7 +80530,7 @@ var ts;
* @param emitCallback A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
var id = ts.getOriginalNodeId(node);
currentSourceFile = node;
moduleInfo = moduleInfoMap[id];
@@ -80298,7 +80739,7 @@ var ts;
|| resolver.getReferencedValueDeclaration(name);
if (valueDeclaration) {
var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
}
exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
@@ -80337,7 +80778,7 @@ var ts;
var previousOnSubstituteNode = context.onSubstituteNode;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
- context.enableEmitNotification(279 /* SourceFile */);
+ context.enableEmitNotification(284 /* SourceFile */);
context.enableSubstitution(72 /* Identifier */);
var currentSourceFile;
return ts.chainBundle(transformSourceFile);
@@ -80767,6 +81208,9 @@ var ts;
case 241 /* InterfaceDeclaration */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
break;
+ case 181 /* MappedType */:
+ diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
+ break;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
@@ -80850,6 +81294,15 @@ var ts;
return result.diagnostics;
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
+ function isInternalDeclaration(node, currentSourceFile) {
+ var parseTreeNode = ts.getParseTreeNode(node);
+ var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
+ return !!ts.forEach(leadingCommentRanges, function (range) {
+ var comment = currentSourceFile.text.substring(range.pos, range.end);
+ return ts.stringContains(comment, "@internal");
+ });
+ }
+ ts.isInternalDeclaration = isInternalDeclaration;
var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
2048 /* WriteClassExpressionAsTypeLiteral */ |
4096 /* UseTypeOfFunction */ |
@@ -80978,10 +81431,10 @@ var ts;
}
}
function transformRoot(node) {
- if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
+ if (node.kind === 284 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
}
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* Bundle */) {
isBundledEmit = true;
refs = ts.createMap();
libs = ts.createMap();
@@ -81011,9 +81464,15 @@ var ts;
var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
}), ts.mapDefined(node.prepends, function (prepend) {
- if (prepend.kind === 282 /* InputFiles */) {
- return ts.createUnparsedSourceFile(prepend, "dts");
- }
+ if (prepend.kind === 287 /* InputFiles */) {
+ var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
+ hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
+ collectReferences(sourceFile, refs);
+ recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
+ collectLibs(sourceFile, libs);
+ return sourceFile;
+ }
+ return prepend;
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
@@ -81105,7 +81564,7 @@ var ts;
}
}
function collectReferences(sourceFile, ret) {
- if (noResolve || ts.isSourceFileJS(sourceFile))
+ if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
return ret;
ts.forEach(sourceFile.referencedFiles, function (f) {
var elem = ts.tryResolveScriptReference(host, sourceFile, f);
@@ -81833,18 +82292,8 @@ var ts;
}
errorNameNode = undefined;
}
- function hasInternalAnnotation(range) {
- var comment = currentSourceFile.text.substring(range.pos, range.end);
- return ts.stringContains(comment, "@internal");
- }
function shouldStripInternal(node) {
- if (stripInternal && node) {
- var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile);
- if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) {
- return true;
- }
- }
- return false;
+ return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
}
function isScopeMarker(node) {
return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
@@ -81866,7 +82315,7 @@ var ts;
function ensureModifierFlags(node, privateDeclaration) {
var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
- var parentIsFile = node.parent.kind === 279 /* SourceFile */;
+ var parentIsFile = node.parent.kind === 284 /* SourceFile */;
if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */);
additions = 0 /* None */;
@@ -82083,7 +82532,7 @@ var ts;
* @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
*/
function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
- var enabledSyntaxKindFeatures = new Array(312 /* Count */);
+ var enabledSyntaxKindFeatures = new Array(317 /* Count */);
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
@@ -82343,10 +82792,14 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- var infoExtension = ".tsbundleinfo";
var brackets = createBracketsMap();
var syntheticParent = { pos: -1, end: -1 };
/*@internal*/
+ function isBuildInfoFile(file) {
+ return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
+ }
+ ts.isBuildInfoFile = isBuildInfoFile;
+ /*@internal*/
/**
* Iterates over the source files that are expected to have an emit output.
*
@@ -82356,13 +82809,14 @@ var ts;
* If an array, the full list of source files to emit.
* Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
*/
- function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) {
+ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles, onlyBuildInfo, includeBuildInfo) {
if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; }
var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
- if (sourceFiles.length) {
- var bundle = ts.createBundle(sourceFiles, host.getPrependNodes());
+ var prepends = host.getPrependNodes();
+ if (sourceFiles.length || prepends.length) {
+ var bundle = ts.createBundle(sourceFiles, prepends);
var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
if (result) {
return result;
@@ -82370,31 +82824,61 @@ var ts;
}
}
else {
- for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
- var sourceFile = sourceFiles_1[_a];
- var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
- if (result) {
- return result;
+ if (!onlyBuildInfo) {
+ for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
+ var sourceFile = sourceFiles_1[_a];
+ var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
+ if (result) {
+ return result;
+ }
}
}
+ if (includeBuildInfo) {
+ var buildInfoPath = getOutputPathForBuildInfo(host.getCompilerOptions());
+ if (buildInfoPath)
+ return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
+ }
}
}
ts.forEachEmittedFile = forEachEmittedFile;
/*@internal*/
+ function getOutputPathForBuildInfo(options) {
+ var configFile = options.configFilePath;
+ if (!configFile || !ts.isIncrementalCompilation(options))
+ return undefined;
+ if (options.tsBuildInfoFile)
+ return options.tsBuildInfoFile;
+ var outPath = options.outFile || options.out;
+ var buildInfoExtensionLess;
+ if (outPath) {
+ buildInfoExtensionLess = ts.removeFileExtension(outPath);
+ }
+ else {
+ var configFileExtensionLess = ts.removeFileExtension(configFile);
+ buildInfoExtensionLess = options.outDir ?
+ options.rootDir ?
+ ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
+ ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
+ configFileExtensionLess;
+ }
+ return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
+ }
+ ts.getOutputPathForBuildInfo = getOutputPathForBuildInfo;
+ /*@internal*/
function getOutputPathsForBundle(options, forceDtsPaths) {
var outPath = options.outFile || options.out;
var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath };
+ var buildInfoPath = getOutputPathForBuildInfo(options);
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
}
ts.getOutputPathsForBundle = getOutputPathsForBundle;
/*@internal*/
function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
var options = host.getCompilerOptions();
- if (sourceFile.kind === 280 /* Bundle */) {
+ if (sourceFile.kind === 285 /* Bundle */) {
return getOutputPathsForBundle(options, forceDtsPaths);
}
else {
@@ -82408,19 +82892,13 @@ var ts;
var isJs = ts.isSourceFileJS(sourceFile);
var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined };
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
}
}
ts.getOutputPathsFor = getOutputPathsFor;
function getSourceMapFilePath(jsFilePath, options) {
return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
}
- function createDefaultBundleInfo() {
- return {
- originalOffset: -1,
- totalLength: -1
- };
- }
// JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
// So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
// For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
@@ -82445,7 +82923,7 @@ var ts;
ts.getOutputExtension = getOutputExtension;
/*@internal*/
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) {
+ function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers, onlyBuildInfo) {
var compilerOptions = host.getCompilerOptions();
var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
@@ -82453,12 +82931,12 @@ var ts;
var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
var writer = ts.createTextWriter(newLine);
var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit;
- var bundleInfo = createDefaultBundleInfo();
+ var bundleBuildInfo;
var emitSkipped = false;
var exportedModulesFromDeclarationEmit;
// Emit each output file
enter();
- forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles);
+ forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles, onlyBuildInfo, !targetSourceFile);
exit();
return {
emitSkipped: emitSkipped,
@@ -82468,9 +82946,16 @@ var ts;
exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
};
function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
- var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath;
- emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
+ var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
+ bundleBuildInfo = {
+ commonSourceDirectory: host.getCommonSourceDirectory(),
+ sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return file.fileName; })
+ };
+ }
+ emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
+ emitBuildInfo(bundleBuildInfo, buildInfoPath);
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
if (jsFilePath) {
@@ -82479,8 +82964,8 @@ var ts;
if (sourceMapFilePath) {
emittedFilesList.push(sourceMapFilePath);
}
- if (bundleInfoPath) {
- emittedFilesList.push(bundleInfoPath);
+ if (buildInfoPath) {
+ emittedFilesList.push(buildInfoPath);
}
}
if (declarationFilePath) {
@@ -82491,8 +82976,21 @@ var ts;
}
}
}
- function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) {
- if (emitOnlyDtsFiles || !jsFilePath) {
+ function emitBuildInfo(bundle, buildInfoPath) {
+ // Write build information if applicable
+ if (!buildInfoPath || targetSourceFile || emitSkipped)
+ return;
+ var program = host.getProgramBuildInfo();
+ if (!bundle && !program)
+ return;
+ if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
+ emitSkipped = true;
+ return;
+ }
+ ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: ts.version }), /*writeByteOrderMark*/ false);
+ }
+ function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) {
+ if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
return;
}
// Make sure not to write js file and source map file if any of them cannot be written
@@ -82512,6 +83010,7 @@ var ts;
inlineSourceMap: compilerOptions.inlineSourceMap,
inlineSources: compilerOptions.inlineSources,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
+ writeBundleFileInfo: !!bundleBuildInfo
};
// Create a printer to print the nodes
var printer = createPrinter(printerOptions, {
@@ -82522,12 +83021,14 @@ var ts;
substituteNode: transform.substituteNode,
});
ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
- printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions);
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
// Clean up emit nodes on parse tree
transform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.js = printer.bundleFileInfo;
}
function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) {
- if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
+ if (!sourceFileOrBundle || !(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
return;
}
var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
@@ -82556,6 +83057,8 @@ var ts;
inlineSourceMap: compilerOptions.inlineSourceMap,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
onlyPrintJsDocStyle: true,
+ writeBundleFileInfo: !!bundleBuildInfo,
+ recordInternalSection: !!bundleBuildInfo
};
var declarationPrinter = createPrinter(printerOptions, {
// resolver hooks
@@ -82568,18 +83071,20 @@ var ts;
emitSkipped = emitSkipped || declBlocked;
if (!declBlocked || emitOnlyDtsFiles) {
ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
- printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, {
+ printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
sourceMap: compilerOptions.declarationMap,
sourceRoot: compilerOptions.sourceRoot,
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
});
- if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) {
+ if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 284 /* SourceFile */) {
var sourceFile = declarationTransform.transformed[0];
exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
}
}
declarationTransform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
}
function collectLinkedAliases(node) {
if (ts.isExportAssignment(node)) {
@@ -82594,16 +83099,16 @@ var ts;
}
ts.forEachChild(node, collectLinkedAliases);
}
- function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) {
- var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined;
- var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined;
+ function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
+ var bundle = sourceFileOrBundle.kind === 285 /* Bundle */ ? sourceFileOrBundle : undefined;
+ var sourceFile = sourceFileOrBundle.kind === 284 /* SourceFile */ ? sourceFileOrBundle : undefined;
var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
var sourceMapGenerator;
if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
}
if (bundle) {
- printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator);
+ printer.writeBundle(bundle, writer, sourceMapGenerator);
}
else {
printer.writeFile(sourceFile, writer, sourceMapGenerator);
@@ -82632,18 +83137,12 @@ var ts;
}
// Write the output file
ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
- // Write bundled offset information if applicable
- if (bundleInfoPath) {
- bundleInfo.totalLength = writer.getTextPos();
- ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false);
- }
// Reset state
writer.clear();
- bundleInfo = createDefaultBundleInfo();
}
function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
- && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
+ && (sourceFileOrBundle.kind !== 284 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
}
function getSourceRoot(mapOptions) {
// Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
@@ -82700,6 +83199,166 @@ var ts;
}
}
ts.emitFiles = emitFiles;
+ /*@internal*/
+ function getBuildInfoText(buildInfo) {
+ return JSON.stringify(buildInfo, undefined, 2);
+ }
+ ts.getBuildInfoText = getBuildInfoText;
+ /*@internal*/
+ function getBuildInfo(buildInfoText) {
+ return JSON.parse(buildInfoText);
+ }
+ ts.getBuildInfo = getBuildInfo;
+ /*@internal*/
+ ts.notImplementedResolver = {
+ hasGlobalName: ts.notImplemented,
+ getReferencedExportContainer: ts.notImplemented,
+ getReferencedImportDeclaration: ts.notImplemented,
+ getReferencedDeclarationWithCollidingName: ts.notImplemented,
+ isDeclarationWithCollidingName: ts.notImplemented,
+ isValueAliasDeclaration: ts.notImplemented,
+ isReferencedAliasDeclaration: ts.notImplemented,
+ isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
+ getNodeCheckFlags: ts.notImplemented,
+ isDeclarationVisible: ts.notImplemented,
+ isLateBound: function (_node) { return false; },
+ collectLinkedAliases: ts.notImplemented,
+ isImplementationOfOverload: ts.notImplemented,
+ isRequiredInitializedParameter: ts.notImplemented,
+ isOptionalUninitializedParameterProperty: ts.notImplemented,
+ isExpandoFunctionDeclaration: ts.notImplemented,
+ getPropertiesOfContainerFunction: ts.notImplemented,
+ createTypeOfDeclaration: ts.notImplemented,
+ createReturnTypeOfSignatureDeclaration: ts.notImplemented,
+ createTypeOfExpression: ts.notImplemented,
+ createLiteralConstValue: ts.notImplemented,
+ isSymbolAccessible: ts.notImplemented,
+ isEntityNameVisible: ts.notImplemented,
+ // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
+ getConstantValue: ts.notImplemented,
+ getReferencedValueDeclaration: ts.notImplemented,
+ getTypeReferenceSerializationKind: ts.notImplemented,
+ isOptionalParameter: ts.notImplemented,
+ moduleExportsSomeValue: ts.notImplemented,
+ isArgumentsLocalBinding: ts.notImplemented,
+ getExternalModuleFileFromDeclaration: ts.notImplemented,
+ getTypeReferenceDirectivesForEntityName: ts.notImplemented,
+ getTypeReferenceDirectivesForSymbol: ts.notImplemented,
+ isLiteralConstDeclaration: ts.notImplemented,
+ getJsxFactoryEntity: ts.notImplemented,
+ getAllAccessorDeclarations: ts.notImplemented,
+ getSymbolOfExternalModuleSpecifier: ts.notImplemented,
+ isBindingCapturedByNode: ts.notImplemented,
+ };
+ function createSourceFilesFromBundleBuildInfo(bundle) {
+ var sourceFiles = bundle.sourceFiles.map(function (fileName) {
+ var sourceFile = ts.createNode(284 /* SourceFile */, 0, 0);
+ sourceFile.fileName = fileName;
+ sourceFile.text = "";
+ sourceFile.statements = ts.createNodeArray();
+ return sourceFile;
+ });
+ var jsBundle = ts.Debug.assertDefined(bundle.js);
+ ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
+ var sourceFile = sourceFiles[prologueInfo.file];
+ sourceFile.text = prologueInfo.text;
+ sourceFile.end = prologueInfo.text.length;
+ sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
+ var statement = ts.createNode(221 /* ExpressionStatement */, directive.pos, directive.end);
+ statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
+ statement.expression.text = directive.expression.text;
+ return statement;
+ }));
+ });
+ return sourceFiles;
+ }
+ /*@internal*/
+ function emitUsingBuildInfo(config, host, getCommandLine) {
+ var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
+ var buildInfoText = host.readFile(ts.Debug.assertDefined(buildInfoPath));
+ if (!buildInfoText)
+ return buildInfoPath;
+ var jsFileText = host.readFile(ts.Debug.assertDefined(jsFilePath));
+ if (!jsFileText)
+ return jsFilePath;
+ var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
+ // error if no source map or for now if inline sourcemap
+ if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
+ return sourceMapFilePath || "inline sourcemap decoding";
+ // read declaration text
+ var declarationText = declarationFilePath && host.readFile(declarationFilePath);
+ if (declarationFilePath && !declarationText)
+ return declarationFilePath;
+ var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
+ // error if no source map or for now if inline sourcemap
+ if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
+ return declarationMapPath || "inline sourcemap decoding";
+ var buildInfo = getBuildInfo(buildInfoText);
+ if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
+ return buildInfoPath;
+ var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo,
+ /*onlyOwnText*/ true);
+ var outputFiles = [];
+ var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
+ var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle);
+ var emitHost = {
+ getPrependNodes: ts.memoize(function () { return prependNodes.concat([ownPrependInput]); }),
+ getCanonicalFileName: host.getCanonicalFileName,
+ getCommonSourceDirectory: function () { return buildInfo.bundle.commonSourceDirectory; },
+ getCompilerOptions: function () { return config.options; },
+ getCurrentDirectory: function () { return host.getCurrentDirectory(); },
+ getNewLine: function () { return host.getNewLine(); },
+ getSourceFile: function () { return undefined; },
+ getSourceFileByPath: function () { return undefined; },
+ getSourceFiles: function () { return sourceFilesForJsEmit; },
+ getLibFileFromReference: ts.notImplemented,
+ isSourceFileFromExternalLibrary: ts.returnFalse,
+ writeFile: function (name, text, writeByteOrderMark) {
+ switch (name) {
+ case jsFilePath:
+ if (jsFileText === text)
+ return;
+ break;
+ case sourceMapFilePath:
+ if (sourceMapText === text)
+ return;
+ break;
+ case buildInfoPath:
+ var newBuildInfo = getBuildInfo(text);
+ newBuildInfo.program = buildInfo.program;
+ // Update sourceFileInfo
+ var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
+ newBuildInfo.bundle.js.sources = js.sources;
+ if (dts) {
+ newBuildInfo.bundle.dts.sources = dts.sources;
+ }
+ newBuildInfo.bundle.sourceFiles = sourceFiles;
+ outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
+ return;
+ case declarationFilePath:
+ if (declarationText === text)
+ return;
+ break;
+ case declarationMapPath:
+ if (declarationMapText === text)
+ return;
+ break;
+ default:
+ ts.Debug.fail("Unexpected path: " + name);
+ }
+ outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
+ },
+ isEmitBlocked: ts.returnFalse,
+ readFile: function (f) { return host.readFile(f); },
+ fileExists: function (f) { return host.fileExists(f); },
+ directoryExists: host.directoryExists && (function (f) { return host.directoryExists(f); }),
+ useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
+ getProgramBuildInfo: function () { return undefined; }
+ };
+ emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, /*emitOnlyDtsFiles*/ false, ts.getTransformers(config.options));
+ return outputFiles;
+ }
+ ts.emitUsingBuildInfo = emitUsingBuildInfo;
var PipelinePhase;
(function (PipelinePhase) {
PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
@@ -82728,6 +83387,10 @@ var ts;
var ownWriter; // Reusable `EmitTextWriter` for basic printing.
var write = writeBase;
var isOwnFileEmit;
+ var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
+ var recordInternalSection = printerOptions.recordInternalSection;
+ var sourceFileTextPos = 0;
+ var sourceFileTextKind = "text" /* Text */;
// Source Maps
var sourceMapsDisabled = true;
var sourceMapGenerator;
@@ -82753,7 +83416,8 @@ var ts;
writeNode: writeNode,
writeList: writeList,
writeFile: writeFile,
- writeBundle: writeBundle
+ writeBundle: writeBundle,
+ bundleFileInfo: bundleFileInfo
};
function printNode(hint, node, sourceFile) {
switch (hint) {
@@ -82768,9 +83432,9 @@ var ts;
break;
}
switch (node.kind) {
- case 279 /* SourceFile */: return printFile(node);
- case 280 /* Bundle */: return printBundle(node);
- case 281 /* UnparsedSource */: return printUnparsedSource(node);
+ case 284 /* SourceFile */: return printFile(node);
+ case 285 /* Bundle */: return printBundle(node);
+ case 286 /* UnparsedSource */: return printUnparsedSource(node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
@@ -82780,7 +83444,7 @@ var ts;
return endPrint();
}
function printBundle(bundle) {
- writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined);
+ writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
return endPrint();
}
function printFile(sourceFile) {
@@ -82808,7 +83472,49 @@ var ts;
reset();
writer = previousWriter;
}
- function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) {
+ function getTextPosWithWriteLine() {
+ return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
+ }
+ function updateOrPushBundleFileTextLike(pos, end, kind) {
+ var last = ts.lastOrUndefined(bundleFileInfo.sections);
+ if (last && last.kind === kind) {
+ last.end = end;
+ }
+ else {
+ bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
+ }
+ }
+ function recordBundleFileInternalSectionStart(node) {
+ if (recordInternalSection &&
+ bundleFileInfo &&
+ currentSourceFile &&
+ (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
+ ts.isInternalDeclaration(node, currentSourceFile) &&
+ sourceFileTextKind !== "internal" /* Internal */) {
+ var prevSourceFileTextKind = sourceFileTextKind;
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = "internal" /* Internal */;
+ return prevSourceFileTextKind;
+ }
+ return undefined;
+ }
+ function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
+ if (prevSourceFileTextKind) {
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = prevSourceFileTextKind;
+ }
+ }
+ function recordBundleFileTextLikeSection(end) {
+ if (sourceFileTextPos < end) {
+ updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
+ return true;
+ }
+ return false;
+ }
+ function writeBundle(bundle, output, sourceMapGenerator) {
+ var _a;
isOwnFileEmit = false;
var previousWriter = writer;
setWriter(output, sourceMapGenerator);
@@ -82816,18 +83522,49 @@ var ts;
emitPrologueDirectivesIfNeeded(bundle);
emitHelpers(bundle);
emitSyntheticTripleSlashReferencesIfNeeded(bundle);
- for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) {
- var prepend = _b[_a];
+ for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
+ var prepend = _c[_b];
writeLine();
+ var pos = writer.getTextPos();
+ var savedSections = bundleFileInfo && bundleFileInfo.sections;
+ if (savedSections)
+ bundleFileInfo.sections = [];
print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
+ if (bundleFileInfo) {
+ var newSections = bundleFileInfo.sections;
+ bundleFileInfo.sections = savedSections;
+ if (prepend.oldFileOfCurrentEmit)
+ (_a = bundleFileInfo.sections).push.apply(_a, newSections);
+ else {
+ newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prepend" /* Prepend */, data: prepend.fileName, texts: newSections });
+ }
+ }
}
- if (bundleInfo) {
- bundleInfo.originalOffset = writer.getTextPos();
- }
- for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) {
- var sourceFile = _d[_c];
+ sourceFileTextPos = getTextPosWithWriteLine();
+ for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
+ var sourceFile = _e[_d];
print(0 /* SourceFile */, sourceFile, sourceFile);
}
+ if (bundleFileInfo && bundle.sourceFiles.length) {
+ var end = writer.getTextPos();
+ if (recordBundleFileTextLikeSection(end)) {
+ // Store prologues
+ var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
+ if (prologues) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.prologues = prologues;
+ }
+ // Store helpes
+ var helpers = getHelpersFromBundledSourceFiles(bundle);
+ if (helpers) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.helpers = helpers;
+ }
+ }
+ }
reset();
writer = previousWriter;
}
@@ -82897,8 +83634,10 @@ var ts;
function emit(node) {
if (node === undefined)
return;
+ var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
var pipelinePhase = getPipelinePhase(0 /* Notification */, node);
pipelinePhase(4 /* Unspecified */, node);
+ recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
}
function emitIdentifierName(node) {
if (node === undefined)
@@ -82925,12 +83664,12 @@ var ts;
}
// falls through
case 2 /* Comments */:
- if (!commentsDisabled && node.kind !== 279 /* SourceFile */) {
+ if (!commentsDisabled && node.kind !== 284 /* SourceFile */) {
return pipelineEmitWithComments;
}
// falls through
case 3 /* SourceMaps */:
- if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) {
+ if (!sourceMapsDisabled && node.kind !== 284 /* SourceFile */ && !ts.isInJsonFile(node)) {
return pipelineEmitWithSourceMap;
}
// falls through
@@ -82967,8 +83706,16 @@ var ts;
case 16 /* TemplateMiddle */:
case 17 /* TemplateTail */:
return emitLiteral(node);
- case 281 /* UnparsedSource */:
- return emitUnparsedSource(node);
+ case 286 /* UnparsedSource */:
+ case 280 /* UnparsedPrepend */:
+ return emitUnparsedSourceOrPrepend(node);
+ case 279 /* UnparsedPrologue */:
+ return writeUnparsedNode(node);
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return emitUnparsedTextLike(node);
+ case 283 /* UnparsedSyntheticReference */:
+ return emitUnparsedSyntheticReference(node);
// Identifiers
case 72 /* Identifier */:
return emitIdentifier(node);
@@ -83012,7 +83759,7 @@ var ts;
return emitTypeReference(node);
case 165 /* FunctionType */:
return emitFunctionType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return emitJSDocFunctionType(node);
case 166 /* ConstructorType */:
return emitConstructorType(node);
@@ -83050,20 +83797,20 @@ var ts;
return emitLiteralType(node);
case 183 /* ImportType */:
return emitImportTypeNode(node);
- case 284 /* JSDocAllType */:
+ case 289 /* JSDocAllType */:
writePunctuation("*");
return;
- case 285 /* JSDocUnknownType */:
+ case 290 /* JSDocUnknownType */:
writePunctuation("?");
return;
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return emitJSDocNullableType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return emitJSDocNonNullableType(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return emitJSDocOptionalType(node);
case 172 /* RestType */:
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return emitRestOrJSDocVariadicType(node);
// Binding patterns
case 184 /* ObjectBindingPattern */:
@@ -83201,30 +83948,30 @@ var ts;
case 278 /* EnumMember */:
return emitEnumMember(node);
// JSDoc nodes (only used in codefixes currently)
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return emitJSDocPropertyLikeTag(node);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return emitJSDocSimpleTypedTag(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return emitJSDocAugmentsTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return emitJSDocTemplateTag(node);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return emitJSDocTypedefTag(node);
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return emitJSDocCallbackTag(node);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return emitJSDocSignature(node);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return emitJSDocTypeLiteral(node);
- case 296 /* JSDocClassTag */:
- case 294 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
return emitJSDocSimpleTag(node);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return emitJSDoc(node);
// Transformation nodes (ignored)
}
@@ -83323,9 +84070,9 @@ var ts;
case 264 /* JsxFragment */:
return emitJsxFragment(node);
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return emitPartiallyEmittedExpression(node);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return emitCommaList(node);
}
}
@@ -83341,22 +84088,45 @@ var ts;
var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node);
pipelinePhase(hint, substituteNode(hint, node));
}
+ function getHelpersFromBundledSourceFiles(bundle) {
+ var result;
+ if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
+ return undefined;
+ }
+ var bundledHelpers = ts.createMap();
+ for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
+ var sourceFile = _b[_a];
+ var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
+ var helpers = getSortedEmitHelpers(sourceFile);
+ if (!helpers)
+ continue;
+ for (var _c = 0, helpers_3 = helpers; _c < helpers_3.length; _c++) {
+ var helper = helpers_3[_c];
+ if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
+ bundledHelpers.set(helper.name, true);
+ (result || (result = [])).push(helper.name);
+ }
+ }
+ }
+ return result;
+ }
function emitHelpers(node) {
var helpersEmitted = false;
- var bundle = node.kind === 280 /* Bundle */ ? node : undefined;
+ var bundle = node.kind === 285 /* Bundle */ ? node : undefined;
if (bundle && moduleKind === ts.ModuleKind.None) {
return;
}
- var numNodes = bundle ? bundle.sourceFiles.length : 1;
+ var numPrepends = bundle ? bundle.prepends.length : 0;
+ var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
for (var i = 0; i < numNodes; i++) {
- var currentNode = bundle ? bundle.sourceFiles[i] : node;
- var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile;
- var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined;
- var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit;
- var helpers = ts.getEmitHelpers(currentNode);
+ var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
+ var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
+ var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined);
+ var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
+ var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
if (helpers) {
- for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) {
- var helper = _b[_a];
+ for (var _a = 0, helpers_4 = helpers; _a < helpers_4.length; _a++) {
+ var helper = helpers_4[_a];
if (!helper.scoped) {
// Skip the helper if it can be skipped and the noEmitHelpers compiler
// option is set, or if it can be imported and the importHelpers compiler
@@ -83376,18 +84146,25 @@ var ts;
// Skip the helper if it is scoped and we are emitting bundled helpers
continue;
}
+ var pos = getTextPosWithWriteLine();
if (typeof helper.text === "string") {
writeLines(helper.text);
}
else {
writeLines(helper.text(makeFileLevelOptimisticUniqueName));
}
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
helpersEmitted = true;
}
}
}
return helpersEmitted;
}
+ function getSortedEmitHelpers(node) {
+ var helpers = ts.getEmitHelpers(node);
+ return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
+ }
//
// Literals/Pseudo-literals
//
@@ -83414,8 +84191,42 @@ var ts;
}
}
// SyntaxKind.UnparsedSource
- function emitUnparsedSource(unparsed) {
- writer.rawWrite(unparsed.text);
+ // SyntaxKind.UnparsedPrepend
+ function emitUnparsedSourceOrPrepend(unparsed) {
+ for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
+ var text = _b[_a];
+ writeLine();
+ emit(text);
+ }
+ }
+ // SyntaxKind.UnparsedPrologue
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ // SyntaxKind.UnparsedSyntheticReference
+ function writeUnparsedNode(unparsed) {
+ writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
+ }
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ function emitUnparsedTextLike(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 281 /* UnparsedText */ ?
+ "text" /* Text */ :
+ "internal" /* Internal */);
+ }
+ }
+ // SyntaxKind.UnparsedSyntheticReference
+ function emitUnparsedSyntheticReference(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ var section = ts.clone(unparsed.section);
+ section.pos = pos;
+ section.end = writer.getTextPos();
+ bundleFileInfo.sections.push(section);
+ }
}
//
// Identifiers
@@ -83470,7 +84281,7 @@ var ts;
emit(node.dotDotDotToken);
emitNodeWithWriter(node.name, writeParameter);
emit(node.questionToken);
- if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) {
+ if (node.parent && node.parent.kind === 294 /* JSDocFunctionType */ && !node.name) {
emit(node.type);
}
else {
@@ -84350,7 +85161,7 @@ var ts;
}
function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
// Emit all the prologue directives (like "use strict").
- var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true);
+ var statementOffset = emitPrologueDirectives(body.statements);
var pos = writer.getTextPos();
emitHelpers(body);
if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
@@ -84755,7 +85566,7 @@ var ts;
}
}
if (node.tags) {
- if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) {
+ if (node.tags.length === 1 && node.tags[0].kind === 307 /* JSDocTypeTag */ && !node.comment) {
writeSpace();
emit(node.tags[0]);
}
@@ -84789,7 +85600,7 @@ var ts;
function emitJSDocTypedefTag(tag) {
emitJSDocTagName(tag.tagName);
if (tag.typeExpression) {
- if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
emitJSDocTypeExpression(tag.typeExpression);
}
else {
@@ -84808,7 +85619,7 @@ var ts;
emit(tag.fullName);
}
emitJSDocComment(tag.comment);
- if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) {
+ if (tag.typeExpression && tag.typeExpression.kind === 297 /* JSDocTypeLiteral */) {
emitJSDocTypeLiteral(tag.typeExpression);
}
}
@@ -84895,6 +85706,16 @@ var ts;
}
function emitSyntheticTripleSlashReferencesIfNeeded(node) {
emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
+ for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
+ for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
+ var ref = _d[_c];
+ emit(ref);
+ writeLine();
+ }
+ }
+ }
}
function emitTripleSlashDirectivesIfNeeded(node) {
if (node.isDeclarationFile)
@@ -84902,7 +85723,10 @@ var ts;
}
function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
if (hasNoDefaultLib) {
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
writeLine();
}
if (currentSourceFile && currentSourceFile.moduleName) {
@@ -84923,17 +85747,26 @@ var ts;
}
for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
var directive = files_1[_c];
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
writeLine();
}
for (var _d = 0, types_19 = types; _d < types_19.length; _d++) {
var directive = types_19[_d];
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
writeLine();
}
for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
var directive = libs_1[_e];
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
writeLine();
}
}
@@ -84958,16 +85791,22 @@ var ts;
* Emits any prologue directives at the start of a Statement list, returning the
* number of prologue directives written to the output.
*/
- function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) {
+ function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
+ var needsToSetSourceFile = !!sourceFile;
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (ts.isPrologueDirective(statement)) {
var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
if (shouldEmitPrologueDirective) {
- if (startWithNewLine || i > 0) {
- writeLine();
+ if (needsToSetSourceFile) {
+ needsToSetSourceFile = false;
+ setSourceFile(sourceFile);
}
+ writeLine();
+ var pos = writer.getTextPos();
emit(statement);
+ if (recordBundleFileSection && bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
if (seenPrologueDirectives) {
seenPrologueDirectives.set(statement.expression.text, true);
}
@@ -84980,23 +85819,70 @@ var ts;
}
return statements.length;
}
+ function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
+ for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
+ var prologue = prologues_1[_a];
+ if (!seenPrologueDirectives.has(prologue.data)) {
+ writeLine();
+ var pos = writer.getTextPos();
+ emit(prologue);
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
+ if (seenPrologueDirectives) {
+ seenPrologueDirectives.set(prologue.data, true);
+ }
+ }
+ }
+ }
function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
if (ts.isSourceFile(sourceFileOrBundle)) {
- setSourceFile(sourceFileOrBundle);
- emitPrologueDirectives(sourceFileOrBundle.statements);
+ emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
}
else {
var seenPrologueDirectives = ts.createMap();
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
- setSourceFile(sourceFile);
- emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives);
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
+ emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
}
setSourceFile(undefined);
}
}
+ function getPrologueDirectivesFromBundledSourceFiles(bundle) {
+ var seenPrologueDirectives = ts.createMap();
+ var prologues;
+ for (var index = 0; index < bundle.sourceFiles.length; index++) {
+ var sourceFile = bundle.sourceFiles[index];
+ var directives = void 0;
+ var end = 0;
+ for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
+ var statement = _b[_a];
+ if (!ts.isPrologueDirective(statement))
+ break;
+ if (seenPrologueDirectives.has(statement.expression.text))
+ continue;
+ seenPrologueDirectives.set(statement.expression.text, true);
+ (directives || (directives = [])).push({
+ pos: statement.pos,
+ end: statement.end,
+ expression: {
+ pos: statement.expression.pos,
+ end: statement.expression.end,
+ text: statement.expression.text
+ }
+ });
+ end = end < statement.end ? statement.end : end;
+ }
+ if (directives)
+ (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
+ }
+ return prologues;
+ }
function emitShebangIfNeeded(sourceFileOrBundle) {
- if (ts.isSourceFile(sourceFileOrBundle)) {
+ if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
var shebang = ts.getShebang(sourceFileOrBundle.text);
if (shebang) {
writeComment(shebang);
@@ -85005,11 +85891,18 @@ var ts;
}
}
else {
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ ts.Debug.assertNode(prepend, ts.isUnparsedSource);
+ if (emitShebangIfNeeded(prepend)) {
+ return true;
+ }
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
// Emit only the first encountered shebang
if (emitShebangIfNeeded(sourceFile)) {
- break;
+ return true;
}
}
}
@@ -85212,6 +86105,7 @@ var ts;
}
// Emit each child.
var previousSibling = void 0;
+ var previousSourceFileTextKind = void 0;
var shouldDecreaseIndentAfterEmit = false;
for (var i = 0; i < count; i++) {
var child = children[start + i];
@@ -85232,6 +86126,7 @@ var ts;
emitLeadingCommentsOfPosition(previousSibling.end);
}
writeDelimiter(format);
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write either a line terminator or whitespace to separate the elements.
if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) {
// If a synthesized node in a single-line list starts on a new
@@ -85248,6 +86143,7 @@ var ts;
}
}
// Emit this child.
+ previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
if (shouldEmitInterveningComments) {
if (emitTrailingCommentsOfPosition) {
var commentRange = ts.getCommentRange(child);
@@ -85282,6 +86178,7 @@ var ts;
if (format & 128 /* Indented */) {
decreaseIndent();
}
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write the closing line terminator or closing whitespace.
if (shouldWriteClosingLineTerminator(parentNode, children, format)) {
writeLine();
@@ -85383,7 +86280,6 @@ var ts;
if (line.length) {
writeLine();
write(line);
- writer.rawWrite(newLine);
}
}
}
@@ -85897,7 +86793,7 @@ var ts;
hasWrittenComment = false;
var emitFlags = ts.getEmitFlags(node);
var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
- var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */;
+ var isEmittedNode = node.kind !== 312 /* NotEmittedStatement */;
// We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
// It is expensive to walk entire tree just to set one kind of node to have no comments.
var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
@@ -86157,19 +87053,28 @@ var ts;
return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
}
// Source Maps
+ function getParsedSourceMap(node) {
+ if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
+ node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
+ }
+ return node.parsedSourceMap || undefined;
+ }
function pipelineEmitWithSourceMap(hint, node) {
var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node);
- if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) {
- var parsed = ts.tryParseRawSourceMap(node.sourceMapText);
- if (parsed) {
- sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath);
+ if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
+ pipelinePhase(hint, node);
+ }
+ else if (ts.isUnparsedNode(node)) {
+ var parsed = getParsedSourceMap(node.parent);
+ if (parsed && sourceMapGenerator) {
+ sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
}
pipelinePhase(hint, node);
}
else {
var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
var emitFlags = ts.getEmitFlags(node);
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 16 /* NoLeadingSourceMap */) === 0
&& pos >= 0) {
emitSourcePos(source, skipSourceTrivia(source, pos));
@@ -86182,7 +87087,7 @@ var ts;
else {
pipelinePhase(hint, node);
}
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 32 /* NoTrailingSourceMap */) === 0
&& end >= 0) {
emitSourcePos(source, end);
@@ -86830,7 +87735,8 @@ var ts;
var value = readFileCache.get(key);
if (value !== undefined)
return value !== false ? value : undefined; // could be .d.ts from output
- if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) {
+ // Cache json or buildInfo
+ if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
return originalReadFile.call(host, fileName);
}
return setReadFileCache(key, fileName);
@@ -86861,7 +87767,7 @@ var ts;
var key = toPath(fileName);
fileExistsCache.delete(key);
var value = readFileCache.get(key);
- if (value && value !== data) {
+ if (value !== undefined && value !== data) {
readFileCache.delete(key);
sourceFileCache.delete(key);
}
@@ -87416,7 +88322,8 @@ var ts;
getProjectReferenceRedirect: getProjectReferenceRedirect,
getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
- forEachResolvedProjectReference: forEachResolvedProjectReference
+ forEachResolvedProjectReference: forEachResolvedProjectReference,
+ emitBuildInfo: emitBuildInfo
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -87843,7 +88750,20 @@ var ts;
return false;
// Before falling back to the host
return host.fileExists(f);
- } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } });
+ } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); } });
+ }
+ function emitBuildInfo(writeFileCallback) {
+ ts.Debug.assert(!options.out && !options.outFile);
+ ts.performance.mark("beforeEmit");
+ var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback),
+ /*targetSourceFile*/ undefined,
+ /*emitOnlyDtsFiles*/ false,
+ /*transformers*/ undefined,
+ /*declaraitonTransformers*/ undefined,
+ /*onlyBuildInfo*/ true);
+ ts.performance.mark("afterEmit");
+ ts.performance.measure("Emit", "beforeEmit", "afterEmit");
+ return emitResult;
}
function getResolvedProjectReferences() {
return resolvedProjectReferences;
@@ -87852,28 +88772,11 @@ var ts;
return projectReferences;
}
function getPrependNodes() {
- if (!projectReferences) {
- return ts.emptyArray;
- }
- var nodes = [];
- for (var i = 0; i < projectReferences.length; i++) {
- var ref = projectReferences[i];
- var resolvedRefOpts = resolvedProjectReferences[i].commandLine;
- if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
- var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
- // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
- if (!out)
- continue;
- var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
- var node = ts.createInputFiles(function (fileName) {
- var path = toPath(fileName);
- var sourceFile = getSourceFileByPath(path);
- return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
- }, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath);
- nodes.push(node);
- }
- }
- return nodes;
+ return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
+ var path = toPath(fileName);
+ var sourceFile = getSourceFileByPath(path);
+ return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
+ });
}
function isSourceFileFromExternalLibrary(file) {
return !!sourceFilesFoundSearchingNodeModules.get(file.path);
@@ -87945,8 +88848,7 @@ var ts;
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
ts.performance.mark("beforeEmit");
var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers);
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217
- emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -88948,6 +89850,14 @@ var ts;
if (options.declaration === false) {
createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
}
+ if (options.incremental === false) {
+ createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
+ }
+ }
+ if (options.tsBuildInfoFile) {
+ if (!ts.isIncrementalCompilation(options)) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
+ }
}
verifyProjectReferences();
// List of collected files is complete; validate exhautiveness if this is a project with a file list
@@ -89142,6 +90052,7 @@ var ts;
}
}
function verifyProjectReferences() {
+ var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getOutputPathForBuildInfo(options) : undefined;
forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
var parentFile = parent && parent.sourceFile;
@@ -89168,6 +90079,10 @@ var ts;
createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
}
}
+ if (!parent && buildInfoPath && buildInfoPath === ts.getOutputPathForBuildInfo(options)) {
+ createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
+ hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
+ }
});
}
function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
@@ -89317,6 +90232,27 @@ var ts;
};
}
ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
+ /* @internal */
+ function createPrependNodes(projectReferences, getCommandLine, readFile) {
+ if (!projectReferences)
+ return ts.emptyArray;
+ var nodes;
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = getCommandLine(ref, i);
+ if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
+ var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
+ // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
+ if (!out)
+ continue;
+ var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
+ (nodes || (nodes = [])).push(node);
+ }
+ }
+ return nodes || ts.emptyArray;
+ }
+ ts.createPrependNodes = createPrependNodes;
function resolveProjectReferencePath(hostOrRef, ref) {
var passedInRef = ref ? ref : hostOrRef;
return ts.resolveConfigFileProjectName(passedInRef.path);
@@ -89860,11 +90796,14 @@ var ts;
var affectedSignatures = oldState.currentAffectedFilesSignatures;
ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
}
+ var changedFilesSet = oldState.changedFilesSet;
if (canCopySemanticDiagnostics) {
- ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
+ ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
}
// Copy old state's changed files set
- ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet);
+ if (changedFilesSet) {
+ ts.copyEntries(changedFilesSet, state.changedFilesSet);
+ }
if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit;
state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
@@ -89902,7 +90841,7 @@ var ts;
// Unchanged file copy diagnostics
var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
if (diagnostics) {
- state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics);
+ state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics);
if (!state.semanticDiagnosticsFromOldState) {
state.semanticDiagnosticsFromOldState = ts.createMap();
}
@@ -89910,8 +90849,45 @@ var ts;
}
}
});
+ if (oldCompilerOptions &&
+ (oldCompilerOptions.outDir !== compilerOptions.outDir ||
+ oldCompilerOptions.declarationDir !== compilerOptions.declarationDir ||
+ (oldCompilerOptions.outFile || oldCompilerOptions.out) !== (compilerOptions.outFile || compilerOptions.out))) {
+ // Add all files to affectedFilesPendingEmit since emit changed
+ state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, newProgram.getSourceFiles().map(function (f) { return f.path; }));
+ if (state.affectedFilesPendingEmitIndex === undefined) {
+ state.affectedFilesPendingEmitIndex = 0;
+ }
+ ts.Debug.assert(state.seenAffectedFiles === undefined);
+ state.seenAffectedFiles = ts.createMap();
+ }
return state;
}
+ function convertToDiagnostics(diagnostics, newProgram) {
+ if (!diagnostics.length)
+ return ts.emptyArray;
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToDiagnosticRelatedInformation(diagnostic, newProgram) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && newProgram.getSourceFileByPath(file), messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToDiagnosticMessageChain(messageText, newProgram) });
+ }
+ function convertToDiagnosticMessageChain(diagnostic, newProgram) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToDiagnosticMessageChain(diagnostic.next, newProgram) });
+ }
/**
* Releases program and other related not needed properties
*/
@@ -90131,8 +91107,11 @@ var ts;
* This is called after completing operation on the next affected file.
* The operations here are postponed to ensure that cancellation during the iteration is handled correctly
*/
- function doneWithAffectedFile(state, affected, isPendingEmit) {
- if (affected === state.program) {
+ function doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit) {
+ if (isBuildInfoEmit) {
+ state.emittedBuildInfo = true;
+ }
+ else if (affected === state.program) {
state.changedFilesSet.clear();
state.programEmitComplete = true;
}
@@ -90149,8 +91128,8 @@ var ts;
/**
* Returns the result with affected file
*/
- function toAffectedFileResult(state, result, affected, isPendingEmit) {
- doneWithAffectedFile(state, affected, isPendingEmit);
+ function toAffectedFileResult(state, result, affected, isPendingEmit, isBuildInfoEmit) {
+ doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit);
return { result: result, affected: affected };
}
/**
@@ -90173,6 +91152,77 @@ var ts;
}
return diagnostics;
}
+ /**
+ * Gets the program information to be emitted in buildInfo so that we can use it to create new program
+ */
+ function getProgramBuildInfo(state) {
+ if (state.compilerOptions.outFile || state.compilerOptions.out)
+ return undefined;
+ var fileInfos = {};
+ state.fileInfos.forEach(function (value, key) {
+ var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
+ fileInfos[key] = signature === undefined ? value : { version: value.version, signature: signature };
+ });
+ var result = { fileInfos: fileInfos, options: state.compilerOptions };
+ if (state.referencedMap) {
+ var referencedMap_1 = {};
+ state.referencedMap.forEach(function (value, key) {
+ referencedMap_1[key] = ts.arrayFrom(value.keys());
+ });
+ result.referencedMap = referencedMap_1;
+ }
+ if (state.exportedModulesMap) {
+ var exportedModulesMap_1 = {};
+ state.exportedModulesMap.forEach(function (value, key) {
+ var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
+ // Not in temporary cache, use existing value
+ if (newValue === undefined)
+ exportedModulesMap_1[key] = ts.arrayFrom(value.keys());
+ // Value in cache and has updated value map, use that
+ else if (newValue)
+ exportedModulesMap_1[key] = ts.arrayFrom(newValue.keys());
+ });
+ result.exportedModulesMap = exportedModulesMap_1;
+ }
+ if (state.semanticDiagnosticsPerFile) {
+ var semanticDiagnosticsPerFile_1 = [];
+ // Currently not recording actual errors since those mean no emit for tsc --build
+ state.semanticDiagnosticsPerFile.forEach(function (value, key) { return semanticDiagnosticsPerFile_1.push(value.length ?
+ [
+ key,
+ state.hasReusableDiagnostic ?
+ value :
+ convertToReusableDiagnostics(value)
+ ] :
+ key); });
+ result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile_1;
+ }
+ return result;
+ }
+ function convertToReusableDiagnostics(diagnostics) {
+ ts.Debug.assert(!!diagnostics.length);
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToReusableDiagnosticRelatedInformation(diagnostic);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToReusableDiagnosticRelatedInformation(diagnostic) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && file.path, messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToReusableDiagnosticMessageChain(messageText) });
+ }
+ function convertToReusableDiagnosticMessageChain(diagnostic) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToReusableDiagnosticMessageChain(diagnostic.next) });
+ }
var BuilderProgramKind;
(function (BuilderProgramKind) {
BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
@@ -90229,6 +91279,7 @@ var ts;
var computeHash = host.createHash || ts.generateDjb2Hash;
var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
var backupState;
+ newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state); };
// To ensure that we arent storing any references to old program or new program without state
newProgram = undefined; // TODO: GH#18217
oldProgram = undefined;
@@ -90272,7 +91323,16 @@ var ts;
if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
affected = getNextAffectedFilePendingEmit(state);
if (!affected) {
- return undefined;
+ if (state.emittedBuildInfo) {
+ return undefined;
+ }
+ var affected_1 = ts.Debug.assertDefined(state.program);
+ return toAffectedFileResult(state,
+ // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
+ // Otherwise just affected file
+ affected_1.emitBuildInfo(writeFile || host.writeFile, cancellationToken), affected_1,
+ /*isPendingEmitFile*/ false,
+ /*isBuildInfoEmit*/ true);
}
isPendingEmitFile = true;
}
@@ -90405,6 +91465,53 @@ var ts;
}
}
ts.createBuilderProgram = createBuilderProgram;
+ function getMapOfReferencedSet(mapLike) {
+ if (!mapLike)
+ return undefined;
+ var map = ts.createMap();
+ // Copies keys/values from template. Note that for..in will not throw if
+ // template is undefined, and instead will just exit the loop.
+ for (var key in mapLike) {
+ if (ts.hasProperty(mapLike, key)) {
+ map.set(key, ts.arrayToSet(mapLike[key]));
+ }
+ }
+ return map;
+ }
+ function createBuildProgramUsingProgramBuildInfo(program) {
+ var fileInfos = ts.createMapFromTemplate(program.fileInfos);
+ var state = {
+ fileInfos: fileInfos,
+ compilerOptions: program.options,
+ referencedMap: getMapOfReferencedSet(program.referencedMap),
+ exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap),
+ semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return ts.isString(value) ? value : value[0]; }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }),
+ hasReusableDiagnostic: true
+ };
+ return {
+ getState: function () { return state; },
+ backupState: ts.noop,
+ restoreState: ts.noop,
+ getProgram: ts.notImplemented,
+ getProgramOrUndefined: function () { return undefined; },
+ releaseProgram: ts.noop,
+ getCompilerOptions: function () { return state.compilerOptions; },
+ getSourceFile: ts.notImplemented,
+ getSourceFiles: ts.notImplemented,
+ getOptionsDiagnostics: ts.notImplemented,
+ getGlobalDiagnostics: ts.notImplemented,
+ getConfigFileParsingDiagnostics: ts.notImplemented,
+ getSyntacticDiagnostics: ts.notImplemented,
+ getDeclarationDiagnostics: ts.notImplemented,
+ getSemanticDiagnostics: ts.notImplemented,
+ emit: ts.notImplemented,
+ getAllDependencies: ts.notImplemented,
+ getCurrentDirectory: ts.notImplemented,
+ emitNextAffectedFile: ts.notImplemented,
+ getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
+ };
+ }
+ ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
return {
getState: ts.notImplemented,
@@ -90424,7 +91531,7 @@ var ts;
getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
getAllDependencies: ts.notImplemented,
- getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); }
+ getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
};
function getProgram() {
return ts.Debug.assertDefined(state.program);
@@ -90450,10 +91557,10 @@ var ts;
/*@internal*/
var ts;
(function (ts) {
- function isPathInNodeModulesStartingWithDot(path) {
- return ts.stringContains(path, "/node_modules/.");
+ function isPathIgnored(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); });
}
- ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot;
+ ts.isPathIgnored = isPathIgnored;
ts.maxNumberOfFilesToIterateForInvalidation = 256;
function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
var filesWithChangedSetOfUnresolvedImports;
@@ -90975,7 +92082,7 @@ var ts;
}
else {
// If something to do with folder/file starting with "." in node_modules folder, skip it
- if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (isPathIgnored(fileOrDirectoryPath))
return false;
// Some file or directory in the watching directory is created
// Return early if it does not have any of the watching extension or not the custom failed lookup path
@@ -91452,6 +92559,8 @@ var ts;
case ".jsx" /* Jsx */:
case ".json" /* Json */:
return ext;
+ case ".tsbuildinfo" /* TsBuildInfo */:
+ return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
default:
return ts.Debug.assertNever(ext);
}
@@ -91733,7 +92842,7 @@ var ts;
writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; },
createHash: ts.maybeBind(system, system.createHash),
- createProgram: createProgram
+ createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
};
}
ts.createProgramHost = createProgramHost;
@@ -91743,7 +92852,7 @@ var ts;
function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
var writeFileName = function (s) { return system.write(s + system.newLine); };
- var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram);
+ var result = createProgramHost(system, createProgram);
ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
result.afterProgramCreate = function (builderProgram) {
var compilerOptions = builderProgram.getCompilerOptions();
@@ -92172,7 +93281,7 @@ var ts;
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
nextSourceFileVersion(fileOrDirectoryPath);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
// If the the added or created file or directory is not supported file name, ignore the file
// But when watched directory is added/removed, we need to reload the file list
@@ -92226,16 +93335,23 @@ var ts;
* This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
*/
UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
- UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream";
- UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate";
- UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked";
- UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream";
+ /**
+ * The project appears out of date because its upstream inputs are newer than its outputs,
+ * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
+ * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
+ */
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
+ UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
+ UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
+ UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
+ UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
+ UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
/**
* Projects with no outputs (i.e. "solution" files)
*/
- UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly";
+ UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
})(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
function createFileMap(toPath) {
// tslint:disable-next-line:no-null-keyword
@@ -92316,24 +93432,18 @@ var ts;
}
return outputs;
}
- function getOutFileOutputs(project) {
- var out = project.options.outFile || project.options.out;
- if (!out) {
- return ts.Debug.fail("outFile must be set");
- }
+ function getOutFileOutputs(project, ignoreBuildInfo) {
+ ts.Debug.assert(!!project.options.outFile || !!project.options.out, "outFile must be set");
+ var _a = ts.getOutputPathsForBundle(project.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
var outputs = [];
- outputs.push(out);
- if (project.options.sourceMap) {
- outputs.push(out + ".map");
- }
- if (ts.getEmitDeclarations(project.options)) {
- var dts = ts.changeExtension(out, ".d.ts" /* Dts */);
- outputs.push(dts);
- if (project.options.declarationMap) {
- outputs.push(dts + ".map");
- }
- }
- return outputs;
+ var addOutput = function (path) { return path && (outputs || (outputs = [])).push(path); };
+ addOutput(jsFilePath);
+ addOutput(sourceMapFilePath);
+ addOutput(declarationFilePath);
+ addOutput(declarationMapPath);
+ if (!ignoreBuildInfo)
+ addOutput(buildInfoPath);
+ return outputs || ts.emptyArray;
}
function rootDirOfOptions(opts, configFileName) {
return opts.rootDir || ts.getDirectoryPath(configFileName);
@@ -92366,14 +93476,14 @@ var ts;
}
function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
host.reportErrorSummary = reportErrorSummary;
return host;
}
ts.createSolutionBuilderHost = createSolutionBuilderHost;
function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
var watchHost = ts.createWatchHost(system, reportWatchStatus);
ts.copyProperties(host, watchHost);
return host;
@@ -92407,7 +93517,18 @@ var ts;
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; });
var originalGetSourceFile = compilerHost.getSourceFile;
var computeHash = host.createHash || ts.generateDjb2Hash;
- updateGetSourceFile();
+ compilerHost.getSourceFile = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
+ if (result) {
+ result.version = computeHash.call(host, result.text);
+ }
+ return result;
+ };
+ var buildInfoChecked = createFileMap(toPath);
// Watch state
var builderPrograms = createFileMap(toPath);
var diagnostics = createFileMap(toPath);
@@ -92445,6 +93566,7 @@ var ts;
projectStatus.clear();
missingRoots.clear();
globalDependencyGraph = undefined;
+ buildInfoChecked.clear();
diagnostics.clear();
projectPendingBuild.clear();
projectErrorsReported.clear();
@@ -92459,29 +93581,6 @@ var ts;
ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); });
ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher);
builderPrograms.clear();
- updateGetSourceFile();
- }
- function updateGetSourceFile() {
- if (options.watch) {
- if (compilerHost.getSourceFile === originalGetSourceFile) {
- compilerHost.getSourceFile = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
- if (result && options.watch) {
- result.version = computeHash.call(host, result.text);
- }
- return result;
- };
- }
- }
- else {
- if (compilerHost.getSourceFile !== originalGetSourceFile) {
- compilerHost.getSourceFile = originalGetSourceFile;
- }
- }
}
function isParsedCommandLine(entry) {
return !!entry.options;
@@ -92713,25 +93812,28 @@ var ts;
upstreamProjectName: ref.path
};
}
- // If the upstream project's newest file is older than our oldest output, we
- // can't be out of date because of it
- if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
- continue;
- }
- // If the upstream project has only change .d.ts files, and we've built
- // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
- if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
- pseudoUpToDate = true;
- upstreamChangedProject = ref.path;
- continue;
+ // Check oldest output file name only if there is no missing output file name
+ if (!missingOutputFileName) {
+ // If the upstream project's newest file is older than our oldest output, we
+ // can't be out of date because of it
+ if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
+ continue;
+ }
+ // If the upstream project has only change .d.ts files, and we've built
+ // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
+ if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
+ pseudoUpToDate = true;
+ upstreamChangedProject = ref.path;
+ continue;
+ }
+ // We have an output older than an upstream output - we are out of date
+ ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
+ return {
+ type: UpToDateStatusType.OutOfDateWithUpstream,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerProjectName: ref.path
+ };
}
- // We have an output older than an upstream output - we are out of date
- ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
- return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: oldestOutputFileName,
- newerProjectName: ref.path
- };
}
}
if (missingOutputFileName !== undefined) {
@@ -92747,9 +93849,23 @@ var ts;
newerInputFileName: newestInputFileName
};
}
+ if (!buildInfoChecked.hasKey(project.options.configFilePath)) {
+ buildInfoChecked.setValue(project.options.configFilePath, true);
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath) {
+ var value = readFileWithCache(buildInfoPath);
+ var buildInfo = value && ts.getBuildInfo(value);
+ if (buildInfo && buildInfo.version !== ts.version) {
+ return {
+ type: UpToDateStatusType.TsVersionOutputOfDate,
+ version: buildInfo.version
+ };
+ }
+ }
+ }
if (usesPrepend && pseudoUpToDate) {
return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
+ type: UpToDateStatusType.OutOfDateWithPrepend,
outOfDateOutputFileName: oldestOutputFileName,
newerProjectName: upstreamChangedProject
};
@@ -92883,7 +93999,9 @@ var ts;
updateOutputTimestamps(proj);
return;
}
- var buildResult = buildSingleProject(resolved);
+ var buildResult = status.type === UpToDateStatusType.OutOfDateWithPrepend ?
+ updateBundle(resolved) : // Fake that files have been built by manipulating prepend and existing output
+ buildSingleProject(resolved); // Actual build
if (buildResult & BuildResultFlags.AnyErrors)
return;
var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue;
@@ -92899,17 +94017,26 @@ var ts;
// If declaration output is changed, build the project
// otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
var status_1 = projectStatus.getValue(project);
- if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
- if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) {
+ if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
+ if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes || status_1.type === UpToDateStatusType.OutOfDateWithPrepend)) {
projectStatus.setValue(project, {
type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: status_1.oldestOutputFileName,
+ outOfDateOutputFileName: status_1.type === UpToDateStatusType.OutOfDateWithPrepend ? status_1.outOfDateOutputFileName : status_1.oldestOutputFileName,
newerProjectName: resolved
});
}
}
else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) {
- status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
+ if (prepend) {
+ projectStatus.setValue(project, {
+ type: UpToDateStatusType.OutOfDateWithPrepend,
+ outOfDateOutputFileName: status_1.oldestOutputFileName,
+ newerProjectName: resolved
+ });
+ }
+ else {
+ status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
+ }
}
addProjToQueue(project);
}
@@ -92966,8 +94093,7 @@ var ts;
}
if (options.verbose)
reportStatus(ts.Diagnostics.Building_project_0, proj);
- var resultFlags = BuildResultFlags.None;
- resultFlags |= BuildResultFlags.DeclarationOutputUnchanged;
+ var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
var configFile = parseConfigFile(proj);
if (!configFile) {
// Failed to read the config file
@@ -92983,8 +94109,7 @@ var ts;
}
// TODO: handle resolve module name to cache result in project reference redirect
projectCompilerOptions = configFile.options;
- var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences);
- projectCompilerOptions = baseCompilerOptions;
+ var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, getOldProgram(proj, configFile), configFile.errors, configFile.projectReferences);
// Don't emit anything in the presence of syntactic errors or options diagnostics
var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
@@ -93045,12 +94170,14 @@ var ts;
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
}
}
@@ -93063,9 +94190,67 @@ var ts;
builderPrograms.setValue(proj, program);
}
}
+ function getOldProgram(proj, parsed) {
+ var value = builderPrograms.getValue(proj);
+ if (value)
+ return value;
+ var buildInfoPath = ts.getOutputPathForBuildInfo(parsed.options);
+ if (!buildInfoPath)
+ return undefined;
+ var content = readFileWithCache(buildInfoPath);
+ if (!content)
+ return undefined;
+ var buildInfo = ts.getBuildInfo(content);
+ if (buildInfo.version !== ts.version)
+ return undefined;
+ return buildInfo.program && ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program);
+ }
+ function updateBundle(proj) {
+ if (options.dry) {
+ reportStatus(ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, proj);
+ return BuildResultFlags.Success;
+ }
+ if (options.verbose)
+ reportStatus(ts.Diagnostics.Updating_output_of_project_0, proj);
+ // Update js, and source map
+ var config = ts.Debug.assertDefined(parseConfigFile(proj));
+ projectCompilerOptions = config.options;
+ var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) { return parseConfigFile(resolveProjectName(ref.path)); });
+ if (ts.isString(outputFiles)) {
+ reportStatus(ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, proj, relName(outputFiles));
+ return buildSingleProject(proj);
+ }
+ // Actual Emit
+ ts.Debug.assert(!!outputFiles.length);
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ var emittedOutputs = createFileMap(toPath);
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
+ emittedOutputs.setValue(name, true);
+ ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
+ });
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
+ reportAndStoreErrors(proj, emitDiagnostics);
+ projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Emit errors" });
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged | BuildResultFlags.EmitErrors;
+ }
+ // Update timestamps for dts
+ var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(config, minimumDate, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
+ oldestOutputFileName: outputFiles[0].name
+ };
+ diagnostics.removeKey(proj);
+ projectStatus.setValue(proj, status);
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged;
+ }
function updateOutputTimestamps(proj) {
if (options.dry) {
- return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath);
+ return reportStatus(ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
}
var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime });
@@ -93192,7 +94377,9 @@ var ts;
// Do nothing
continue;
}
- var buildResult = buildSingleProject(next);
+ var buildResult = status.type === UpToDateStatusType.OutOfDateWithPrepend && !options.force ?
+ updateBundle(next) : // Fake that files have been built by manipulating prepend and existing output
+ buildSingleProject(next); // Actual build
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
@@ -93254,6 +94441,9 @@ var ts;
var inputFile = _a[_i];
outputs.push.apply(outputs, getOutputFileNames(inputFile, project));
}
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath)
+ outputs.push(buildInfoPath);
return outputs;
}
}
@@ -93285,6 +94475,8 @@ var ts;
}
// Don't report anything for "up to date because it was already built" -- too verbose
break;
+ case UpToDateStatusType.OutOfDateWithPrepend:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(configFileName), relName(status.newerProjectName));
case UpToDateStatusType.UpToDateWithUpstreamTypes:
return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName));
case UpToDateStatusType.UpstreamOutOfDate:
@@ -93293,6 +94485,8 @@ var ts;
return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName));
case UpToDateStatusType.Unbuildable:
return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason);
+ case UpToDateStatusType.TsVersionOutputOfDate:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(configFileName), status.version, ts.version);
case UpToDateStatusType.ContainerOnly:
// Don't report status on "solution" projects
case UpToDateStatusType.ComputingUpstream:
@@ -93691,8 +94885,8 @@ var ts;
if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
continue;
}
- var result_7 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
- var packageJson = result_7.config;
+ var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
+ var packageJson = result_1.config;
// npm 3's package.json contains a "_requiredBy" field
// we should include all the top level module names for npm 2, and only module names whose
// "_requiredBy" field starts with "#" or equals "/" for npm 3.
@@ -94099,7 +95293,7 @@ var ts;
case 242 /* TypeAliasDeclaration */:
case 168 /* TypeLiteral */:
return 2 /* Type */;
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
// If it has no name node, it shares the name with the value declaration below it.
return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */;
case 278 /* EnumMember */:
@@ -94124,14 +95318,14 @@ var ts;
case 255 /* ExportDeclaration */:
return 7 /* All */;
// An external module can be a Value
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 4 /* Namespace */ | 1 /* Value */;
}
return 7 /* All */;
}
ts.getMeaningFromDeclaration = getMeaningFromDeclaration;
function getMeaningFromLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return 1 /* Value */;
}
else if (node.parent.kind === 254 /* ExportAssignment */ || node.parent.kind === 259 /* ExternalModuleReference */) {
@@ -94337,7 +95531,7 @@ var ts;
return undefined;
}
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
case 239 /* FunctionDeclaration */:
@@ -94355,7 +95549,7 @@ var ts;
ts.getContainerNode = getContainerNode;
function getNodeKind(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */;
case 244 /* ModuleDeclaration */:
return "module" /* moduleElement */;
@@ -94364,8 +95558,8 @@ var ts;
return "class" /* classElement */;
case 241 /* InterfaceDeclaration */: return "interface" /* interfaceElement */;
case 242 /* TypeAliasDeclaration */:
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
return "type" /* typeElement */;
case 243 /* EnumDeclaration */: return "enum" /* enumElement */;
case 237 /* VariableDeclaration */:
@@ -94782,8 +95976,8 @@ var ts;
isWhiteSpaceOnlyJsxText(child);
if (lookInPreviousChild) {
// actual start of the node is past the position - previous token should be at the end of previous child
- var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
- return candidate_2 && findRightmostToken(candidate_2, sourceFile);
+ var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
+ return candidate_1 && findRightmostToken(candidate_1, sourceFile);
}
else {
// candidate should be in this node
@@ -94791,7 +95985,7 @@ var ts;
}
}
}
- ts.Debug.assert(startNode !== undefined || n.kind === 279 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
+ ts.Debug.assert(startNode !== undefined || n.kind === 284 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
// Here we know that none of child token nodes embrace the position,
// the only known case is when position is at the end of the file.
// Try to find the rightmost token in the file without filtering.
@@ -95638,6 +96832,17 @@ var ts;
return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName));
}
ts.getScriptKind = getScriptKind;
+ function getSymbolTarget(symbol) {
+ var next = symbol;
+ while (isTransientSymbol(next) && next.target) {
+ next = next.target;
+ }
+ return next;
+ }
+ ts.getSymbolTarget = getSymbolTarget;
+ function isTransientSymbol(symbol) {
+ return (symbol.flags & 33554432 /* Transient */) !== 0;
+ }
function getUniqueSymbolId(symbol, checker) {
return ts.getSymbolId(ts.skipAlias(symbol, checker));
}
@@ -95696,14 +96901,14 @@ var ts;
ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext);
if (visited === node) {
// This only happens for leaf nodes - internal nodes always see their children change.
- var clone_8 = ts.getSynthesizedClone(node);
- if (ts.isStringLiteral(clone_8)) {
- clone_8.textSourceNode = node;
+ var clone_1 = ts.getSynthesizedClone(node);
+ if (ts.isStringLiteral(clone_1)) {
+ clone_1.textSourceNode = node;
}
- else if (ts.isNumericLiteral(clone_8)) {
- clone_8.numericLiteralFlags = node.numericLiteralFlags;
+ else if (ts.isNumericLiteral(clone_1)) {
+ clone_1.numericLiteralFlags = node.numericLiteralFlags;
}
- return ts.setTextRange(clone_8, node);
+ return ts.setTextRange(clone_1, node);
}
// PERF: As an optimization, rather than calling getSynthesizedClone, we'll update
// the new node created by visitEachChild with the extra changes getSynthesizedClone
@@ -95789,8 +96994,27 @@ var ts;
return lastPos;
}
ts.getRenameLocation = getRenameLocation;
- function copyComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
- ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) {
+ function copyLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
+ }
+ ts.copyLeadingComments = copyLeadingComments;
+ function copyTrailingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticTrailingComment));
+ }
+ ts.copyTrailingComments = copyTrailingComments;
+ /**
+ * This function copies the trailing comments for the token that comes before `sourceNode`, as leading comments of `targetNode`.
+ * This is useful because sometimes a comment that refers to `sourceNode` will be a leading comment for `sourceNode`, according to the
+ * notion of trivia ownership, and instead will be a trailing comment for the token before `sourceNode`, e.g.:
+ * `function foo(\* not leading comment for a *\ a: string) {}`
+ * The comment refers to `a` but belongs to the `(` token, but we might want to copy it.
+ */
+ function copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
+ }
+ ts.copyTrailingAsLeadingComments = copyTrailingAsLeadingComments;
+ function getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, cb) {
+ return function (pos, end, kind, htnl) {
if (kind === 3 /* MultiLineCommentTrivia */) {
// Remove leading /*
pos += 2;
@@ -95801,10 +97025,9 @@ var ts;
// Remove leading //
pos += 2;
}
- ts.addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
- });
+ cb(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
+ };
}
- ts.copyComments = copyComments;
function indexInTextChange(change, name) {
if (ts.startsWith(change, name))
return 0;
@@ -95885,6 +97108,30 @@ var ts;
return checker.getTypeAtLocation(caseClause.parent.parent.expression);
}
ts.getSwitchedType = getSwitchedType;
+ function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
+ var checker = program.getTypeChecker();
+ var typeIsAccessible = true;
+ var notAccessible = function () { typeIsAccessible = false; };
+ var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
+ trackSymbol: function (symbol, declaration, meaning) {
+ // TODO: GH#18217
+ typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
+ },
+ reportInaccessibleThisError: notAccessible,
+ reportPrivateInBaseOfClassExpression: notAccessible,
+ reportInaccessibleUniqueSymbolError: notAccessible,
+ moduleResolverHost: {
+ readFile: host.readFile,
+ fileExists: host.fileExists,
+ directoryExists: host.directoryExists,
+ getSourceFiles: program.getSourceFiles,
+ getCurrentDirectory: program.getCurrentDirectory,
+ getCommonSourceDirectory: program.getCommonSourceDirectory,
+ }
+ });
+ return typeIsAccessible ? res : undefined;
+ }
+ ts.getTypeNodeIfAccessible = getTypeNodeIfAccessible;
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -96128,7 +97375,7 @@ var ts;
var lastEnd = 0;
for (var i = 0; i < dense.length; i += 3) {
var start = dense[i];
- var length_5 = dense[i + 1];
+ var length_1 = dense[i + 1];
var type = dense[i + 2];
// Make a whitespace entry between the last item and this one.
if (lastEnd >= 0) {
@@ -96137,8 +97384,8 @@ var ts;
entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace });
}
}
- entries.push({ length: length_5, classification: convertClassification(type) });
- lastEnd = start + length_5;
+ entries.push({ length: length_1, classification: convertClassification(type) });
+ lastEnd = start + length_1;
}
var whitespaceLength = text.length - lastEnd;
if (whitespaceLength > 0) {
@@ -96536,18 +97783,18 @@ var ts;
pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param"
pos = tag.tagName.end;
switch (tag.kind) {
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
processJSDocParameterTag(tag);
break;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
processJSDocTemplateTag(tag);
pos = tag.end;
break;
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
- case 300 /* JSDocReturnTag */:
+ case 305 /* JSDocReturnTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
@@ -96851,6 +98098,7 @@ var ts;
case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */;
case ".ts" /* Ts */: return ".ts" /* tsModifier */;
case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */;
+ case ".tsbuildinfo" /* TsBuildInfo */: return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported.");
case undefined: return "" /* none */;
default:
return ts.Debug.assertNever(extension);
@@ -97081,8 +98329,8 @@ var ts;
* both foo.ts and foo.tsx become foo
*/
var foundFiles = ts.createMap(); // maps file to its extension
- for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
- var filePath = files_3[_i];
+ for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
+ var filePath = files_1[_i];
filePath = ts.normalizePath(filePath);
if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) {
continue;
@@ -97127,7 +98375,7 @@ var ts;
continue;
var patterns = paths[path];
if (patterns) {
- var _loop_11 = function (name, kind, extension) {
+ var _loop_1 = function (name, kind, extension) {
// Path mappings may provide a duplicate way to get to something we've already added, so don't add again.
if (!result.some(function (entry) { return entry.name === name; })) {
result.push(nameAndKind(name, kind, extension));
@@ -97135,7 +98383,7 @@ var ts;
};
for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) {
var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension;
- _loop_11(name, kind, extension);
+ _loop_1(name, kind, extension);
}
}
}
@@ -97170,7 +98418,7 @@ var ts;
// (But do if we didn't find anything, e.g. 'package.json' missing.)
var foundGlobal = false;
if (fragmentDirectory === undefined) {
- var _loop_12 = function (moduleName) {
+ var _loop_2 = function (moduleName) {
if (!result.some(function (entry) { return entry.name === moduleName; })) {
foundGlobal = true;
result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined));
@@ -97178,7 +98426,7 @@ var ts;
};
for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) {
var moduleName = _c[_b];
- _loop_12(moduleName);
+ _loop_2(moduleName);
}
}
if (!foundGlobal) {
@@ -97292,8 +98540,8 @@ var ts;
// Check for typings specified in compiler options
var seen = ts.createMap();
var typeRoots = tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray;
- for (var _i = 0, typeRoots_2 = typeRoots; _i < typeRoots_2.length; _i++) {
- var root = typeRoots_2[_i];
+ for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
+ var root = typeRoots_1[_i];
getCompletionEntriesFromDirectories(root);
}
// Also get all @types typings installed in visible node_modules directories
@@ -97655,8 +98903,8 @@ var ts;
// Based on the order we add things we will always see locals first, then globals, then module exports.
// So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name.
var uniques = ts.createMap();
- for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) {
- var symbol = symbols_3[_i];
+ for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
+ var symbol = symbols_1[_i];
var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined;
var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences);
if (!entry) {
@@ -97875,7 +99123,7 @@ var ts;
return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker));
}
function isModuleSymbol(symbol) {
- return symbol.declarations.some(function (d) { return d.kind === 279 /* SourceFile */; });
+ return symbol.declarations.some(function (d) { return d.kind === 284 /* SourceFile */; });
}
function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) {
var typeChecker = program.getTypeChecker();
@@ -97926,11 +99174,11 @@ var ts;
if (tag.tagName.pos <= position && position <= tag.tagName.end) {
return { kind: 1 /* JsDocTagName */ };
}
- if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
currentToken = ts.getTokenAtPosition(sourceFile, position);
if (!currentToken ||
(!ts.isDeclarationName(currentToken) &&
- (currentToken.parent.kind !== 305 /* JSDocPropertyTag */ ||
+ (currentToken.parent.kind !== 310 /* JSDocPropertyTag */ ||
currentToken.parent.name !== currentToken))) {
// Use as type location if inside tag's type expression
insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
@@ -97956,9 +99204,9 @@ var ts;
// Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS|
// Skip this partial identifier and adjust the contextToken to the token that precedes it.
if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) {
- var start_3 = ts.timestamp();
+ var start_1 = ts.timestamp();
contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217
- log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_3));
+ log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1));
}
// Find the node where completion is requested on.
// Also determine whether we are trying to complete with members of that node
@@ -98101,11 +99349,11 @@ var ts;
return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer };
function isTagWithTypeExpression(tag) {
switch (tag.kind) {
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 304 /* JSDocTypedefTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 309 /* JSDocTypedefTag */:
return true;
default:
return false;
@@ -98145,7 +99393,7 @@ var ts;
}
}
// If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods).
- if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 279 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) {
+ if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 284 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) {
addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node));
}
return;
@@ -98278,7 +99526,7 @@ var ts;
var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */;
symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined");
// Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
- if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 279 /* SourceFile */) {
+ if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 284 /* SourceFile */) {
var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false);
if (thisType) {
for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) {
@@ -98311,7 +99559,7 @@ var ts;
}
function isSnippetScope(scopeNode) {
switch (scopeNode.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 206 /* TemplateExpression */:
case 270 /* JsxExpression */:
case 218 /* Block */:
@@ -99143,7 +100391,7 @@ var ts;
function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) {
// class c { method() { } | method2() { } }
switch (location.kind) {
- case 306 /* SyntaxList */:
+ case 311 /* SyntaxList */:
return ts.tryCast(location.parent, ts.isObjectTypeDeclaration);
case 1 /* EndOfFileToken */:
var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration);
@@ -99328,7 +100576,7 @@ var ts;
var child = throwStatement;
while (child.parent) {
var parent = child.parent;
- if (ts.isFunctionBlock(parent) || parent.kind === 279 /* SourceFile */) {
+ if (ts.isFunctionBlock(parent) || parent.kind === 284 /* SourceFile */) {
return parent;
}
// A throw-statement is only owned by a try-statement if the try-statement has
@@ -99386,7 +100634,7 @@ var ts;
var container = declaration.parent;
switch (container.kind) {
case 245 /* ModuleBlock */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 218 /* Block */:
case 271 /* CaseClause */:
case 272 /* DefaultClause */:
@@ -99884,7 +101132,7 @@ var ts;
}
else if (!isAvailableThroughGlobal) {
var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration);
- ts.Debug.assert(sourceFileLike.kind === 279 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */);
+ ts.Debug.assert(sourceFileLike.kind === 284 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */);
if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) {
addIndirectUsers(sourceFileLike);
}
@@ -100050,10 +101298,10 @@ var ts;
function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
var refs = [];
var checker = program.getTypeChecker();
- for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
- var referencingFile = sourceFiles_3[_i];
+ for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
+ var referencingFile = sourceFiles_1[_i];
var searchSourceFile = searchModuleSymbol.valueDeclaration;
- if (searchSourceFile.kind === 279 /* SourceFile */) {
+ if (searchSourceFile.kind === 284 /* SourceFile */) {
for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
var ref = _b[_a];
if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) {
@@ -100081,8 +101329,8 @@ var ts;
/** Returns a map from a module symbol Id to all import statements that directly reference the module. */
function getDirectImportsMap(sourceFiles, checker, cancellationToken) {
var map = ts.createMap();
- for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
- var sourceFile = sourceFiles_4[_i];
+ for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
+ var sourceFile = sourceFiles_2[_i];
if (cancellationToken)
cancellationToken.throwIfCancellationRequested();
forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
@@ -100101,7 +101349,7 @@ var ts;
}
/** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */
function forEachPossibleImportOrExportStatement(sourceFileLike, action) {
- return ts.forEach(sourceFileLike.kind === 279 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
+ return ts.forEach(sourceFileLike.kind === 284 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action));
});
}
@@ -100325,7 +101573,7 @@ var ts;
return node.getSourceFile();
}
var parent = node.parent;
- if (parent.kind === 279 /* SourceFile */) {
+ if (parent.kind === 284 /* SourceFile */) {
return parent;
}
ts.Debug.assert(parent.kind === 245 /* ModuleBlock */);
@@ -100387,16 +101635,16 @@ var ts;
}
FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition;
function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return undefined;
}
var checker = program.getTypeChecker();
// If invoked directly on a shorthand property assignment, then return
// the declaration of the symbol being assigned (not the symbol being assigned to).
if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) {
- var result_8 = [];
- FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_8.push(nodeEntry(node)); });
- return result_8;
+ var result_1 = [];
+ FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_1.push(nodeEntry(node)); });
+ return result_1;
}
else if (node.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
// References to and accesses on the super keyword only have one possible implementation, so no
@@ -100428,27 +101676,27 @@ var ts;
case 0 /* Symbol */: {
var symbol = def.symbol;
var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
- var name_4 = displayParts_1.map(function (p) { return p.text; }).join("");
- return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 };
+ var name_1 = displayParts_1.map(function (p) { return p.text; }).join("");
+ return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_1, kind: kind_1, displayParts: displayParts_1 };
}
case 1 /* Label */: {
- var node_3 = def.node;
- return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] };
+ var node_1 = def.node;
+ return { node: node_1, name: node_1.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_1.text, ts.SymbolDisplayPartKind.text)] };
}
case 2 /* Keyword */: {
- var node_4 = def.node;
- var name_5 = ts.tokenToString(node_4.kind);
- return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] };
+ var node_2 = def.node;
+ var name_2 = ts.tokenToString(node_2.kind);
+ return { node: node_2, name: name_2, kind: "keyword" /* keyword */, displayParts: [{ text: name_2, kind: "keyword" /* keyword */ }] };
}
case 3 /* This */: {
- var node_5 = def.node;
- var symbol = checker.getSymbolAtLocation(node_5);
- var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")];
- return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
+ var node_3 = def.node;
+ var symbol = checker.getSymbolAtLocation(node_3);
+ var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_3.getSourceFile(), ts.getContainerNode(node_3), node_3).displayParts || [ts.textPart("this")];
+ return { node: node_3, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
}
case 4 /* String */: {
- var node_6 = def.node;
- return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] };
+ var node_4 = def.node;
+ return { node: node_4, name: node_4.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_4), ts.SymbolDisplayPartKind.stringLiteral)] };
}
default:
return ts.Debug.assertNever(def);
@@ -100607,8 +101855,8 @@ var ts;
case 248 /* ImportEqualsDeclaration */:
case 253 /* ImportSpecifier */:
case 241 /* InterfaceDeclaration */:
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
case 267 /* JsxAttribute */:
case 244 /* ModuleDeclaration */:
case 247 /* NamespaceExportDeclaration */:
@@ -100633,8 +101881,8 @@ var ts;
return !!decl.initializer || ts.isCatchClause(decl.parent);
case 155 /* MethodSignature */:
case 153 /* PropertySignature */:
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
return false;
default:
return ts.Debug.failBadSyntaxKind(decl);
@@ -100726,7 +101974,7 @@ var ts;
result = references;
continue;
}
- var _loop_13 = function (entry) {
+ var _loop_3 = function (entry) {
if (!entry.definition || entry.definition.type !== 0 /* Symbol */) {
result.push(entry);
return "continue";
@@ -100758,7 +102006,7 @@ var ts;
};
for (var _b = 0, references_1 = references; _b < references_1.length; _b++) {
var entry = references_1[_b];
- _loop_13(entry);
+ _loop_3(entry);
}
}
return result;
@@ -100794,7 +102042,7 @@ var ts;
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
switch (decl.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.)
break;
case 244 /* ModuleDeclaration */:
@@ -101018,8 +102266,8 @@ var ts;
var sourceId = ts.getNodeId(sourceFile);
var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = ts.createMap());
var anyNewSymbols = false;
- for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) {
- var sym = symbols_4[_i];
+ for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
+ var sym = symbols_2[_i];
anyNewSymbols = ts.addToSeen(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols;
}
return anyNewSymbols;
@@ -101158,14 +102406,14 @@ var ts;
return undefined;
}
var scope;
- for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) {
- var declaration = declarations_11[_i];
+ for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
+ var declaration = declarations_1[_i];
var container = ts.getContainerNode(declaration);
if (scope && scope !== container) {
// Different declarations have different containers, bail out
return undefined;
}
- if (!container || container.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
+ if (!container || container.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
// This is a global variable and not an external module, any declaration defined
// within this scope is visible outside the file
return undefined;
@@ -101210,8 +102458,8 @@ var ts;
if (!signature.name || !ts.isIdentifier(signature.name))
return;
var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name));
- for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
- var sourceFile = sourceFiles_5[_i];
+ for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
+ var sourceFile = sourceFiles_3[_i];
for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) {
var name = _b[_a];
if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText)
@@ -101724,7 +102972,7 @@ var ts;
staticFlag &= ts.getModifierFlags(searchSpaceNode);
searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) {
return undefined;
}
@@ -101737,7 +102985,7 @@ var ts;
default:
return undefined;
}
- var references = ts.flatMap(searchSpaceNode.kind === 279 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
+ var references = ts.flatMap(searchSpaceNode.kind === 284 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) {
if (!ts.isThis(node)) {
@@ -101756,8 +103004,8 @@ var ts;
// Make sure the container belongs to the same class
// and has the appropriate static modifier from the original container.
return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag;
- case 279 /* SourceFile */:
- return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
+ case 284 /* SourceFile */:
+ return container.kind === 284 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
}
});
}).map(function (n) { return FindAllReferences.nodeEntry(n); });
@@ -101913,8 +103161,8 @@ var ts;
// To achieve that we will keep iterating until the result stabilizes.
// Remember the last meaning
lastIterationMeaning = meaning;
- for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) {
- var declaration = declarations_12[_i];
+ for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
+ var declaration = declarations_2[_i];
var declarationMeaning = ts.getMeaningFromDeclaration(declaration);
if (declarationMeaning & meaning) {
meaning |= declarationMeaning;
@@ -102063,8 +103311,8 @@ var ts;
// Type annotation needed due to #7294
var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer];
var foundExactMatch = false;
- for (var _i = 0, elements_5 = elements; _i < elements_5.length; _i++) {
- var element = elements_5[_i];
+ for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
+ var element = elements_1[_i];
foundExactMatch = tryUpdateString(element) || foundExactMatch;
}
return foundExactMatch;
@@ -102086,7 +103334,7 @@ var ts;
}
function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) {
var allFiles = program.getSourceFiles();
- var _loop_14 = function (sourceFile) {
+ var _loop_4 = function (sourceFile) {
var newFromOld = oldToNew(sourceFile.path);
var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path;
var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath);
@@ -102118,7 +103366,7 @@ var ts;
};
for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) {
var sourceFile = allFiles_1[_i];
- _loop_14(sourceFile);
+ _loop_4(sourceFile);
}
}
function combineNormal(pathA, pathB) {
@@ -102148,9 +103396,9 @@ var ts;
return undefined;
// First try resolved module
if (resolved.resolvedModule) {
- var result_9 = tryChange(resolved.resolvedModule.resolvedFileName);
- if (result_9)
- return result_9;
+ var result_2 = tryChange(resolved.resolvedModule.resolvedFileName);
+ if (result_2)
+ return result_2;
}
// Then failed lookups except package.json since we dont want to touch them (only included ts/js files)
var result = ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson);
@@ -102260,10 +103508,10 @@ var ts;
// bar(({pr/*goto*/op1})=>{});
if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) &&
(node === (parent.propertyName || parent.name))) {
- var name_6 = ts.getNameFromPropertyName(node);
+ var name_3 = ts.getNameFromPropertyName(node);
var type = typeChecker.getTypeAtLocation(parent.parent);
- return name_6 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) {
- var prop = t.getProperty(name_6);
+ return name_3 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) {
+ var prop = t.getProperty(name_3);
return prop && getDefinitionFromSymbol(typeChecker, prop, node);
});
}
@@ -102611,11 +103859,11 @@ var ts;
JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
function getCommentHavingNodes(declaration) {
switch (declaration.kind) {
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return [declaration];
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
return [declaration, declaration.parent];
default:
return ts.getJSDocCommentsAndTags(declaration);
@@ -102636,16 +103884,16 @@ var ts;
function getCommentText(tag) {
var comment = tag.comment;
switch (tag.kind) {
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return withNode(tag.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return withList(tag.typeParameters);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return withNode(tag.typeExpression);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
var name = tag.name;
return name ? withNode(name) : comment;
default:
@@ -102856,7 +104104,7 @@ var ts;
: undefined;
return { commentOwner: commentOwner, parameters: parameters_1 };
}
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return "quit";
case 244 /* ModuleDeclaration */:
// If in walking up the tree, we hit a a nested namespace declaration,
@@ -102908,7 +104156,7 @@ var ts;
if (!patternMatcher)
return ts.emptyArray;
var rawItems = [];
- var _loop_15 = function (sourceFile) {
+ var _loop_5 = function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
if (excludeDtsFiles && sourceFile.isDeclarationFile) {
return "continue";
@@ -102918,9 +104166,9 @@ var ts;
});
};
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
- for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
- var sourceFile = sourceFiles_6[_i];
- _loop_15(sourceFile);
+ for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
+ var sourceFile = sourceFiles_4[_i];
+ _loop_5(sourceFile);
}
rawItems.sort(compareNavigateToItems);
return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem);
@@ -102933,8 +104181,8 @@ var ts;
if (!match) {
return; // continue to next named declarations
}
- for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) {
- var declaration = declarations_13[_i];
+ for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
+ var declaration = declarations_3[_i];
if (!shouldKeepItem(declaration, checker))
continue;
if (patternMatcher.patternContainsDots) {
@@ -103416,7 +104664,7 @@ var ts;
}
}
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
var sourceFile = node;
return ts.isExternalModule(sourceFile)
? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\""
@@ -103468,10 +104716,10 @@ var ts;
case 243 /* EnumDeclaration */:
case 241 /* InterfaceDeclaration */:
case 244 /* ModuleDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 242 /* TypeAliasDeclaration */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return true;
case 157 /* Constructor */:
case 156 /* MethodDeclaration */:
@@ -103492,7 +104740,7 @@ var ts;
}
switch (navigationBarNodeKind(item.parent)) {
case 245 /* ModuleBlock */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
return true;
@@ -103577,7 +104825,7 @@ var ts;
return !member.name || member.name.kind === 149 /* ComputedPropertyName */;
}
function getNodeSpan(node) {
- return node.kind === 279 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
+ return node.kind === 284 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
}
function getModifiers(node) {
if (node.parent && node.parent.kind === 237 /* VariableDeclaration */) {
@@ -103698,8 +104946,8 @@ var ts;
else {
// Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: false,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include,
suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
});
}
@@ -104037,8 +105285,8 @@ var ts;
var lastSingleLineCommentEnd = -1;
var singleLineCommentCount = 0;
var sourceText = sourceFile.getFullText();
- for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) {
- var _a = comments_2[_i], kind = _a.kind, pos = _a.pos, end = _a.end;
+ for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
+ var _a = comments_1[_i], kind = _a.kind, pos = _a.pos, end = _a.end;
cancellationToken.throwIfCancellationRequested();
switch (kind) {
case 2 /* SingleLineCommentTrivia */:
@@ -104448,15 +105696,15 @@ var ts;
// Assumes 'value' is already lowercase.
function indexOfIgnoringCase(str, value) {
var n = str.length - value.length;
- var _loop_16 = function (start) {
+ var _loop_6 = function (start) {
if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) {
return { value: start };
}
};
for (var start = 0; start <= n; start++) {
- var state_4 = _loop_16(start);
- if (typeof state_4 === "object")
- return state_4.value;
+ var state_1 = _loop_6(start);
+ if (typeof state_1 === "object")
+ return state_1.value;
}
return -1;
}
@@ -105467,7 +106715,7 @@ var ts;
return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
}
function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) {
- var _loop_17 = function (n) {
+ var _loop_7 = function (n) {
// If the node is not a subspan of its parent, this is a big problem.
// There have been crashes that might be caused by this violation.
ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); });
@@ -105477,9 +106725,9 @@ var ts;
}
};
for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) {
- var state_5 = _loop_17(n);
- if (typeof state_5 === "object")
- return state_5.value;
+ var state_2 = _loop_7(n);
+ if (typeof state_2 === "object")
+ return state_2.value;
}
return undefined;
}
@@ -105757,8 +107005,8 @@ var ts;
var name = importNameForConvertToDefaultImport(importNode);
if (!name)
continue;
- var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
- var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName);
+ var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
+ var resolvedFile = module && program.getSourceFile(module.resolvedFileName);
if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
}
@@ -105773,8 +107021,8 @@ var ts;
case 196 /* FunctionExpression */:
var decl = ts.getDeclarationOfExpando(node);
if (decl) {
- var symbol_2 = decl.symbol;
- if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) {
+ var symbol_1 = decl.symbol;
+ if (symbol_1 && (symbol_1.exports && symbol_1.exports.size || symbol_1.members && symbol_1.members.size)) {
diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration));
break;
}
@@ -106395,7 +107643,7 @@ var ts;
// For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo`
// there documentation comments might be attached to the right hand side symbol of their declarations.
// The pattern of such special property access is that the parent symbol is the symbol of the file.
- if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 279 /* SourceFile */; })) {
+ if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 284 /* SourceFile */; })) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
if (!declaration.parent || declaration.parent.kind !== 204 /* BinaryExpression */) {
@@ -106520,7 +107768,7 @@ var ts;
// If the parent is not sourceFile or module block it is local variable
for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) {
// Reached source file or module block
- if (parent.kind === 279 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) {
+ if (parent.kind === 284 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) {
return false;
}
}
@@ -106634,7 +107882,7 @@ var ts;
return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; });
});
options = ts.cloneCompilerOptions(options);
- var _loop_18 = function (opt) {
+ var _loop_8 = function (opt) {
if (!ts.hasProperty(options, opt.name)) {
return "continue";
}
@@ -106653,7 +107901,7 @@ var ts;
};
for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) {
var opt = commandLineOptionsStringToEnum_1[_i];
- _loop_18(opt);
+ _loop_8(opt);
}
return options;
}
@@ -107845,7 +109093,7 @@ var ts;
case 244 /* ModuleDeclaration */:
var body = parent.body;
return !!body && body.kind === 245 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 218 /* Block */:
case 245 /* ModuleBlock */:
return ts.rangeContainsRange(parent.statements, node);
@@ -108964,7 +110212,7 @@ var ts;
// - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually
// - parent and child are not on the same line
var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) &&
- (parent.kind === 279 /* SourceFile */ || !parentAndChildShareLine);
+ (parent.kind === 284 /* SourceFile */ || !parentAndChildShareLine);
if (!useActualIndentation) {
return -1 /* Unknown */;
}
@@ -109052,7 +110300,7 @@ var ts;
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return getList(node.typeParameters);
case 192 /* NewExpression */:
case 191 /* CallExpression */:
@@ -109301,11 +110549,23 @@ var ts;
ts.Debug.assert(typeof end === "number");
n.__end = end;
}
- var Position;
- (function (Position) {
- Position[Position["FullStart"] = 0] = "FullStart";
- Position[Position["Start"] = 1] = "Start";
- })(Position = textChanges_3.Position || (textChanges_3.Position = {}));
+ var LeadingTriviaOption;
+ (function (LeadingTriviaOption) {
+ /** Exclude all leading trivia (use getStart()) */
+ LeadingTriviaOption[LeadingTriviaOption["Exclude"] = 0] = "Exclude";
+ /** Include leading trivia and,
+ * if there are no line breaks between the node and the previous token,
+ * include all trivia between the node and the previous token
+ */
+ LeadingTriviaOption[LeadingTriviaOption["IncludeAll"] = 1] = "IncludeAll";
+ })(LeadingTriviaOption = textChanges_3.LeadingTriviaOption || (textChanges_3.LeadingTriviaOption = {}));
+ var TrailingTriviaOption;
+ (function (TrailingTriviaOption) {
+ /** Exclude all trailing trivia (use getEnd()) */
+ TrailingTriviaOption[TrailingTriviaOption["Exclude"] = 0] = "Exclude";
+ /** Include trailing trivia */
+ TrailingTriviaOption[TrailingTriviaOption["Include"] = 1] = "Include";
+ })(TrailingTriviaOption = textChanges_3.TrailingTriviaOption || (textChanges_3.TrailingTriviaOption = {}));
function skipWhitespacesAndLineBreaks(text, start) {
return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
@@ -109321,9 +110581,9 @@ var ts;
}
return false;
}
- textChanges_3.useNonAdjustedPositions = {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: true,
+ var useNonAdjustedPositions = {
+ leadingTriviaOption: LeadingTriviaOption.Exclude,
+ trailingTriviaOption: TrailingTriviaOption.Exclude,
};
var ChangeKind;
(function (ChangeKind) {
@@ -109333,10 +110593,11 @@ var ts;
ChangeKind[ChangeKind["Text"] = 3] = "Text";
})(ChangeKind || (ChangeKind = {}));
function getAdjustedRange(sourceFile, startNode, endNode, options) {
- return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) };
+ return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) };
}
- function getAdjustedStartPosition(sourceFile, node, options, position) {
- if (options.useNonAdjustedStartPosition) {
+ function getAdjustedStartPosition(sourceFile, node, options) {
+ var leadingTriviaOption = options.leadingTriviaOption;
+ if (leadingTriviaOption === LeadingTriviaOption.Exclude) {
return node.getStart(sourceFile);
}
var fullStart = node.getFullStart();
@@ -109354,7 +110615,7 @@ var ts;
// fullstart
// when b is replaced - we usually want to keep the leading trvia
// when b is deleted - we delete it
- return position === Position.Start ? start : fullStart;
+ return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start;
}
// get start position of the line following the line that contains fullstart position
// (but only if the fullstart isn't the very beginning of the file)
@@ -109366,11 +110627,12 @@ var ts;
}
function getAdjustedEndPosition(sourceFile, node, options) {
var end = node.end;
- if (options.useNonAdjustedEndPosition || ts.isExpression(node)) {
+ var trailingTriviaOption = options.trailingTriviaOption;
+ if (trailingTriviaOption === TrailingTriviaOption.Exclude || (ts.isExpression(node) && trailingTriviaOption !== TrailingTriviaOption.Include)) {
return end;
}
var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
- return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))
+ return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)))
? newEnd
: end;
}
@@ -109415,15 +110677,15 @@ var ts;
this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) });
};
ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
- var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
+ var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
@@ -109431,11 +110693,11 @@ var ts;
this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode });
};
ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
};
ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options);
};
ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) {
@@ -109443,14 +110705,14 @@ var ts;
this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes });
};
ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
};
ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) {
- this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text);
+ this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text);
};
ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
};
ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
@@ -109478,7 +110740,7 @@ var ts;
};
ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) {
if (blankLineBetween === void 0) { blankLineBetween = false; }
- this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
+ this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
};
ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) {
var pos = before.getStart(sourceFile);
@@ -109585,7 +110847,7 @@ var ts;
this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true));
};
ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) {
- var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start);
+ var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {});
this.insertNodeAt(sourceFile, pos, newNode, {
prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter,
suffix: this.newLineCharacter
@@ -109825,7 +111087,7 @@ var ts;
ChangeTracker.prototype.finishDeleteDeclarations = function () {
var _this = this;
var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
- var _loop_19 = function (sourceFile, node) {
+ var _loop_9 = function (sourceFile, node) {
if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) {
if (ts.isArray(node)) {
this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node));
@@ -109838,7 +111100,7 @@ var ts;
var this_1 = this;
for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) {
var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node;
- _loop_19(sourceFile, node);
+ _loop_9(sourceFile, node);
}
deletedNodesInLists.forEach(function (node) {
var sourceFile = node.getSourceFile();
@@ -109875,7 +111137,7 @@ var ts;
textChanges_3.ChangeTracker = ChangeTracker;
// find first non-whitespace position in the leading trivia of the node
function startPositionToDeleteNodeInList(sourceFile, node) {
- return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
+ return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
function getClassOrObjectBraceEnds(cls, sourceFile) {
return [ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile).end];
@@ -109895,14 +111157,14 @@ var ts;
// order changes by start position
// If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa.
var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); });
- var _loop_20 = function (i) {
+ var _loop_10 = function (i) {
ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () {
return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range);
});
};
// verify that change intervals do not overlap, except possibly at end points.
for (var i = 0; i < normalized.length - 1; i++) {
- _loop_20(i);
+ _loop_10(i);
}
var textChanges = normalized.map(function (c) {
return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
@@ -110212,7 +111474,7 @@ var ts;
case 249 /* ImportDeclaration */:
deleteNode(changes, sourceFile, node,
// For first import, leave header comment in place
- node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined);
+ node === sourceFile.imports[0].parent ? { leadingTriviaOption: LeadingTriviaOption.Exclude } : undefined);
break;
case 186 /* BindingElement */:
var pattern = node.parent;
@@ -110250,7 +111512,7 @@ var ts;
deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
}
else {
- deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined);
+ deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { trailingTriviaOption: TrailingTriviaOption.Exclude } : undefined);
}
}
}
@@ -110321,8 +111583,8 @@ var ts;
/** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */
// Exported for tests only! (TODO: improve tests to not need this)
function deleteNode(changes, sourceFile, node, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, node, options);
var endPosition = getAdjustedEndPosition(sourceFile, node, options);
changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
}
@@ -110615,18 +111877,18 @@ var ts;
}
function transformJSDocType(node) {
switch (node.kind) {
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return transformJSDocOptionalType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return transformJSDocType(node.type);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return transformJSDocNullableType(node);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return transformJSDocVariadicType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return transformJSDocFunctionType(node);
case 164 /* TypeReference */:
return transformJSDocTypeReference(node);
@@ -110650,7 +111912,7 @@ var ts;
}
function transformJSDocParameter(node) {
var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 290 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
+ var isRest = node.type.kind === 295 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
var name = node.name || (isRest ? "rest" : "arg" + index);
var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken;
return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
@@ -110806,7 +112068,7 @@ var ts;
}
if (ts.isPropertyAccessExpression(parent)) {
var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken);
- var typeNode = getTypeNodeIfAccessible(type, parent, program, host);
+ var typeNode = ts.getTypeNodeIfAccessible(type, parent, program, host);
if (typeNode) {
// Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags
var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ "");
@@ -110910,7 +112172,7 @@ var ts;
}
}
function annotate(changes, sourceFile, declaration, type, program, host) {
- var typeNode = getTypeNodeIfAccessible(type, declaration, program, host);
+ var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host);
if (typeNode) {
if (ts.isInJSFile(sourceFile) && declaration.kind !== 153 /* PropertySignature */) {
var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration;
@@ -110936,7 +112198,7 @@ var ts;
// only infer parameters that have (1) no type and (2) an accessible inferred type
if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name))
return;
- var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host);
+ var typeNode = inference.type && ts.getTypeNodeIfAccessible(inference.type, param, program, host);
var name = ts.getSynthesizedClone(param.name);
ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), "");
@@ -110969,40 +112231,17 @@ var ts;
return undefined;
}
switch (oldTag.kind) {
- case 299 /* JSDocParameterTag */: {
+ case 304 /* JSDocParameterTag */: {
var oldParam = oldTag;
var newParam = newTag;
return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText
? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment)
: undefined;
}
- case 300 /* JSDocReturnTag */:
+ case 305 /* JSDocReturnTag */:
return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment);
}
}
- function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
- var checker = program.getTypeChecker();
- var typeIsAccessible = true;
- var notAccessible = function () { typeIsAccessible = false; };
- var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
- trackSymbol: function (symbol, declaration, meaning) {
- // TODO: GH#18217
- typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
- },
- reportInaccessibleThisError: notAccessible,
- reportPrivateInBaseOfClassExpression: notAccessible,
- reportInaccessibleUniqueSymbolError: notAccessible,
- moduleResolverHost: {
- readFile: host.readFile,
- fileExists: host.fileExists,
- directoryExists: host.directoryExists,
- getSourceFiles: program.getSourceFiles,
- getCurrentDirectory: program.getCurrentDirectory,
- getCommonSourceDirectory: program.getCommonSourceDirectory,
- }
- });
- return typeIsAccessible ? res : undefined;
- }
function getReferences(token, program, cancellationToken) {
// Position shouldn't matter since token is not a SourceFile.
return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) {
@@ -111301,8 +112540,8 @@ var ts;
}
function removeLowPriorityInferences(inferences, priorities) {
var toRemove = [];
- for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
- var i = inferences_2[_i];
+ for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
+ var i = inferences_1[_i];
for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) {
var _b = priorities_1[_a], high = _b.high, low = _b.low;
if (high(i)) {
@@ -111394,8 +112633,8 @@ var ts;
types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); }));
if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) {
var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217
- var types_20 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); });
- types_20.push(checker.createPromiseType(types_20.length ? checker.getUnionType(types_20, 2 /* Subtype */) : checker.getAnyType()));
+ var types_1 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); });
+ types_1.push(checker.createPromiseType(types_1.length ? checker.getUnionType(types_1, 2 /* Subtype */) : checker.getAnyType()));
}
else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) {
types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)));
@@ -111404,7 +112643,7 @@ var ts;
types.push(checker.createArrayType(recur(usageContext.numberIndexContext)));
}
else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) {
- var members_6 = ts.createUnderscoreEscapedMap();
+ var members_1 = ts.createUnderscoreEscapedMap();
var callSignatures = [];
var constructSignatures = [];
var stringIndexInfo = void 0;
@@ -111412,7 +112651,7 @@ var ts;
usageContext.properties.forEach(function (context, name) {
var symbol = checker.createSymbol(4 /* Property */, name);
symbol.type = recur(context);
- members_6.set(name, symbol);
+ members_1.set(name, symbol);
});
}
if (usageContext.callContexts) {
@@ -111430,7 +112669,7 @@ var ts;
if (usageContext.stringIndexContext) {
stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false);
}
- types.push(checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217
+ types.push(checker.createAnonymousType(/*symbol*/ undefined, members_1, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217
}
return types;
function recur(innerContext) {
@@ -111515,7 +112754,7 @@ var ts;
precedingNode = ctorDeclaration.parent.parent;
newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
if (ctorDeclaration.parent.declarations.length === 1) {
- ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
+ ts.copyLeadingComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
changes.delete(sourceFile, precedingNode);
}
else {
@@ -111526,7 +112765,7 @@ var ts;
if (!newClassDeclaration) {
return undefined;
}
- ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile);
+ ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile);
// Because the preceding node could be touched, we need to insert nodes before delete nodes.
changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
function createClassElementsFromSymbol(symbol) {
@@ -111579,7 +112818,7 @@ var ts;
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 121 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
- ts.copyComments(assignmentBinaryExpression, method, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
case 197 /* ArrowFunction */: {
@@ -111597,7 +112836,7 @@ var ts;
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 121 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
- ts.copyComments(assignmentBinaryExpression, method, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
default: {
@@ -111607,7 +112846,7 @@ var ts;
}
var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
/*type*/ undefined, assignmentBinaryExpression.right);
- ts.copyComments(assignmentBinaryExpression.parent, prop, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile);
return prop;
}
}
@@ -111699,7 +112938,7 @@ var ts;
var newNodes = transformExpression(node, transformer, node);
changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes);
}
- var _loop_21 = function (statement) {
+ var _loop_11 = function (statement) {
ts.forEachChild(statement, function visit(node) {
if (ts.isCallExpression(node)) {
startTransformation(node, statement);
@@ -111711,7 +112950,7 @@ var ts;
};
for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) {
var statement = returnStatements_1[_i];
- _loop_21(statement);
+ _loop_11(statement);
}
}
function getReturnStatementsWithPromiseHandlers(body) {
@@ -112036,8 +113275,8 @@ var ts;
if (innerCbBody.length > 0) {
return innerCbBody;
}
- var type_6 = transformer.checker.getTypeAtLocation(func);
- var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType();
+ var type_1 = transformer.checker.getTypeAtLocation(func);
+ var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType();
var rightHandSide = ts.getSynthesizedDeepClone(funcBody);
var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide;
if (!shouldReturn) {
@@ -113363,7 +114602,7 @@ var ts;
});
typeDeclToMembers.forEach(function (infos, classDeclaration) {
var supers = getAllSupers(classDeclaration, checker);
- var _loop_22 = function (info) {
+ var _loop_12 = function (info) {
// If some superclass added this property, don't add it again.
if (supers.some(function (superClassOrInterface) {
var superInfos = typeDeclToMembers.get(superClassOrInterface);
@@ -113390,7 +114629,7 @@ var ts;
};
for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
var info = infos_1[_i];
- _loop_22(info);
+ _loop_12(info);
}
});
}));
@@ -114356,7 +115595,7 @@ var ts;
var typeNode = info.typeNode, type = info.type;
var original = typeNode.getText(sourceFile);
var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)];
- if (typeNode.kind === 286 /* JSDocNullableType */) {
+ if (typeNode.kind === 291 /* JSDocNullableType */) {
// for nullable types, suggest the flow-compatible `T | null | undefined`
// in addition to the jsdoc/closure-compatible `T | null`
actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
@@ -114376,7 +115615,7 @@ var ts;
if (!info)
return;
var typeNode = info.typeNode, type = info.type;
- var fixedType = typeNode.kind === 286 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
+ var fixedType = typeNode.kind === 291 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
doChange(changes, sourceFile, typeNode, fixedType, checker);
});
}
@@ -114625,8 +115864,8 @@ var ts;
outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences));
break;
}
- for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) {
- var signature = signatures_7[_i];
+ for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
+ var signature = signatures_1[_i];
// Need to ensure nodes are fresh each time so they can have different positions.
outputMethod(signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false));
}
@@ -114709,8 +115948,8 @@ var ts;
var maxArgsSignature = signatures[0];
var minArgumentCount = signatures[0].minArgumentCount;
var someSigHasRestParameter = false;
- for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
- var sig = signatures_8[_i];
+ for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
+ var sig = signatures_2[_i];
minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount);
if (sig.hasRestParameter) {
someSigHasRestParameter = true;
@@ -114869,8 +116108,8 @@ var ts;
ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport));
}
if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) {
- var sourceFile_3 = context.sourceFile;
- var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_3, expr, ts.createPropertyAccess(expr, "default"), {}); });
+ var sourceFile_1 = context.sourceFile;
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_1, expr, ts.createPropertyAccess(expr, "default"), {}); });
fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member));
}
return fixes;
@@ -115008,6 +116247,7 @@ var ts;
return ts.textChanges.getNewFileText(toStatements(valueInfo, outputKind), 3 /* TS */, formatSettings.newLineCharacter || "\n", ts.formatting.getFormatContext(formatSettings));
}
ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText;
+ /* @internal */
var OutputKind;
(function (OutputKind) {
OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals";
@@ -115149,9 +116389,9 @@ var ts;
forEachOwnNodeOfFunction(fnAst, function (node) {
if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) &&
ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 100 /* ThisKeyword */) {
- var name_7 = node.left.name.text;
- if (!ts.isJsPrivate(name_7)) {
- ts.getOrUpdate(members, name_7, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_7, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); });
+ var name_4 = node.left.name.text;
+ if (!ts.isJsPrivate(name_4)) {
+ ts.getOrUpdate(members, name_4, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_4, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); });
}
}
});
@@ -115666,7 +116906,7 @@ var ts;
});
var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName;
var neededNamedImports = [];
- var _loop_23 = function (element) {
+ var _loop_13 = function (element) {
var propertyName = (element.propertyName || element.name).text;
ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) {
var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName);
@@ -115685,7 +116925,7 @@ var ts;
};
for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) {
var element = _a[_i];
- _loop_23(element);
+ _loop_13(element);
}
changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName)));
if (neededNamedImports.length) {
@@ -116175,7 +117415,7 @@ var ts;
// * Module/namespace or source file
if (isScope(current)) {
scopes.push(current);
- if (current.kind === 279 /* SourceFile */) {
+ if (current.kind === 284 /* SourceFile */) {
return scopes;
}
}
@@ -116740,8 +117980,8 @@ var ts;
ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one.
var prevMember;
var allProperties = true;
- for (var _i = 0, members_7 = members; _i < members_7.length; _i++) {
- var member = members_7[_i];
+ for (var _i = 0, members_2 = members; _i < members_2.length; _i++) {
+ var member = members_2[_i];
if (member.pos > maxPos) {
return prevMember || members[0];
}
@@ -116915,7 +118155,7 @@ var ts;
: ts.getEnclosingBlockScopeContainer(scopes[0]);
ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
- var _loop_24 = function (i) {
+ var _loop_14 = function (i) {
var scopeUsages = usagesPerScope[i];
// Special case: in the innermost scope, all usages are available.
// (The computed value reflects the value at the top-level of the scope, but the
@@ -116955,7 +118195,7 @@ var ts;
}
};
for (var i = 0; i < scopes.length; i++) {
- _loop_24(i);
+ _loop_14(i);
}
return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
function isInGenericContext(node) {
@@ -117189,7 +118429,7 @@ var ts;
function isBlockLike(node) {
switch (node.kind) {
case 218 /* Block */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 245 /* ModuleBlock */:
case 271 /* CaseClause */:
return true;
@@ -117506,10 +118746,10 @@ var ts;
}
function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) {
var checker = program.getTypeChecker();
- var _loop_25 = function (sourceFile) {
+ var _loop_15 = function (sourceFile) {
if (sourceFile === oldFile)
return "continue";
- var _loop_26 = function (statement) {
+ var _loop_16 = function (statement) {
forEachImportInStatement(statement, function (importNode) {
if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol)
return;
@@ -117531,12 +118771,12 @@ var ts;
};
for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
var statement = _a[_i];
- _loop_26(statement);
+ _loop_16(statement);
}
};
for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
var sourceFile = _a[_i];
- _loop_25(sourceFile);
+ _loop_15(sourceFile);
}
}
function getNamespaceLikeImport(node) {
@@ -117651,9 +118891,9 @@ var ts;
if (isTopLevelDeclarationStatement(statement) &&
!isExported(sourceFile, statement, useEs6Exports) &&
forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) {
- var exports_2 = addExport(statement, useEs6Exports);
- if (exports_2)
- return exports_2;
+ var exports = addExport(statement, useEs6Exports);
+ if (exports)
+ return exports;
}
return statement;
});
@@ -118128,13 +119368,13 @@ var ts;
var returnStatement_1 = ts.createReturn(expression);
body = ts.createBlock([returnStatement_1], /* multiLine */ true);
ts.suppressLeadingAndTrailingTrivia(body);
- ts.copyComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
+ ts.copyLeadingComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
}
else if (actionName === removeBracesActionName && returnStatement) {
var actualExpression = expression || ts.createVoidZero();
body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression;
ts.suppressLeadingAndTrailingTrivia(body);
- ts.copyComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
+ ts.copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
}
else {
ts.Debug.fail("invalid action");
@@ -118173,6 +119413,410 @@ var ts;
})(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var refactor;
+ (function (refactor) {
+ var convertToNamedParameters;
+ (function (convertToNamedParameters) {
+ var refactorName = "Convert to named parameters";
+ var minimumParameterLength = 2;
+ refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
+ function getAvailableActions(context) {
+ var file = context.file, startPosition = context.startPosition;
+ var isJSFile = ts.isSourceFileJS(file);
+ if (isJSFile)
+ return ts.emptyArray; // TODO: GH#30113
+ var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker());
+ if (!functionDeclaration)
+ return ts.emptyArray;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_named_parameters);
+ return [{
+ name: refactorName,
+ description: description,
+ actions: [{
+ name: refactorName,
+ description: description
+ }]
+ }];
+ }
+ function getEditsForAction(context, actionName) {
+ ts.Debug.assert(actionName === refactorName);
+ var file = context.file, startPosition = context.startPosition, program = context.program, cancellationToken = context.cancellationToken, host = context.host;
+ var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker());
+ if (!functionDeclaration || !cancellationToken)
+ return undefined;
+ var groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken);
+ if (groupedReferences.valid) {
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(file, program, host, t, functionDeclaration, groupedReferences); });
+ return { renameFilename: undefined, renameLocation: undefined, edits: edits };
+ }
+ return { edits: [] }; // TODO: GH#30113
+ }
+ function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) {
+ var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); });
+ changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ",
+ // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter
+ indentation: 0,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include
+ });
+ var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); });
+ for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) {
+ var call = functionCalls_1[_i];
+ if (call.arguments && call.arguments.length) {
+ var newArgument = ts.getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true);
+ changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include });
+ }
+ }
+ }
+ function getGroupedReferences(functionDeclaration, program, cancellationToken) {
+ var functionNames = getFunctionNames(functionDeclaration);
+ var classNames = ts.isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : [];
+ var names = ts.deduplicate(functionNames.concat(classNames), ts.equateValues);
+ var checker = program.getTypeChecker();
+ var references = ts.flatMap(names, /*mapfn*/ function (/*mapfn*/ name) { return ts.FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken); });
+ var groupedReferences = groupReferences(references);
+ if (!ts.every(groupedReferences.declarations, function (decl) { return ts.contains(names, decl); })) {
+ groupedReferences.valid = false;
+ }
+ return groupedReferences;
+ function groupReferences(referenceEntries) {
+ var classReferences = { accessExpressions: [], typeUsages: [] };
+ var groupedReferences = { functionCalls: [], declarations: [], classReferences: classReferences, valid: true };
+ var functionSymbols = ts.map(functionNames, checker.getSymbolAtLocation);
+ var classSymbols = ts.map(classNames, checker.getSymbolAtLocation);
+ var isConstructor = ts.isConstructorDeclaration(functionDeclaration);
+ for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) {
+ var entry = referenceEntries_1[_i];
+ if (entry.kind !== 1 /* Node */) {
+ groupedReferences.valid = false;
+ continue;
+ }
+ if (ts.contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ var call = entryToFunctionCall(entry);
+ if (call) {
+ groupedReferences.functionCalls.push(call);
+ continue;
+ }
+ }
+ // if the refactored function is a constructor, we must also check if the references to its class are valid
+ if (isConstructor && ts.contains(classSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ var accessExpression = entryToAccessExpression(entry);
+ if (accessExpression) {
+ classReferences.accessExpressions.push(accessExpression);
+ continue;
+ }
+ // Only class declarations are allowed to be used as a type (in a heritage clause),
+ // otherwise `findAllReferences` might not be able to track constructor calls.
+ if (ts.isClassDeclaration(functionDeclaration.parent)) {
+ var type = entryToType(entry);
+ if (type) {
+ classReferences.typeUsages.push(type);
+ continue;
+ }
+ }
+ }
+ groupedReferences.valid = false;
+ }
+ return groupedReferences;
+ }
+ }
+ function symbolComparer(a, b) {
+ return ts.getSymbolTarget(a) === ts.getSymbolTarget(b);
+ }
+ function entryToDeclaration(entry) {
+ if (ts.isDeclaration(entry.node.parent)) {
+ return entry.node;
+ }
+ return undefined;
+ }
+ function entryToFunctionCall(entry) {
+ if (entry.node.parent) {
+ var functionReference = entry.node;
+ var parent = functionReference.parent;
+ switch (parent.kind) {
+ // Function call (foo(...) or super(...))
+ case 191 /* CallExpression */:
+ var callExpression = ts.tryCast(parent, ts.isCallExpression);
+ if (callExpression && callExpression.expression === functionReference) {
+ return callExpression;
+ }
+ break;
+ // Constructor call (new Foo(...))
+ case 192 /* NewExpression */:
+ var newExpression = ts.tryCast(parent, ts.isNewExpression);
+ if (newExpression && newExpression.expression === functionReference) {
+ return newExpression;
+ }
+ break;
+ // Method call (x.foo(...))
+ case 189 /* PropertyAccessExpression */:
+ var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
+ if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) {
+ var callExpression_1 = ts.tryCast(propertyAccessExpression.parent, ts.isCallExpression);
+ if (callExpression_1 && callExpression_1.expression === propertyAccessExpression) {
+ return callExpression_1;
+ }
+ }
+ break;
+ // Method call (x["foo"](...))
+ case 190 /* ElementAccessExpression */:
+ var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
+ if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) {
+ var callExpression_2 = ts.tryCast(elementAccessExpression.parent, ts.isCallExpression);
+ if (callExpression_2 && callExpression_2.expression === elementAccessExpression) {
+ return callExpression_2;
+ }
+ }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function entryToAccessExpression(entry) {
+ if (entry.node.parent) {
+ var reference = entry.node;
+ var parent = reference.parent;
+ switch (parent.kind) {
+ // `C.foo`
+ case 189 /* PropertyAccessExpression */:
+ var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
+ if (propertyAccessExpression && propertyAccessExpression.expression === reference) {
+ return propertyAccessExpression;
+ }
+ break;
+ // `C["foo"]`
+ case 190 /* ElementAccessExpression */:
+ var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
+ if (elementAccessExpression && elementAccessExpression.expression === reference) {
+ return elementAccessExpression;
+ }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function entryToType(entry) {
+ var reference = entry.node;
+ if (ts.getMeaningFromLocation(reference) === 2 /* Type */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) {
+ return reference;
+ }
+ return undefined;
+ }
+ function getFunctionDeclarationAtPosition(file, startPosition, checker) {
+ var node = ts.getTouchingToken(file, startPosition);
+ var functionDeclaration = ts.getContainingFunction(node);
+ if (functionDeclaration
+ && isValidFunctionDeclaration(functionDeclaration, checker)
+ && ts.rangeContainsRange(functionDeclaration, node)
+ && !(functionDeclaration.body && ts.rangeContainsRange(functionDeclaration.body, node)))
+ return functionDeclaration;
+ return undefined;
+ }
+ function isValidFunctionDeclaration(functionDeclaration, checker) {
+ if (!isValidParameterNodeArray(functionDeclaration.parameters))
+ return false;
+ switch (functionDeclaration.kind) {
+ case 239 /* FunctionDeclaration */:
+ case 156 /* MethodDeclaration */:
+ return !!functionDeclaration.name && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration);
+ case 157 /* Constructor */:
+ if (ts.isClassDeclaration(functionDeclaration.parent)) {
+ return !!functionDeclaration.body && !!functionDeclaration.parent.name && !checker.isImplementationOfOverload(functionDeclaration);
+ }
+ else {
+ return isValidVariableDeclaration(functionDeclaration.parent.parent) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration);
+ }
+ case 196 /* FunctionExpression */:
+ case 197 /* ArrowFunction */:
+ return isValidVariableDeclaration(functionDeclaration.parent);
+ }
+ return false;
+ }
+ function isValidParameterNodeArray(parameters) {
+ return getRefactorableParametersLength(parameters) >= minimumParameterLength && ts.every(parameters, isValidParameterDeclaration);
+ }
+ function isValidParameterDeclaration(paramDeclaration) {
+ return !paramDeclaration.modifiers && !paramDeclaration.decorators && ts.isIdentifier(paramDeclaration.name);
+ }
+ function isValidVariableDeclaration(node) {
+ return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113
+ }
+ function hasThisParameter(parameters) {
+ return parameters.length > 0 && ts.isThis(parameters[0].name);
+ }
+ function getRefactorableParametersLength(parameters) {
+ if (hasThisParameter(parameters)) {
+ return parameters.length - 1;
+ }
+ return parameters.length;
+ }
+ function getRefactorableParameters(parameters) {
+ if (hasThisParameter(parameters)) {
+ parameters = ts.createNodeArray(parameters.slice(1), parameters.hasTrailingComma);
+ }
+ return parameters;
+ }
+ function createNewArgument(functionDeclaration, functionArguments) {
+ var parameters = getRefactorableParameters(functionDeclaration.parameters);
+ var hasRestParameter = ts.isRestParameter(ts.last(parameters));
+ var nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments;
+ var properties = ts.map(nonRestArguments, function (arg, i) {
+ var property = ts.createPropertyAssignment(getParameterName(parameters[i]), arg);
+ ts.suppressLeadingAndTrailingTrivia(property.initializer);
+ copyComments(arg, property);
+ return property;
+ });
+ if (hasRestParameter && functionArguments.length >= parameters.length) {
+ var restArguments = functionArguments.slice(parameters.length - 1);
+ var restProperty = ts.createPropertyAssignment(getParameterName(ts.last(parameters)), ts.createArrayLiteral(restArguments));
+ properties.push(restProperty);
+ }
+ var objectLiteral = ts.createObjectLiteral(properties, /*multiLine*/ false);
+ return objectLiteral;
+ }
+ function createNewParameters(functionDeclaration, program, host) {
+ var refactorableParameters = getRefactorableParameters(functionDeclaration.parameters);
+ var bindingElements = ts.map(refactorableParameters, createBindingElementFromParameterDeclaration);
+ var objectParameterName = ts.createObjectBindingPattern(bindingElements);
+ var objectParameterType = createParameterTypeNode(refactorableParameters);
+ var checker = program.getTypeChecker();
+ var objectInitializer;
+ // If every parameter in the original function was optional, add an empty object initializer to the new object parameter
+ if (ts.every(refactorableParameters, checker.isOptionalParameter)) {
+ objectInitializer = ts.createObjectLiteral();
+ }
+ var objectParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, objectParameterName,
+ /*questionToken*/ undefined, objectParameterType, objectInitializer);
+ if (hasThisParameter(functionDeclaration.parameters)) {
+ var thisParameter = functionDeclaration.parameters[0];
+ var newThisParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, thisParameter.name,
+ /*questionToken*/ undefined, thisParameter.type);
+ ts.suppressLeadingAndTrailingTrivia(newThisParameter.name);
+ copyComments(thisParameter.name, newThisParameter.name);
+ if (thisParameter.type) {
+ ts.suppressLeadingAndTrailingTrivia(newThisParameter.type);
+ copyComments(thisParameter.type, newThisParameter.type);
+ }
+ return ts.createNodeArray([newThisParameter, objectParameter]);
+ }
+ return ts.createNodeArray([objectParameter]);
+ function createParameterTypeNode(parameters) {
+ var members = ts.map(parameters, createPropertySignatureFromParameterDeclaration);
+ var typeNode = ts.addEmitFlags(ts.createTypeLiteralNode(members), 1 /* SingleLine */);
+ return typeNode;
+ }
+ function createPropertySignatureFromParameterDeclaration(parameterDeclaration) {
+ var parameterType = parameterDeclaration.type;
+ if (!parameterType && (parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration))) {
+ parameterType = getTypeNode(parameterDeclaration);
+ }
+ var propertySignature = ts.createPropertySignature(
+ /*modifiers*/ undefined, getParameterName(parameterDeclaration), parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration) ? ts.createToken(56 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType,
+ /*initializer*/ undefined);
+ ts.suppressLeadingAndTrailingTrivia(propertySignature);
+ copyComments(parameterDeclaration.name, propertySignature.name);
+ if (parameterDeclaration.type && propertySignature.type) {
+ copyComments(parameterDeclaration.type, propertySignature.type);
+ }
+ return propertySignature;
+ }
+ function getTypeNode(node) {
+ var checker = program.getTypeChecker();
+ var type = checker.getTypeAtLocation(node);
+ return ts.getTypeNodeIfAccessible(type, node, program, host);
+ }
+ }
+ function createBindingElementFromParameterDeclaration(parameterDeclaration) {
+ var element = ts.createBindingElement(
+ /*dotDotDotToken*/ undefined,
+ /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer);
+ ts.suppressLeadingAndTrailingTrivia(element);
+ if (parameterDeclaration.initializer && element.initializer) {
+ copyComments(parameterDeclaration.initializer, element.initializer);
+ }
+ return element;
+ }
+ function copyComments(sourceNode, targetNode) {
+ var sourceFile = sourceNode.getSourceFile();
+ var text = sourceFile.text;
+ if (hasLeadingLineBreak(sourceNode, text)) {
+ ts.copyLeadingComments(sourceNode, targetNode, sourceFile);
+ }
+ else {
+ ts.copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile);
+ }
+ ts.copyTrailingComments(sourceNode, targetNode, sourceFile);
+ }
+ function hasLeadingLineBreak(node, text) {
+ var start = node.getFullStart();
+ var end = node.getStart();
+ for (var i = start; i < end; i++) {
+ if (text.charCodeAt(i) === 10 /* lineFeed */)
+ return true;
+ }
+ return false;
+ }
+ function getParameterName(paramDeclaration) {
+ return ts.getTextOfIdentifierOrLiteral(paramDeclaration.name);
+ }
+ function getClassNames(constructorDeclaration) {
+ switch (constructorDeclaration.parent.kind) {
+ case 240 /* ClassDeclaration */:
+ var classDeclaration = constructorDeclaration.parent;
+ return [classDeclaration.name];
+ case 209 /* ClassExpression */:
+ var classExpression = constructorDeclaration.parent;
+ var variableDeclaration = constructorDeclaration.parent.parent;
+ var className = classExpression.name;
+ if (className)
+ return [className, variableDeclaration.name];
+ return [variableDeclaration.name];
+ }
+ }
+ function getFunctionNames(functionDeclaration) {
+ switch (functionDeclaration.kind) {
+ case 239 /* FunctionDeclaration */:
+ case 156 /* MethodDeclaration */:
+ return [functionDeclaration.name];
+ case 157 /* Constructor */:
+ var ctrKeyword = ts.findChildOfKind(functionDeclaration, 124 /* ConstructorKeyword */, functionDeclaration.getSourceFile());
+ if (functionDeclaration.parent.kind === 209 /* ClassExpression */) {
+ var variableDeclaration = functionDeclaration.parent.parent;
+ return [variableDeclaration.name, ctrKeyword];
+ }
+ return [ctrKeyword];
+ case 197 /* ArrowFunction */:
+ return [functionDeclaration.parent.name];
+ case 196 /* FunctionExpression */:
+ if (functionDeclaration.name)
+ return [functionDeclaration.name, functionDeclaration.parent.name];
+ return [functionDeclaration.parent.name];
+ default:
+ return ts.Debug.assertNever(functionDeclaration);
+ }
+ }
+ })(convertToNamedParameters = refactor.convertToNamedParameters || (refactor.convertToNamedParameters = {}));
+ })(refactor = ts.refactor || (ts.refactor = {}));
+})(ts || (ts = {}));
var ts;
(function (ts) {
/** The version of the language service API */
@@ -118253,7 +119897,7 @@ var ts;
if (!children.length) {
return undefined;
}
- var child = ts.find(children, function (kid) { return kid.kind < 283 /* FirstJSDocNode */ || kid.kind > 305 /* LastJSDocNode */; });
+ var child = ts.find(children, function (kid) { return kid.kind < 288 /* FirstJSDocNode */ || kid.kind > 310 /* LastJSDocNode */; });
return child.kind < 148 /* FirstNode */ ?
child :
child.getFirstToken(sourceFile);
@@ -118323,11 +119967,11 @@ var ts;
}
}
function createSyntaxList(nodes, parent) {
- var list = createNode(306 /* SyntaxList */, nodes.pos, nodes.end, parent);
+ var list = createNode(311 /* SyntaxList */, nodes.pos, nodes.end, parent);
list._children = [];
var pos = nodes.pos;
- for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) {
- var node = nodes_7[_i];
+ for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
+ var node = nodes_1[_i];
addSyntheticNodes(list._children, pos, node.pos, parent);
list._children.push(node);
pos = node.end;
@@ -118571,8 +120215,8 @@ var ts;
return ts.emptyArray;
var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations);
if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) {
- for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) {
- var declaration = declarations_14[_i];
+ for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
+ var declaration = declarations_4[_i];
var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217
// TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs
if (inheritedDocs)
@@ -119324,14 +120968,14 @@ var ts;
var typeChecker = program.getTypeChecker();
var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker);
if (!symbol || typeChecker.isUnknownSymbol(symbol)) {
- var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined;
- return type_7 && {
+ var type_2 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined;
+ return type_2 && {
kind: "" /* unknown */,
kindModifiers: "" /* none */,
textSpan: ts.createTextSpanFromNode(node, sourceFile),
- displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }),
- documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined,
- tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined
+ displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_2, ts.getContainerNode(node)); }),
+ documentation: type_2.symbol ? type_2.symbol.getDocumentationComment(typeChecker) : undefined,
+ tags: type_2.symbol ? type_2.symbol.getJsDocTags() : undefined
};
}
var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) {
diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts
index 0c77acd5540a3..6b5bd1778e661 100644
--- a/lib/typescriptServices.d.ts
+++ b/lib/typescriptServices.d.ts
@@ -355,40 +355,45 @@ declare namespace ts {
ShorthandPropertyAssignment = 276,
SpreadAssignment = 277,
EnumMember = 278,
- SourceFile = 279,
- Bundle = 280,
- UnparsedSource = 281,
- InputFiles = 282,
- JSDocTypeExpression = 283,
- JSDocAllType = 284,
- JSDocUnknownType = 285,
- JSDocNullableType = 286,
- JSDocNonNullableType = 287,
- JSDocOptionalType = 288,
- JSDocFunctionType = 289,
- JSDocVariadicType = 290,
- JSDocComment = 291,
- JSDocTypeLiteral = 292,
- JSDocSignature = 293,
- JSDocTag = 294,
- JSDocAugmentsTag = 295,
- JSDocClassTag = 296,
- JSDocCallbackTag = 297,
- JSDocEnumTag = 298,
- JSDocParameterTag = 299,
- JSDocReturnTag = 300,
- JSDocThisTag = 301,
- JSDocTypeTag = 302,
- JSDocTemplateTag = 303,
- JSDocTypedefTag = 304,
- JSDocPropertyTag = 305,
- SyntaxList = 306,
- NotEmittedStatement = 307,
- PartiallyEmittedExpression = 308,
- CommaListExpression = 309,
- MergeDeclarationMarker = 310,
- EndOfDeclarationMarker = 311,
- Count = 312,
+ UnparsedPrologue = 279,
+ UnparsedPrepend = 280,
+ UnparsedText = 281,
+ UnparsedInternalText = 282,
+ UnparsedSyntheticReference = 283,
+ SourceFile = 284,
+ Bundle = 285,
+ UnparsedSource = 286,
+ InputFiles = 287,
+ JSDocTypeExpression = 288,
+ JSDocAllType = 289,
+ JSDocUnknownType = 290,
+ JSDocNullableType = 291,
+ JSDocNonNullableType = 292,
+ JSDocOptionalType = 293,
+ JSDocFunctionType = 294,
+ JSDocVariadicType = 295,
+ JSDocComment = 296,
+ JSDocTypeLiteral = 297,
+ JSDocSignature = 298,
+ JSDocTag = 299,
+ JSDocAugmentsTag = 300,
+ JSDocClassTag = 301,
+ JSDocCallbackTag = 302,
+ JSDocEnumTag = 303,
+ JSDocParameterTag = 304,
+ JSDocReturnTag = 305,
+ JSDocThisTag = 306,
+ JSDocTypeTag = 307,
+ JSDocTemplateTag = 308,
+ JSDocTypedefTag = 309,
+ JSDocPropertyTag = 310,
+ SyntaxList = 311,
+ NotEmittedStatement = 312,
+ PartiallyEmittedExpression = 313,
+ CommaListExpression = 314,
+ MergeDeclarationMarker = 315,
+ EndOfDeclarationMarker = 316,
+ Count = 317,
FirstAssignment = 59,
LastAssignment = 71,
FirstCompoundAssignment = 60,
@@ -414,10 +419,10 @@ declare namespace ts {
FirstBinaryOperator = 28,
LastBinaryOperator = 71,
FirstNode = 148,
- FirstJSDocNode = 283,
- LastJSDocNode = 305,
- FirstJSDocTagNode = 294,
- LastJSDocTagNode = 305
+ FirstJSDocNode = 288,
+ LastJSDocNode = 310,
+ FirstJSDocTagNode = 299,
+ LastJSDocTagNode = 310,
}
enum NodeFlags {
None = 0,
@@ -446,7 +451,7 @@ declare namespace ts {
ReachabilityCheckFlags = 384,
ReachabilityAndEmitFlags = 1408,
ContextFlags = 12679168,
- TypeExcludesFlags = 20480
+ TypeExcludesFlags = 20480,
}
enum ModifierFlags {
None = 0,
@@ -1003,7 +1008,7 @@ declare namespace ts {
Octal = 32,
HexSpecifier = 64,
BinarySpecifier = 128,
- OctalSpecifier = 256
+ OctalSpecifier = 256,
}
interface NumericLiteral extends LiteralExpression {
kind: SyntaxKind.NumericLiteral;
@@ -1745,10 +1750,44 @@ declare namespace ts {
}
interface UnparsedSource extends Node {
kind: SyntaxKind.UnparsedSource;
- fileName?: string;
+ fileName: string;
text: string;
+ prologues: ReadonlyArray;
+ helpers: ReadonlyArray | undefined;
+ referencedFiles: ReadonlyArray;
+ typeReferenceDirectives: ReadonlyArray | undefined;
+ libReferenceDirectives: ReadonlyArray;
+ hasNoDefaultLib?: boolean;
sourceMapPath?: string;
sourceMapText?: string;
+ syntheticReferences?: ReadonlyArray;
+ texts: ReadonlyArray;
+ }
+ type UnparsedSourceText = UnparsedPrepend | UnparsedTextLike;
+ type UnparsedNode = UnparsedPrologue | UnparsedSourceText | UnparsedSyntheticReference;
+ interface UnparsedSection extends Node {
+ kind: SyntaxKind;
+ data?: string;
+ parent: UnparsedSource;
+ }
+ interface UnparsedPrologue extends UnparsedSection {
+ kind: SyntaxKind.UnparsedPrologue;
+ data: string;
+ parent: UnparsedSource;
+ }
+ interface UnparsedPrepend extends UnparsedSection {
+ kind: SyntaxKind.UnparsedPrepend;
+ data: string;
+ parent: UnparsedSource;
+ texts: ReadonlyArray;
+ }
+ interface UnparsedTextLike extends UnparsedSection {
+ kind: SyntaxKind.UnparsedText | SyntaxKind.UnparsedInternalText;
+ parent: UnparsedSource;
+ }
+ interface UnparsedSyntheticReference extends UnparsedSection {
+ kind: SyntaxKind.UnparsedSyntheticReference;
+ parent: UnparsedSource;
}
interface JsonSourceFile extends SourceFile {
statements: NodeArray;
@@ -2022,7 +2061,7 @@ declare namespace ts {
WriteTypeParametersOrArguments = 1,
UseOnlyExternalAliasing = 2,
AllowAnyNodeKind = 4,
- UseAliasDefinedOutsideCurrentScope = 8
+ UseAliasDefinedOutsideCurrentScope = 8,
}
enum TypePredicateKind {
This = 0,
@@ -2100,7 +2139,7 @@ declare namespace ts {
ExportHasLocal = 944,
BlockScoped = 418,
PropertyOrAccessor = 98308,
- ClassMember = 106500
+ ClassMember = 106500,
}
interface Symbol {
flags: SymbolFlags;
@@ -2208,7 +2247,7 @@ declare namespace ts {
Instantiable = 63176704,
StructuredOrInstantiable = 66846720,
Narrowable = 133970943,
- NotUnionOrUnit = 67637251
+ NotUnionOrUnit = 67637251,
}
type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
interface Type {
@@ -2255,7 +2294,7 @@ declare namespace ts {
MarkerType = 8192,
JSLiteral = 16384,
FreshLiteral = 32768,
- ClassOrInterface = 3
+ ClassOrInterface = 3,
}
interface ObjectType extends Type {
objectFlags: ObjectFlags;
@@ -2503,6 +2542,8 @@ declare namespace ts {
reactNamespace?: string;
jsxFactory?: string;
composite?: boolean;
+ incremental?: boolean;
+ tsBuildInfoFile?: string;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
@@ -2679,7 +2720,8 @@ declare namespace ts {
Dts = ".d.ts",
Js = ".js",
Jsx = ".jsx",
- Json = ".json"
+ Json = ".json",
+ TsBuildInfo = ".tsbuildinfo"
}
interface ResolvedModuleWithFailedLookupLocations {
readonly resolvedModule: ResolvedModuleFull | undefined;
@@ -2752,7 +2794,7 @@ declare namespace ts {
NoHoisting = 2097152,
HasEndOfDeclarationMarker = 4194304,
Iterator = 8388608,
- NoAsciiEscaping = 16777216
+ NoAsciiEscaping = 16777216,
}
interface EmitHelper {
readonly name: string;
@@ -2760,6 +2802,10 @@ declare namespace ts {
readonly text: string | ((node: EmitHelperUniqueNameCallback) => string);
readonly priority?: number;
}
+ interface UnscopedEmitHelper extends EmitHelper {
+ readonly scoped: false;
+ readonly text: string;
+ }
type EmitHelperUniqueNameCallback = (name: string) => string;
enum EmitHint {
SourceFile = 0,
@@ -3459,6 +3505,9 @@ declare namespace ts {
function isSourceFile(node: Node): node is SourceFile;
function isBundle(node: Node): node is Bundle;
function isUnparsedSource(node: Node): node is UnparsedSource;
+ function isUnparsedPrepend(node: Node): node is UnparsedPrepend;
+ function isUnparsedTextLike(node: Node): node is UnparsedTextLike;
+ function isUnparsedNode(node: Node): node is UnparsedNode;
function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression;
function isJSDocAllType(node: JSDocAllType): node is JSDocAllType;
function isJSDocUnknownType(node: Node): node is JSDocUnknownType;
@@ -3994,10 +4043,10 @@ declare namespace ts {
function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression;
function createBundle(sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle;
function createUnparsedSourceFile(text: string): UnparsedSource;
- function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts"): UnparsedSource;
+ function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts", stripInternal?: boolean): UnparsedSource;
function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource;
function createInputFiles(javascriptText: string, declarationText: string): InputFiles;
- function createInputFiles(readFileText: (path: string) => string | undefined, javascriptPath: string, javascriptMapPath: string | undefined, declarationPath: string, declarationMapPath: string | undefined): InputFiles;
+ function createInputFiles(readFileText: (path: string) => string | undefined, javascriptPath: string, javascriptMapPath: string | undefined, declarationPath: string, declarationMapPath: string | undefined, buildInfoPath: string | undefined): InputFiles;
function createInputFiles(javascriptText: string, declarationText: string, javascriptMapPath: string | undefined, javascriptMapText: string | undefined, declarationMapPath: string | undefined, declarationMapText: string | undefined): InputFiles;
function updateBundle(node: Bundle, sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray): CallExpression;
diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js
index c7d8109b6beec..38cecfac882fa 100644
--- a/lib/typescriptServices.js
+++ b/lib/typescriptServices.js
@@ -812,7 +812,7 @@ var ts;
}
/**
* Deduplicates an unsorted array.
- * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates.
+ * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates.
* @param comparer An optional `Comparer` used to sort entries before comparison, though the
* result will remain in the original order in `array`.
*/
@@ -1028,6 +1028,21 @@ var ts;
} };
}
ts.arrayIterator = arrayIterator;
+ function arrayReverseIterator(array) {
+ var i = array.length;
+ return {
+ next: function () {
+ if (i === 0) {
+ return { value: undefined, done: true };
+ }
+ else {
+ i--;
+ return { value: array[i], done: false };
+ }
+ }
+ };
+ }
+ ts.arrayReverseIterator = arrayReverseIterator;
/**
* Stable sort of an array. Elements equal to each other maintain their relative position in the array.
*/
@@ -2867,47 +2882,53 @@ var ts;
SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment";
// Enum
SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember";
+ // Unparsed
+ SyntaxKind[SyntaxKind["UnparsedPrologue"] = 279] = "UnparsedPrologue";
+ SyntaxKind[SyntaxKind["UnparsedPrepend"] = 280] = "UnparsedPrepend";
+ SyntaxKind[SyntaxKind["UnparsedText"] = 281] = "UnparsedText";
+ SyntaxKind[SyntaxKind["UnparsedInternalText"] = 282] = "UnparsedInternalText";
+ SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 283] = "UnparsedSyntheticReference";
// Top-level nodes
- SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile";
- SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle";
- SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource";
- SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles";
+ SyntaxKind[SyntaxKind["SourceFile"] = 284] = "SourceFile";
+ SyntaxKind[SyntaxKind["Bundle"] = 285] = "Bundle";
+ SyntaxKind[SyntaxKind["UnparsedSource"] = 286] = "UnparsedSource";
+ SyntaxKind[SyntaxKind["InputFiles"] = 287] = "InputFiles";
// JSDoc nodes
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression";
+ SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 288] = "JSDocTypeExpression";
// The * type
- SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType";
+ SyntaxKind[SyntaxKind["JSDocAllType"] = 289] = "JSDocAllType";
// The ? type
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature";
- SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag";
- SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag";
- SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag";
+ SyntaxKind[SyntaxKind["JSDocUnknownType"] = 290] = "JSDocUnknownType";
+ SyntaxKind[SyntaxKind["JSDocNullableType"] = 291] = "JSDocNullableType";
+ SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 292] = "JSDocNonNullableType";
+ SyntaxKind[SyntaxKind["JSDocOptionalType"] = 293] = "JSDocOptionalType";
+ SyntaxKind[SyntaxKind["JSDocFunctionType"] = 294] = "JSDocFunctionType";
+ SyntaxKind[SyntaxKind["JSDocVariadicType"] = 295] = "JSDocVariadicType";
+ SyntaxKind[SyntaxKind["JSDocComment"] = 296] = "JSDocComment";
+ SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 297] = "JSDocTypeLiteral";
+ SyntaxKind[SyntaxKind["JSDocSignature"] = 298] = "JSDocSignature";
+ SyntaxKind[SyntaxKind["JSDocTag"] = 299] = "JSDocTag";
+ SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 300] = "JSDocAugmentsTag";
+ SyntaxKind[SyntaxKind["JSDocClassTag"] = 301] = "JSDocClassTag";
+ SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 302] = "JSDocCallbackTag";
+ SyntaxKind[SyntaxKind["JSDocEnumTag"] = 303] = "JSDocEnumTag";
+ SyntaxKind[SyntaxKind["JSDocParameterTag"] = 304] = "JSDocParameterTag";
+ SyntaxKind[SyntaxKind["JSDocReturnTag"] = 305] = "JSDocReturnTag";
+ SyntaxKind[SyntaxKind["JSDocThisTag"] = 306] = "JSDocThisTag";
+ SyntaxKind[SyntaxKind["JSDocTypeTag"] = 307] = "JSDocTypeTag";
+ SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 308] = "JSDocTemplateTag";
+ SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 309] = "JSDocTypedefTag";
+ SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 310] = "JSDocPropertyTag";
// Synthesized list
- SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList";
+ SyntaxKind[SyntaxKind["SyntaxList"] = 311] = "SyntaxList";
// Transformation nodes
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker";
+ SyntaxKind[SyntaxKind["NotEmittedStatement"] = 312] = "NotEmittedStatement";
+ SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 313] = "PartiallyEmittedExpression";
+ SyntaxKind[SyntaxKind["CommaListExpression"] = 314] = "CommaListExpression";
+ SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 315] = "MergeDeclarationMarker";
+ SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 316] = "EndOfDeclarationMarker";
// Enum value count
- SyntaxKind[SyntaxKind["Count"] = 312] = "Count";
+ SyntaxKind[SyntaxKind["Count"] = 317] = "Count";
// Markers
SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment";
SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment";
@@ -2934,10 +2955,10 @@ var ts;
SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator";
SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator";
SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode";
+ SyntaxKind[SyntaxKind["FirstJSDocNode"] = 288] = "FirstJSDocNode";
+ SyntaxKind[SyntaxKind["LastJSDocNode"] = 310] = "LastJSDocNode";
+ SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 299] = "FirstJSDocTagNode";
+ SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 310] = "LastJSDocTagNode";
/* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword";
/* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword";
})(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
@@ -3555,6 +3576,7 @@ var ts;
InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
InferenceFlags[InferenceFlags["NoFixing"] = 4] = "NoFixing";
+ InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 8] = "SkippedGenericFunction";
})(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
/**
* Ternary values are defined such that
@@ -3814,6 +3836,7 @@ var ts;
Extension["Js"] = ".js";
Extension["Jsx"] = ".jsx";
Extension["Json"] = ".json";
+ Extension["TsBuildInfo"] = ".tsbuildinfo";
})(Extension = ts.Extension || (ts.Extension = {}));
/* @internal */
var TransformFlags;
@@ -3971,6 +3994,20 @@ var ts;
EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
})(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
+ /*@internal*/
+ var BundleFileSectionKind;
+ (function (BundleFileSectionKind) {
+ BundleFileSectionKind["Prologue"] = "prologue";
+ BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
+ BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
+ BundleFileSectionKind["Reference"] = "reference";
+ BundleFileSectionKind["Type"] = "type";
+ BundleFileSectionKind["Lib"] = "lib";
+ BundleFileSectionKind["Prepend"] = "prepend";
+ BundleFileSectionKind["Text"] = "text";
+ BundleFileSectionKind["Internal"] = "internal";
+ // comments?
+ })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
var ListFormat;
(function (ListFormat) {
ListFormat[ListFormat["None"] = 0] = "None";
@@ -4378,6 +4415,8 @@ var ts;
: FileWatcherEventKind.Changed;
}
ts.getFileWatcherEventKind = getFileWatcherEventKind;
+ /*@internal*/
+ ts.ignoredPaths = ["/node_modules/.", "/.git"];
/**
* Watch the directory recursively using host provided method to watch child directories
* that means if this is recursive watcher, watch the children directories as well
@@ -4402,6 +4441,8 @@ var ts;
else {
directoryWatcher = {
watcher: host.watchDirectory(dirName, function (fileName) {
+ if (isIgnoredPath(fileName))
+ return;
// Call the actual callback
callbackCache.forEach(function (callbacks, rootDirName) {
if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
@@ -4451,7 +4492,7 @@ var ts;
var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
// Filter our the symbolic link directories since those arent included in recursive watch
// which is same behaviour when recursive: true is passed to fs.watch
- return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
+ return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
}) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
return newChildWatches || ts.emptyArray;
/**
@@ -4468,6 +4509,16 @@ var ts;
(newChildWatches || (newChildWatches = [])).push(childWatcher);
}
}
+ function isIgnoredPath(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
+ }
+ function isInPath(path, searchPath) {
+ if (ts.stringContains(path, searchPath))
+ return true;
+ if (host.useCaseSensitiveFileNames)
+ return false;
+ return ts.stringContains(toCanonicalFilePath(path), searchPath);
+ }
}
ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher;
function getNodeMajorVersion() {
@@ -5833,6 +5884,7 @@ var ts;
Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."),
Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."),
+ Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."),
The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."),
Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."),
File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),
@@ -6100,6 +6152,16 @@ var ts;
Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."),
Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."),
Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."),
+ Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"),
+ Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
+ A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"),
+ A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"),
+ Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"),
+ Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"),
+ Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
+ Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."),
+ Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"),
+ Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"),
The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"),
The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."),
The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."),
@@ -6316,6 +6378,7 @@ var ts;
Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"),
+ Convert_to_named_parameters: diag(95075, ts.DiagnosticCategory.Message, "Convert_to_named_parameters_95075", "Convert to named parameters"),
};
})(ts || (ts = {}));
var ts;
@@ -6803,16 +6866,20 @@ var ts;
return pos;
}
var shebangTriviaRegex = /^#!.*/;
+ /*@internal*/
function isShebangTrivia(text, pos) {
// Shebangs check must only be done at the start of the file
ts.Debug.assert(pos === 0);
return shebangTriviaRegex.test(text);
}
+ ts.isShebangTrivia = isShebangTrivia;
+ /*@internal*/
function scanShebangTrivia(text, pos) {
var shebang = shebangTriviaRegex.exec(text)[0];
pos = pos + shebang.length;
return pos;
}
+ ts.scanShebangTrivia = scanShebangTrivia;
/**
* Invokes a callback for each comment range following the provided position.
*
@@ -8522,7 +8589,7 @@ var ts;
}
}
function getSourceFileOfNode(node) {
- while (node && node.kind !== 279 /* SourceFile */) {
+ while (node && node.kind !== 284 /* SourceFile */) {
node = node.parent;
}
return node;
@@ -8668,7 +8735,7 @@ var ts;
// the syntax list itself considers them as normal trivia. Therefore if we simply skip
// trivia for the list, we may have skipped the JSDocComment as well. So we should process its
// first child to determine the actual position of its first token.
- if (node.kind === 306 /* SyntaxList */ && node._children.length > 0) {
+ if (node.kind === 311 /* SyntaxList */ && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -8687,7 +8754,7 @@ var ts;
}
ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
function isJSDocTypeExpressionOrChild(node) {
- return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
+ return node.kind === 288 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
}
function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
if (includeTrivia === void 0) { includeTrivia = false; }
@@ -8814,7 +8881,7 @@ var ts;
return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body);
}
function isBlockScopedContainerTopLevel(node) {
- return node.kind === 279 /* SourceFile */ ||
+ return node.kind === 284 /* SourceFile */ ||
node.kind === 244 /* ModuleDeclaration */ ||
ts.isFunctionLike(node);
}
@@ -8832,7 +8899,7 @@ var ts;
// - defined in the top level scope and source file is an external module
// - defined inside ambient module declaration located in the top level scope and source file not an external module
switch (node.parent.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node.parent);
case 245 /* ModuleBlock */:
return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
@@ -8850,7 +8917,7 @@ var ts;
ts.isEffectiveExternalModule = isEffectiveExternalModule;
function isBlockScope(node, parentNode) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 274 /* CatchClause */:
case 244 /* ModuleDeclaration */:
@@ -8875,9 +8942,9 @@ var ts;
ts.isBlockScope = isBlockScope;
function isDeclarationWithTypeParameters(node) {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
- case 293 /* JSDocSignature */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 298 /* JSDocSignature */:
return true;
default:
ts.assertType(node);
@@ -8893,12 +8960,12 @@ var ts;
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 240 /* ClassDeclaration */:
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
@@ -9043,7 +9110,7 @@ var ts;
function getErrorSpanForNode(sourceFile, node) {
var errorNode = node;
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
if (pos_1 === sourceFile.text.length) {
// file is empty - return span for the beginning of the file
@@ -9218,7 +9285,7 @@ var ts;
return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
case 150 /* TypeParameter */:
return node === parent.constraint;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return node === parent.constraint;
case 154 /* PropertyDeclaration */:
case 153 /* PropertySignature */:
@@ -9478,7 +9545,7 @@ var ts;
}
ts.getContainingClass = getContainingClass;
function getThisContainer(node, includeArrowFunctions) {
- ts.Debug.assert(node.kind !== 279 /* SourceFile */);
+ ts.Debug.assert(node.kind !== 284 /* SourceFile */);
while (true) {
node = node.parent;
if (!node) {
@@ -9532,7 +9599,7 @@ var ts;
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 243 /* EnumDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return node;
}
}
@@ -10240,7 +10307,7 @@ var ts;
}
ts.isJSDocConstructSignature = isJSDocConstructSignature;
function isJSDocTypeAlias(node) {
- return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 309 /* JSDocTypedefTag */ || node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocTypeAlias = isJSDocTypeAlias;
function isTypeAlias(node) {
@@ -10384,7 +10451,7 @@ var ts;
ts.hasRestParameter = hasRestParameter;
function isRestParameter(node) {
var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
- return node.dotDotDotToken !== undefined || !!type && type.kind === 290 /* JSDocVariadicType */;
+ return node.dotDotDotToken !== undefined || !!type && type.kind === 295 /* JSDocVariadicType */;
}
ts.isRestParameter = isRestParameter;
var AssignmentKind;
@@ -10869,7 +10936,7 @@ var ts;
|| kind === 158 /* GetAccessor */
|| kind === 159 /* SetAccessor */
|| kind === 244 /* ModuleDeclaration */
- || kind === 279 /* SourceFile */;
+ || kind === 284 /* SourceFile */;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(range) {
@@ -10946,7 +11013,7 @@ var ts;
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return 0;
case 208 /* SpreadElement */:
return 1;
@@ -11264,6 +11331,9 @@ var ts;
lineStart = true;
}
}
+ function getTextPosWithWriteLine() {
+ return lineStart ? output.length : (output.length + newLine.length);
+ }
reset();
return {
write: write,
@@ -11292,7 +11362,8 @@ var ts;
writeStringLiteral: write,
writeSymbol: function (s, _) { return write(s); },
writeTrailingSemicolon: write,
- writeComment: write
+ writeComment: write,
+ getTextPosWithWriteLine: getTextPosWithWriteLine
};
}
ts.createTextWriter = createTextWriter;
@@ -11583,7 +11654,7 @@ var ts;
ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
/** template tags are only available when a typedef isn't already using them */
function isNonTypeAliasTemplate(tag) {
- return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
+ return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 296 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
}
/**
* Gets the effective type annotation of the value parameter of a set accessor. If the node
@@ -12555,19 +12626,29 @@ var ts;
|| kind === 96 /* NullKeyword */
|| kind === 132 /* NeverKeyword */
|| kind === 211 /* ExpressionWithTypeArguments */
- || kind === 284 /* JSDocAllType */
- || kind === 285 /* JSDocUnknownType */
- || kind === 286 /* JSDocNullableType */
- || kind === 287 /* JSDocNonNullableType */
- || kind === 288 /* JSDocOptionalType */
- || kind === 289 /* JSDocFunctionType */
- || kind === 290 /* JSDocVariadicType */;
+ || kind === 289 /* JSDocAllType */
+ || kind === 290 /* JSDocUnknownType */
+ || kind === 291 /* JSDocNullableType */
+ || kind === 292 /* JSDocNonNullableType */
+ || kind === 293 /* JSDocOptionalType */
+ || kind === 294 /* JSDocFunctionType */
+ || kind === 295 /* JSDocVariadicType */;
}
ts.isTypeNodeKind = isTypeNodeKind;
function isAccessExpression(node) {
return node.kind === 189 /* PropertyAccessExpression */ || node.kind === 190 /* ElementAccessExpression */;
}
ts.isAccessExpression = isAccessExpression;
+ function isBundleFileTextLike(section) {
+ switch (section.kind) {
+ case "text" /* Text */:
+ case "internal" /* Internal */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isBundleFileTextLike = isBundleFileTextLike;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
@@ -13029,8 +13110,8 @@ var ts;
switch (declaration.kind) {
case 72 /* Identifier */:
return declaration;
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */: {
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */: {
var name = declaration.name;
if (name.kind === 148 /* QualifiedName */) {
return name.right;
@@ -13054,7 +13135,7 @@ var ts;
return undefined;
}
}
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return getNameOfJSDocTypedef(declaration);
case 254 /* ExportAssignment */: {
var expression = declaration.expression;
@@ -13258,7 +13339,7 @@ var ts;
return ts.emptyArray;
}
if (ts.isJSDocTypeAlias(node)) {
- ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */);
+ ts.Debug.assert(node.parent.kind === 296 /* JSDocComment */);
return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
}
if (node.typeParameters) {
@@ -13530,7 +13611,7 @@ var ts;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 308 /* PartiallyEmittedExpression */) {
+ while (node.kind === 313 /* PartiallyEmittedExpression */) {
node = node.expression;
}
return node;
@@ -13877,108 +13958,128 @@ var ts;
ts.isEnumMember = isEnumMember;
// Top-level nodes
function isSourceFile(node) {
- return node.kind === 279 /* SourceFile */;
+ return node.kind === 284 /* SourceFile */;
}
ts.isSourceFile = isSourceFile;
function isBundle(node) {
- return node.kind === 280 /* Bundle */;
+ return node.kind === 285 /* Bundle */;
}
ts.isBundle = isBundle;
function isUnparsedSource(node) {
- return node.kind === 281 /* UnparsedSource */;
+ return node.kind === 286 /* UnparsedSource */;
}
ts.isUnparsedSource = isUnparsedSource;
+ function isUnparsedPrepend(node) {
+ return node.kind === 280 /* UnparsedPrepend */;
+ }
+ ts.isUnparsedPrepend = isUnparsedPrepend;
+ function isUnparsedTextLike(node) {
+ switch (node.kind) {
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isUnparsedTextLike = isUnparsedTextLike;
+ function isUnparsedNode(node) {
+ return isUnparsedTextLike(node) ||
+ node.kind === 279 /* UnparsedPrologue */ ||
+ node.kind === 283 /* UnparsedSyntheticReference */;
+ }
+ ts.isUnparsedNode = isUnparsedNode;
// JSDoc
function isJSDocTypeExpression(node) {
- return node.kind === 283 /* JSDocTypeExpression */;
+ return node.kind === 288 /* JSDocTypeExpression */;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 284 /* JSDocAllType */;
+ return node.kind === 289 /* JSDocAllType */;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 285 /* JSDocUnknownType */;
+ return node.kind === 290 /* JSDocUnknownType */;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 286 /* JSDocNullableType */;
+ return node.kind === 291 /* JSDocNullableType */;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 287 /* JSDocNonNullableType */;
+ return node.kind === 292 /* JSDocNonNullableType */;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 288 /* JSDocOptionalType */;
+ return node.kind === 293 /* JSDocOptionalType */;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 289 /* JSDocFunctionType */;
+ return node.kind === 294 /* JSDocFunctionType */;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 290 /* JSDocVariadicType */;
+ return node.kind === 295 /* JSDocVariadicType */;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 291 /* JSDocComment */;
+ return node.kind === 296 /* JSDocComment */;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 295 /* JSDocAugmentsTag */;
+ return node.kind === 300 /* JSDocAugmentsTag */;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 296 /* JSDocClassTag */;
+ return node.kind === 301 /* JSDocClassTag */;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocEnumTag(node) {
- return node.kind === 298 /* JSDocEnumTag */;
+ return node.kind === 303 /* JSDocEnumTag */;
}
ts.isJSDocEnumTag = isJSDocEnumTag;
function isJSDocThisTag(node) {
- return node.kind === 301 /* JSDocThisTag */;
+ return node.kind === 306 /* JSDocThisTag */;
}
ts.isJSDocThisTag = isJSDocThisTag;
function isJSDocParameterTag(node) {
- return node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 300 /* JSDocReturnTag */;
+ return node.kind === 305 /* JSDocReturnTag */;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 302 /* JSDocTypeTag */;
+ return node.kind === 307 /* JSDocTypeTag */;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 303 /* JSDocTemplateTag */;
+ return node.kind === 308 /* JSDocTemplateTag */;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 304 /* JSDocTypedefTag */;
+ return node.kind === 309 /* JSDocTypedefTag */;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */;
+ return node.kind === 310 /* JSDocPropertyTag */;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 310 /* JSDocPropertyTag */ || node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 292 /* JSDocTypeLiteral */;
+ return node.kind === 297 /* JSDocTypeLiteral */;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
function isJSDocCallbackTag(node) {
- return node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocCallbackTag = isJSDocCallbackTag;
function isJSDocSignature(node) {
- return node.kind === 293 /* JSDocSignature */;
+ return node.kind === 298 /* JSDocSignature */;
}
ts.isJSDocSignature = isJSDocSignature;
})(ts || (ts = {}));
@@ -13989,7 +14090,7 @@ var ts;
(function (ts) {
/* @internal */
function isSyntaxList(n) {
- return n.kind === 306 /* SyntaxList */;
+ return n.kind === 311 /* SyntaxList */;
}
ts.isSyntaxList = isSyntaxList;
/* @internal */
@@ -14141,11 +14242,11 @@ var ts;
switch (kind) {
case 155 /* MethodSignature */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 166 /* ConstructorType */:
return true;
default:
@@ -14436,8 +14537,8 @@ var ts;
case 208 /* SpreadElement */:
case 212 /* AsExpression */:
case 210 /* OmittedExpression */:
- case 309 /* CommaListExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 314 /* CommaListExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -14451,12 +14552,12 @@ var ts;
ts.isAssertionExpression = isAssertionExpression;
/* @internal */
function isPartiallyEmittedExpression(node) {
- return node.kind === 308 /* PartiallyEmittedExpression */;
+ return node.kind === 313 /* PartiallyEmittedExpression */;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
/* @internal */
function isNotEmittedStatement(node) {
- return node.kind === 307 /* NotEmittedStatement */;
+ return node.kind === 312 /* NotEmittedStatement */;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
/* @internal */
@@ -14567,9 +14668,9 @@ var ts;
|| kind === 242 /* TypeAliasDeclaration */
|| kind === 150 /* TypeParameter */
|| kind === 237 /* VariableDeclaration */
- || kind === 304 /* JSDocTypedefTag */
- || kind === 297 /* JSDocCallbackTag */
- || kind === 305 /* JSDocPropertyTag */;
+ || kind === 309 /* JSDocTypedefTag */
+ || kind === 302 /* JSDocCallbackTag */
+ || kind === 310 /* JSDocPropertyTag */;
}
function isDeclarationStatementKind(kind) {
return kind === 239 /* FunctionDeclaration */
@@ -14604,14 +14705,14 @@ var ts;
|| kind === 219 /* VariableStatement */
|| kind === 224 /* WhileStatement */
|| kind === 231 /* WithStatement */
- || kind === 307 /* NotEmittedStatement */
- || kind === 311 /* EndOfDeclarationMarker */
- || kind === 310 /* MergeDeclarationMarker */;
+ || kind === 312 /* NotEmittedStatement */
+ || kind === 316 /* EndOfDeclarationMarker */
+ || kind === 315 /* MergeDeclarationMarker */;
}
/* @internal */
function isDeclaration(node) {
if (node.kind === 150 /* TypeParameter */) {
- return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node);
+ return (node.parent && node.parent.kind !== 308 /* JSDocTemplateTag */) || ts.isInJSFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -14706,18 +14807,18 @@ var ts;
/** True if node is of some JSDoc syntax kind. */
/* @internal */
function isJSDocNode(node) {
- return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */;
+ return node.kind >= 288 /* FirstJSDocNode */ && node.kind <= 310 /* LastJSDocNode */;
}
ts.isJSDocNode = isJSDocNode;
/** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node) {
- return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
+ return node.kind === 296 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
}
ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
// TODO: determine what this does before making it public.
/* @internal */
function isJSDocTag(node) {
- return node.kind >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */;
+ return node.kind >= 299 /* FirstJSDocTagNode */ && node.kind <= 310 /* LastJSDocTagNode */;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -15034,6 +15135,10 @@ var ts;
return !!(compilerOptions.declaration || compilerOptions.composite);
}
ts.getEmitDeclarations = getEmitDeclarations;
+ function isIncrementalCompilation(options) {
+ return !!(options.incremental || options.composite);
+ }
+ ts.isIncrementalCompilation = isIncrementalCompilation;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
}
@@ -16318,7 +16423,7 @@ var ts;
var SourceFileConstructor;
// tslint:enable variable-name
function createNode(kind, pos, end) {
- if (kind === 279 /* SourceFile */) {
+ if (kind === 284 /* SourceFile */) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 72 /* Identifier */) {
@@ -16569,7 +16674,7 @@ var ts;
case 218 /* Block */:
case 245 /* ModuleBlock */:
return visitNodes(cbNode, cbNodes, node.statements);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return visitNodes(cbNode, cbNodes, node.statements) ||
visitNode(cbNode, node.endOfFileToken);
case 219 /* VariableStatement */:
@@ -16718,7 +16823,7 @@ var ts;
return visitNode(cbNode, node.expression);
case 258 /* MissingDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return visitNodes(cbNode, cbNodes, node.elements);
case 260 /* JsxElement */:
return visitNode(cbNode, node.openingElement) ||
@@ -16747,60 +16852,60 @@ var ts;
return visitNode(cbNode, node.tagName);
case 171 /* OptionalType */:
case 172 /* RestType */:
- case 283 /* JSDocTypeExpression */:
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 288 /* JSDocOptionalType */:
- case 290 /* JSDocVariadicType */:
+ case 288 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 293 /* JSDocOptionalType */:
+ case 295 /* JSDocVariadicType */:
return visitNode(cbNode, node.type);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return visitNodes(cbNode, cbNodes, node.tags);
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return visitNode(cbNode, node.tagName) ||
(node.isNameFirst
? visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression)
: visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name));
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.constraint) ||
visitNodes(cbNode, cbNodes, node.typeParameters);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return visitNode(cbNode, node.tagName) ||
(node.typeExpression &&
- node.typeExpression.kind === 283 /* JSDocTypeExpression */
+ node.typeExpression.kind === 288 /* JSDocTypeExpression */
? visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName)
: visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression));
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.typeExpression);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return ts.forEach(node.jsDocPropertyTags, cbNode);
- case 294 /* JSDocTag */:
- case 296 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
return visitNode(cbNode, node.tagName);
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
}
@@ -17174,7 +17279,7 @@ var ts;
function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
// code from createNode is inlined here so createNode won't have to deal with special case of creating source files
// this is quite rare comparing to other nodes and createNode should be as fast as possible
- var sourceFile = new SourceFileConstructor(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
+ var sourceFile = new SourceFileConstructor(284 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
@@ -18374,9 +18479,9 @@ var ts;
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(284 /* JSDocAllType */);
+ var result = createNode(289 /* JSDocAllType */);
if (postFixEquals) {
- return createPostfixType(288 /* JSDocOptionalType */, result);
+ return createPostfixType(293 /* JSDocOptionalType */, result);
}
else {
nextToken();
@@ -18384,7 +18489,7 @@ var ts;
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(287 /* JSDocNonNullableType */);
+ var result = createNode(292 /* JSDocNonNullableType */);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -18408,18 +18513,18 @@ var ts;
token() === 30 /* GreaterThanToken */ ||
token() === 59 /* EqualsToken */ ||
token() === 50 /* BarToken */) {
- var result = createNode(285 /* JSDocUnknownType */, pos);
+ var result = createNode(290 /* JSDocUnknownType */, pos);
return finishNode(result);
}
else {
- var result = createNode(286 /* JSDocNullableType */, pos);
+ var result = createNode(291 /* JSDocNullableType */, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(289 /* JSDocFunctionType */);
+ var result = createNodeWithJSDoc(294 /* JSDocFunctionType */);
nextToken();
fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
return finishNode(result);
@@ -18443,12 +18548,12 @@ var ts;
var type = parseTypeOrTypePredicate();
scanner.setInJSDocType(false);
if (dotdotdot) {
- var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos);
+ var variadic = createNode(295 /* JSDocVariadicType */, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 59 /* EqualsToken */) {
- return createPostfixType(288 /* JSDocOptionalType */, type);
+ return createPostfixType(293 /* JSDocOptionalType */, type);
}
return type;
}
@@ -18820,7 +18925,7 @@ var ts;
return finishNode(node);
}
var type = parseType();
- if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) {
+ if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 291 /* JSDocNullableType */ && type.pos === type.type.pos) {
type.kind = 171 /* OptionalType */;
}
return type;
@@ -19007,14 +19112,14 @@ var ts;
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 52 /* ExclamationToken */:
- type = createPostfixType(287 /* JSDocNonNullableType */, type);
+ type = createPostfixType(292 /* JSDocNonNullableType */, type);
break;
case 56 /* QuestionToken */:
// If not in JSDoc and next token is start of a type we have a conditional type
if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
return type;
}
- type = createPostfixType(286 /* JSDocNullableType */, type);
+ type = createPostfixType(291 /* JSDocNullableType */, type);
break;
case 22 /* OpenBracketToken */:
parseExpected(22 /* OpenBracketToken */);
@@ -21951,7 +22056,7 @@ var ts;
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
// Parses out a JSDoc type expression.
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(283 /* JSDocTypeExpression */);
+ var result = createNode(288 /* JSDocTypeExpression */);
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -22114,7 +22219,7 @@ var ts;
}
}
function createJSDocComment() {
- var result = createNode(291 /* JSDocComment */, start);
+ var result = createNode(296 /* JSDocComment */, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
@@ -22281,7 +22386,7 @@ var ts;
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(start, tagName) {
- var result = createNode(294 /* JSDocTag */, start);
+ var result = createNode(299 /* JSDocTag */, start);
result.tagName = tagName;
return finishNode(result);
}
@@ -22340,8 +22445,8 @@ var ts;
typeExpression = tryParseTypeExpression();
}
var result = target === 1 /* Property */ ?
- createNode(305 /* JSDocPropertyTag */, start) :
- createNode(299 /* JSDocParameterTag */, start);
+ createNode(310 /* JSDocPropertyTag */, start) :
+ createNode(304 /* JSDocParameterTag */, start);
var comment = parseTagComments(indent + scanner.getStartPos() - start);
var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
if (nestedTypeLiteral) {
@@ -22358,18 +22463,18 @@ var ts;
}
function parseNestedTypeLiteral(typeExpression, name, target, indent) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(288 /* JSDocTypeExpression */, scanner.getTokenPos());
var child = void 0;
var jsdocTypeLiteral = void 0;
var start_2 = scanner.getStartPos();
var children = void 0;
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
- if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) {
+ if (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 169 /* ArrayType */) {
jsdocTypeLiteral.isArrayType = true;
@@ -22380,25 +22485,25 @@ var ts;
}
}
function parseReturnTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 305 /* JSDocReturnTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(300 /* JSDocReturnTag */, start);
+ var result = createNode(305 /* JSDocReturnTag */, start);
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 307 /* JSDocTypeTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(302 /* JSDocTypeTag */, start);
+ var result = createNode(307 /* JSDocTypeTag */, start);
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
return finishNode(result);
}
function parseAugmentsTag(start, tagName) {
- var result = createNode(295 /* JSDocAugmentsTag */, start);
+ var result = createNode(300 /* JSDocAugmentsTag */, start);
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
return finishNode(result);
@@ -22425,19 +22530,19 @@ var ts;
return node;
}
function parseClassTag(start, tagName) {
- var tag = createNode(296 /* JSDocClassTag */, start);
+ var tag = createNode(301 /* JSDocClassTag */, start);
tag.tagName = tagName;
return finishNode(tag);
}
function parseThisTag(start, tagName) {
- var tag = createNode(301 /* JSDocThisTag */, start);
+ var tag = createNode(306 /* JSDocThisTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
return finishNode(tag);
}
function parseEnumTag(start, tagName) {
- var tag = createNode(298 /* JSDocEnumTag */, start);
+ var tag = createNode(303 /* JSDocEnumTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
@@ -22446,7 +22551,7 @@ var ts;
function parseTypedefTag(start, tagName, indent) {
var typeExpression = tryParseTypeExpression();
skipWhitespaceOrAsterisk();
- var typedefTag = createNode(304 /* JSDocTypedefTag */, start);
+ var typedefTag = createNode(309 /* JSDocTypedefTag */, start);
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace();
typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
@@ -22460,9 +22565,9 @@ var ts;
var childTypeTag = void 0;
while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start);
}
- if (child.kind === 302 /* JSDocTypeTag */) {
+ if (child.kind === 307 /* JSDocTypeTag */) {
if (childTypeTag) {
break;
}
@@ -22508,14 +22613,14 @@ var ts;
return typeNameOrNamespaceName;
}
function parseCallbackTag(start, tagName, indent) {
- var callbackTag = createNode(297 /* JSDocCallbackTag */, start);
+ var callbackTag = createNode(302 /* JSDocCallbackTag */, start);
callbackTag.tagName = tagName;
callbackTag.fullName = parseJSDocTypeNameWithNamespace();
callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
skipWhitespace();
callbackTag.comment = parseTagComments(indent);
var child;
- var jsdocSignature = createNode(293 /* JSDocSignature */, start);
+ var jsdocSignature = createNode(298 /* JSDocSignature */, start);
jsdocSignature.parameters = [];
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
@@ -22523,7 +22628,7 @@ var ts;
var returnTag = tryParse(function () {
if (parseOptionalJsdoc(58 /* AtToken */)) {
var tag = parseTag(indent);
- if (tag && tag.kind === 300 /* JSDocReturnTag */) {
+ if (tag && tag.kind === 305 /* JSDocReturnTag */) {
return tag;
}
}
@@ -22568,7 +22673,7 @@ var ts;
case 58 /* AtToken */:
if (canParseTag) {
var child = tryParseChildTag(target, indent);
- if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) &&
+ if (child && (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) &&
target !== 4 /* CallbackParameter */ &&
name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
@@ -22638,7 +22743,7 @@ var ts;
skipWhitespace();
typeParameters.push(typeParameter);
} while (parseOptionalJsdoc(27 /* CommaToken */));
- var result = createNode(303 /* JSDocTemplateTag */, start);
+ var result = createNode(308 /* JSDocTemplateTag */, start);
result.tagName = tagName;
result.constraint = constraint;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -23724,6 +23829,22 @@ var ts;
category: ts.Diagnostics.Basic_Options,
description: ts.Diagnostics.Enable_project_compilation,
},
+ {
+ name: "incremental",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_incremental_compilation,
+ },
+ {
+ name: "tsBuildInfoFile",
+ type: "string",
+ isFilePath: true,
+ paramType: ts.Diagnostics.FILE,
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
+ },
{
name: "removeComments",
type: "boolean",
@@ -27442,7 +27563,7 @@ var ts;
return "__constructor" /* Constructor */;
case 165 /* FunctionType */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return "__call" /* Call */;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
@@ -27451,7 +27572,7 @@ var ts;
return "__index" /* Index */;
case 255 /* ExportDeclaration */:
return "__export" /* ExportStar */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// json file should behave as
// module.exports = ...
return "export=" /* ExportEquals */;
@@ -27462,12 +27583,12 @@ var ts;
}
ts.Debug.fail("Unknown binary declaration kind");
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
case 151 /* Parameter */:
// Parameters with names are handled at the top of this function. Parameters
// without names can only come from JSDocFunctionTypes.
- ts.Debug.assert(node.parent.kind === 289 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
+ ts.Debug.assert(node.parent.kind === 294 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
var functionType = node.parent;
var index = functionType.parameters.indexOf(node);
return "arg" + index;
@@ -27706,7 +27827,7 @@ var ts;
if (hasExplicitReturn)
node.flags |= 256 /* HasExplicitReturn */;
}
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
node.flags |= emitFlags;
}
if (currentReturnTarget) {
@@ -27850,12 +27971,12 @@ var ts;
case 191 /* CallExpression */:
bindCallExpressionFlow(node);
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
bindJSDocTypeAlias(node);
break;
// In source files and blocks, bind functions first to match hoisting that occurs at runtime
- case 279 /* SourceFile */: {
+ case 284 /* SourceFile */: {
bindEachFunctionsFirst(node.statements);
bind(node.endOfFileToken);
break;
@@ -28542,7 +28663,7 @@ var ts;
case 243 /* EnumDeclaration */:
case 188 /* ObjectLiteralExpression */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 268 /* JsxAttributes */:
return 1 /* IsContainer */;
case 241 /* InterfaceDeclaration */:
@@ -28551,7 +28672,7 @@ var ts;
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
return 1 /* IsContainer */ | 32 /* HasLocals */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
case 156 /* MethodDeclaration */:
if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
@@ -28564,8 +28685,8 @@ var ts;
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
- case 289 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
case 165 /* FunctionType */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
@@ -28619,7 +28740,7 @@ var ts;
// handlers to take care of declaring these child members.
case 244 /* ModuleDeclaration */:
return declareModuleMember(node, symbolFlags, symbolExcludes);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return declareSourceFileMember(node, symbolFlags, symbolExcludes);
case 209 /* ClassExpression */:
case 240 /* ClassDeclaration */:
@@ -28627,7 +28748,7 @@ var ts;
case 243 /* EnumDeclaration */:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 188 /* ObjectLiteralExpression */:
case 241 /* InterfaceDeclaration */:
case 268 /* JsxAttributes */:
@@ -28641,7 +28762,7 @@ var ts;
case 166 /* ConstructorType */:
case 160 /* CallSignature */:
case 161 /* ConstructSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 162 /* IndexSignature */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
@@ -28651,9 +28772,9 @@ var ts;
case 239 /* FunctionDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
- case 289 /* JSDocFunctionType */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 294 /* JSDocFunctionType */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
// All the children of these container types are never visible through another
@@ -28676,8 +28797,8 @@ var ts;
: declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
function hasExportDeclarations(node) {
- var body = node.kind === 279 /* SourceFile */ ? node : node.body;
- if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
+ var body = node.kind === 284 /* SourceFile */ ? node : node.body;
+ if (body && (body.kind === 284 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
var stat = _a[_i];
if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) {
@@ -28811,7 +28932,7 @@ var ts;
case 244 /* ModuleDeclaration */:
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalOrCommonJsModule(container)) {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
@@ -28949,7 +29070,7 @@ var ts;
function checkStrictModeFunctionDeclaration(node) {
if (languageVersion < 2 /* ES2015 */) {
// Report error if function is not top level function declaration
- if (blockScopeContainer.kind !== 279 /* SourceFile */ &&
+ if (blockScopeContainer.kind !== 284 /* SourceFile */ &&
blockScopeContainer.kind !== 244 /* ModuleDeclaration */ &&
!ts.isFunctionLike(blockScopeContainer)) {
// We check first if the name is inside class declaration or class expression; if so give explicit message
@@ -29224,12 +29345,12 @@ var ts;
case 159 /* SetAccessor */:
return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */);
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
case 166 /* ConstructorType */:
return bindFunctionOrConstructorType(node);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 181 /* MappedType */:
return bindAnonymousTypeWorker(node);
case 188 /* ObjectLiteralExpression */:
@@ -29288,7 +29409,7 @@ var ts;
return bindExportDeclaration(node);
case 254 /* ExportAssignment */:
return bindExportAssignment(node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
updateStrictModeStatementList(node.statements);
return bindSourceFileIfExternalModule();
case 218 /* Block */:
@@ -29298,22 +29419,22 @@ var ts;
// falls through
case 245 /* ModuleBlock */:
return updateStrictModeStatementList(node.statements);
- case 299 /* JSDocParameterTag */:
- if (node.parent.kind === 293 /* JSDocSignature */) {
+ case 304 /* JSDocParameterTag */:
+ if (node.parent.kind === 298 /* JSDocSignature */) {
return bindParameter(node);
}
- if (node.parent.kind !== 292 /* JSDocTypeLiteral */) {
+ if (node.parent.kind !== 297 /* JSDocTypeLiteral */) {
break;
}
// falls through
- case 305 /* JSDocPropertyTag */:
+ case 310 /* JSDocPropertyTag */:
var propTag = node;
- var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ?
+ var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 293 /* JSDocOptionalType */ ?
4 /* Property */ | 16777216 /* Optional */ :
4 /* Property */;
return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
}
}
@@ -29485,7 +29606,7 @@ var ts;
var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
if (thisContainer.commonJsModuleIndicator) {
declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
@@ -29502,7 +29623,7 @@ var ts;
if (node.expression.kind === 100 /* ThisKeyword */) {
bindThisPropertyAssignment(node);
}
- else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) {
+ else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 284 /* SourceFile */) {
if (ts.isPrototypeAccess(node.expression)) {
bindPrototypePropertyAssignment(node, node.parent);
}
@@ -29539,7 +29660,7 @@ var ts;
}
function bindObjectDefinePropertyAssignment(node) {
var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
- var isToplevel = node.parent.parent.kind === 279 /* SourceFile */;
+ var isToplevel = node.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false);
bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
}
@@ -29606,8 +29727,8 @@ var ts;
function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) {
var namespaceSymbol = lookupSymbolForPropertyAccess(name);
var isToplevel = ts.isBinaryExpression(propertyAccess.parent)
- ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */
- : propertyAccess.parent.parent.kind === 279 /* SourceFile */;
+ ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 284 /* SourceFile */
+ : propertyAccess.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty);
bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
}
@@ -29745,7 +29866,7 @@ var ts;
}
}
function bindParameter(node) {
- if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) {
+ if (node.kind === 304 /* JSDocParameterTag */ && container.kind !== 298 /* JSDocSignature */) {
return;
}
if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) {
@@ -30488,7 +30609,7 @@ var ts;
break;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
// These nodes are TypeScript syntax.
transformFlags |= 3 /* AssertTypeScript */;
excludeFlags = 536872257 /* OuterExpressionExcludes */;
@@ -30689,7 +30810,7 @@ var ts;
transformFlags |= 192 /* AssertES2015 */;
}
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) {
transformFlags |= 192 /* AssertES2015 */;
}
@@ -30769,7 +30890,7 @@ var ts;
return 637666625 /* BindingPatternExcludes */;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
case 195 /* ParenthesizedExpression */:
case 98 /* SuperKeyword */:
return 536872257 /* OuterExpressionExcludes */;
@@ -31180,10 +31301,10 @@ var ts;
isContextSensitive: isContextSensitive,
getFullyQualifiedName: getFullyQualifiedName,
getResolvedSignature: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 0 /* Normal */);
},
getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16 /* IsForSignatureHelp */);
},
getConstantValue: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
@@ -31310,10 +31431,10 @@ var ts;
},
getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
};
- function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) {
+ function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
apparentArgumentCount = argumentCount;
- var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined;
+ var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
apparentArgumentCount = undefined;
return res;
}
@@ -31588,9 +31709,11 @@ var ts;
var CheckMode;
(function (CheckMode) {
CheckMode[CheckMode["Normal"] = 0] = "Normal";
- CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive";
+ CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
- CheckMode[CheckMode["Contextual"] = 3] = "Contextual";
+ CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
+ CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
+ CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
})(CheckMode || (CheckMode = {}));
var CallbackCheck;
(function (CallbackCheck) {
@@ -31946,7 +32069,7 @@ var ts;
return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 });
}
function isGlobalSourceFile(node) {
- return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
+ return node.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
}
function getSymbol(symbols, name, meaning) {
if (meaning) {
@@ -32120,7 +32243,7 @@ var ts;
// - parameters are only in the scope of function body
// This restriction does not apply to JSDoc comment types because they are parented
// at a higher level than type parameters would normally be
- if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) {
+ if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 296 /* JSDocComment */) {
useResult = result.flags & 262144 /* TypeParameter */
// type parameters are visible in parameter list, return type and type parameter list
? lastLocation === location.type ||
@@ -32162,14 +32285,14 @@ var ts;
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
isInExternalModule = true;
// falls through
case 244 /* ModuleDeclaration */:
var moduleExports = getSymbolOfNode(location).exports;
- if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) {
+ if (location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location)) {
// It's an external module. First see if the module has an export default and if the local
// name of that export default matches.
if (result = moduleExports.get("default" /* Default */)) {
@@ -32341,8 +32464,8 @@ var ts;
location = location.parent;
}
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
// js type aliases do not resolve names from their host, so skip past it
location = ts.getJSDocHost(location);
break;
@@ -32361,7 +32484,7 @@ var ts;
}
if (!result) {
if (lastLocation) {
- ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */);
+ ts.Debug.assert(lastLocation.kind === 284 /* SourceFile */);
if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
return lastLocation.symbol;
}
@@ -33217,7 +33340,7 @@ var ts;
function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) {
var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
if (!dontResolveAlias && symbol) {
- if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) {
+ if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 284 /* SourceFile */)) {
var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
? "allowSyntheticDefaultImports"
: "esModuleInterop";
@@ -33568,7 +33691,7 @@ var ts;
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
@@ -33808,10 +33931,10 @@ var ts;
return node && getSymbolOfNode(node);
}
function hasExternalModuleSymbol(declaration) {
- return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isAmbientModule(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
- return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
var aliasesToMakeVisible;
@@ -34268,7 +34391,7 @@ var ts;
var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
(symbol.parent || // is exported function symbol
ts.forEach(symbol.declarations, function (declaration) {
- return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
+ return declaration.parent.kind === 284 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
}));
if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
// typeof is allowed only for static/non local functions
@@ -34634,7 +34757,7 @@ var ts;
var savedContextFlags = context.flags;
context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
- type.symbol.declarations[0] &&
+ type.symbol.declarations && type.symbol.declarations[0] &&
ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
typeParameterShadowsNameInScope(type, context);
var name = shouldUseGeneratedName
@@ -34653,7 +34776,7 @@ var ts;
function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */);
if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) {
- parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */);
+ parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 304 /* JSDocParameterTag */);
}
var parameterType = getTypeOfSymbol(parameterSymbol);
if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
@@ -34811,7 +34934,7 @@ var ts;
return top;
}
function getSpecifierForModuleSymbol(symbol, context) {
- var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */);
+ var file = ts.getDeclarationOfKind(symbol, 284 /* SourceFile */);
if (file && file.moduleName !== undefined) {
// Use the amd name if it is available
return file.moduleName;
@@ -35064,7 +35187,7 @@ var ts;
ts.isExternalModuleAugmentation(node.parent.parent);
}
function isDefaultBindingContext(location) {
- return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location);
+ return location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location);
}
function getNameOfSymbolFromNameType(symbol, context) {
var nameType = symbol.nameType;
@@ -35141,8 +35264,8 @@ var ts;
return false;
function determineIfDeclarationIsVisible() {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
// Top-level jsdoc type aliases are considered exported
// First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file
return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
@@ -35169,7 +35292,7 @@ var ts;
var parent = getDeclarationContainer(node);
// If the node is not exported or it is not ambient module element (except import declaration)
if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
- !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
+ !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 284 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
return isGlobalSourceFile(parent);
}
// Exported members/ambient module elements (exception import declaration) are visible if parent is visible
@@ -35211,7 +35334,7 @@ var ts;
// Type parameters are always visible
case 150 /* TypeParameter */:
// Source file and namespace export are always visible
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 247 /* NamespaceExportDeclaration */:
return true;
// Export assignments do not create name bindings outside the module
@@ -36321,15 +36444,15 @@ var ts;
case 155 /* MethodSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 308 /* JSDocTemplateTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 181 /* MappedType */:
case 175 /* ConditionalType */:
var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
@@ -38321,10 +38444,10 @@ var ts;
function isJSDocOptionalParameter(node) {
return ts.isInJSFile(node) && (
// node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
- node.type && node.type.kind === 288 /* JSDocOptionalType */
+ node.type && node.type.kind === 293 /* JSDocOptionalType */
|| ts.getJSDocParameterTags(node).some(function (_a) {
var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}));
}
function tryFindAmbientModule(moduleName, withAugmentations) {
@@ -38358,7 +38481,7 @@ var ts;
return false;
}
var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}
function createIdentifierTypePredicate(parameterName, parameterIndex, type) {
return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
@@ -38689,8 +38812,21 @@ var ts;
}
return undefined;
}
- function getSignatureInstantiation(signature, typeArguments, isJavascript) {
- return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ if (inferredTypeParameters) {
+ var returnSignature = getSingleCallSignature(getReturnTypeOfSignature(instantiatedSignature));
+ if (returnSignature) {
+ var newReturnSignature = cloneSignature(returnSignature);
+ newReturnSignature.typeParameters = inferredTypeParameters;
+ newReturnSignature.target = returnSignature.target;
+ newReturnSignature.mapper = returnSignature.mapper;
+ var newInstantiatedSignature = cloneSignature(instantiatedSignature);
+ newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
+ return newInstantiatedSignature;
+ }
+ }
+ return instantiatedSignature;
}
function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
@@ -39062,7 +39198,7 @@ var ts;
}
function getTypeReferenceTypeWorker(node, symbol, typeArguments) {
if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
- if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
+ if (symbol.valueDeclaration && symbol.valueDeclaration.parent && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
var jsdocType = getJSDocTypeReference(node, symbol, typeArguments);
if (jsdocType) {
return jsdocType;
@@ -39098,7 +39234,7 @@ var ts;
}
function getConstrainedTypeVariable(typeVariable, node) {
var constraints;
- while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) {
+ while (node && !ts.isStatement(node) && node.kind !== 296 /* JSDocComment */) {
var parent = node.parent;
if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) {
var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType);
@@ -40671,8 +40807,8 @@ var ts;
function getTypeFromTypeNode(node) {
switch (node.kind) {
case 120 /* AnyKeyword */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return anyType;
case 143 /* UnknownKeyword */:
return unknownType;
@@ -40719,23 +40855,23 @@ var ts;
return getTypeFromUnionTypeNode(node);
case 174 /* IntersectionType */:
return getTypeFromIntersectionTypeNode(node);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return getTypeFromJSDocNullableTypeNode(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return addOptionality(getTypeFromTypeNode(node.type));
case 177 /* ParenthesizedType */:
case 172 /* RestType */:
- case 287 /* JSDocNonNullableType */:
- case 283 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 288 /* JSDocTypeExpression */:
return getTypeFromTypeNode(node.type);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return getTypeFromJSDocVariadicType(node);
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 297 /* JSDocTypeLiteral */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
case 179 /* TypeOperator */:
return getTypeFromTypeOperatorNode(node);
@@ -41673,7 +41809,7 @@ var ts;
return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation);
}
// recreate a tuple from the elements, if possible
- var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true);
+ var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
if (isTupleLikeType(tupleizedType)) {
return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation);
}
@@ -44096,7 +44232,7 @@ var ts;
return;
}
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
return;
case 239 /* FunctionDeclaration */:
@@ -46377,7 +46513,7 @@ var ts;
return ts.findAncestor(node.parent, function (node) {
return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
node.kind === 245 /* ModuleBlock */ ||
- node.kind === 279 /* SourceFile */ ||
+ node.kind === 284 /* SourceFile */ ||
node.kind === 154 /* PropertyDeclaration */;
});
}
@@ -46498,7 +46634,7 @@ var ts;
// to the constructor in the initializer, we will need to substitute that
// binding with an alias as the class name is not in scope.
var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
- while (container.kind !== 279 /* SourceFile */) {
+ while (container.kind !== 284 /* SourceFile */) {
if (container.parent === declaration) {
if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
@@ -46921,7 +47057,7 @@ var ts;
}
function getTypeForThisExpressionFromJSDoc(node) {
var jsdocType = ts.getJSDocType(node);
- if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) {
+ if (jsdocType && jsdocType.kind === 294 /* JSDocFunctionType */) {
var jsDocFunctionType = jsdocType;
if (jsDocFunctionType.parameters.length > 0 &&
jsDocFunctionType.parameters[0].name &&
@@ -49523,23 +49659,34 @@ var ts;
// Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) {
var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
- var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature;
+ // We clone the contextualMapper to avoid fixing. For example, when the source signature is (x: T) => T[] and
+ // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
+ // for T but leave it possible to later infer '[any]' back to A.
+ var restType = getEffectiveRestType(contextualSignature);
+ var mapper = contextualMapper && restType && restType.flags & 262144 /* TypeParameter */ ? cloneTypeMapper(contextualMapper) : contextualMapper;
+ var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
forEachMatchingParameterType(sourceSignature, signature, function (source, target) {
// Type parameters from outer context referenced by source type are fixed by instantiation of the source type
inferTypes(context.inferences, source, target);
});
if (!contextualMapper) {
inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */);
+ var signaturePredicate = getTypePredicateOfSignature(signature);
+ var contextualPredicate = getTypePredicateOfSignature(sourceSignature);
+ if (signaturePredicate && contextualPredicate && signaturePredicate.kind === contextualPredicate.kind &&
+ (signaturePredicate.kind === 0 /* This */ || signaturePredicate.parameterIndex === contextualPredicate.parameterIndex)) {
+ inferTypes(context.inferences, contextualPredicate.type, signaturePredicate.type, 8 /* ReturnType */);
+ }
}
return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
}
- function inferJsxTypeArguments(node, signature, excludeArgument, context) {
+ function inferJsxTypeArguments(node, signature, checkMode, context) {
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context);
+ var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
inferTypes(context.inferences, checkAttrType, paramType);
return getInferredTypes(context);
}
- function inferTypeArguments(node, signature, args, excludeArgument, context) {
+ function inferTypeArguments(node, signature, args, checkMode, context) {
// Clear out all the inference results from the last time inferTypeArguments was called on this context
for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) {
var inference = _a[_i];
@@ -49552,7 +49699,7 @@ var ts;
}
}
if (ts.isJsxOpeningLikeElement(node)) {
- return inferJsxTypeArguments(node, signature, excludeArgument, context);
+ return inferJsxTypeArguments(node, signature, checkMode, context);
}
// If a contextual type is available, infer from that type to the return type of the call expression. For
// example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression
@@ -49596,10 +49743,7 @@ var ts;
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- // For context sensitive arguments we pass the identityMapper, which is a signal to treat all
- // context sensitive function expressions as wildcards
- var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context;
- var argType = checkExpressionWithContextualType(arg, paramType, mapper);
+ var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
inferTypes(context.inferences, argType, paramType);
}
}
@@ -49623,7 +49767,7 @@ var ts;
// and the argument are ...x forms.
return arg.kind === 215 /* SyntheticExpression */ ?
createArrayType(arg.type) :
- getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context));
+ getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
}
}
var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType;
@@ -49631,7 +49775,7 @@ var ts;
var types = [];
var spreadIndex = -1;
for (var i = index; i < argCount; i++) {
- var argType = checkExpressionWithContextualType(args[i], contextualType, context);
+ var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
if (spreadIndex < 0 && isSpreadArgument(args[i])) {
spreadIndex = i - index;
}
@@ -49681,19 +49825,18 @@ var ts;
* @param node a JSX opening-like element we are trying to figure its call signature
* @param signature a candidate signature we are trying whether it is a call signature
* @param relation a relationship to check parameter and argument type
- * @param excludeArgument
*/
- function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors) {
// Stateless function components can have maximum of three arguments: "props", "context", and "updater".
// However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
// can be specified by users through attributes property.
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined);
+ var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined, checkMode);
return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes);
}
- function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignature(node, args, signature, relation, checkMode, reportErrors) {
if (ts.isJsxOpeningLikeElement(node)) {
- return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors);
+ return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors);
}
var thisType = getThisTypeOfSignature(signature);
if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) {
@@ -49715,11 +49858,11 @@ var ts;
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined);
- // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter),
+ var argType = checkExpressionWithContextualType(arg, paramType, /*contextualMapper*/ undefined, checkMode);
+ // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
// we obtain the regular type of any object literal arguments because we may not have inferred complete
// parameter types yet and therefore excess property checks may yield false positives (see #17041).
- var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType;
+ var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) {
return false;
}
@@ -49924,7 +50067,7 @@ var ts;
}
return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
}
- function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) {
+ function resolveCall(node, signatures, candidatesOutArray, checkMode, fallbackError) {
var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */;
var isDecorator = node.kind === 152 /* Decorator */;
var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
@@ -49960,7 +50103,7 @@ var ts;
// For a decorator, no arguments are susceptible to contextual typing due to the fact
// decorators are applied to a declaration by the emitter, and not to an expression.
var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
- var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined;
+ var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
// The following variables are captured and modified by calls to chooseOverload.
// If overload resolution or type argument inference fails, we want to report the
// best error possible. The best error is one which says that an argument was not
@@ -49988,7 +50131,7 @@ var ts;
var result;
// If we are in signature help, a trailing comma indicates that we intend to provide another argument,
// so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
- var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma;
+ var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma;
// Section 4.12.1:
// if the candidate list contains one or more signatures for which the type of each argument
// expression is a subtype of each corresponding parameter type, the return type of the first
@@ -50014,12 +50157,7 @@ var ts;
// skip the checkApplicableSignature check.
if (reportErrors) {
if (candidateForArgumentError) {
- // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...]
- // The importance of excludeArgument is to prevent us from typing function expression parameters
- // in arguments too early. If possible, we'd like to only type them once we know the correct
- // overload. However, this matters for the case where the call is correct. When the call is
- // an error, we don't need to exclude any arguments, although it would cause no harm to do so.
- checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true);
+ checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, 0 /* Normal */, /*reportErrors*/ true);
}
else if (candidateForArgumentArityError) {
diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
@@ -50051,7 +50189,7 @@ var ts;
if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
return undefined;
}
- if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false)) {
candidateForArgumentError = candidate;
return undefined;
}
@@ -50075,9 +50213,10 @@ var ts;
}
else {
inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
+ typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
+ argCheckMode |= inferenceContext.flags & 8 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
}
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// If the original signature has a generic rest type, instantiation may produce a
// signature with different arity and we need to perform another arity check.
if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -50088,21 +50227,21 @@ var ts;
else {
checkCandidate = candidate;
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
}
continue;
}
- if (excludeArgument) {
+ if (argCheckMode) {
// If one or more context sensitive arguments were excluded, we start including
// them now (and keeping do so for any subsequent candidates) and perform a second
// round of type inference and applicability checking for this particular candidate.
- excludeArgument = undefined;
+ argCheckMode = 0 /* Normal */;
if (inferenceContext) {
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// If the original signature has a generic rest type, instantiation may produce a
// signature with different arity and we need to perform another arity check.
if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -50110,7 +50249,7 @@ var ts;
continue;
}
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
@@ -50124,20 +50263,6 @@ var ts;
return undefined;
}
}
- function getExcludeArgument(args) {
- var excludeArgument;
- // We do not need to call `getEffectiveArgumentCount` here as it only
- // applies when calculating the number of arguments for a decorator.
- for (var i = 0; i < args.length; i++) {
- if (isContextSensitive(args[i])) {
- if (!excludeArgument) {
- excludeArgument = new Array(args.length);
- }
- excludeArgument[i] = true;
- }
- }
- return excludeArgument;
- }
// No signature was applicable. We have already reported the errors for the invalid signature.
// If this is a type resolution session, e.g. Language Service, try to get better information than anySignature.
function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
@@ -50226,7 +50351,7 @@ var ts;
}
function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext);
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
return createSignatureInstantiation(candidate, typeArgumentTypes);
}
function getLongestCandidateIndex(candidates, argsCount) {
@@ -50245,7 +50370,7 @@ var ts;
}
return maxParamsIndex;
}
- function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveCallExpression(node, candidatesOutArray, checkMode) {
if (node.expression.kind === 98 /* SuperKeyword */) {
var superType = checkSuperExpression(node.expression);
if (isTypeAny(superType)) {
@@ -50261,7 +50386,7 @@ var ts;
var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
if (baseTypeNode) {
var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
- return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, baseConstructors, candidatesOutArray, checkMode);
}
}
return resolveUntypedCall(node);
@@ -50311,12 +50436,31 @@ var ts;
}
return resolveErrorCall(node);
}
+ // When a call to a generic function is an argument to an outer call to a generic function for which
+ // inference is in process, we have a choice to make. If the inner call relies on inferences made from
+ // its contextual type to its return type, deferring the inner call processing allows the best possible
+ // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
+ // the inner call, the inner call should be processed early. There's no sure way to know which choice is
+ // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
+ // If no type arguments are specified in the inner call and at least one call signature is generic and
+ // returns a function type, we choose to defer processing. This narrowly permits function composition
+ // operators to flow inferences through return types, but otherwise processes calls right away. We
+ // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
+ // propagated out and eventually turned into silentNeverType (a type that is assignable to anything and
+ // from which we never make inferences).
+ if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
+ skippedGenericFunction(node, checkMode);
+ return resolvingSignature;
+ }
// If the function is explicitly marked with `@class`, then it must be constructed.
if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
+ }
+ function isGenericFunctionReturningFunction(signature) {
+ return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
}
/**
* TS 1.0 spec: 4.12
@@ -50328,7 +50472,7 @@ var ts;
return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
!numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
}
- function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveNewExpression(node, candidatesOutArray, checkMode) {
if (node.arguments && languageVersion < 1 /* ES5 */) {
var spreadIndex = getSpreadArgumentIndex(node.arguments);
if (spreadIndex >= 0) {
@@ -50376,7 +50520,7 @@ var ts;
error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
return resolveErrorCall(node);
}
- return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, constructSignatures, candidatesOutArray, checkMode);
}
// If expressionType's apparent type is an object type with no construct signatures but
// one or more call signatures, the expression is processed as a function call. A compile-time
@@ -50384,7 +50528,7 @@ var ts;
// operation is Any. It is an error to have a Void this type.
var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
if (callSignatures.length) {
- var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode);
if (!noImplicitAny) {
if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
@@ -50481,7 +50625,7 @@ var ts;
addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead));
}
}
- function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
var tagType = checkExpression(node.tag);
var apparentType = getApparentType(tagType);
if (apparentType === errorType) {
@@ -50497,7 +50641,7 @@ var ts;
invocationError(node, apparentType, 0 /* Call */);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
}
/**
* Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
@@ -50522,7 +50666,7 @@ var ts;
/**
* Resolves a decorator as if it were a call expression.
*/
- function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveDecorator(node, candidatesOutArray, checkMode) {
var funcType = checkExpression(node.expression);
var apparentType = getApparentType(funcType);
if (apparentType === errorType) {
@@ -50547,7 +50691,7 @@ var ts;
invocationErrorRecovery(apparentType, 0 /* Call */, diag);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode, headMessage);
}
function createSignatureForJSXIntrinsic(node, result) {
var namespace = getJsxNamespaceAt(node);
@@ -50566,11 +50710,11 @@ var ts;
/*hasRestparameter*/ false,
/*hasLiteralTypes*/ false);
}
- function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
if (isJsxIntrinsicIdentifier(node.tagName)) {
var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
var fakeSignature = createSignatureForJSXIntrinsic(node, result);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes);
+ checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
return fakeSignature;
}
var exprTypes = checkExpression(node.tagName);
@@ -50587,7 +50731,7 @@ var ts;
error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
return resolveErrorCall(node);
}
- return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, signatures, candidatesOutArray, checkMode);
}
/**
* Sometimes, we have a decorator that could accept zero arguments,
@@ -50601,19 +50745,19 @@ var ts;
signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
});
}
- function resolveSignature(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveSignature(node, candidatesOutArray, checkMode) {
switch (node.kind) {
case 191 /* CallExpression */:
- return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveCallExpression(node, candidatesOutArray, checkMode);
case 192 /* NewExpression */:
- return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveNewExpression(node, candidatesOutArray, checkMode);
case 193 /* TaggedTemplateExpression */:
- return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
case 152 /* Decorator */:
- return resolveDecorator(node, candidatesOutArray, isForSignatureHelp);
+ return resolveDecorator(node, candidatesOutArray, checkMode);
case 262 /* JsxOpeningElement */:
case 261 /* JsxSelfClosingElement */:
- return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp);
+ return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
}
throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
}
@@ -50624,8 +50768,7 @@ var ts;
* the function will fill it up with appropriate candidate signatures
* @return a signature of the call-like expression or undefined if one can't be found
*/
- function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) {
- if (isForSignatureHelp === void 0) { isForSignatureHelp = false; }
+ function getResolvedSignature(node, candidatesOutArray, checkMode) {
var links = getNodeLinks(node);
// If getResolvedSignature has already been called, we will have cached the resolvedSignature.
// However, it is possible that either candidatesOutArray was not passed in the first time,
@@ -50636,11 +50779,15 @@ var ts;
return cached;
}
links.resolvedSignature = resolvingSignature;
- var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp);
- // If signature resolution originated in control flow type analysis (for example to compute the
- // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
- // types from the control flow analysis.
- links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
+ // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
+ // resolution should be deferred.
+ if (result !== resolvingSignature) {
+ // If signature resolution originated in control flow type analysis (for example to compute the
+ // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
+ // types from the control flow analysis.
+ links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ }
return result;
}
/**
@@ -50716,10 +50863,15 @@ var ts;
* @param node The call/new expression to be checked.
* @returns On success, the expression's signature's return type. On failure, anyType.
*/
- function checkCallExpression(node) {
+ function checkCallExpression(node, checkMode) {
if (!checkGrammarTypeArguments(node, node.typeArguments))
checkGrammarArguments(node.arguments);
- var signature = getResolvedSignature(node);
+ var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
+ if (signature === resolvingSignature) {
+ // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
+ // returns a function type. We defer checking and return anyFunctionType.
+ return silentNeverType;
+ }
if (node.expression.kind === 98 /* SuperKeyword */) {
return voidType;
}
@@ -50963,7 +51115,7 @@ var ts;
if (isTupleType(restType)) {
var associatedNames = restType.target.associatedNames;
var index = pos - paramCount;
- return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index;
+ return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
}
return restParameter.escapedName;
}
@@ -51171,7 +51323,7 @@ var ts;
var functionFlags = ts.getFunctionFlags(func);
var type;
if (func.body.kind !== 218 /* Block */) {
- type = checkExpressionCached(func.body, checkMode);
+ type = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -51349,7 +51501,7 @@ var ts;
ts.forEachReturnStatement(func.body, function (returnStatement) {
var expr = returnStatement.expression;
if (expr) {
- var type = checkExpressionCached(expr, checkMode);
+ var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -51442,7 +51594,7 @@ var ts;
ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
checkNodeDeferred(node);
// The identityMapper object is used to indicate that function expressions are wildcards
- if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) {
+ if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
// Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) {
var links_1 = getNodeLinks(node);
@@ -51479,7 +51631,7 @@ var ts;
var signature = getSignaturesOfType(type, 0 /* Call */)[0];
if (isContextSensitive(node)) {
var contextualMapper = getContextualMapper(node);
- if (checkMode === 2 /* Inferential */) {
+ if (checkMode && checkMode & 2 /* Inferential */) {
inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper);
}
var instantiatedContextualSignature = contextualMapper === identityMapper ?
@@ -52401,15 +52553,13 @@ var ts;
}
return node;
}
- function checkExpressionWithContextualType(node, contextualType, contextualMapper) {
+ function checkExpressionWithContextualType(node, contextualType, contextualMapper, checkMode) {
var context = getContextNode(node);
var saveContextualType = context.contextualType;
var saveContextualMapper = context.contextualMapper;
context.contextualType = contextualType;
context.contextualMapper = contextualMapper;
- var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ :
- contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */;
- var type = checkExpression(node, checkMode);
+ var type = checkExpression(node, checkMode | 1 /* Contextual */ | (contextualMapper ? 2 /* Inferential */ : 0));
// We strip literal freshness when an appropriate contextual type is present such that contextually typed
// literals always preserve their literal types (otherwise they might widen during type inference). An alternative
// here would be to not mark contextually typed literals as fresh in the first place.
@@ -52422,7 +52572,7 @@ var ts;
function checkExpressionCached(node, checkMode) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- if (checkMode) {
+ if (checkMode && checkMode !== 0 /* Normal */) {
return checkExpression(node, checkMode);
}
// When computing a type that we're going to cache, we need to ignore any ongoing control flow
@@ -52519,20 +52669,122 @@ var ts;
return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
}
function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
- if (checkMode === 2 /* Inferential */) {
+ if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
var signature = getSingleCallSignature(type);
if (signature && signature.typeParameters) {
+ if (checkMode & 8 /* SkipGenericFunctions */) {
+ skippedGenericFunction(node, checkMode);
+ return anyFunctionType;
+ }
var contextualType = getApparentTypeOfContextualType(node);
if (contextualType) {
var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType));
if (contextualSignature && !contextualSignature.typeParameters) {
- return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node)));
+ var context = getContextualMapper(node);
+ // We have an expression that is an argument of a generic function for which we are performing
+ // type argument inference. The expression is of a function type with a single generic call
+ // signature and a contextual function type with a single non-generic call signature. Now check
+ // if the outer function returns a function type with a single non-generic call signature and
+ // if some of the outer function type parameters have no inferences so far. If so, we can
+ // potentially add inferred type parameters to the outer function return type.
+ var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature));
+ if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
+ // Instantiate the expression type with its own type parameters as type arguments. This
+ // ensures that the type parameters are not erased to type any during type inference such
+ // that they can be inferred as actual types.
+ var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
+ var strippedType = getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters));
+ // Infer from the stripped expression type to the contextual type starting with an empty
+ // set of inference candidates.
+ var inferences = ts.map(context.typeParameters, createInferenceInfo);
+ inferTypes(inferences, strippedType, contextualType);
+ // If we produced some inference candidates and if the type parameters for which we produced
+ // candidates do not already have existing inferences, we adopt the new inference candidates and
+ // add the type parameters of the expression type to the set of inferred type parameters for
+ // the outer function return type.
+ if (ts.some(inferences, hasInferenceCandidates) && !hasOverlappingInferences(context.inferences, inferences)) {
+ mergeInferences(context.inferences, inferences);
+ context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
+ return strippedType;
+ }
+ }
+ return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
}
}
}
}
return type;
}
+ function skippedGenericFunction(node, checkMode) {
+ if (checkMode & 2 /* Inferential */) {
+ // We have skipped a generic function during inferential typing. Obtain the inference context and
+ // indicate this has occurred such that we know a second pass of inference is be needed.
+ var context = getContextualMapper(node);
+ context.flags |= 8 /* SkippedGenericFunction */;
+ }
+ }
+ function hasInferenceCandidates(info) {
+ return !!(info.candidates || info.contraCandidates);
+ }
+ function hasOverlappingInferences(a, b) {
+ for (var i = 0; i < a.length; i++) {
+ if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
+ return true;
+ }
+ }
+ return false;
+ }
+ function mergeInferences(target, source) {
+ for (var i = 0; i < target.length; i++) {
+ if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
+ target[i] = source[i];
+ }
+ }
+ }
+ function getUniqueTypeParameters(context, typeParameters) {
+ var result = [];
+ var oldTypeParameters;
+ var newTypeParameters;
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var tp = typeParameters_2[_i];
+ var name = tp.symbol.escapedName;
+ if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
+ var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
+ var symbol = createSymbol(262144 /* TypeParameter */, newName);
+ var newTypeParameter = createTypeParameter(symbol);
+ newTypeParameter.target = tp;
+ oldTypeParameters = ts.append(oldTypeParameters, tp);
+ newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
+ result.push(newTypeParameter);
+ }
+ else {
+ result.push(tp);
+ }
+ }
+ if (newTypeParameters) {
+ var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
+ for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
+ var tp = newTypeParameters_1[_a];
+ tp.mapper = mapper;
+ }
+ }
+ return result;
+ }
+ function hasTypeParameterByName(typeParameters, name) {
+ return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
+ }
+ function getUniqueTypeParameterName(typeParameters, baseName) {
+ var len = baseName.length;
+ while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
+ len--;
+ var s = baseName.slice(0, len);
+ for (var index = 1; true; index++) {
+ var augmentedName = (s + index);
+ if (!hasTypeParameterByName(typeParameters, augmentedName)) {
+ return augmentedName;
+ }
+ }
+ }
/**
* Returns the type of an expression. Unlike checkExpression, this function is simply concerned
* with computing the type and may not fully check all contained sub-expressions for errors.
@@ -52572,7 +52824,7 @@ var ts;
}
var saveContextualType = node.contextualType;
node.contextualType = anyType;
- var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */);
+ var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
node.contextualType = saveContextualType;
return type;
}
@@ -52664,7 +52916,7 @@ var ts;
}
/* falls through */
case 192 /* NewExpression */:
- return checkCallExpression(node);
+ return checkCallExpression(node, checkMode);
case 193 /* TaggedTemplateExpression */:
return checkTaggedTemplateExpression(node);
case 195 /* ParenthesizedExpression */:
@@ -52923,7 +53175,7 @@ var ts;
checkAsyncFunctionReturnType(node, returnTypeNode);
}
}
- if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) {
+ if (node.kind !== 162 /* IndexSignature */ && node.kind !== 294 /* JSDocFunctionType */) {
registerForUnusedIdentifiersCheck(node);
}
}
@@ -53679,8 +53931,8 @@ var ts;
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
// A jsdoc typedef and callback are, by definition, type aliases
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return 2 /* ExportType */;
case 244 /* ModuleDeclaration */:
return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
@@ -53689,7 +53941,7 @@ var ts;
case 240 /* ClassDeclaration */:
case 243 /* EnumDeclaration */:
return 2 /* ExportType */ | 1 /* ExportValue */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
case 254 /* ExportAssignment */:
// Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
@@ -54330,7 +54582,7 @@ var ts;
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 244 /* ModuleDeclaration */:
case 218 /* Block */:
case 246 /* CaseBlock */:
@@ -54423,8 +54675,8 @@ var ts;
return;
var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
var seenParentsWithEveryUnused = new ts.NodeSet();
- for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
- var typeParameter = typeParameters_2[_i];
+ for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
+ var typeParameter = typeParameters_3[_i];
if (!isTypeParameterUnused(typeParameter))
continue;
var name = ts.idText(typeParameter.name);
@@ -54677,7 +54929,7 @@ var ts;
}
// In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
var parent = getDeclarationContainer(node);
- if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
+ if (parent.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
// If the declaration happens to be in external module, report error that require and exports are reserved keywords
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
@@ -54692,7 +54944,7 @@ var ts;
}
// In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
var parent = getDeclarationContainer(node);
- if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
+ if (parent.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
// If the declaration happens to be in external module, report error that Promise is a reserved identifier.
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
@@ -54749,7 +55001,7 @@ var ts;
(container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) ||
container.kind === 245 /* ModuleBlock */ ||
container.kind === 244 /* ModuleDeclaration */ ||
- container.kind === 279 /* SourceFile */);
+ container.kind === 284 /* SourceFile */);
// here we know that function scoped variable is shadowed by block scoped one
// if they are defined in the same scope - binder has already reported redeclaration error
// otherwise if variable has an initializer - show error that initialization will fail
@@ -56599,7 +56851,7 @@ var ts;
return false;
}
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule) {
error(moduleName, node.kind === 255 /* ExportDeclaration */ ?
ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
@@ -56730,7 +56982,7 @@ var ts;
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ &&
!node.moduleSpecifier && node.flags & 4194304 /* Ambient */;
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
}
}
@@ -56747,7 +56999,7 @@ var ts;
}
}
function checkGrammarModuleElementContext(node, errorMessage) {
- var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
+ var isInAppropriateContext = node.parent.kind === 284 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
if (!isInAppropriateContext) {
grammarErrorOnFirstToken(node, errorMessage);
}
@@ -56776,7 +57028,7 @@ var ts;
// If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
return;
}
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
if (node.isExportEquals) {
error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
@@ -56946,32 +57198,32 @@ var ts;
return checkInferType(node);
case 183 /* ImportType */:
return checkImportType(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return checkJSDocAugmentsTag(node);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return checkJSDocTypeAliasTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return checkJSDocTemplateTag(node);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return checkJSDocTypeTag(node);
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
return checkJSDocParameterTag(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
checkJSDocFunctionType(node);
// falls through
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
- case 292 /* JSDocTypeLiteral */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
+ case 297 /* JSDocTypeLiteral */:
checkJSDocTypeIsInJsFile(node);
ts.forEachChild(node, checkSourceElement);
return;
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
checkJSDocVariadicType(node);
return;
- case 283 /* JSDocTypeExpression */:
+ case 288 /* JSDocTypeExpression */:
return checkSourceElement(node.type);
case 180 /* IndexedAccessType */:
return checkIndexedAccessType(node);
@@ -57279,7 +57531,7 @@ var ts;
copySymbols(location.locals, meaning);
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
// falls through
@@ -57498,10 +57750,10 @@ var ts;
return entityNameSymbol;
}
}
- if (entityName.parent.kind === 299 /* JSDocParameterTag */) {
+ if (entityName.parent.kind === 304 /* JSDocParameterTag */) {
return ts.getParameterSymbolFromJSDoc(entityName.parent);
}
- if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) {
+ if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 308 /* JSDocTemplateTag */) {
ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true.
var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
return typeParameter && typeParameter.symbol;
@@ -57543,7 +57795,7 @@ var ts;
return undefined;
}
function getSymbolAtLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
}
var parent = node.parent;
@@ -57885,7 +58137,7 @@ var ts;
}
var parentSymbol_1 = getParentOfSymbol(symbol);
if (parentSymbol_1) {
- if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) {
+ if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 284 /* SourceFile */) {
var symbolFile = parentSymbol_1.valueDeclaration;
var referenceFile = ts.getSourceFileOfNode(node);
// If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
@@ -58000,7 +58252,7 @@ var ts;
}
function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
- if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
+ if (node === undefined || node.parent.kind !== 284 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
// parent is not source file or it is not reference to internal module
return false;
}
@@ -58429,7 +58681,7 @@ var ts;
break;
}
}
- if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
+ if (current.valueDeclaration && current.valueDeclaration.kind === 284 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
return false;
}
// check that at least one declaration of top level symbol originates from type declaration file
@@ -58462,7 +58714,7 @@ var ts;
if (!moduleSymbol) {
return undefined;
}
- return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */);
+ return ts.getDeclarationOfKind(moduleSymbol, 284 /* SourceFile */);
}
function initializeTypeChecker() {
// Bind all source files and propagate errors
@@ -58694,7 +58946,7 @@ var ts;
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
}
else if (flags & 128 /* Abstract */) {
@@ -58717,7 +58969,7 @@ var ts;
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
}
else if (node.kind === 151 /* Parameter */) {
@@ -58762,7 +59014,7 @@ var ts;
flags |= 1 /* Export */;
break;
case 80 /* DefaultKeyword */:
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
}
@@ -58885,7 +59137,7 @@ var ts;
case 151 /* Parameter */:
return false;
default:
- if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return false;
}
switch (node.kind) {
@@ -59808,7 +60060,7 @@ var ts;
// to prevent noisiness. So use a bit on the block to indicate if
// this has already been reported, and don't report if it has.
//
- if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
var links_2 = getNodeLinks(node.parent);
// Check if the containing block ever report this error
if (!links_2.hasReportedStatementInAmbientContext) {
@@ -61862,14 +62114,14 @@ var ts;
// JSDoc
/* @internal */
function createJSDocTypeExpression(type) {
- var node = createSynthesizedNode(283 /* JSDocTypeExpression */);
+ var node = createSynthesizedNode(288 /* JSDocTypeExpression */);
node.type = type;
return node;
}
ts.createJSDocTypeExpression = createJSDocTypeExpression;
/* @internal */
function createJSDocTypeTag(typeExpression, comment) {
- var tag = createJSDocTag(302 /* JSDocTypeTag */, "type");
+ var tag = createJSDocTag(307 /* JSDocTypeTag */, "type");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61877,7 +62129,7 @@ var ts;
ts.createJSDocTypeTag = createJSDocTypeTag;
/* @internal */
function createJSDocReturnTag(typeExpression, comment) {
- var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns");
+ var tag = createJSDocTag(305 /* JSDocReturnTag */, "returns");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61885,7 +62137,7 @@ var ts;
ts.createJSDocReturnTag = createJSDocReturnTag;
/* @internal */
function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
- var tag = createJSDocTag(299 /* JSDocParameterTag */, "param");
+ var tag = createJSDocTag(304 /* JSDocParameterTag */, "param");
tag.typeExpression = typeExpression;
tag.name = name;
tag.isBracketed = isBracketed;
@@ -61895,7 +62147,7 @@ var ts;
ts.createJSDocParamTag = createJSDocParamTag;
/* @internal */
function createJSDocComment(comment, tags) {
- var node = createSynthesizedNode(291 /* JSDocComment */);
+ var node = createSynthesizedNode(296 /* JSDocComment */);
node.comment = comment;
node.tags = tags;
return node;
@@ -62154,7 +62406,7 @@ var ts;
(typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
(libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
(hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
- var updated = createSynthesizedNode(279 /* SourceFile */);
+ var updated = createSynthesizedNode(284 /* SourceFile */);
updated.flags |= node.flags;
updated.statements = createNodeArray(statements);
updated.endOfFileToken = node.endOfFileToken;
@@ -62238,7 +62490,7 @@ var ts;
* @param original The original statement.
*/
function createNotEmittedStatement(original) {
- var node = createSynthesizedNode(307 /* NotEmittedStatement */);
+ var node = createSynthesizedNode(312 /* NotEmittedStatement */);
node.original = original;
setTextRange(node, original);
return node;
@@ -62250,7 +62502,7 @@ var ts;
*/
/* @internal */
function createEndOfDeclarationMarker(original) {
- var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */);
+ var node = createSynthesizedNode(316 /* EndOfDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -62262,7 +62514,7 @@ var ts;
*/
/* @internal */
function createMergeDeclarationMarker(original) {
- var node = createSynthesizedNode(310 /* MergeDeclarationMarker */);
+ var node = createSynthesizedNode(315 /* MergeDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -62277,7 +62529,7 @@ var ts;
* @param location The location for the expression. Defaults to the positions from "original" if provided.
*/
function createPartiallyEmittedExpression(expression, original) {
- var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */);
+ var node = createSynthesizedNode(313 /* PartiallyEmittedExpression */);
node.expression = expression;
node.original = original;
setTextRange(node, original);
@@ -62293,7 +62545,7 @@ var ts;
ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
function flattenCommaElements(node) {
if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
- if (node.kind === 309 /* CommaListExpression */) {
+ if (node.kind === 314 /* CommaListExpression */) {
return node.elements;
}
if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
@@ -62303,7 +62555,7 @@ var ts;
return node;
}
function createCommaList(elements) {
- var node = createSynthesizedNode(309 /* CommaListExpression */);
+ var node = createSynthesizedNode(314 /* CommaListExpression */);
node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
return node;
}
@@ -62316,33 +62568,197 @@ var ts;
ts.updateCommaList = updateCommaList;
function createBundle(sourceFiles, prepends) {
if (prepends === void 0) { prepends = ts.emptyArray; }
- var node = ts.createNode(280 /* Bundle */);
+ var node = ts.createNode(285 /* Bundle */);
node.prepends = prepends;
node.sourceFiles = sourceFiles;
return node;
}
ts.createBundle = createBundle;
- function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, map) {
- var node = ts.createNode(281 /* UnparsedSource */);
+ var allUnscopedEmitHelpers;
+ function getAllUnscopedEmitHelpers() {
+ return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
+ ts.valuesHelper,
+ ts.readHelper,
+ ts.spreadHelper,
+ ts.restHelper,
+ ts.decorateHelper,
+ ts.metadataHelper,
+ ts.paramHelper,
+ ts.awaiterHelper,
+ ts.assignHelper,
+ ts.awaitHelper,
+ ts.asyncGeneratorHelper,
+ ts.asyncDelegator,
+ ts.asyncValues,
+ ts.extendsHelper,
+ ts.templateObjectHelper,
+ ts.generatorHelper,
+ ts.importStarHelper,
+ ts.importDefaultHelper
+ ], function (helper) { return helper.name; }));
+ }
+ function createUnparsedSource() {
+ var node = ts.createNode(286 /* UnparsedSource */);
+ node.prologues = ts.emptyArray;
+ node.referencedFiles = ts.emptyArray;
+ node.libReferenceDirectives = ts.emptyArray;
+ node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
+ return node;
+ }
+ function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
+ var node = createUnparsedSource();
+ var stripInternal;
+ var bundleFileInfo;
if (!ts.isString(textOrInputFiles)) {
ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
- node.fileName = mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath;
+ node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
Object.defineProperties(node, {
text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
});
+ if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
+ node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
+ ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
+ stripInternal = mapTextOrStripInternal;
+ bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
+ if (node.oldFileOfCurrentEmit) {
+ parseOldFileOfCurrentEmit(node, ts.Debug.assertDefined(bundleFileInfo));
+ return node;
+ }
+ }
}
else {
+ node.fileName = "";
node.text = textOrInputFiles;
node.sourceMapPath = mapPathOrType;
- node.sourceMapText = map;
+ node.sourceMapText = mapTextOrStripInternal;
}
+ ts.Debug.assert(!node.oldFileOfCurrentEmit);
+ parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
return node;
}
ts.createUnparsedSourceFile = createUnparsedSourceFile;
- function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapText) {
- var node = ts.createNode(282 /* InputFiles */);
+ function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
+ var prologues;
+ var helpers;
+ var referencedFiles;
+ var typeReferenceDirectives;
+ var libReferenceDirectives;
+ var texts;
+ for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "prologue" /* Prologue */:
+ (prologues || (prologues = [])).push(createUnparsedNode(section, node));
+ break;
+ case "emitHelpers" /* EmitHelpers */:
+ (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ node.hasNoDefaultLib = true;
+ break;
+ case "reference" /* Reference */:
+ (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "type" /* Type */:
+ (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
+ break;
+ case "lib" /* Lib */:
+ (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "prepend" /* Prepend */:
+ var prependNode = createUnparsedNode(section, node);
+ var prependTexts = void 0;
+ for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
+ var text = _c[_b];
+ if (!stripInternal || text.kind !== "internal" /* Internal */) {
+ (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
+ }
+ }
+ prependNode.texts = prependTexts || ts.emptyArray;
+ (texts || (texts = [])).push(prependNode);
+ break;
+ case "internal" /* Internal */:
+ if (stripInternal)
+ break;
+ // falls through
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.prologues = prologues || ts.emptyArray;
+ node.helpers = helpers;
+ node.referencedFiles = referencedFiles || ts.emptyArray;
+ node.typeReferenceDirectives = typeReferenceDirectives;
+ node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
+ node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
+ }
+ function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
+ ts.Debug.assert(!!node.oldFileOfCurrentEmit);
+ var texts;
+ var syntheticReferences;
+ for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "internal" /* Internal */:
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
+ break;
+ // Ignore
+ case "prologue" /* Prologue */:
+ case "emitHelpers" /* EmitHelpers */:
+ case "prepend" /* Prepend */:
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.texts = texts || ts.emptyArray;
+ node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
+ node.syntheticReferences = syntheticReferences;
+ return node;
+ }
+ function mapBundleFileSectionKindToSyntaxKind(kind) {
+ switch (kind) {
+ case "prologue" /* Prologue */: return 279 /* UnparsedPrologue */;
+ case "prepend" /* Prepend */: return 280 /* UnparsedPrepend */;
+ case "internal" /* Internal */: return 282 /* UnparsedInternalText */;
+ case "text" /* Text */: return 281 /* UnparsedText */;
+ case "emitHelpers" /* EmitHelpers */:
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
+ default:
+ return ts.Debug.assertNever(kind);
+ }
+ }
+ function createUnparsedNode(section, parent) {
+ var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ return node;
+ }
+ function createUnparsedSyntheticReference(section, parent) {
+ var node = ts.createNode(283 /* UnparsedSyntheticReference */, section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ node.section = section;
+ return node;
+ }
+ function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
+ var node = ts.createNode(287 /* InputFiles */);
if (!ts.isString(javascriptTextOrReadFileText)) {
var cache_1 = ts.createMap();
var textGetter_1 = function (path) {
@@ -62359,15 +62775,25 @@ var ts;
var result = textGetter_1(path);
return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
};
+ var buildInfo_1;
+ var getAndCacheBuildInfo_1 = function (getText) {
+ if (buildInfo_1 === undefined) {
+ var result = getText();
+ buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
+ }
+ return buildInfo_1 || undefined;
+ };
node.javascriptPath = declarationTextOrJavascriptPath;
node.javascriptMapPath = javascriptMapPath;
node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
node.declarationMapPath = declarationMapPath;
+ node.buildInfoPath = declarationMapTextOrBuildInfoPath;
Object.defineProperties(node, {
javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
- declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } } // TODO:: if there is inline sourceMap in dtsFile, use that
+ declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
+ buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
});
}
else {
@@ -62376,7 +62802,12 @@ var ts;
node.javascriptMapText = javascriptMapTextOrDeclarationPath;
node.declarationText = declarationTextOrJavascriptPath;
node.declarationMapPath = declarationMapPath;
- node.declarationMapText = declarationMapText;
+ node.declarationMapText = declarationMapTextOrBuildInfoPath;
+ node.javascriptPath = javascriptPath;
+ node.declarationPath = declarationPath,
+ node.buildInfoPath = buildInfoPath;
+ node.buildInfo = buildInfo;
+ node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
}
return node;
}
@@ -62514,7 +62945,7 @@ var ts;
// To avoid holding onto transformation artifacts, we keep track of any
// parse tree node we are annotating. This allows us to clean them up after
// all transformations have completed.
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return node.emitNode = { annotatedNodes: [node] };
}
var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
@@ -62960,38 +63391,38 @@ var ts;
return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
}
ts.getHelperName = getHelperName;
- var valuesHelper = {
+ ts.valuesHelper = {
name: "typescript:values",
scoped: false,
text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };"
};
function createValuesHelper(context, expression, location) {
- context.requestEmitHelper(valuesHelper);
+ context.requestEmitHelper(ts.valuesHelper);
return ts.setTextRange(ts.createCall(getHelperName("__values"),
/*typeArguments*/ undefined, [expression]), location);
}
ts.createValuesHelper = createValuesHelper;
- var readHelper = {
+ ts.readHelper = {
name: "typescript:read",
scoped: false,
text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };"
};
function createReadHelper(context, iteratorRecord, count, location) {
- context.requestEmitHelper(readHelper);
+ context.requestEmitHelper(ts.readHelper);
return ts.setTextRange(ts.createCall(getHelperName("__read"),
/*typeArguments*/ undefined, count !== undefined
? [iteratorRecord, ts.createLiteral(count)]
: [iteratorRecord]), location);
}
ts.createReadHelper = createReadHelper;
- var spreadHelper = {
+ ts.spreadHelper = {
name: "typescript:spread",
scoped: false,
text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };"
};
function createSpreadHelper(context, argumentList, location) {
- context.requestEmitHelper(readHelper);
- context.requestEmitHelper(spreadHelper);
+ context.requestEmitHelper(ts.readHelper);
+ context.requestEmitHelper(ts.spreadHelper);
return ts.setTextRange(ts.createCall(getHelperName("__spread"),
/*typeArguments*/ undefined, argumentList), location);
}
@@ -63837,7 +64268,7 @@ var ts;
case 190 /* ElementAccessExpression */:
case 189 /* PropertyAccessExpression */:
case 213 /* NonNullExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
node = node.expression;
continue;
}
@@ -63853,7 +64284,7 @@ var ts;
ts.parenthesizeConciseBody = parenthesizeConciseBody;
function isCommaSequence(node) {
return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
- node.kind === 309 /* CommaListExpression */;
+ node.kind === 314 /* CommaListExpression */;
}
ts.isCommaSequence = isCommaSequence;
var OuterExpressionKinds;
@@ -63872,7 +64303,7 @@ var ts;
case 212 /* AsExpression */:
case 213 /* NonNullExpression */:
return (kinds & 2 /* Assertions */) !== 0;
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0;
}
return false;
@@ -63909,7 +64340,7 @@ var ts;
case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
- case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
+ case 313 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
}
}
/**
@@ -64701,12 +65132,12 @@ var ts;
case 278 /* EnumMember */:
return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
default:
// No need to visit nodes with no children.
@@ -64762,7 +65193,7 @@ var ts;
case 220 /* EmptyStatement */:
case 210 /* OmittedExpression */:
case 236 /* DebuggerStatement */:
- case 307 /* NotEmittedStatement */:
+ case 312 /* NotEmittedStatement */:
// No need to visit nodes with no children.
break;
// Names
@@ -65139,14 +65570,14 @@ var ts;
result = reduceNode(node.initializer, cbNode, result);
break;
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
result = reduceNodes(node.statements, cbNodes, result);
break;
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
result = reduceNodes(node.elements, cbNodes, result);
break;
default:
@@ -65427,7 +65858,7 @@ var ts;
}
exit();
}
- function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) {
+ function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
var _a;
ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
@@ -65437,6 +65868,14 @@ var ts;
var nameIndexToNewNameIndexMap;
var mappingIterator = decodeMappings(map.mappings);
for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) {
+ if (end && (raw.generatedLine > end.line ||
+ (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
+ break;
+ }
+ if (start && (raw.generatedLine < start.line ||
+ (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
+ continue;
+ }
// Then reencode all the updated mappings into the overall map
var newSourceIndex = void 0;
var newSourceLine = void 0;
@@ -65465,8 +65904,10 @@ var ts;
}
}
}
- var newGeneratedLine = raw.generatedLine + generatedLine;
- var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter;
+ var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
+ var newGeneratedLine = rawGeneratedLine + generatedLine;
+ var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
+ var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
}
exit();
@@ -65949,7 +66390,7 @@ var ts;
function chainBundle(transformSourceFile) {
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
+ return node.kind === 284 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
}
function transformBundle(node) {
return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
@@ -66610,7 +67051,7 @@ var ts;
function makeAssignmentElement(name) {
return name;
}
- var restHelper = {
+ ts.restHelper = {
name: "typescript:rest",
scoped: false,
text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };"
@@ -66619,7 +67060,7 @@ var ts;
* `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
*/
function createRestCall(context, value, elements, computedTempVariables, location) {
- context.requestEmitHelper(restHelper);
+ context.requestEmitHelper(ts.restHelper);
var propertyNames = [];
var computedTempVariableOffset = 0;
for (var i = 0; i < elements.length - 1; i++) {
@@ -66720,14 +67161,14 @@ var ts;
var pendingExpressions;
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* Bundle */) {
return transformBundle(node);
}
return transformSourceFile(node);
}
function transformBundle(node) {
return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
- if (prepend.kind === 282 /* InputFiles */) {
+ if (prepend.kind === 287 /* InputFiles */) {
return ts.createUnparsedSourceFile(prepend, "js");
}
return prepend;
@@ -66776,7 +67217,7 @@ var ts;
*/
function onBeforeVisitNode(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 245 /* ModuleBlock */:
case 218 /* Block */:
@@ -69007,7 +69448,7 @@ var ts;
// enums in any other scope are emitted as a `let` declaration.
var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
- ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
+ ], currentLexicalScope.kind === 284 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
ts.setOriginalNode(statement, node);
recordEmittedDeclarationInScope(node);
if (isFirstEmittedDeclarationInScope(node)) {
@@ -69572,7 +70013,7 @@ var ts;
// If we are nested within a namespace declaration, we may need to qualifiy
// an identifier that is exported from a merged namespace.
var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
- if (container && container.kind !== 279 /* SourceFile */) {
+ if (container && container.kind !== 284 /* SourceFile */) {
var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) ||
(applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */);
if (substitute) {
@@ -69623,39 +70064,39 @@ var ts;
argumentsArray.push(descriptor);
}
}
- context.requestEmitHelper(decorateHelper);
+ context.requestEmitHelper(ts.decorateHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"),
/*typeArguments*/ undefined, argumentsArray), location);
}
- var decorateHelper = {
+ ts.decorateHelper = {
name: "typescript:decorate",
scoped: false,
priority: 2,
text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };"
};
function createMetadataHelper(context, metadataKey, metadataValue) {
- context.requestEmitHelper(metadataHelper);
+ context.requestEmitHelper(ts.metadataHelper);
return ts.createCall(ts.getHelperName("__metadata"),
/*typeArguments*/ undefined, [
ts.createLiteral(metadataKey),
metadataValue
]);
}
- var metadataHelper = {
+ ts.metadataHelper = {
name: "typescript:metadata",
scoped: false,
priority: 3,
text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };"
};
function createParamHelper(context, expression, parameterOffset, location) {
- context.requestEmitHelper(paramHelper);
+ context.requestEmitHelper(ts.paramHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__param"),
/*typeArguments*/ undefined, [
ts.createLiteral(parameterOffset),
expression
]), location);
}
- var paramHelper = {
+ ts.paramHelper = {
name: "typescript:param",
scoped: false,
priority: 4,
@@ -70206,14 +70647,14 @@ var ts;
], 2 /* Const */));
}
ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
- var awaiterHelper = {
+ ts.awaiterHelper = {
name: "typescript:awaiter",
scoped: false,
priority: 5,
text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };"
};
function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) {
- context.requestEmitHelper(awaiterHelper);
+ context.requestEmitHelper(ts.awaiterHelper);
var generatorFunc = ts.createFunctionExpression(
/*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */),
/*name*/ undefined,
@@ -70845,7 +71286,7 @@ var ts;
}
}
ts.transformES2018 = transformES2018;
- var assignHelper = {
+ ts.assignHelper = {
name: "typescript:assign",
scoped: false,
priority: 1,
@@ -70856,28 +71297,28 @@ var ts;
return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"),
/*typeArguments*/ undefined, attributesSegments);
}
- context.requestEmitHelper(assignHelper);
+ context.requestEmitHelper(ts.assignHelper);
return ts.createCall(ts.getHelperName("__assign"),
/*typeArguments*/ undefined, attributesSegments);
}
ts.createAssignHelper = createAssignHelper;
- var awaitHelper = {
+ ts.awaitHelper = {
name: "typescript:await",
scoped: false,
text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
};
function createAwaitHelper(context, expression) {
- context.requestEmitHelper(awaitHelper);
+ context.requestEmitHelper(ts.awaitHelper);
return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]);
}
- var asyncGeneratorHelper = {
+ ts.asyncGeneratorHelper = {
name: "typescript:asyncGenerator",
scoped: false,
text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
};
function createAsyncGeneratorHelper(context, generatorFunc) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncGeneratorHelper);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncGeneratorHelper);
// Mark this node as originally an async function
(generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */;
return ts.createCall(ts.getHelperName("__asyncGenerator"),
@@ -70887,24 +71328,24 @@ var ts;
generatorFunc
]);
}
- var asyncDelegator = {
+ ts.asyncDelegator = {
name: "typescript:asyncDelegator",
scoped: false,
text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };"
};
function createAsyncDelegatorHelper(context, expression, location) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncDelegator);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncDelegator);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"),
/*typeArguments*/ undefined, [expression]), location);
}
- var asyncValues = {
+ ts.asyncValues = {
name: "typescript:asyncValues",
scoped: false,
text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };"
};
function createAsyncValuesHelper(context, expression, location) {
- context.requestEmitHelper(asyncValues);
+ context.requestEmitHelper(ts.asyncValues);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"),
/*typeArguments*/ undefined, [expression]), location);
}
@@ -74716,7 +75157,7 @@ var ts;
}
ts.transformES2015 = transformES2015;
function createExtendsHelper(context, name) {
- context.requestEmitHelper(extendsHelper);
+ context.requestEmitHelper(ts.extendsHelper);
return ts.createCall(ts.getHelperName("__extends"),
/*typeArguments*/ undefined, [
name,
@@ -74724,20 +75165,20 @@ var ts;
]);
}
function createTemplateObjectHelper(context, cooked, raw) {
- context.requestEmitHelper(templateObjectHelper);
+ context.requestEmitHelper(ts.templateObjectHelper);
return ts.createCall(ts.getHelperName("__makeTemplateObject"),
/*typeArguments*/ undefined, [
cooked,
raw
]);
}
- var extendsHelper = {
+ ts.extendsHelper = {
name: "typescript:extends",
scoped: false,
priority: 0,
text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();"
};
- var templateObjectHelper = {
+ ts.templateObjectHelper = {
name: "typescript:makeTemplateObject",
scoped: false,
priority: 0,
@@ -77431,7 +77872,7 @@ var ts;
}
ts.transformGenerators = transformGenerators;
function createGeneratorHelper(context, body) {
- context.requestEmitHelper(generatorHelper);
+ context.requestEmitHelper(ts.generatorHelper);
return ts.createCall(ts.getHelperName("__generator"),
/*typeArguments*/ undefined, [ts.createThis(), body]);
}
@@ -77494,7 +77935,7 @@ var ts;
// entering a finally block.
//
// For examples of how these are used, see the comments in ./transformers/generators.ts
- var generatorHelper = {
+ ts.generatorHelper = {
name: "typescript:generator",
scoped: false,
priority: 6,
@@ -77527,7 +77968,7 @@ var ts;
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* SourceFile */); // Restore state when substituting nodes in a file.
var moduleInfoMap = []; // The ExternalModuleInfo for each file.
var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
var currentSourceFile; // The current file.
@@ -77869,9 +78310,9 @@ var ts;
return visitFunctionDeclaration(node);
case 240 /* ClassDeclaration */:
return visitClassDeclaration(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
@@ -78029,7 +78470,7 @@ var ts;
}
var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]);
}
return promise;
@@ -78043,7 +78484,7 @@ var ts;
var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
}
var func;
@@ -78077,11 +78518,11 @@ var ts;
return innerExpr;
}
if (ts.getImportNeedsImportStarHelper(node)) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
}
if (ts.getImportNeedsImportDefaultHelper(node)) {
- context.requestEmitHelper(importDefaultHelper);
+ context.requestEmitHelper(ts.importDefaultHelper);
return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
}
return innerExpr;
@@ -78650,7 +79091,7 @@ var ts;
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
currentSourceFile = node;
currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
noSubstitution = [];
@@ -78738,7 +79179,7 @@ var ts;
}
if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)),
/*location*/ node);
}
@@ -78864,13 +79305,13 @@ var ts;
text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
};
// emit helper for `import * as Name from "foo"`
- var importStarHelper = {
+ ts.importStarHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
};
// emit helper for `import Name from "foo"`
- var importDefaultHelper = {
+ ts.importDefaultHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
@@ -78893,7 +79334,7 @@ var ts;
context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols.
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* SourceFile */); // Restore state when substituting nodes in a file.
var moduleInfoMap = []; // The ExternalModuleInfo for each file.
var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
var exportFunctionsMap = []; // The export function associated with a source file.
@@ -79463,7 +79904,7 @@ var ts;
function shouldHoistVariableDeclarationList(node) {
// hoist only non-block scoped declarations or block scoped declarations parented by source file
return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
- && (enclosingBlockScopedContainer.kind === 279 /* SourceFile */
+ && (enclosingBlockScopedContainer.kind === 284 /* SourceFile */
|| (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
}
/**
@@ -79806,9 +80247,9 @@ var ts;
return visitCatchClause(node);
case 218 /* Block */:
return visitBlock(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return destructuringAndImportCallVisitor(node);
@@ -80056,7 +80497,7 @@ var ts;
}
else if (ts.isIdentifier(node)) {
var container = resolver.getReferencedExportContainer(node);
- return container !== undefined && container.kind === 279 /* SourceFile */;
+ return container !== undefined && container.kind === 284 /* SourceFile */;
}
else {
return false;
@@ -80089,7 +80530,7 @@ var ts;
* @param emitCallback A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
var id = ts.getOriginalNodeId(node);
currentSourceFile = node;
moduleInfo = moduleInfoMap[id];
@@ -80298,7 +80739,7 @@ var ts;
|| resolver.getReferencedValueDeclaration(name);
if (valueDeclaration) {
var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
}
exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
@@ -80337,7 +80778,7 @@ var ts;
var previousOnSubstituteNode = context.onSubstituteNode;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
- context.enableEmitNotification(279 /* SourceFile */);
+ context.enableEmitNotification(284 /* SourceFile */);
context.enableSubstitution(72 /* Identifier */);
var currentSourceFile;
return ts.chainBundle(transformSourceFile);
@@ -80767,6 +81208,9 @@ var ts;
case 241 /* InterfaceDeclaration */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
break;
+ case 181 /* MappedType */:
+ diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
+ break;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
@@ -80850,6 +81294,15 @@ var ts;
return result.diagnostics;
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
+ function isInternalDeclaration(node, currentSourceFile) {
+ var parseTreeNode = ts.getParseTreeNode(node);
+ var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
+ return !!ts.forEach(leadingCommentRanges, function (range) {
+ var comment = currentSourceFile.text.substring(range.pos, range.end);
+ return ts.stringContains(comment, "@internal");
+ });
+ }
+ ts.isInternalDeclaration = isInternalDeclaration;
var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
2048 /* WriteClassExpressionAsTypeLiteral */ |
4096 /* UseTypeOfFunction */ |
@@ -80978,10 +81431,10 @@ var ts;
}
}
function transformRoot(node) {
- if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
+ if (node.kind === 284 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
}
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* Bundle */) {
isBundledEmit = true;
refs = ts.createMap();
libs = ts.createMap();
@@ -81011,9 +81464,15 @@ var ts;
var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
}), ts.mapDefined(node.prepends, function (prepend) {
- if (prepend.kind === 282 /* InputFiles */) {
- return ts.createUnparsedSourceFile(prepend, "dts");
- }
+ if (prepend.kind === 287 /* InputFiles */) {
+ var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
+ hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
+ collectReferences(sourceFile, refs);
+ recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
+ collectLibs(sourceFile, libs);
+ return sourceFile;
+ }
+ return prepend;
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
@@ -81105,7 +81564,7 @@ var ts;
}
}
function collectReferences(sourceFile, ret) {
- if (noResolve || ts.isSourceFileJS(sourceFile))
+ if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
return ret;
ts.forEach(sourceFile.referencedFiles, function (f) {
var elem = ts.tryResolveScriptReference(host, sourceFile, f);
@@ -81833,18 +82292,8 @@ var ts;
}
errorNameNode = undefined;
}
- function hasInternalAnnotation(range) {
- var comment = currentSourceFile.text.substring(range.pos, range.end);
- return ts.stringContains(comment, "@internal");
- }
function shouldStripInternal(node) {
- if (stripInternal && node) {
- var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile);
- if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) {
- return true;
- }
- }
- return false;
+ return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
}
function isScopeMarker(node) {
return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
@@ -81866,7 +82315,7 @@ var ts;
function ensureModifierFlags(node, privateDeclaration) {
var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
- var parentIsFile = node.parent.kind === 279 /* SourceFile */;
+ var parentIsFile = node.parent.kind === 284 /* SourceFile */;
if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */);
additions = 0 /* None */;
@@ -82083,7 +82532,7 @@ var ts;
* @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
*/
function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
- var enabledSyntaxKindFeatures = new Array(312 /* Count */);
+ var enabledSyntaxKindFeatures = new Array(317 /* Count */);
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
@@ -82343,10 +82792,14 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- var infoExtension = ".tsbundleinfo";
var brackets = createBracketsMap();
var syntheticParent = { pos: -1, end: -1 };
/*@internal*/
+ function isBuildInfoFile(file) {
+ return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
+ }
+ ts.isBuildInfoFile = isBuildInfoFile;
+ /*@internal*/
/**
* Iterates over the source files that are expected to have an emit output.
*
@@ -82356,13 +82809,14 @@ var ts;
* If an array, the full list of source files to emit.
* Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
*/
- function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) {
+ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles, onlyBuildInfo, includeBuildInfo) {
if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; }
var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
- if (sourceFiles.length) {
- var bundle = ts.createBundle(sourceFiles, host.getPrependNodes());
+ var prepends = host.getPrependNodes();
+ if (sourceFiles.length || prepends.length) {
+ var bundle = ts.createBundle(sourceFiles, prepends);
var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
if (result) {
return result;
@@ -82370,31 +82824,61 @@ var ts;
}
}
else {
- for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
- var sourceFile = sourceFiles_1[_a];
- var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
- if (result) {
- return result;
+ if (!onlyBuildInfo) {
+ for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
+ var sourceFile = sourceFiles_1[_a];
+ var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
+ if (result) {
+ return result;
+ }
}
}
+ if (includeBuildInfo) {
+ var buildInfoPath = getOutputPathForBuildInfo(host.getCompilerOptions());
+ if (buildInfoPath)
+ return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
+ }
}
}
ts.forEachEmittedFile = forEachEmittedFile;
/*@internal*/
+ function getOutputPathForBuildInfo(options) {
+ var configFile = options.configFilePath;
+ if (!configFile || !ts.isIncrementalCompilation(options))
+ return undefined;
+ if (options.tsBuildInfoFile)
+ return options.tsBuildInfoFile;
+ var outPath = options.outFile || options.out;
+ var buildInfoExtensionLess;
+ if (outPath) {
+ buildInfoExtensionLess = ts.removeFileExtension(outPath);
+ }
+ else {
+ var configFileExtensionLess = ts.removeFileExtension(configFile);
+ buildInfoExtensionLess = options.outDir ?
+ options.rootDir ?
+ ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
+ ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
+ configFileExtensionLess;
+ }
+ return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
+ }
+ ts.getOutputPathForBuildInfo = getOutputPathForBuildInfo;
+ /*@internal*/
function getOutputPathsForBundle(options, forceDtsPaths) {
var outPath = options.outFile || options.out;
var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath };
+ var buildInfoPath = getOutputPathForBuildInfo(options);
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
}
ts.getOutputPathsForBundle = getOutputPathsForBundle;
/*@internal*/
function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
var options = host.getCompilerOptions();
- if (sourceFile.kind === 280 /* Bundle */) {
+ if (sourceFile.kind === 285 /* Bundle */) {
return getOutputPathsForBundle(options, forceDtsPaths);
}
else {
@@ -82408,19 +82892,13 @@ var ts;
var isJs = ts.isSourceFileJS(sourceFile);
var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined };
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
}
}
ts.getOutputPathsFor = getOutputPathsFor;
function getSourceMapFilePath(jsFilePath, options) {
return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
}
- function createDefaultBundleInfo() {
- return {
- originalOffset: -1,
- totalLength: -1
- };
- }
// JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
// So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
// For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
@@ -82445,7 +82923,7 @@ var ts;
ts.getOutputExtension = getOutputExtension;
/*@internal*/
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) {
+ function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers, onlyBuildInfo) {
var compilerOptions = host.getCompilerOptions();
var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
@@ -82453,12 +82931,12 @@ var ts;
var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
var writer = ts.createTextWriter(newLine);
var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit;
- var bundleInfo = createDefaultBundleInfo();
+ var bundleBuildInfo;
var emitSkipped = false;
var exportedModulesFromDeclarationEmit;
// Emit each output file
enter();
- forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles);
+ forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles, onlyBuildInfo, !targetSourceFile);
exit();
return {
emitSkipped: emitSkipped,
@@ -82468,9 +82946,16 @@ var ts;
exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
};
function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
- var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath;
- emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
+ var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
+ bundleBuildInfo = {
+ commonSourceDirectory: host.getCommonSourceDirectory(),
+ sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return file.fileName; })
+ };
+ }
+ emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
+ emitBuildInfo(bundleBuildInfo, buildInfoPath);
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
if (jsFilePath) {
@@ -82479,8 +82964,8 @@ var ts;
if (sourceMapFilePath) {
emittedFilesList.push(sourceMapFilePath);
}
- if (bundleInfoPath) {
- emittedFilesList.push(bundleInfoPath);
+ if (buildInfoPath) {
+ emittedFilesList.push(buildInfoPath);
}
}
if (declarationFilePath) {
@@ -82491,8 +82976,21 @@ var ts;
}
}
}
- function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) {
- if (emitOnlyDtsFiles || !jsFilePath) {
+ function emitBuildInfo(bundle, buildInfoPath) {
+ // Write build information if applicable
+ if (!buildInfoPath || targetSourceFile || emitSkipped)
+ return;
+ var program = host.getProgramBuildInfo();
+ if (!bundle && !program)
+ return;
+ if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
+ emitSkipped = true;
+ return;
+ }
+ ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: ts.version }), /*writeByteOrderMark*/ false);
+ }
+ function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) {
+ if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
return;
}
// Make sure not to write js file and source map file if any of them cannot be written
@@ -82512,6 +83010,7 @@ var ts;
inlineSourceMap: compilerOptions.inlineSourceMap,
inlineSources: compilerOptions.inlineSources,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
+ writeBundleFileInfo: !!bundleBuildInfo
};
// Create a printer to print the nodes
var printer = createPrinter(printerOptions, {
@@ -82522,12 +83021,14 @@ var ts;
substituteNode: transform.substituteNode,
});
ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
- printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions);
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
// Clean up emit nodes on parse tree
transform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.js = printer.bundleFileInfo;
}
function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) {
- if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
+ if (!sourceFileOrBundle || !(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
return;
}
var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
@@ -82556,6 +83057,8 @@ var ts;
inlineSourceMap: compilerOptions.inlineSourceMap,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
onlyPrintJsDocStyle: true,
+ writeBundleFileInfo: !!bundleBuildInfo,
+ recordInternalSection: !!bundleBuildInfo
};
var declarationPrinter = createPrinter(printerOptions, {
// resolver hooks
@@ -82568,18 +83071,20 @@ var ts;
emitSkipped = emitSkipped || declBlocked;
if (!declBlocked || emitOnlyDtsFiles) {
ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
- printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, {
+ printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
sourceMap: compilerOptions.declarationMap,
sourceRoot: compilerOptions.sourceRoot,
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
});
- if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) {
+ if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 284 /* SourceFile */) {
var sourceFile = declarationTransform.transformed[0];
exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
}
}
declarationTransform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
}
function collectLinkedAliases(node) {
if (ts.isExportAssignment(node)) {
@@ -82594,16 +83099,16 @@ var ts;
}
ts.forEachChild(node, collectLinkedAliases);
}
- function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) {
- var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined;
- var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined;
+ function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
+ var bundle = sourceFileOrBundle.kind === 285 /* Bundle */ ? sourceFileOrBundle : undefined;
+ var sourceFile = sourceFileOrBundle.kind === 284 /* SourceFile */ ? sourceFileOrBundle : undefined;
var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
var sourceMapGenerator;
if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
}
if (bundle) {
- printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator);
+ printer.writeBundle(bundle, writer, sourceMapGenerator);
}
else {
printer.writeFile(sourceFile, writer, sourceMapGenerator);
@@ -82632,18 +83137,12 @@ var ts;
}
// Write the output file
ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
- // Write bundled offset information if applicable
- if (bundleInfoPath) {
- bundleInfo.totalLength = writer.getTextPos();
- ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false);
- }
// Reset state
writer.clear();
- bundleInfo = createDefaultBundleInfo();
}
function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
- && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
+ && (sourceFileOrBundle.kind !== 284 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
}
function getSourceRoot(mapOptions) {
// Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
@@ -82700,6 +83199,166 @@ var ts;
}
}
ts.emitFiles = emitFiles;
+ /*@internal*/
+ function getBuildInfoText(buildInfo) {
+ return JSON.stringify(buildInfo, undefined, 2);
+ }
+ ts.getBuildInfoText = getBuildInfoText;
+ /*@internal*/
+ function getBuildInfo(buildInfoText) {
+ return JSON.parse(buildInfoText);
+ }
+ ts.getBuildInfo = getBuildInfo;
+ /*@internal*/
+ ts.notImplementedResolver = {
+ hasGlobalName: ts.notImplemented,
+ getReferencedExportContainer: ts.notImplemented,
+ getReferencedImportDeclaration: ts.notImplemented,
+ getReferencedDeclarationWithCollidingName: ts.notImplemented,
+ isDeclarationWithCollidingName: ts.notImplemented,
+ isValueAliasDeclaration: ts.notImplemented,
+ isReferencedAliasDeclaration: ts.notImplemented,
+ isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
+ getNodeCheckFlags: ts.notImplemented,
+ isDeclarationVisible: ts.notImplemented,
+ isLateBound: function (_node) { return false; },
+ collectLinkedAliases: ts.notImplemented,
+ isImplementationOfOverload: ts.notImplemented,
+ isRequiredInitializedParameter: ts.notImplemented,
+ isOptionalUninitializedParameterProperty: ts.notImplemented,
+ isExpandoFunctionDeclaration: ts.notImplemented,
+ getPropertiesOfContainerFunction: ts.notImplemented,
+ createTypeOfDeclaration: ts.notImplemented,
+ createReturnTypeOfSignatureDeclaration: ts.notImplemented,
+ createTypeOfExpression: ts.notImplemented,
+ createLiteralConstValue: ts.notImplemented,
+ isSymbolAccessible: ts.notImplemented,
+ isEntityNameVisible: ts.notImplemented,
+ // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
+ getConstantValue: ts.notImplemented,
+ getReferencedValueDeclaration: ts.notImplemented,
+ getTypeReferenceSerializationKind: ts.notImplemented,
+ isOptionalParameter: ts.notImplemented,
+ moduleExportsSomeValue: ts.notImplemented,
+ isArgumentsLocalBinding: ts.notImplemented,
+ getExternalModuleFileFromDeclaration: ts.notImplemented,
+ getTypeReferenceDirectivesForEntityName: ts.notImplemented,
+ getTypeReferenceDirectivesForSymbol: ts.notImplemented,
+ isLiteralConstDeclaration: ts.notImplemented,
+ getJsxFactoryEntity: ts.notImplemented,
+ getAllAccessorDeclarations: ts.notImplemented,
+ getSymbolOfExternalModuleSpecifier: ts.notImplemented,
+ isBindingCapturedByNode: ts.notImplemented,
+ };
+ function createSourceFilesFromBundleBuildInfo(bundle) {
+ var sourceFiles = bundle.sourceFiles.map(function (fileName) {
+ var sourceFile = ts.createNode(284 /* SourceFile */, 0, 0);
+ sourceFile.fileName = fileName;
+ sourceFile.text = "";
+ sourceFile.statements = ts.createNodeArray();
+ return sourceFile;
+ });
+ var jsBundle = ts.Debug.assertDefined(bundle.js);
+ ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
+ var sourceFile = sourceFiles[prologueInfo.file];
+ sourceFile.text = prologueInfo.text;
+ sourceFile.end = prologueInfo.text.length;
+ sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
+ var statement = ts.createNode(221 /* ExpressionStatement */, directive.pos, directive.end);
+ statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
+ statement.expression.text = directive.expression.text;
+ return statement;
+ }));
+ });
+ return sourceFiles;
+ }
+ /*@internal*/
+ function emitUsingBuildInfo(config, host, getCommandLine) {
+ var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
+ var buildInfoText = host.readFile(ts.Debug.assertDefined(buildInfoPath));
+ if (!buildInfoText)
+ return buildInfoPath;
+ var jsFileText = host.readFile(ts.Debug.assertDefined(jsFilePath));
+ if (!jsFileText)
+ return jsFilePath;
+ var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
+ // error if no source map or for now if inline sourcemap
+ if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
+ return sourceMapFilePath || "inline sourcemap decoding";
+ // read declaration text
+ var declarationText = declarationFilePath && host.readFile(declarationFilePath);
+ if (declarationFilePath && !declarationText)
+ return declarationFilePath;
+ var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
+ // error if no source map or for now if inline sourcemap
+ if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
+ return declarationMapPath || "inline sourcemap decoding";
+ var buildInfo = getBuildInfo(buildInfoText);
+ if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
+ return buildInfoPath;
+ var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo,
+ /*onlyOwnText*/ true);
+ var outputFiles = [];
+ var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
+ var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle);
+ var emitHost = {
+ getPrependNodes: ts.memoize(function () { return prependNodes.concat([ownPrependInput]); }),
+ getCanonicalFileName: host.getCanonicalFileName,
+ getCommonSourceDirectory: function () { return buildInfo.bundle.commonSourceDirectory; },
+ getCompilerOptions: function () { return config.options; },
+ getCurrentDirectory: function () { return host.getCurrentDirectory(); },
+ getNewLine: function () { return host.getNewLine(); },
+ getSourceFile: function () { return undefined; },
+ getSourceFileByPath: function () { return undefined; },
+ getSourceFiles: function () { return sourceFilesForJsEmit; },
+ getLibFileFromReference: ts.notImplemented,
+ isSourceFileFromExternalLibrary: ts.returnFalse,
+ writeFile: function (name, text, writeByteOrderMark) {
+ switch (name) {
+ case jsFilePath:
+ if (jsFileText === text)
+ return;
+ break;
+ case sourceMapFilePath:
+ if (sourceMapText === text)
+ return;
+ break;
+ case buildInfoPath:
+ var newBuildInfo = getBuildInfo(text);
+ newBuildInfo.program = buildInfo.program;
+ // Update sourceFileInfo
+ var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
+ newBuildInfo.bundle.js.sources = js.sources;
+ if (dts) {
+ newBuildInfo.bundle.dts.sources = dts.sources;
+ }
+ newBuildInfo.bundle.sourceFiles = sourceFiles;
+ outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
+ return;
+ case declarationFilePath:
+ if (declarationText === text)
+ return;
+ break;
+ case declarationMapPath:
+ if (declarationMapText === text)
+ return;
+ break;
+ default:
+ ts.Debug.fail("Unexpected path: " + name);
+ }
+ outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
+ },
+ isEmitBlocked: ts.returnFalse,
+ readFile: function (f) { return host.readFile(f); },
+ fileExists: function (f) { return host.fileExists(f); },
+ directoryExists: host.directoryExists && (function (f) { return host.directoryExists(f); }),
+ useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
+ getProgramBuildInfo: function () { return undefined; }
+ };
+ emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, /*emitOnlyDtsFiles*/ false, ts.getTransformers(config.options));
+ return outputFiles;
+ }
+ ts.emitUsingBuildInfo = emitUsingBuildInfo;
var PipelinePhase;
(function (PipelinePhase) {
PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
@@ -82728,6 +83387,10 @@ var ts;
var ownWriter; // Reusable `EmitTextWriter` for basic printing.
var write = writeBase;
var isOwnFileEmit;
+ var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
+ var recordInternalSection = printerOptions.recordInternalSection;
+ var sourceFileTextPos = 0;
+ var sourceFileTextKind = "text" /* Text */;
// Source Maps
var sourceMapsDisabled = true;
var sourceMapGenerator;
@@ -82753,7 +83416,8 @@ var ts;
writeNode: writeNode,
writeList: writeList,
writeFile: writeFile,
- writeBundle: writeBundle
+ writeBundle: writeBundle,
+ bundleFileInfo: bundleFileInfo
};
function printNode(hint, node, sourceFile) {
switch (hint) {
@@ -82768,9 +83432,9 @@ var ts;
break;
}
switch (node.kind) {
- case 279 /* SourceFile */: return printFile(node);
- case 280 /* Bundle */: return printBundle(node);
- case 281 /* UnparsedSource */: return printUnparsedSource(node);
+ case 284 /* SourceFile */: return printFile(node);
+ case 285 /* Bundle */: return printBundle(node);
+ case 286 /* UnparsedSource */: return printUnparsedSource(node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
@@ -82780,7 +83444,7 @@ var ts;
return endPrint();
}
function printBundle(bundle) {
- writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined);
+ writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
return endPrint();
}
function printFile(sourceFile) {
@@ -82808,7 +83472,49 @@ var ts;
reset();
writer = previousWriter;
}
- function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) {
+ function getTextPosWithWriteLine() {
+ return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
+ }
+ function updateOrPushBundleFileTextLike(pos, end, kind) {
+ var last = ts.lastOrUndefined(bundleFileInfo.sections);
+ if (last && last.kind === kind) {
+ last.end = end;
+ }
+ else {
+ bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
+ }
+ }
+ function recordBundleFileInternalSectionStart(node) {
+ if (recordInternalSection &&
+ bundleFileInfo &&
+ currentSourceFile &&
+ (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
+ ts.isInternalDeclaration(node, currentSourceFile) &&
+ sourceFileTextKind !== "internal" /* Internal */) {
+ var prevSourceFileTextKind = sourceFileTextKind;
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = "internal" /* Internal */;
+ return prevSourceFileTextKind;
+ }
+ return undefined;
+ }
+ function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
+ if (prevSourceFileTextKind) {
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = prevSourceFileTextKind;
+ }
+ }
+ function recordBundleFileTextLikeSection(end) {
+ if (sourceFileTextPos < end) {
+ updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
+ return true;
+ }
+ return false;
+ }
+ function writeBundle(bundle, output, sourceMapGenerator) {
+ var _a;
isOwnFileEmit = false;
var previousWriter = writer;
setWriter(output, sourceMapGenerator);
@@ -82816,18 +83522,49 @@ var ts;
emitPrologueDirectivesIfNeeded(bundle);
emitHelpers(bundle);
emitSyntheticTripleSlashReferencesIfNeeded(bundle);
- for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) {
- var prepend = _b[_a];
+ for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
+ var prepend = _c[_b];
writeLine();
+ var pos = writer.getTextPos();
+ var savedSections = bundleFileInfo && bundleFileInfo.sections;
+ if (savedSections)
+ bundleFileInfo.sections = [];
print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
+ if (bundleFileInfo) {
+ var newSections = bundleFileInfo.sections;
+ bundleFileInfo.sections = savedSections;
+ if (prepend.oldFileOfCurrentEmit)
+ (_a = bundleFileInfo.sections).push.apply(_a, newSections);
+ else {
+ newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prepend" /* Prepend */, data: prepend.fileName, texts: newSections });
+ }
+ }
}
- if (bundleInfo) {
- bundleInfo.originalOffset = writer.getTextPos();
- }
- for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) {
- var sourceFile = _d[_c];
+ sourceFileTextPos = getTextPosWithWriteLine();
+ for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
+ var sourceFile = _e[_d];
print(0 /* SourceFile */, sourceFile, sourceFile);
}
+ if (bundleFileInfo && bundle.sourceFiles.length) {
+ var end = writer.getTextPos();
+ if (recordBundleFileTextLikeSection(end)) {
+ // Store prologues
+ var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
+ if (prologues) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.prologues = prologues;
+ }
+ // Store helpes
+ var helpers = getHelpersFromBundledSourceFiles(bundle);
+ if (helpers) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.helpers = helpers;
+ }
+ }
+ }
reset();
writer = previousWriter;
}
@@ -82897,8 +83634,10 @@ var ts;
function emit(node) {
if (node === undefined)
return;
+ var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
var pipelinePhase = getPipelinePhase(0 /* Notification */, node);
pipelinePhase(4 /* Unspecified */, node);
+ recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
}
function emitIdentifierName(node) {
if (node === undefined)
@@ -82925,12 +83664,12 @@ var ts;
}
// falls through
case 2 /* Comments */:
- if (!commentsDisabled && node.kind !== 279 /* SourceFile */) {
+ if (!commentsDisabled && node.kind !== 284 /* SourceFile */) {
return pipelineEmitWithComments;
}
// falls through
case 3 /* SourceMaps */:
- if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) {
+ if (!sourceMapsDisabled && node.kind !== 284 /* SourceFile */ && !ts.isInJsonFile(node)) {
return pipelineEmitWithSourceMap;
}
// falls through
@@ -82967,8 +83706,16 @@ var ts;
case 16 /* TemplateMiddle */:
case 17 /* TemplateTail */:
return emitLiteral(node);
- case 281 /* UnparsedSource */:
- return emitUnparsedSource(node);
+ case 286 /* UnparsedSource */:
+ case 280 /* UnparsedPrepend */:
+ return emitUnparsedSourceOrPrepend(node);
+ case 279 /* UnparsedPrologue */:
+ return writeUnparsedNode(node);
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return emitUnparsedTextLike(node);
+ case 283 /* UnparsedSyntheticReference */:
+ return emitUnparsedSyntheticReference(node);
// Identifiers
case 72 /* Identifier */:
return emitIdentifier(node);
@@ -83012,7 +83759,7 @@ var ts;
return emitTypeReference(node);
case 165 /* FunctionType */:
return emitFunctionType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return emitJSDocFunctionType(node);
case 166 /* ConstructorType */:
return emitConstructorType(node);
@@ -83050,20 +83797,20 @@ var ts;
return emitLiteralType(node);
case 183 /* ImportType */:
return emitImportTypeNode(node);
- case 284 /* JSDocAllType */:
+ case 289 /* JSDocAllType */:
writePunctuation("*");
return;
- case 285 /* JSDocUnknownType */:
+ case 290 /* JSDocUnknownType */:
writePunctuation("?");
return;
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return emitJSDocNullableType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return emitJSDocNonNullableType(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return emitJSDocOptionalType(node);
case 172 /* RestType */:
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return emitRestOrJSDocVariadicType(node);
// Binding patterns
case 184 /* ObjectBindingPattern */:
@@ -83201,30 +83948,30 @@ var ts;
case 278 /* EnumMember */:
return emitEnumMember(node);
// JSDoc nodes (only used in codefixes currently)
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return emitJSDocPropertyLikeTag(node);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return emitJSDocSimpleTypedTag(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return emitJSDocAugmentsTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return emitJSDocTemplateTag(node);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return emitJSDocTypedefTag(node);
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return emitJSDocCallbackTag(node);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return emitJSDocSignature(node);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return emitJSDocTypeLiteral(node);
- case 296 /* JSDocClassTag */:
- case 294 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
return emitJSDocSimpleTag(node);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return emitJSDoc(node);
// Transformation nodes (ignored)
}
@@ -83323,9 +84070,9 @@ var ts;
case 264 /* JsxFragment */:
return emitJsxFragment(node);
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return emitPartiallyEmittedExpression(node);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return emitCommaList(node);
}
}
@@ -83341,22 +84088,45 @@ var ts;
var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node);
pipelinePhase(hint, substituteNode(hint, node));
}
+ function getHelpersFromBundledSourceFiles(bundle) {
+ var result;
+ if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
+ return undefined;
+ }
+ var bundledHelpers = ts.createMap();
+ for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
+ var sourceFile = _b[_a];
+ var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
+ var helpers = getSortedEmitHelpers(sourceFile);
+ if (!helpers)
+ continue;
+ for (var _c = 0, helpers_3 = helpers; _c < helpers_3.length; _c++) {
+ var helper = helpers_3[_c];
+ if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
+ bundledHelpers.set(helper.name, true);
+ (result || (result = [])).push(helper.name);
+ }
+ }
+ }
+ return result;
+ }
function emitHelpers(node) {
var helpersEmitted = false;
- var bundle = node.kind === 280 /* Bundle */ ? node : undefined;
+ var bundle = node.kind === 285 /* Bundle */ ? node : undefined;
if (bundle && moduleKind === ts.ModuleKind.None) {
return;
}
- var numNodes = bundle ? bundle.sourceFiles.length : 1;
+ var numPrepends = bundle ? bundle.prepends.length : 0;
+ var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
for (var i = 0; i < numNodes; i++) {
- var currentNode = bundle ? bundle.sourceFiles[i] : node;
- var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile;
- var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined;
- var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit;
- var helpers = ts.getEmitHelpers(currentNode);
+ var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
+ var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
+ var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined);
+ var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
+ var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
if (helpers) {
- for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) {
- var helper = _b[_a];
+ for (var _a = 0, helpers_4 = helpers; _a < helpers_4.length; _a++) {
+ var helper = helpers_4[_a];
if (!helper.scoped) {
// Skip the helper if it can be skipped and the noEmitHelpers compiler
// option is set, or if it can be imported and the importHelpers compiler
@@ -83376,18 +84146,25 @@ var ts;
// Skip the helper if it is scoped and we are emitting bundled helpers
continue;
}
+ var pos = getTextPosWithWriteLine();
if (typeof helper.text === "string") {
writeLines(helper.text);
}
else {
writeLines(helper.text(makeFileLevelOptimisticUniqueName));
}
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
helpersEmitted = true;
}
}
}
return helpersEmitted;
}
+ function getSortedEmitHelpers(node) {
+ var helpers = ts.getEmitHelpers(node);
+ return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
+ }
//
// Literals/Pseudo-literals
//
@@ -83414,8 +84191,42 @@ var ts;
}
}
// SyntaxKind.UnparsedSource
- function emitUnparsedSource(unparsed) {
- writer.rawWrite(unparsed.text);
+ // SyntaxKind.UnparsedPrepend
+ function emitUnparsedSourceOrPrepend(unparsed) {
+ for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
+ var text = _b[_a];
+ writeLine();
+ emit(text);
+ }
+ }
+ // SyntaxKind.UnparsedPrologue
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ // SyntaxKind.UnparsedSyntheticReference
+ function writeUnparsedNode(unparsed) {
+ writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
+ }
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ function emitUnparsedTextLike(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 281 /* UnparsedText */ ?
+ "text" /* Text */ :
+ "internal" /* Internal */);
+ }
+ }
+ // SyntaxKind.UnparsedSyntheticReference
+ function emitUnparsedSyntheticReference(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ var section = ts.clone(unparsed.section);
+ section.pos = pos;
+ section.end = writer.getTextPos();
+ bundleFileInfo.sections.push(section);
+ }
}
//
// Identifiers
@@ -83470,7 +84281,7 @@ var ts;
emit(node.dotDotDotToken);
emitNodeWithWriter(node.name, writeParameter);
emit(node.questionToken);
- if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) {
+ if (node.parent && node.parent.kind === 294 /* JSDocFunctionType */ && !node.name) {
emit(node.type);
}
else {
@@ -84350,7 +85161,7 @@ var ts;
}
function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
// Emit all the prologue directives (like "use strict").
- var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true);
+ var statementOffset = emitPrologueDirectives(body.statements);
var pos = writer.getTextPos();
emitHelpers(body);
if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
@@ -84755,7 +85566,7 @@ var ts;
}
}
if (node.tags) {
- if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) {
+ if (node.tags.length === 1 && node.tags[0].kind === 307 /* JSDocTypeTag */ && !node.comment) {
writeSpace();
emit(node.tags[0]);
}
@@ -84789,7 +85600,7 @@ var ts;
function emitJSDocTypedefTag(tag) {
emitJSDocTagName(tag.tagName);
if (tag.typeExpression) {
- if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
emitJSDocTypeExpression(tag.typeExpression);
}
else {
@@ -84808,7 +85619,7 @@ var ts;
emit(tag.fullName);
}
emitJSDocComment(tag.comment);
- if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) {
+ if (tag.typeExpression && tag.typeExpression.kind === 297 /* JSDocTypeLiteral */) {
emitJSDocTypeLiteral(tag.typeExpression);
}
}
@@ -84895,6 +85706,16 @@ var ts;
}
function emitSyntheticTripleSlashReferencesIfNeeded(node) {
emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
+ for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
+ for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
+ var ref = _d[_c];
+ emit(ref);
+ writeLine();
+ }
+ }
+ }
}
function emitTripleSlashDirectivesIfNeeded(node) {
if (node.isDeclarationFile)
@@ -84902,7 +85723,10 @@ var ts;
}
function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
if (hasNoDefaultLib) {
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
writeLine();
}
if (currentSourceFile && currentSourceFile.moduleName) {
@@ -84923,17 +85747,26 @@ var ts;
}
for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
var directive = files_1[_c];
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
writeLine();
}
for (var _d = 0, types_19 = types; _d < types_19.length; _d++) {
var directive = types_19[_d];
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
writeLine();
}
for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
var directive = libs_1[_e];
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
writeLine();
}
}
@@ -84958,16 +85791,22 @@ var ts;
* Emits any prologue directives at the start of a Statement list, returning the
* number of prologue directives written to the output.
*/
- function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) {
+ function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
+ var needsToSetSourceFile = !!sourceFile;
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (ts.isPrologueDirective(statement)) {
var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
if (shouldEmitPrologueDirective) {
- if (startWithNewLine || i > 0) {
- writeLine();
+ if (needsToSetSourceFile) {
+ needsToSetSourceFile = false;
+ setSourceFile(sourceFile);
}
+ writeLine();
+ var pos = writer.getTextPos();
emit(statement);
+ if (recordBundleFileSection && bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
if (seenPrologueDirectives) {
seenPrologueDirectives.set(statement.expression.text, true);
}
@@ -84980,23 +85819,70 @@ var ts;
}
return statements.length;
}
+ function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
+ for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
+ var prologue = prologues_1[_a];
+ if (!seenPrologueDirectives.has(prologue.data)) {
+ writeLine();
+ var pos = writer.getTextPos();
+ emit(prologue);
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
+ if (seenPrologueDirectives) {
+ seenPrologueDirectives.set(prologue.data, true);
+ }
+ }
+ }
+ }
function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
if (ts.isSourceFile(sourceFileOrBundle)) {
- setSourceFile(sourceFileOrBundle);
- emitPrologueDirectives(sourceFileOrBundle.statements);
+ emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
}
else {
var seenPrologueDirectives = ts.createMap();
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
- setSourceFile(sourceFile);
- emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives);
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
+ emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
}
setSourceFile(undefined);
}
}
+ function getPrologueDirectivesFromBundledSourceFiles(bundle) {
+ var seenPrologueDirectives = ts.createMap();
+ var prologues;
+ for (var index = 0; index < bundle.sourceFiles.length; index++) {
+ var sourceFile = bundle.sourceFiles[index];
+ var directives = void 0;
+ var end = 0;
+ for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
+ var statement = _b[_a];
+ if (!ts.isPrologueDirective(statement))
+ break;
+ if (seenPrologueDirectives.has(statement.expression.text))
+ continue;
+ seenPrologueDirectives.set(statement.expression.text, true);
+ (directives || (directives = [])).push({
+ pos: statement.pos,
+ end: statement.end,
+ expression: {
+ pos: statement.expression.pos,
+ end: statement.expression.end,
+ text: statement.expression.text
+ }
+ });
+ end = end < statement.end ? statement.end : end;
+ }
+ if (directives)
+ (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
+ }
+ return prologues;
+ }
function emitShebangIfNeeded(sourceFileOrBundle) {
- if (ts.isSourceFile(sourceFileOrBundle)) {
+ if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
var shebang = ts.getShebang(sourceFileOrBundle.text);
if (shebang) {
writeComment(shebang);
@@ -85005,11 +85891,18 @@ var ts;
}
}
else {
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ ts.Debug.assertNode(prepend, ts.isUnparsedSource);
+ if (emitShebangIfNeeded(prepend)) {
+ return true;
+ }
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
// Emit only the first encountered shebang
if (emitShebangIfNeeded(sourceFile)) {
- break;
+ return true;
}
}
}
@@ -85212,6 +86105,7 @@ var ts;
}
// Emit each child.
var previousSibling = void 0;
+ var previousSourceFileTextKind = void 0;
var shouldDecreaseIndentAfterEmit = false;
for (var i = 0; i < count; i++) {
var child = children[start + i];
@@ -85232,6 +86126,7 @@ var ts;
emitLeadingCommentsOfPosition(previousSibling.end);
}
writeDelimiter(format);
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write either a line terminator or whitespace to separate the elements.
if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) {
// If a synthesized node in a single-line list starts on a new
@@ -85248,6 +86143,7 @@ var ts;
}
}
// Emit this child.
+ previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
if (shouldEmitInterveningComments) {
if (emitTrailingCommentsOfPosition) {
var commentRange = ts.getCommentRange(child);
@@ -85282,6 +86178,7 @@ var ts;
if (format & 128 /* Indented */) {
decreaseIndent();
}
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write the closing line terminator or closing whitespace.
if (shouldWriteClosingLineTerminator(parentNode, children, format)) {
writeLine();
@@ -85383,7 +86280,6 @@ var ts;
if (line.length) {
writeLine();
write(line);
- writer.rawWrite(newLine);
}
}
}
@@ -85897,7 +86793,7 @@ var ts;
hasWrittenComment = false;
var emitFlags = ts.getEmitFlags(node);
var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
- var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */;
+ var isEmittedNode = node.kind !== 312 /* NotEmittedStatement */;
// We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
// It is expensive to walk entire tree just to set one kind of node to have no comments.
var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
@@ -86157,19 +87053,28 @@ var ts;
return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
}
// Source Maps
+ function getParsedSourceMap(node) {
+ if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
+ node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
+ }
+ return node.parsedSourceMap || undefined;
+ }
function pipelineEmitWithSourceMap(hint, node) {
var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node);
- if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) {
- var parsed = ts.tryParseRawSourceMap(node.sourceMapText);
- if (parsed) {
- sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath);
+ if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
+ pipelinePhase(hint, node);
+ }
+ else if (ts.isUnparsedNode(node)) {
+ var parsed = getParsedSourceMap(node.parent);
+ if (parsed && sourceMapGenerator) {
+ sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
}
pipelinePhase(hint, node);
}
else {
var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
var emitFlags = ts.getEmitFlags(node);
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 16 /* NoLeadingSourceMap */) === 0
&& pos >= 0) {
emitSourcePos(source, skipSourceTrivia(source, pos));
@@ -86182,7 +87087,7 @@ var ts;
else {
pipelinePhase(hint, node);
}
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 32 /* NoTrailingSourceMap */) === 0
&& end >= 0) {
emitSourcePos(source, end);
@@ -86830,7 +87735,8 @@ var ts;
var value = readFileCache.get(key);
if (value !== undefined)
return value !== false ? value : undefined; // could be .d.ts from output
- if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) {
+ // Cache json or buildInfo
+ if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
return originalReadFile.call(host, fileName);
}
return setReadFileCache(key, fileName);
@@ -86861,7 +87767,7 @@ var ts;
var key = toPath(fileName);
fileExistsCache.delete(key);
var value = readFileCache.get(key);
- if (value && value !== data) {
+ if (value !== undefined && value !== data) {
readFileCache.delete(key);
sourceFileCache.delete(key);
}
@@ -87416,7 +88322,8 @@ var ts;
getProjectReferenceRedirect: getProjectReferenceRedirect,
getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
- forEachResolvedProjectReference: forEachResolvedProjectReference
+ forEachResolvedProjectReference: forEachResolvedProjectReference,
+ emitBuildInfo: emitBuildInfo
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -87843,7 +88750,20 @@ var ts;
return false;
// Before falling back to the host
return host.fileExists(f);
- } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } });
+ } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); } });
+ }
+ function emitBuildInfo(writeFileCallback) {
+ ts.Debug.assert(!options.out && !options.outFile);
+ ts.performance.mark("beforeEmit");
+ var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback),
+ /*targetSourceFile*/ undefined,
+ /*emitOnlyDtsFiles*/ false,
+ /*transformers*/ undefined,
+ /*declaraitonTransformers*/ undefined,
+ /*onlyBuildInfo*/ true);
+ ts.performance.mark("afterEmit");
+ ts.performance.measure("Emit", "beforeEmit", "afterEmit");
+ return emitResult;
}
function getResolvedProjectReferences() {
return resolvedProjectReferences;
@@ -87852,28 +88772,11 @@ var ts;
return projectReferences;
}
function getPrependNodes() {
- if (!projectReferences) {
- return ts.emptyArray;
- }
- var nodes = [];
- for (var i = 0; i < projectReferences.length; i++) {
- var ref = projectReferences[i];
- var resolvedRefOpts = resolvedProjectReferences[i].commandLine;
- if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
- var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
- // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
- if (!out)
- continue;
- var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
- var node = ts.createInputFiles(function (fileName) {
- var path = toPath(fileName);
- var sourceFile = getSourceFileByPath(path);
- return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
- }, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath);
- nodes.push(node);
- }
- }
- return nodes;
+ return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
+ var path = toPath(fileName);
+ var sourceFile = getSourceFileByPath(path);
+ return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
+ });
}
function isSourceFileFromExternalLibrary(file) {
return !!sourceFilesFoundSearchingNodeModules.get(file.path);
@@ -87945,8 +88848,7 @@ var ts;
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
ts.performance.mark("beforeEmit");
var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers);
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217
- emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -88948,6 +89850,14 @@ var ts;
if (options.declaration === false) {
createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
}
+ if (options.incremental === false) {
+ createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
+ }
+ }
+ if (options.tsBuildInfoFile) {
+ if (!ts.isIncrementalCompilation(options)) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
+ }
}
verifyProjectReferences();
// List of collected files is complete; validate exhautiveness if this is a project with a file list
@@ -89142,6 +90052,7 @@ var ts;
}
}
function verifyProjectReferences() {
+ var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getOutputPathForBuildInfo(options) : undefined;
forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
var parentFile = parent && parent.sourceFile;
@@ -89168,6 +90079,10 @@ var ts;
createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
}
}
+ if (!parent && buildInfoPath && buildInfoPath === ts.getOutputPathForBuildInfo(options)) {
+ createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
+ hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
+ }
});
}
function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
@@ -89317,6 +90232,27 @@ var ts;
};
}
ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
+ /* @internal */
+ function createPrependNodes(projectReferences, getCommandLine, readFile) {
+ if (!projectReferences)
+ return ts.emptyArray;
+ var nodes;
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = getCommandLine(ref, i);
+ if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
+ var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
+ // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
+ if (!out)
+ continue;
+ var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
+ (nodes || (nodes = [])).push(node);
+ }
+ }
+ return nodes || ts.emptyArray;
+ }
+ ts.createPrependNodes = createPrependNodes;
function resolveProjectReferencePath(hostOrRef, ref) {
var passedInRef = ref ? ref : hostOrRef;
return ts.resolveConfigFileProjectName(passedInRef.path);
@@ -89860,11 +90796,14 @@ var ts;
var affectedSignatures = oldState.currentAffectedFilesSignatures;
ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
}
+ var changedFilesSet = oldState.changedFilesSet;
if (canCopySemanticDiagnostics) {
- ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
+ ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
}
// Copy old state's changed files set
- ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet);
+ if (changedFilesSet) {
+ ts.copyEntries(changedFilesSet, state.changedFilesSet);
+ }
if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit;
state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
@@ -89902,7 +90841,7 @@ var ts;
// Unchanged file copy diagnostics
var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
if (diagnostics) {
- state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics);
+ state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics);
if (!state.semanticDiagnosticsFromOldState) {
state.semanticDiagnosticsFromOldState = ts.createMap();
}
@@ -89910,8 +90849,45 @@ var ts;
}
}
});
+ if (oldCompilerOptions &&
+ (oldCompilerOptions.outDir !== compilerOptions.outDir ||
+ oldCompilerOptions.declarationDir !== compilerOptions.declarationDir ||
+ (oldCompilerOptions.outFile || oldCompilerOptions.out) !== (compilerOptions.outFile || compilerOptions.out))) {
+ // Add all files to affectedFilesPendingEmit since emit changed
+ state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, newProgram.getSourceFiles().map(function (f) { return f.path; }));
+ if (state.affectedFilesPendingEmitIndex === undefined) {
+ state.affectedFilesPendingEmitIndex = 0;
+ }
+ ts.Debug.assert(state.seenAffectedFiles === undefined);
+ state.seenAffectedFiles = ts.createMap();
+ }
return state;
}
+ function convertToDiagnostics(diagnostics, newProgram) {
+ if (!diagnostics.length)
+ return ts.emptyArray;
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToDiagnosticRelatedInformation(diagnostic, newProgram) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && newProgram.getSourceFileByPath(file), messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToDiagnosticMessageChain(messageText, newProgram) });
+ }
+ function convertToDiagnosticMessageChain(diagnostic, newProgram) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToDiagnosticMessageChain(diagnostic.next, newProgram) });
+ }
/**
* Releases program and other related not needed properties
*/
@@ -90131,8 +91107,11 @@ var ts;
* This is called after completing operation on the next affected file.
* The operations here are postponed to ensure that cancellation during the iteration is handled correctly
*/
- function doneWithAffectedFile(state, affected, isPendingEmit) {
- if (affected === state.program) {
+ function doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit) {
+ if (isBuildInfoEmit) {
+ state.emittedBuildInfo = true;
+ }
+ else if (affected === state.program) {
state.changedFilesSet.clear();
state.programEmitComplete = true;
}
@@ -90149,8 +91128,8 @@ var ts;
/**
* Returns the result with affected file
*/
- function toAffectedFileResult(state, result, affected, isPendingEmit) {
- doneWithAffectedFile(state, affected, isPendingEmit);
+ function toAffectedFileResult(state, result, affected, isPendingEmit, isBuildInfoEmit) {
+ doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit);
return { result: result, affected: affected };
}
/**
@@ -90173,6 +91152,77 @@ var ts;
}
return diagnostics;
}
+ /**
+ * Gets the program information to be emitted in buildInfo so that we can use it to create new program
+ */
+ function getProgramBuildInfo(state) {
+ if (state.compilerOptions.outFile || state.compilerOptions.out)
+ return undefined;
+ var fileInfos = {};
+ state.fileInfos.forEach(function (value, key) {
+ var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
+ fileInfos[key] = signature === undefined ? value : { version: value.version, signature: signature };
+ });
+ var result = { fileInfos: fileInfos, options: state.compilerOptions };
+ if (state.referencedMap) {
+ var referencedMap_1 = {};
+ state.referencedMap.forEach(function (value, key) {
+ referencedMap_1[key] = ts.arrayFrom(value.keys());
+ });
+ result.referencedMap = referencedMap_1;
+ }
+ if (state.exportedModulesMap) {
+ var exportedModulesMap_1 = {};
+ state.exportedModulesMap.forEach(function (value, key) {
+ var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
+ // Not in temporary cache, use existing value
+ if (newValue === undefined)
+ exportedModulesMap_1[key] = ts.arrayFrom(value.keys());
+ // Value in cache and has updated value map, use that
+ else if (newValue)
+ exportedModulesMap_1[key] = ts.arrayFrom(newValue.keys());
+ });
+ result.exportedModulesMap = exportedModulesMap_1;
+ }
+ if (state.semanticDiagnosticsPerFile) {
+ var semanticDiagnosticsPerFile_1 = [];
+ // Currently not recording actual errors since those mean no emit for tsc --build
+ state.semanticDiagnosticsPerFile.forEach(function (value, key) { return semanticDiagnosticsPerFile_1.push(value.length ?
+ [
+ key,
+ state.hasReusableDiagnostic ?
+ value :
+ convertToReusableDiagnostics(value)
+ ] :
+ key); });
+ result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile_1;
+ }
+ return result;
+ }
+ function convertToReusableDiagnostics(diagnostics) {
+ ts.Debug.assert(!!diagnostics.length);
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToReusableDiagnosticRelatedInformation(diagnostic);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToReusableDiagnosticRelatedInformation(diagnostic) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && file.path, messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToReusableDiagnosticMessageChain(messageText) });
+ }
+ function convertToReusableDiagnosticMessageChain(diagnostic) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToReusableDiagnosticMessageChain(diagnostic.next) });
+ }
var BuilderProgramKind;
(function (BuilderProgramKind) {
BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
@@ -90229,6 +91279,7 @@ var ts;
var computeHash = host.createHash || ts.generateDjb2Hash;
var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
var backupState;
+ newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state); };
// To ensure that we arent storing any references to old program or new program without state
newProgram = undefined; // TODO: GH#18217
oldProgram = undefined;
@@ -90272,7 +91323,16 @@ var ts;
if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
affected = getNextAffectedFilePendingEmit(state);
if (!affected) {
- return undefined;
+ if (state.emittedBuildInfo) {
+ return undefined;
+ }
+ var affected_1 = ts.Debug.assertDefined(state.program);
+ return toAffectedFileResult(state,
+ // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
+ // Otherwise just affected file
+ affected_1.emitBuildInfo(writeFile || host.writeFile, cancellationToken), affected_1,
+ /*isPendingEmitFile*/ false,
+ /*isBuildInfoEmit*/ true);
}
isPendingEmitFile = true;
}
@@ -90405,6 +91465,53 @@ var ts;
}
}
ts.createBuilderProgram = createBuilderProgram;
+ function getMapOfReferencedSet(mapLike) {
+ if (!mapLike)
+ return undefined;
+ var map = ts.createMap();
+ // Copies keys/values from template. Note that for..in will not throw if
+ // template is undefined, and instead will just exit the loop.
+ for (var key in mapLike) {
+ if (ts.hasProperty(mapLike, key)) {
+ map.set(key, ts.arrayToSet(mapLike[key]));
+ }
+ }
+ return map;
+ }
+ function createBuildProgramUsingProgramBuildInfo(program) {
+ var fileInfos = ts.createMapFromTemplate(program.fileInfos);
+ var state = {
+ fileInfos: fileInfos,
+ compilerOptions: program.options,
+ referencedMap: getMapOfReferencedSet(program.referencedMap),
+ exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap),
+ semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return ts.isString(value) ? value : value[0]; }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }),
+ hasReusableDiagnostic: true
+ };
+ return {
+ getState: function () { return state; },
+ backupState: ts.noop,
+ restoreState: ts.noop,
+ getProgram: ts.notImplemented,
+ getProgramOrUndefined: function () { return undefined; },
+ releaseProgram: ts.noop,
+ getCompilerOptions: function () { return state.compilerOptions; },
+ getSourceFile: ts.notImplemented,
+ getSourceFiles: ts.notImplemented,
+ getOptionsDiagnostics: ts.notImplemented,
+ getGlobalDiagnostics: ts.notImplemented,
+ getConfigFileParsingDiagnostics: ts.notImplemented,
+ getSyntacticDiagnostics: ts.notImplemented,
+ getDeclarationDiagnostics: ts.notImplemented,
+ getSemanticDiagnostics: ts.notImplemented,
+ emit: ts.notImplemented,
+ getAllDependencies: ts.notImplemented,
+ getCurrentDirectory: ts.notImplemented,
+ emitNextAffectedFile: ts.notImplemented,
+ getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
+ };
+ }
+ ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
return {
getState: ts.notImplemented,
@@ -90424,7 +91531,7 @@ var ts;
getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
getAllDependencies: ts.notImplemented,
- getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); }
+ getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
};
function getProgram() {
return ts.Debug.assertDefined(state.program);
@@ -90450,10 +91557,10 @@ var ts;
/*@internal*/
var ts;
(function (ts) {
- function isPathInNodeModulesStartingWithDot(path) {
- return ts.stringContains(path, "/node_modules/.");
+ function isPathIgnored(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); });
}
- ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot;
+ ts.isPathIgnored = isPathIgnored;
ts.maxNumberOfFilesToIterateForInvalidation = 256;
function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
var filesWithChangedSetOfUnresolvedImports;
@@ -90975,7 +92082,7 @@ var ts;
}
else {
// If something to do with folder/file starting with "." in node_modules folder, skip it
- if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (isPathIgnored(fileOrDirectoryPath))
return false;
// Some file or directory in the watching directory is created
// Return early if it does not have any of the watching extension or not the custom failed lookup path
@@ -91452,6 +92559,8 @@ var ts;
case ".jsx" /* Jsx */:
case ".json" /* Json */:
return ext;
+ case ".tsbuildinfo" /* TsBuildInfo */:
+ return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
default:
return ts.Debug.assertNever(ext);
}
@@ -91733,7 +92842,7 @@ var ts;
writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; },
createHash: ts.maybeBind(system, system.createHash),
- createProgram: createProgram
+ createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
};
}
ts.createProgramHost = createProgramHost;
@@ -91743,7 +92852,7 @@ var ts;
function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
var writeFileName = function (s) { return system.write(s + system.newLine); };
- var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram);
+ var result = createProgramHost(system, createProgram);
ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
result.afterProgramCreate = function (builderProgram) {
var compilerOptions = builderProgram.getCompilerOptions();
@@ -92172,7 +93281,7 @@ var ts;
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
nextSourceFileVersion(fileOrDirectoryPath);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
// If the the added or created file or directory is not supported file name, ignore the file
// But when watched directory is added/removed, we need to reload the file list
@@ -92226,16 +93335,23 @@ var ts;
* This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
*/
UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
- UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream";
- UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate";
- UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked";
- UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream";
+ /**
+ * The project appears out of date because its upstream inputs are newer than its outputs,
+ * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
+ * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
+ */
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
+ UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
+ UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
+ UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
+ UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
+ UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
/**
* Projects with no outputs (i.e. "solution" files)
*/
- UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly";
+ UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
})(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
function createFileMap(toPath) {
// tslint:disable-next-line:no-null-keyword
@@ -92316,24 +93432,18 @@ var ts;
}
return outputs;
}
- function getOutFileOutputs(project) {
- var out = project.options.outFile || project.options.out;
- if (!out) {
- return ts.Debug.fail("outFile must be set");
- }
+ function getOutFileOutputs(project, ignoreBuildInfo) {
+ ts.Debug.assert(!!project.options.outFile || !!project.options.out, "outFile must be set");
+ var _a = ts.getOutputPathsForBundle(project.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
var outputs = [];
- outputs.push(out);
- if (project.options.sourceMap) {
- outputs.push(out + ".map");
- }
- if (ts.getEmitDeclarations(project.options)) {
- var dts = ts.changeExtension(out, ".d.ts" /* Dts */);
- outputs.push(dts);
- if (project.options.declarationMap) {
- outputs.push(dts + ".map");
- }
- }
- return outputs;
+ var addOutput = function (path) { return path && (outputs || (outputs = [])).push(path); };
+ addOutput(jsFilePath);
+ addOutput(sourceMapFilePath);
+ addOutput(declarationFilePath);
+ addOutput(declarationMapPath);
+ if (!ignoreBuildInfo)
+ addOutput(buildInfoPath);
+ return outputs || ts.emptyArray;
}
function rootDirOfOptions(opts, configFileName) {
return opts.rootDir || ts.getDirectoryPath(configFileName);
@@ -92366,14 +93476,14 @@ var ts;
}
function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
host.reportErrorSummary = reportErrorSummary;
return host;
}
ts.createSolutionBuilderHost = createSolutionBuilderHost;
function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
var watchHost = ts.createWatchHost(system, reportWatchStatus);
ts.copyProperties(host, watchHost);
return host;
@@ -92407,7 +93517,18 @@ var ts;
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; });
var originalGetSourceFile = compilerHost.getSourceFile;
var computeHash = host.createHash || ts.generateDjb2Hash;
- updateGetSourceFile();
+ compilerHost.getSourceFile = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
+ if (result) {
+ result.version = computeHash.call(host, result.text);
+ }
+ return result;
+ };
+ var buildInfoChecked = createFileMap(toPath);
// Watch state
var builderPrograms = createFileMap(toPath);
var diagnostics = createFileMap(toPath);
@@ -92445,6 +93566,7 @@ var ts;
projectStatus.clear();
missingRoots.clear();
globalDependencyGraph = undefined;
+ buildInfoChecked.clear();
diagnostics.clear();
projectPendingBuild.clear();
projectErrorsReported.clear();
@@ -92459,29 +93581,6 @@ var ts;
ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); });
ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher);
builderPrograms.clear();
- updateGetSourceFile();
- }
- function updateGetSourceFile() {
- if (options.watch) {
- if (compilerHost.getSourceFile === originalGetSourceFile) {
- compilerHost.getSourceFile = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
- if (result && options.watch) {
- result.version = computeHash.call(host, result.text);
- }
- return result;
- };
- }
- }
- else {
- if (compilerHost.getSourceFile !== originalGetSourceFile) {
- compilerHost.getSourceFile = originalGetSourceFile;
- }
- }
}
function isParsedCommandLine(entry) {
return !!entry.options;
@@ -92713,25 +93812,28 @@ var ts;
upstreamProjectName: ref.path
};
}
- // If the upstream project's newest file is older than our oldest output, we
- // can't be out of date because of it
- if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
- continue;
- }
- // If the upstream project has only change .d.ts files, and we've built
- // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
- if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
- pseudoUpToDate = true;
- upstreamChangedProject = ref.path;
- continue;
+ // Check oldest output file name only if there is no missing output file name
+ if (!missingOutputFileName) {
+ // If the upstream project's newest file is older than our oldest output, we
+ // can't be out of date because of it
+ if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
+ continue;
+ }
+ // If the upstream project has only change .d.ts files, and we've built
+ // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
+ if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
+ pseudoUpToDate = true;
+ upstreamChangedProject = ref.path;
+ continue;
+ }
+ // We have an output older than an upstream output - we are out of date
+ ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
+ return {
+ type: UpToDateStatusType.OutOfDateWithUpstream,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerProjectName: ref.path
+ };
}
- // We have an output older than an upstream output - we are out of date
- ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
- return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: oldestOutputFileName,
- newerProjectName: ref.path
- };
}
}
if (missingOutputFileName !== undefined) {
@@ -92747,9 +93849,23 @@ var ts;
newerInputFileName: newestInputFileName
};
}
+ if (!buildInfoChecked.hasKey(project.options.configFilePath)) {
+ buildInfoChecked.setValue(project.options.configFilePath, true);
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath) {
+ var value = readFileWithCache(buildInfoPath);
+ var buildInfo = value && ts.getBuildInfo(value);
+ if (buildInfo && buildInfo.version !== ts.version) {
+ return {
+ type: UpToDateStatusType.TsVersionOutputOfDate,
+ version: buildInfo.version
+ };
+ }
+ }
+ }
if (usesPrepend && pseudoUpToDate) {
return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
+ type: UpToDateStatusType.OutOfDateWithPrepend,
outOfDateOutputFileName: oldestOutputFileName,
newerProjectName: upstreamChangedProject
};
@@ -92883,7 +93999,9 @@ var ts;
updateOutputTimestamps(proj);
return;
}
- var buildResult = buildSingleProject(resolved);
+ var buildResult = status.type === UpToDateStatusType.OutOfDateWithPrepend ?
+ updateBundle(resolved) : // Fake that files have been built by manipulating prepend and existing output
+ buildSingleProject(resolved); // Actual build
if (buildResult & BuildResultFlags.AnyErrors)
return;
var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue;
@@ -92899,17 +94017,26 @@ var ts;
// If declaration output is changed, build the project
// otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
var status_1 = projectStatus.getValue(project);
- if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
- if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) {
+ if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
+ if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes || status_1.type === UpToDateStatusType.OutOfDateWithPrepend)) {
projectStatus.setValue(project, {
type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: status_1.oldestOutputFileName,
+ outOfDateOutputFileName: status_1.type === UpToDateStatusType.OutOfDateWithPrepend ? status_1.outOfDateOutputFileName : status_1.oldestOutputFileName,
newerProjectName: resolved
});
}
}
else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) {
- status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
+ if (prepend) {
+ projectStatus.setValue(project, {
+ type: UpToDateStatusType.OutOfDateWithPrepend,
+ outOfDateOutputFileName: status_1.oldestOutputFileName,
+ newerProjectName: resolved
+ });
+ }
+ else {
+ status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
+ }
}
addProjToQueue(project);
}
@@ -92966,8 +94093,7 @@ var ts;
}
if (options.verbose)
reportStatus(ts.Diagnostics.Building_project_0, proj);
- var resultFlags = BuildResultFlags.None;
- resultFlags |= BuildResultFlags.DeclarationOutputUnchanged;
+ var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
var configFile = parseConfigFile(proj);
if (!configFile) {
// Failed to read the config file
@@ -92983,8 +94109,7 @@ var ts;
}
// TODO: handle resolve module name to cache result in project reference redirect
projectCompilerOptions = configFile.options;
- var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences);
- projectCompilerOptions = baseCompilerOptions;
+ var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, getOldProgram(proj, configFile), configFile.errors, configFile.projectReferences);
// Don't emit anything in the presence of syntactic errors or options diagnostics
var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
@@ -93045,12 +94170,14 @@ var ts;
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
}
}
@@ -93063,9 +94190,67 @@ var ts;
builderPrograms.setValue(proj, program);
}
}
+ function getOldProgram(proj, parsed) {
+ var value = builderPrograms.getValue(proj);
+ if (value)
+ return value;
+ var buildInfoPath = ts.getOutputPathForBuildInfo(parsed.options);
+ if (!buildInfoPath)
+ return undefined;
+ var content = readFileWithCache(buildInfoPath);
+ if (!content)
+ return undefined;
+ var buildInfo = ts.getBuildInfo(content);
+ if (buildInfo.version !== ts.version)
+ return undefined;
+ return buildInfo.program && ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program);
+ }
+ function updateBundle(proj) {
+ if (options.dry) {
+ reportStatus(ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, proj);
+ return BuildResultFlags.Success;
+ }
+ if (options.verbose)
+ reportStatus(ts.Diagnostics.Updating_output_of_project_0, proj);
+ // Update js, and source map
+ var config = ts.Debug.assertDefined(parseConfigFile(proj));
+ projectCompilerOptions = config.options;
+ var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) { return parseConfigFile(resolveProjectName(ref.path)); });
+ if (ts.isString(outputFiles)) {
+ reportStatus(ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, proj, relName(outputFiles));
+ return buildSingleProject(proj);
+ }
+ // Actual Emit
+ ts.Debug.assert(!!outputFiles.length);
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ var emittedOutputs = createFileMap(toPath);
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
+ emittedOutputs.setValue(name, true);
+ ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
+ });
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
+ reportAndStoreErrors(proj, emitDiagnostics);
+ projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Emit errors" });
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged | BuildResultFlags.EmitErrors;
+ }
+ // Update timestamps for dts
+ var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(config, minimumDate, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
+ oldestOutputFileName: outputFiles[0].name
+ };
+ diagnostics.removeKey(proj);
+ projectStatus.setValue(proj, status);
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged;
+ }
function updateOutputTimestamps(proj) {
if (options.dry) {
- return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath);
+ return reportStatus(ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
}
var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime });
@@ -93192,7 +94377,9 @@ var ts;
// Do nothing
continue;
}
- var buildResult = buildSingleProject(next);
+ var buildResult = status.type === UpToDateStatusType.OutOfDateWithPrepend && !options.force ?
+ updateBundle(next) : // Fake that files have been built by manipulating prepend and existing output
+ buildSingleProject(next); // Actual build
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
@@ -93254,6 +94441,9 @@ var ts;
var inputFile = _a[_i];
outputs.push.apply(outputs, getOutputFileNames(inputFile, project));
}
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath)
+ outputs.push(buildInfoPath);
return outputs;
}
}
@@ -93285,6 +94475,8 @@ var ts;
}
// Don't report anything for "up to date because it was already built" -- too verbose
break;
+ case UpToDateStatusType.OutOfDateWithPrepend:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(configFileName), relName(status.newerProjectName));
case UpToDateStatusType.UpToDateWithUpstreamTypes:
return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName));
case UpToDateStatusType.UpstreamOutOfDate:
@@ -93293,6 +94485,8 @@ var ts;
return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName));
case UpToDateStatusType.Unbuildable:
return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason);
+ case UpToDateStatusType.TsVersionOutputOfDate:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(configFileName), status.version, ts.version);
case UpToDateStatusType.ContainerOnly:
// Don't report status on "solution" projects
case UpToDateStatusType.ComputingUpstream:
@@ -93691,8 +94885,8 @@ var ts;
if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
continue;
}
- var result_7 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
- var packageJson = result_7.config;
+ var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
+ var packageJson = result_1.config;
// npm 3's package.json contains a "_requiredBy" field
// we should include all the top level module names for npm 2, and only module names whose
// "_requiredBy" field starts with "#" or equals "/" for npm 3.
@@ -94099,7 +95293,7 @@ var ts;
case 242 /* TypeAliasDeclaration */:
case 168 /* TypeLiteral */:
return 2 /* Type */;
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
// If it has no name node, it shares the name with the value declaration below it.
return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */;
case 278 /* EnumMember */:
@@ -94124,14 +95318,14 @@ var ts;
case 255 /* ExportDeclaration */:
return 7 /* All */;
// An external module can be a Value
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 4 /* Namespace */ | 1 /* Value */;
}
return 7 /* All */;
}
ts.getMeaningFromDeclaration = getMeaningFromDeclaration;
function getMeaningFromLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return 1 /* Value */;
}
else if (node.parent.kind === 254 /* ExportAssignment */ || node.parent.kind === 259 /* ExternalModuleReference */) {
@@ -94337,7 +95531,7 @@ var ts;
return undefined;
}
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
case 239 /* FunctionDeclaration */:
@@ -94355,7 +95549,7 @@ var ts;
ts.getContainerNode = getContainerNode;
function getNodeKind(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */;
case 244 /* ModuleDeclaration */:
return "module" /* moduleElement */;
@@ -94364,8 +95558,8 @@ var ts;
return "class" /* classElement */;
case 241 /* InterfaceDeclaration */: return "interface" /* interfaceElement */;
case 242 /* TypeAliasDeclaration */:
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
return "type" /* typeElement */;
case 243 /* EnumDeclaration */: return "enum" /* enumElement */;
case 237 /* VariableDeclaration */:
@@ -94782,8 +95976,8 @@ var ts;
isWhiteSpaceOnlyJsxText(child);
if (lookInPreviousChild) {
// actual start of the node is past the position - previous token should be at the end of previous child
- var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
- return candidate_2 && findRightmostToken(candidate_2, sourceFile);
+ var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
+ return candidate_1 && findRightmostToken(candidate_1, sourceFile);
}
else {
// candidate should be in this node
@@ -94791,7 +95985,7 @@ var ts;
}
}
}
- ts.Debug.assert(startNode !== undefined || n.kind === 279 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
+ ts.Debug.assert(startNode !== undefined || n.kind === 284 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n));
// Here we know that none of child token nodes embrace the position,
// the only known case is when position is at the end of the file.
// Try to find the rightmost token in the file without filtering.
@@ -95638,6 +96832,17 @@ var ts;
return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName));
}
ts.getScriptKind = getScriptKind;
+ function getSymbolTarget(symbol) {
+ var next = symbol;
+ while (isTransientSymbol(next) && next.target) {
+ next = next.target;
+ }
+ return next;
+ }
+ ts.getSymbolTarget = getSymbolTarget;
+ function isTransientSymbol(symbol) {
+ return (symbol.flags & 33554432 /* Transient */) !== 0;
+ }
function getUniqueSymbolId(symbol, checker) {
return ts.getSymbolId(ts.skipAlias(symbol, checker));
}
@@ -95696,14 +96901,14 @@ var ts;
ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext);
if (visited === node) {
// This only happens for leaf nodes - internal nodes always see their children change.
- var clone_8 = ts.getSynthesizedClone(node);
- if (ts.isStringLiteral(clone_8)) {
- clone_8.textSourceNode = node;
+ var clone_1 = ts.getSynthesizedClone(node);
+ if (ts.isStringLiteral(clone_1)) {
+ clone_1.textSourceNode = node;
}
- else if (ts.isNumericLiteral(clone_8)) {
- clone_8.numericLiteralFlags = node.numericLiteralFlags;
+ else if (ts.isNumericLiteral(clone_1)) {
+ clone_1.numericLiteralFlags = node.numericLiteralFlags;
}
- return ts.setTextRange(clone_8, node);
+ return ts.setTextRange(clone_1, node);
}
// PERF: As an optimization, rather than calling getSynthesizedClone, we'll update
// the new node created by visitEachChild with the extra changes getSynthesizedClone
@@ -95789,8 +96994,27 @@ var ts;
return lastPos;
}
ts.getRenameLocation = getRenameLocation;
- function copyComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
- ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) {
+ function copyLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
+ }
+ ts.copyLeadingComments = copyLeadingComments;
+ function copyTrailingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticTrailingComment));
+ }
+ ts.copyTrailingComments = copyTrailingComments;
+ /**
+ * This function copies the trailing comments for the token that comes before `sourceNode`, as leading comments of `targetNode`.
+ * This is useful because sometimes a comment that refers to `sourceNode` will be a leading comment for `sourceNode`, according to the
+ * notion of trivia ownership, and instead will be a trailing comment for the token before `sourceNode`, e.g.:
+ * `function foo(\* not leading comment for a *\ a: string) {}`
+ * The comment refers to `a` but belongs to the `(` token, but we might want to copy it.
+ */
+ function copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) {
+ ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment));
+ }
+ ts.copyTrailingAsLeadingComments = copyTrailingAsLeadingComments;
+ function getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, cb) {
+ return function (pos, end, kind, htnl) {
if (kind === 3 /* MultiLineCommentTrivia */) {
// Remove leading /*
pos += 2;
@@ -95801,10 +97025,9 @@ var ts;
// Remove leading //
pos += 2;
}
- ts.addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
- });
+ cb(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl);
+ };
}
- ts.copyComments = copyComments;
function indexInTextChange(change, name) {
if (ts.startsWith(change, name))
return 0;
@@ -95885,6 +97108,30 @@ var ts;
return checker.getTypeAtLocation(caseClause.parent.parent.expression);
}
ts.getSwitchedType = getSwitchedType;
+ function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
+ var checker = program.getTypeChecker();
+ var typeIsAccessible = true;
+ var notAccessible = function () { typeIsAccessible = false; };
+ var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
+ trackSymbol: function (symbol, declaration, meaning) {
+ // TODO: GH#18217
+ typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
+ },
+ reportInaccessibleThisError: notAccessible,
+ reportPrivateInBaseOfClassExpression: notAccessible,
+ reportInaccessibleUniqueSymbolError: notAccessible,
+ moduleResolverHost: {
+ readFile: host.readFile,
+ fileExists: host.fileExists,
+ directoryExists: host.directoryExists,
+ getSourceFiles: program.getSourceFiles,
+ getCurrentDirectory: program.getCurrentDirectory,
+ getCommonSourceDirectory: program.getCommonSourceDirectory,
+ }
+ });
+ return typeIsAccessible ? res : undefined;
+ }
+ ts.getTypeNodeIfAccessible = getTypeNodeIfAccessible;
})(ts || (ts = {}));
var ts;
(function (ts) {
@@ -96128,7 +97375,7 @@ var ts;
var lastEnd = 0;
for (var i = 0; i < dense.length; i += 3) {
var start = dense[i];
- var length_5 = dense[i + 1];
+ var length_1 = dense[i + 1];
var type = dense[i + 2];
// Make a whitespace entry between the last item and this one.
if (lastEnd >= 0) {
@@ -96137,8 +97384,8 @@ var ts;
entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace });
}
}
- entries.push({ length: length_5, classification: convertClassification(type) });
- lastEnd = start + length_5;
+ entries.push({ length: length_1, classification: convertClassification(type) });
+ lastEnd = start + length_1;
}
var whitespaceLength = text.length - lastEnd;
if (whitespaceLength > 0) {
@@ -96536,18 +97783,18 @@ var ts;
pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param"
pos = tag.tagName.end;
switch (tag.kind) {
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
processJSDocParameterTag(tag);
break;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
processJSDocTemplateTag(tag);
pos = tag.end;
break;
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
- case 300 /* JSDocReturnTag */:
+ case 305 /* JSDocReturnTag */:
processElement(tag.typeExpression);
pos = tag.end;
break;
@@ -96851,6 +98098,7 @@ var ts;
case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */;
case ".ts" /* Ts */: return ".ts" /* tsModifier */;
case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */;
+ case ".tsbuildinfo" /* TsBuildInfo */: return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported.");
case undefined: return "" /* none */;
default:
return ts.Debug.assertNever(extension);
@@ -97081,8 +98329,8 @@ var ts;
* both foo.ts and foo.tsx become foo
*/
var foundFiles = ts.createMap(); // maps file to its extension
- for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
- var filePath = files_3[_i];
+ for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
+ var filePath = files_1[_i];
filePath = ts.normalizePath(filePath);
if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) {
continue;
@@ -97127,7 +98375,7 @@ var ts;
continue;
var patterns = paths[path];
if (patterns) {
- var _loop_11 = function (name, kind, extension) {
+ var _loop_1 = function (name, kind, extension) {
// Path mappings may provide a duplicate way to get to something we've already added, so don't add again.
if (!result.some(function (entry) { return entry.name === name; })) {
result.push(nameAndKind(name, kind, extension));
@@ -97135,7 +98383,7 @@ var ts;
};
for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) {
var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension;
- _loop_11(name, kind, extension);
+ _loop_1(name, kind, extension);
}
}
}
@@ -97170,7 +98418,7 @@ var ts;
// (But do if we didn't find anything, e.g. 'package.json' missing.)
var foundGlobal = false;
if (fragmentDirectory === undefined) {
- var _loop_12 = function (moduleName) {
+ var _loop_2 = function (moduleName) {
if (!result.some(function (entry) { return entry.name === moduleName; })) {
foundGlobal = true;
result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined));
@@ -97178,7 +98426,7 @@ var ts;
};
for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) {
var moduleName = _c[_b];
- _loop_12(moduleName);
+ _loop_2(moduleName);
}
}
if (!foundGlobal) {
@@ -97292,8 +98540,8 @@ var ts;
// Check for typings specified in compiler options
var seen = ts.createMap();
var typeRoots = tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray;
- for (var _i = 0, typeRoots_2 = typeRoots; _i < typeRoots_2.length; _i++) {
- var root = typeRoots_2[_i];
+ for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
+ var root = typeRoots_1[_i];
getCompletionEntriesFromDirectories(root);
}
// Also get all @types typings installed in visible node_modules directories
@@ -97655,8 +98903,8 @@ var ts;
// Based on the order we add things we will always see locals first, then globals, then module exports.
// So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name.
var uniques = ts.createMap();
- for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) {
- var symbol = symbols_3[_i];
+ for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
+ var symbol = symbols_1[_i];
var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined;
var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences);
if (!entry) {
@@ -97875,7 +99123,7 @@ var ts;
return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker));
}
function isModuleSymbol(symbol) {
- return symbol.declarations.some(function (d) { return d.kind === 279 /* SourceFile */; });
+ return symbol.declarations.some(function (d) { return d.kind === 284 /* SourceFile */; });
}
function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) {
var typeChecker = program.getTypeChecker();
@@ -97926,11 +99174,11 @@ var ts;
if (tag.tagName.pos <= position && position <= tag.tagName.end) {
return { kind: 1 /* JsDocTagName */ };
}
- if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
currentToken = ts.getTokenAtPosition(sourceFile, position);
if (!currentToken ||
(!ts.isDeclarationName(currentToken) &&
- (currentToken.parent.kind !== 305 /* JSDocPropertyTag */ ||
+ (currentToken.parent.kind !== 310 /* JSDocPropertyTag */ ||
currentToken.parent.name !== currentToken))) {
// Use as type location if inside tag's type expression
insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
@@ -97956,9 +99204,9 @@ var ts;
// Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS|
// Skip this partial identifier and adjust the contextToken to the token that precedes it.
if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) {
- var start_3 = ts.timestamp();
+ var start_1 = ts.timestamp();
contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217
- log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_3));
+ log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1));
}
// Find the node where completion is requested on.
// Also determine whether we are trying to complete with members of that node
@@ -98101,11 +99349,11 @@ var ts;
return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer };
function isTagWithTypeExpression(tag) {
switch (tag.kind) {
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 304 /* JSDocTypedefTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 309 /* JSDocTypedefTag */:
return true;
default:
return false;
@@ -98145,7 +99393,7 @@ var ts;
}
}
// If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods).
- if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 279 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) {
+ if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 284 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) {
addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node));
}
return;
@@ -98278,7 +99526,7 @@ var ts;
var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */;
symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined");
// Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions`
- if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 279 /* SourceFile */) {
+ if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 284 /* SourceFile */) {
var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false);
if (thisType) {
for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) {
@@ -98311,7 +99559,7 @@ var ts;
}
function isSnippetScope(scopeNode) {
switch (scopeNode.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 206 /* TemplateExpression */:
case 270 /* JsxExpression */:
case 218 /* Block */:
@@ -99143,7 +100391,7 @@ var ts;
function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) {
// class c { method() { } | method2() { } }
switch (location.kind) {
- case 306 /* SyntaxList */:
+ case 311 /* SyntaxList */:
return ts.tryCast(location.parent, ts.isObjectTypeDeclaration);
case 1 /* EndOfFileToken */:
var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration);
@@ -99328,7 +100576,7 @@ var ts;
var child = throwStatement;
while (child.parent) {
var parent = child.parent;
- if (ts.isFunctionBlock(parent) || parent.kind === 279 /* SourceFile */) {
+ if (ts.isFunctionBlock(parent) || parent.kind === 284 /* SourceFile */) {
return parent;
}
// A throw-statement is only owned by a try-statement if the try-statement has
@@ -99386,7 +100634,7 @@ var ts;
var container = declaration.parent;
switch (container.kind) {
case 245 /* ModuleBlock */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 218 /* Block */:
case 271 /* CaseClause */:
case 272 /* DefaultClause */:
@@ -99884,7 +101132,7 @@ var ts;
}
else if (!isAvailableThroughGlobal) {
var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration);
- ts.Debug.assert(sourceFileLike.kind === 279 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */);
+ ts.Debug.assert(sourceFileLike.kind === 284 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */);
if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) {
addIndirectUsers(sourceFileLike);
}
@@ -100050,10 +101298,10 @@ var ts;
function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
var refs = [];
var checker = program.getTypeChecker();
- for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
- var referencingFile = sourceFiles_3[_i];
+ for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) {
+ var referencingFile = sourceFiles_1[_i];
var searchSourceFile = searchModuleSymbol.valueDeclaration;
- if (searchSourceFile.kind === 279 /* SourceFile */) {
+ if (searchSourceFile.kind === 284 /* SourceFile */) {
for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
var ref = _b[_a];
if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) {
@@ -100081,8 +101329,8 @@ var ts;
/** Returns a map from a module symbol Id to all import statements that directly reference the module. */
function getDirectImportsMap(sourceFiles, checker, cancellationToken) {
var map = ts.createMap();
- for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
- var sourceFile = sourceFiles_4[_i];
+ for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
+ var sourceFile = sourceFiles_2[_i];
if (cancellationToken)
cancellationToken.throwIfCancellationRequested();
forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
@@ -100101,7 +101349,7 @@ var ts;
}
/** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */
function forEachPossibleImportOrExportStatement(sourceFileLike, action) {
- return ts.forEach(sourceFileLike.kind === 279 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
+ return ts.forEach(sourceFileLike.kind === 284 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) {
return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action));
});
}
@@ -100325,7 +101573,7 @@ var ts;
return node.getSourceFile();
}
var parent = node.parent;
- if (parent.kind === 279 /* SourceFile */) {
+ if (parent.kind === 284 /* SourceFile */) {
return parent;
}
ts.Debug.assert(parent.kind === 245 /* ModuleBlock */);
@@ -100387,16 +101635,16 @@ var ts;
}
FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition;
function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return undefined;
}
var checker = program.getTypeChecker();
// If invoked directly on a shorthand property assignment, then return
// the declaration of the symbol being assigned (not the symbol being assigned to).
if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) {
- var result_8 = [];
- FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_8.push(nodeEntry(node)); });
- return result_8;
+ var result_1 = [];
+ FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_1.push(nodeEntry(node)); });
+ return result_1;
}
else if (node.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
// References to and accesses on the super keyword only have one possible implementation, so no
@@ -100428,27 +101676,27 @@ var ts;
case 0 /* Symbol */: {
var symbol = def.symbol;
var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
- var name_4 = displayParts_1.map(function (p) { return p.text; }).join("");
- return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 };
+ var name_1 = displayParts_1.map(function (p) { return p.text; }).join("");
+ return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_1, kind: kind_1, displayParts: displayParts_1 };
}
case 1 /* Label */: {
- var node_3 = def.node;
- return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] };
+ var node_1 = def.node;
+ return { node: node_1, name: node_1.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_1.text, ts.SymbolDisplayPartKind.text)] };
}
case 2 /* Keyword */: {
- var node_4 = def.node;
- var name_5 = ts.tokenToString(node_4.kind);
- return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] };
+ var node_2 = def.node;
+ var name_2 = ts.tokenToString(node_2.kind);
+ return { node: node_2, name: name_2, kind: "keyword" /* keyword */, displayParts: [{ text: name_2, kind: "keyword" /* keyword */ }] };
}
case 3 /* This */: {
- var node_5 = def.node;
- var symbol = checker.getSymbolAtLocation(node_5);
- var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")];
- return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
+ var node_3 = def.node;
+ var symbol = checker.getSymbolAtLocation(node_3);
+ var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_3.getSourceFile(), ts.getContainerNode(node_3), node_3).displayParts || [ts.textPart("this")];
+ return { node: node_3, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 };
}
case 4 /* String */: {
- var node_6 = def.node;
- return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] };
+ var node_4 = def.node;
+ return { node: node_4, name: node_4.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_4), ts.SymbolDisplayPartKind.stringLiteral)] };
}
default:
return ts.Debug.assertNever(def);
@@ -100607,8 +101855,8 @@ var ts;
case 248 /* ImportEqualsDeclaration */:
case 253 /* ImportSpecifier */:
case 241 /* InterfaceDeclaration */:
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
case 267 /* JsxAttribute */:
case 244 /* ModuleDeclaration */:
case 247 /* NamespaceExportDeclaration */:
@@ -100633,8 +101881,8 @@ var ts;
return !!decl.initializer || ts.isCatchClause(decl.parent);
case 155 /* MethodSignature */:
case 153 /* PropertySignature */:
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
return false;
default:
return ts.Debug.failBadSyntaxKind(decl);
@@ -100726,7 +101974,7 @@ var ts;
result = references;
continue;
}
- var _loop_13 = function (entry) {
+ var _loop_3 = function (entry) {
if (!entry.definition || entry.definition.type !== 0 /* Symbol */) {
result.push(entry);
return "continue";
@@ -100758,7 +102006,7 @@ var ts;
};
for (var _b = 0, references_1 = references; _b < references_1.length; _b++) {
var entry = references_1[_b];
- _loop_13(entry);
+ _loop_3(entry);
}
}
return result;
@@ -100794,7 +102042,7 @@ var ts;
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
switch (decl.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.)
break;
case 244 /* ModuleDeclaration */:
@@ -101018,8 +102266,8 @@ var ts;
var sourceId = ts.getNodeId(sourceFile);
var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = ts.createMap());
var anyNewSymbols = false;
- for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) {
- var sym = symbols_4[_i];
+ for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
+ var sym = symbols_2[_i];
anyNewSymbols = ts.addToSeen(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols;
}
return anyNewSymbols;
@@ -101158,14 +102406,14 @@ var ts;
return undefined;
}
var scope;
- for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) {
- var declaration = declarations_11[_i];
+ for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
+ var declaration = declarations_1[_i];
var container = ts.getContainerNode(declaration);
if (scope && scope !== container) {
// Different declarations have different containers, bail out
return undefined;
}
- if (!container || container.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
+ if (!container || container.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) {
// This is a global variable and not an external module, any declaration defined
// within this scope is visible outside the file
return undefined;
@@ -101210,8 +102458,8 @@ var ts;
if (!signature.name || !ts.isIdentifier(signature.name))
return;
var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name));
- for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
- var sourceFile = sourceFiles_5[_i];
+ for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) {
+ var sourceFile = sourceFiles_3[_i];
for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) {
var name = _b[_a];
if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText)
@@ -101724,7 +102972,7 @@ var ts;
staticFlag &= ts.getModifierFlags(searchSpaceNode);
searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) {
return undefined;
}
@@ -101737,7 +102985,7 @@ var ts;
default:
return undefined;
}
- var references = ts.flatMap(searchSpaceNode.kind === 279 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
+ var references = ts.flatMap(searchSpaceNode.kind === 284 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) {
if (!ts.isThis(node)) {
@@ -101756,8 +103004,8 @@ var ts;
// Make sure the container belongs to the same class
// and has the appropriate static modifier from the original container.
return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag;
- case 279 /* SourceFile */:
- return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
+ case 284 /* SourceFile */:
+ return container.kind === 284 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node);
}
});
}).map(function (n) { return FindAllReferences.nodeEntry(n); });
@@ -101913,8 +103161,8 @@ var ts;
// To achieve that we will keep iterating until the result stabilizes.
// Remember the last meaning
lastIterationMeaning = meaning;
- for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) {
- var declaration = declarations_12[_i];
+ for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
+ var declaration = declarations_2[_i];
var declarationMeaning = ts.getMeaningFromDeclaration(declaration);
if (declarationMeaning & meaning) {
meaning |= declarationMeaning;
@@ -102063,8 +103311,8 @@ var ts;
// Type annotation needed due to #7294
var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer];
var foundExactMatch = false;
- for (var _i = 0, elements_5 = elements; _i < elements_5.length; _i++) {
- var element = elements_5[_i];
+ for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
+ var element = elements_1[_i];
foundExactMatch = tryUpdateString(element) || foundExactMatch;
}
return foundExactMatch;
@@ -102086,7 +103334,7 @@ var ts;
}
function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) {
var allFiles = program.getSourceFiles();
- var _loop_14 = function (sourceFile) {
+ var _loop_4 = function (sourceFile) {
var newFromOld = oldToNew(sourceFile.path);
var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path;
var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath);
@@ -102118,7 +103366,7 @@ var ts;
};
for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) {
var sourceFile = allFiles_1[_i];
- _loop_14(sourceFile);
+ _loop_4(sourceFile);
}
}
function combineNormal(pathA, pathB) {
@@ -102148,9 +103396,9 @@ var ts;
return undefined;
// First try resolved module
if (resolved.resolvedModule) {
- var result_9 = tryChange(resolved.resolvedModule.resolvedFileName);
- if (result_9)
- return result_9;
+ var result_2 = tryChange(resolved.resolvedModule.resolvedFileName);
+ if (result_2)
+ return result_2;
}
// Then failed lookups except package.json since we dont want to touch them (only included ts/js files)
var result = ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson);
@@ -102260,10 +103508,10 @@ var ts;
// bar(({pr/*goto*/op1})=>{});
if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) &&
(node === (parent.propertyName || parent.name))) {
- var name_6 = ts.getNameFromPropertyName(node);
+ var name_3 = ts.getNameFromPropertyName(node);
var type = typeChecker.getTypeAtLocation(parent.parent);
- return name_6 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) {
- var prop = t.getProperty(name_6);
+ return name_3 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) {
+ var prop = t.getProperty(name_3);
return prop && getDefinitionFromSymbol(typeChecker, prop, node);
});
}
@@ -102611,11 +103859,11 @@ var ts;
JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
function getCommentHavingNodes(declaration) {
switch (declaration.kind) {
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return [declaration];
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
return [declaration, declaration.parent];
default:
return ts.getJSDocCommentsAndTags(declaration);
@@ -102636,16 +103884,16 @@ var ts;
function getCommentText(tag) {
var comment = tag.comment;
switch (tag.kind) {
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return withNode(tag.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return withList(tag.typeParameters);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return withNode(tag.typeExpression);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
var name = tag.name;
return name ? withNode(name) : comment;
default:
@@ -102856,7 +104104,7 @@ var ts;
: undefined;
return { commentOwner: commentOwner, parameters: parameters_1 };
}
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return "quit";
case 244 /* ModuleDeclaration */:
// If in walking up the tree, we hit a a nested namespace declaration,
@@ -102908,7 +104156,7 @@ var ts;
if (!patternMatcher)
return ts.emptyArray;
var rawItems = [];
- var _loop_15 = function (sourceFile) {
+ var _loop_5 = function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
if (excludeDtsFiles && sourceFile.isDeclarationFile) {
return "continue";
@@ -102918,9 +104166,9 @@ var ts;
});
};
// Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[]
- for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
- var sourceFile = sourceFiles_6[_i];
- _loop_15(sourceFile);
+ for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
+ var sourceFile = sourceFiles_4[_i];
+ _loop_5(sourceFile);
}
rawItems.sort(compareNavigateToItems);
return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem);
@@ -102933,8 +104181,8 @@ var ts;
if (!match) {
return; // continue to next named declarations
}
- for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) {
- var declaration = declarations_13[_i];
+ for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
+ var declaration = declarations_3[_i];
if (!shouldKeepItem(declaration, checker))
continue;
if (patternMatcher.patternContainsDots) {
@@ -103416,7 +104664,7 @@ var ts;
}
}
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
var sourceFile = node;
return ts.isExternalModule(sourceFile)
? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\""
@@ -103468,10 +104716,10 @@ var ts;
case 243 /* EnumDeclaration */:
case 241 /* InterfaceDeclaration */:
case 244 /* ModuleDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 242 /* TypeAliasDeclaration */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return true;
case 157 /* Constructor */:
case 156 /* MethodDeclaration */:
@@ -103492,7 +104740,7 @@ var ts;
}
switch (navigationBarNodeKind(item.parent)) {
case 245 /* ModuleBlock */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
return true;
@@ -103577,7 +104825,7 @@ var ts;
return !member.name || member.name.kind === 149 /* ComputedPropertyName */;
}
function getNodeSpan(node) {
- return node.kind === 279 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
+ return node.kind === 284 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile);
}
function getModifiers(node) {
if (node.parent && node.parent.kind === 237 /* VariableDeclaration */) {
@@ -103698,8 +104946,8 @@ var ts;
else {
// Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: false,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include,
suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options),
});
}
@@ -104037,8 +105285,8 @@ var ts;
var lastSingleLineCommentEnd = -1;
var singleLineCommentCount = 0;
var sourceText = sourceFile.getFullText();
- for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) {
- var _a = comments_2[_i], kind = _a.kind, pos = _a.pos, end = _a.end;
+ for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
+ var _a = comments_1[_i], kind = _a.kind, pos = _a.pos, end = _a.end;
cancellationToken.throwIfCancellationRequested();
switch (kind) {
case 2 /* SingleLineCommentTrivia */:
@@ -104448,15 +105696,15 @@ var ts;
// Assumes 'value' is already lowercase.
function indexOfIgnoringCase(str, value) {
var n = str.length - value.length;
- var _loop_16 = function (start) {
+ var _loop_6 = function (start) {
if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) {
return { value: start };
}
};
for (var start = 0; start <= n; start++) {
- var state_4 = _loop_16(start);
- if (typeof state_4 === "object")
- return state_4.value;
+ var state_1 = _loop_6(start);
+ if (typeof state_1 === "object")
+ return state_1.value;
}
return -1;
}
@@ -105467,7 +106715,7 @@ var ts;
return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
}
function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) {
- var _loop_17 = function (n) {
+ var _loop_7 = function (n) {
// If the node is not a subspan of its parent, this is a big problem.
// There have been crashes that might be caused by this violation.
ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); });
@@ -105477,9 +106725,9 @@ var ts;
}
};
for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) {
- var state_5 = _loop_17(n);
- if (typeof state_5 === "object")
- return state_5.value;
+ var state_2 = _loop_7(n);
+ if (typeof state_2 === "object")
+ return state_2.value;
}
return undefined;
}
@@ -105757,8 +107005,8 @@ var ts;
var name = importNameForConvertToDefaultImport(importNode);
if (!name)
continue;
- var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
- var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName);
+ var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
+ var resolvedFile = module && program.getSourceFile(module.resolvedFileName);
if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
}
@@ -105773,8 +107021,8 @@ var ts;
case 196 /* FunctionExpression */:
var decl = ts.getDeclarationOfExpando(node);
if (decl) {
- var symbol_2 = decl.symbol;
- if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) {
+ var symbol_1 = decl.symbol;
+ if (symbol_1 && (symbol_1.exports && symbol_1.exports.size || symbol_1.members && symbol_1.members.size)) {
diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration));
break;
}
@@ -106395,7 +107643,7 @@ var ts;
// For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo`
// there documentation comments might be attached to the right hand side symbol of their declarations.
// The pattern of such special property access is that the parent symbol is the symbol of the file.
- if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 279 /* SourceFile */; })) {
+ if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 284 /* SourceFile */; })) {
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var declaration = _a[_i];
if (!declaration.parent || declaration.parent.kind !== 204 /* BinaryExpression */) {
@@ -106520,7 +107768,7 @@ var ts;
// If the parent is not sourceFile or module block it is local variable
for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) {
// Reached source file or module block
- if (parent.kind === 279 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) {
+ if (parent.kind === 284 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) {
return false;
}
}
@@ -106634,7 +107882,7 @@ var ts;
return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; });
});
options = ts.cloneCompilerOptions(options);
- var _loop_18 = function (opt) {
+ var _loop_8 = function (opt) {
if (!ts.hasProperty(options, opt.name)) {
return "continue";
}
@@ -106653,7 +107901,7 @@ var ts;
};
for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) {
var opt = commandLineOptionsStringToEnum_1[_i];
- _loop_18(opt);
+ _loop_8(opt);
}
return options;
}
@@ -107845,7 +109093,7 @@ var ts;
case 244 /* ModuleDeclaration */:
var body = parent.body;
return !!body && body.kind === 245 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 218 /* Block */:
case 245 /* ModuleBlock */:
return ts.rangeContainsRange(parent.statements, node);
@@ -108964,7 +110212,7 @@ var ts;
// - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually
// - parent and child are not on the same line
var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) &&
- (parent.kind === 279 /* SourceFile */ || !parentAndChildShareLine);
+ (parent.kind === 284 /* SourceFile */ || !parentAndChildShareLine);
if (!useActualIndentation) {
return -1 /* Unknown */;
}
@@ -109052,7 +110300,7 @@ var ts;
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return getList(node.typeParameters);
case 192 /* NewExpression */:
case 191 /* CallExpression */:
@@ -109301,11 +110549,23 @@ var ts;
ts.Debug.assert(typeof end === "number");
n.__end = end;
}
- var Position;
- (function (Position) {
- Position[Position["FullStart"] = 0] = "FullStart";
- Position[Position["Start"] = 1] = "Start";
- })(Position = textChanges_3.Position || (textChanges_3.Position = {}));
+ var LeadingTriviaOption;
+ (function (LeadingTriviaOption) {
+ /** Exclude all leading trivia (use getStart()) */
+ LeadingTriviaOption[LeadingTriviaOption["Exclude"] = 0] = "Exclude";
+ /** Include leading trivia and,
+ * if there are no line breaks between the node and the previous token,
+ * include all trivia between the node and the previous token
+ */
+ LeadingTriviaOption[LeadingTriviaOption["IncludeAll"] = 1] = "IncludeAll";
+ })(LeadingTriviaOption = textChanges_3.LeadingTriviaOption || (textChanges_3.LeadingTriviaOption = {}));
+ var TrailingTriviaOption;
+ (function (TrailingTriviaOption) {
+ /** Exclude all trailing trivia (use getEnd()) */
+ TrailingTriviaOption[TrailingTriviaOption["Exclude"] = 0] = "Exclude";
+ /** Include trailing trivia */
+ TrailingTriviaOption[TrailingTriviaOption["Include"] = 1] = "Include";
+ })(TrailingTriviaOption = textChanges_3.TrailingTriviaOption || (textChanges_3.TrailingTriviaOption = {}));
function skipWhitespacesAndLineBreaks(text, start) {
return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
@@ -109321,9 +110581,9 @@ var ts;
}
return false;
}
- textChanges_3.useNonAdjustedPositions = {
- useNonAdjustedStartPosition: true,
- useNonAdjustedEndPosition: true,
+ var useNonAdjustedPositions = {
+ leadingTriviaOption: LeadingTriviaOption.Exclude,
+ trailingTriviaOption: TrailingTriviaOption.Exclude,
};
var ChangeKind;
(function (ChangeKind) {
@@ -109333,10 +110593,11 @@ var ts;
ChangeKind[ChangeKind["Text"] = 3] = "Text";
})(ChangeKind || (ChangeKind = {}));
function getAdjustedRange(sourceFile, startNode, endNode, options) {
- return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) };
+ return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) };
}
- function getAdjustedStartPosition(sourceFile, node, options, position) {
- if (options.useNonAdjustedStartPosition) {
+ function getAdjustedStartPosition(sourceFile, node, options) {
+ var leadingTriviaOption = options.leadingTriviaOption;
+ if (leadingTriviaOption === LeadingTriviaOption.Exclude) {
return node.getStart(sourceFile);
}
var fullStart = node.getFullStart();
@@ -109354,7 +110615,7 @@ var ts;
// fullstart
// when b is replaced - we usually want to keep the leading trvia
// when b is deleted - we delete it
- return position === Position.Start ? start : fullStart;
+ return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start;
}
// get start position of the line following the line that contains fullstart position
// (but only if the fullstart isn't the very beginning of the file)
@@ -109366,11 +110627,12 @@ var ts;
}
function getAdjustedEndPosition(sourceFile, node, options) {
var end = node.end;
- if (options.useNonAdjustedEndPosition || ts.isExpression(node)) {
+ var trailingTriviaOption = options.trailingTriviaOption;
+ if (trailingTriviaOption === TrailingTriviaOption.Exclude || (ts.isExpression(node) && trailingTriviaOption !== TrailingTriviaOption.Include)) {
return end;
}
var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
- return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))
+ return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)))
? newEnd
: end;
}
@@ -109415,15 +110677,15 @@ var ts;
this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) });
};
ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
var endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart);
- var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
+ var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
};
ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) {
@@ -109431,11 +110693,11 @@ var ts;
this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode });
};
ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
};
ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options);
};
ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) {
@@ -109443,14 +110705,14 @@ var ts;
this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes });
};
ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
};
ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) {
- this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text);
+ this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text);
};
ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) {
- if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; }
+ if (options === void 0) { options = useNonAdjustedPositions; }
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
};
ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) {
@@ -109478,7 +110740,7 @@ var ts;
};
ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) {
if (blankLineBetween === void 0) { blankLineBetween = false; }
- this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
+ this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween));
};
ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) {
var pos = before.getStart(sourceFile);
@@ -109585,7 +110847,7 @@ var ts;
this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true));
};
ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) {
- var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start);
+ var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {});
this.insertNodeAt(sourceFile, pos, newNode, {
prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter,
suffix: this.newLineCharacter
@@ -109825,7 +111087,7 @@ var ts;
ChangeTracker.prototype.finishDeleteDeclarations = function () {
var _this = this;
var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
- var _loop_19 = function (sourceFile, node) {
+ var _loop_9 = function (sourceFile, node) {
if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) {
if (ts.isArray(node)) {
this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node));
@@ -109838,7 +111100,7 @@ var ts;
var this_1 = this;
for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) {
var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node;
- _loop_19(sourceFile, node);
+ _loop_9(sourceFile, node);
}
deletedNodesInLists.forEach(function (node) {
var sourceFile = node.getSourceFile();
@@ -109875,7 +111137,7 @@ var ts;
textChanges_3.ChangeTracker = ChangeTracker;
// find first non-whitespace position in the leading trivia of the node
function startPositionToDeleteNodeInList(sourceFile, node) {
- return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
+ return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
function getClassOrObjectBraceEnds(cls, sourceFile) {
return [ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile).end];
@@ -109895,14 +111157,14 @@ var ts;
// order changes by start position
// If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa.
var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); });
- var _loop_20 = function (i) {
+ var _loop_10 = function (i) {
ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () {
return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range);
});
};
// verify that change intervals do not overlap, except possibly at end points.
for (var i = 0; i < normalized.length - 1; i++) {
- _loop_20(i);
+ _loop_10(i);
}
var textChanges = normalized.map(function (c) {
return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
@@ -110212,7 +111474,7 @@ var ts;
case 249 /* ImportDeclaration */:
deleteNode(changes, sourceFile, node,
// For first import, leave header comment in place
- node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined);
+ node === sourceFile.imports[0].parent ? { leadingTriviaOption: LeadingTriviaOption.Exclude } : undefined);
break;
case 186 /* BindingElement */:
var pattern = node.parent;
@@ -110250,7 +111512,7 @@ var ts;
deleteNodeInList(changes, deletedNodesInLists, sourceFile, node);
}
else {
- deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined);
+ deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { trailingTriviaOption: TrailingTriviaOption.Exclude } : undefined);
}
}
}
@@ -110321,8 +111583,8 @@ var ts;
/** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */
// Exported for tests only! (TODO: improve tests to not need this)
function deleteNode(changes, sourceFile, node, options) {
- if (options === void 0) { options = {}; }
- var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart);
+ if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; }
+ var startPosition = getAdjustedStartPosition(sourceFile, node, options);
var endPosition = getAdjustedEndPosition(sourceFile, node, options);
changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
}
@@ -110615,18 +111877,18 @@ var ts;
}
function transformJSDocType(node) {
switch (node.kind) {
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return transformJSDocOptionalType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return transformJSDocType(node.type);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return transformJSDocNullableType(node);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return transformJSDocVariadicType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return transformJSDocFunctionType(node);
case 164 /* TypeReference */:
return transformJSDocTypeReference(node);
@@ -110650,7 +111912,7 @@ var ts;
}
function transformJSDocParameter(node) {
var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 290 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
+ var isRest = node.type.kind === 295 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217
var name = node.name || (isRest ? "rest" : "arg" + index);
var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken;
return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
@@ -110806,7 +112068,7 @@ var ts;
}
if (ts.isPropertyAccessExpression(parent)) {
var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken);
- var typeNode = getTypeNodeIfAccessible(type, parent, program, host);
+ var typeNode = ts.getTypeNodeIfAccessible(type, parent, program, host);
if (typeNode) {
// Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags
var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ "");
@@ -110910,7 +112172,7 @@ var ts;
}
}
function annotate(changes, sourceFile, declaration, type, program, host) {
- var typeNode = getTypeNodeIfAccessible(type, declaration, program, host);
+ var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host);
if (typeNode) {
if (ts.isInJSFile(sourceFile) && declaration.kind !== 153 /* PropertySignature */) {
var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration;
@@ -110936,7 +112198,7 @@ var ts;
// only infer parameters that have (1) no type and (2) an accessible inferred type
if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name))
return;
- var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host);
+ var typeNode = inference.type && ts.getTypeNodeIfAccessible(inference.type, param, program, host);
var name = ts.getSynthesizedClone(param.name);
ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), "");
@@ -110969,40 +112231,17 @@ var ts;
return undefined;
}
switch (oldTag.kind) {
- case 299 /* JSDocParameterTag */: {
+ case 304 /* JSDocParameterTag */: {
var oldParam = oldTag;
var newParam = newTag;
return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText
? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment)
: undefined;
}
- case 300 /* JSDocReturnTag */:
+ case 305 /* JSDocReturnTag */:
return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment);
}
}
- function getTypeNodeIfAccessible(type, enclosingScope, program, host) {
- var checker = program.getTypeChecker();
- var typeIsAccessible = true;
- var notAccessible = function () { typeIsAccessible = false; };
- var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, {
- trackSymbol: function (symbol, declaration, meaning) {
- // TODO: GH#18217
- typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */;
- },
- reportInaccessibleThisError: notAccessible,
- reportPrivateInBaseOfClassExpression: notAccessible,
- reportInaccessibleUniqueSymbolError: notAccessible,
- moduleResolverHost: {
- readFile: host.readFile,
- fileExists: host.fileExists,
- directoryExists: host.directoryExists,
- getSourceFiles: program.getSourceFiles,
- getCurrentDirectory: program.getCurrentDirectory,
- getCommonSourceDirectory: program.getCommonSourceDirectory,
- }
- });
- return typeIsAccessible ? res : undefined;
- }
function getReferences(token, program, cancellationToken) {
// Position shouldn't matter since token is not a SourceFile.
return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) {
@@ -111301,8 +112540,8 @@ var ts;
}
function removeLowPriorityInferences(inferences, priorities) {
var toRemove = [];
- for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
- var i = inferences_2[_i];
+ for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
+ var i = inferences_1[_i];
for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) {
var _b = priorities_1[_a], high = _b.high, low = _b.low;
if (high(i)) {
@@ -111394,8 +112633,8 @@ var ts;
types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); }));
if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) {
var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217
- var types_20 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); });
- types_20.push(checker.createPromiseType(types_20.length ? checker.getUnionType(types_20, 2 /* Subtype */) : checker.getAnyType()));
+ var types_1 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); });
+ types_1.push(checker.createPromiseType(types_1.length ? checker.getUnionType(types_1, 2 /* Subtype */) : checker.getAnyType()));
}
else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) {
types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)));
@@ -111404,7 +112643,7 @@ var ts;
types.push(checker.createArrayType(recur(usageContext.numberIndexContext)));
}
else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) {
- var members_6 = ts.createUnderscoreEscapedMap();
+ var members_1 = ts.createUnderscoreEscapedMap();
var callSignatures = [];
var constructSignatures = [];
var stringIndexInfo = void 0;
@@ -111412,7 +112651,7 @@ var ts;
usageContext.properties.forEach(function (context, name) {
var symbol = checker.createSymbol(4 /* Property */, name);
symbol.type = recur(context);
- members_6.set(name, symbol);
+ members_1.set(name, symbol);
});
}
if (usageContext.callContexts) {
@@ -111430,7 +112669,7 @@ var ts;
if (usageContext.stringIndexContext) {
stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false);
}
- types.push(checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217
+ types.push(checker.createAnonymousType(/*symbol*/ undefined, members_1, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217
}
return types;
function recur(innerContext) {
@@ -111515,7 +112754,7 @@ var ts;
precedingNode = ctorDeclaration.parent.parent;
newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration);
if (ctorDeclaration.parent.declarations.length === 1) {
- ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
+ ts.copyLeadingComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217
changes.delete(sourceFile, precedingNode);
}
else {
@@ -111526,7 +112765,7 @@ var ts;
if (!newClassDeclaration) {
return undefined;
}
- ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile);
+ ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile);
// Because the preceding node could be touched, we need to insert nodes before delete nodes.
changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration);
function createClassElementsFromSymbol(symbol) {
@@ -111579,7 +112818,7 @@ var ts;
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 121 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body);
- ts.copyComments(assignmentBinaryExpression, method, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
case 197 /* ArrowFunction */: {
@@ -111597,7 +112836,7 @@ var ts;
var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 121 /* AsyncKeyword */));
var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined,
/*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock);
- ts.copyComments(assignmentBinaryExpression, method, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile);
return method;
}
default: {
@@ -111607,7 +112846,7 @@ var ts;
}
var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined,
/*type*/ undefined, assignmentBinaryExpression.right);
- ts.copyComments(assignmentBinaryExpression.parent, prop, sourceFile);
+ ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile);
return prop;
}
}
@@ -111699,7 +112938,7 @@ var ts;
var newNodes = transformExpression(node, transformer, node);
changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes);
}
- var _loop_21 = function (statement) {
+ var _loop_11 = function (statement) {
ts.forEachChild(statement, function visit(node) {
if (ts.isCallExpression(node)) {
startTransformation(node, statement);
@@ -111711,7 +112950,7 @@ var ts;
};
for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) {
var statement = returnStatements_1[_i];
- _loop_21(statement);
+ _loop_11(statement);
}
}
function getReturnStatementsWithPromiseHandlers(body) {
@@ -112036,8 +113275,8 @@ var ts;
if (innerCbBody.length > 0) {
return innerCbBody;
}
- var type_6 = transformer.checker.getTypeAtLocation(func);
- var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType();
+ var type_1 = transformer.checker.getTypeAtLocation(func);
+ var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType();
var rightHandSide = ts.getSynthesizedDeepClone(funcBody);
var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide;
if (!shouldReturn) {
@@ -113363,7 +114602,7 @@ var ts;
});
typeDeclToMembers.forEach(function (infos, classDeclaration) {
var supers = getAllSupers(classDeclaration, checker);
- var _loop_22 = function (info) {
+ var _loop_12 = function (info) {
// If some superclass added this property, don't add it again.
if (supers.some(function (superClassOrInterface) {
var superInfos = typeDeclToMembers.get(superClassOrInterface);
@@ -113390,7 +114629,7 @@ var ts;
};
for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) {
var info = infos_1[_i];
- _loop_22(info);
+ _loop_12(info);
}
});
}));
@@ -114356,7 +115595,7 @@ var ts;
var typeNode = info.typeNode, type = info.type;
var original = typeNode.getText(sourceFile);
var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)];
- if (typeNode.kind === 286 /* JSDocNullableType */) {
+ if (typeNode.kind === 291 /* JSDocNullableType */) {
// for nullable types, suggest the flow-compatible `T | null | undefined`
// in addition to the jsdoc/closure-compatible `T | null`
actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
@@ -114376,7 +115615,7 @@ var ts;
if (!info)
return;
var typeNode = info.typeNode, type = info.type;
- var fixedType = typeNode.kind === 286 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
+ var fixedType = typeNode.kind === 291 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type;
doChange(changes, sourceFile, typeNode, fixedType, checker);
});
}
@@ -114625,8 +115864,8 @@ var ts;
outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences));
break;
}
- for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) {
- var signature = signatures_7[_i];
+ for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
+ var signature = signatures_1[_i];
// Need to ensure nodes are fresh each time so they can have different positions.
outputMethod(signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false));
}
@@ -114709,8 +115948,8 @@ var ts;
var maxArgsSignature = signatures[0];
var minArgumentCount = signatures[0].minArgumentCount;
var someSigHasRestParameter = false;
- for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
- var sig = signatures_8[_i];
+ for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
+ var sig = signatures_2[_i];
minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount);
if (sig.hasRestParameter) {
someSigHasRestParameter = true;
@@ -114869,8 +116108,8 @@ var ts;
ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport));
}
if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) {
- var sourceFile_3 = context.sourceFile;
- var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_3, expr, ts.createPropertyAccess(expr, "default"), {}); });
+ var sourceFile_1 = context.sourceFile;
+ var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_1, expr, ts.createPropertyAccess(expr, "default"), {}); });
fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member));
}
return fixes;
@@ -115008,6 +116247,7 @@ var ts;
return ts.textChanges.getNewFileText(toStatements(valueInfo, outputKind), 3 /* TS */, formatSettings.newLineCharacter || "\n", ts.formatting.getFormatContext(formatSettings));
}
ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText;
+ /* @internal */
var OutputKind;
(function (OutputKind) {
OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals";
@@ -115149,9 +116389,9 @@ var ts;
forEachOwnNodeOfFunction(fnAst, function (node) {
if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) &&
ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 100 /* ThisKeyword */) {
- var name_7 = node.left.name.text;
- if (!ts.isJsPrivate(name_7)) {
- ts.getOrUpdate(members, name_7, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_7, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); });
+ var name_4 = node.left.name.text;
+ if (!ts.isJsPrivate(name_4)) {
+ ts.getOrUpdate(members, name_4, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_4, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); });
}
}
});
@@ -115666,7 +116906,7 @@ var ts;
});
var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName;
var neededNamedImports = [];
- var _loop_23 = function (element) {
+ var _loop_13 = function (element) {
var propertyName = (element.propertyName || element.name).text;
ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) {
var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName);
@@ -115685,7 +116925,7 @@ var ts;
};
for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) {
var element = _a[_i];
- _loop_23(element);
+ _loop_13(element);
}
changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName)));
if (neededNamedImports.length) {
@@ -116175,7 +117415,7 @@ var ts;
// * Module/namespace or source file
if (isScope(current)) {
scopes.push(current);
- if (current.kind === 279 /* SourceFile */) {
+ if (current.kind === 284 /* SourceFile */) {
return scopes;
}
}
@@ -116740,8 +117980,8 @@ var ts;
ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one.
var prevMember;
var allProperties = true;
- for (var _i = 0, members_7 = members; _i < members_7.length; _i++) {
- var member = members_7[_i];
+ for (var _i = 0, members_2 = members; _i < members_2.length; _i++) {
+ var member = members_2[_i];
if (member.pos > maxPos) {
return prevMember || members[0];
}
@@ -116915,7 +118155,7 @@ var ts;
: ts.getEnclosingBlockScopeContainer(scopes[0]);
ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
- var _loop_24 = function (i) {
+ var _loop_14 = function (i) {
var scopeUsages = usagesPerScope[i];
// Special case: in the innermost scope, all usages are available.
// (The computed value reflects the value at the top-level of the scope, but the
@@ -116955,7 +118195,7 @@ var ts;
}
};
for (var i = 0; i < scopes.length; i++) {
- _loop_24(i);
+ _loop_14(i);
}
return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
function isInGenericContext(node) {
@@ -117189,7 +118429,7 @@ var ts;
function isBlockLike(node) {
switch (node.kind) {
case 218 /* Block */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 245 /* ModuleBlock */:
case 271 /* CaseClause */:
return true;
@@ -117506,10 +118746,10 @@ var ts;
}
function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) {
var checker = program.getTypeChecker();
- var _loop_25 = function (sourceFile) {
+ var _loop_15 = function (sourceFile) {
if (sourceFile === oldFile)
return "continue";
- var _loop_26 = function (statement) {
+ var _loop_16 = function (statement) {
forEachImportInStatement(statement, function (importNode) {
if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol)
return;
@@ -117531,12 +118771,12 @@ var ts;
};
for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
var statement = _a[_i];
- _loop_26(statement);
+ _loop_16(statement);
}
};
for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
var sourceFile = _a[_i];
- _loop_25(sourceFile);
+ _loop_15(sourceFile);
}
}
function getNamespaceLikeImport(node) {
@@ -117651,9 +118891,9 @@ var ts;
if (isTopLevelDeclarationStatement(statement) &&
!isExported(sourceFile, statement, useEs6Exports) &&
forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) {
- var exports_2 = addExport(statement, useEs6Exports);
- if (exports_2)
- return exports_2;
+ var exports = addExport(statement, useEs6Exports);
+ if (exports)
+ return exports;
}
return statement;
});
@@ -118128,13 +119368,13 @@ var ts;
var returnStatement_1 = ts.createReturn(expression);
body = ts.createBlock([returnStatement_1], /* multiLine */ true);
ts.suppressLeadingAndTrailingTrivia(body);
- ts.copyComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
+ ts.copyLeadingComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true);
}
else if (actionName === removeBracesActionName && returnStatement) {
var actualExpression = expression || ts.createVoidZero();
body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression;
ts.suppressLeadingAndTrailingTrivia(body);
- ts.copyComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
+ ts.copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false);
}
else {
ts.Debug.fail("invalid action");
@@ -118173,6 +119413,410 @@ var ts;
})(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
+/* @internal */
+var ts;
+(function (ts) {
+ var refactor;
+ (function (refactor) {
+ var convertToNamedParameters;
+ (function (convertToNamedParameters) {
+ var refactorName = "Convert to named parameters";
+ var minimumParameterLength = 2;
+ refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions });
+ function getAvailableActions(context) {
+ var file = context.file, startPosition = context.startPosition;
+ var isJSFile = ts.isSourceFileJS(file);
+ if (isJSFile)
+ return ts.emptyArray; // TODO: GH#30113
+ var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker());
+ if (!functionDeclaration)
+ return ts.emptyArray;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_named_parameters);
+ return [{
+ name: refactorName,
+ description: description,
+ actions: [{
+ name: refactorName,
+ description: description
+ }]
+ }];
+ }
+ function getEditsForAction(context, actionName) {
+ ts.Debug.assert(actionName === refactorName);
+ var file = context.file, startPosition = context.startPosition, program = context.program, cancellationToken = context.cancellationToken, host = context.host;
+ var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker());
+ if (!functionDeclaration || !cancellationToken)
+ return undefined;
+ var groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken);
+ if (groupedReferences.valid) {
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(file, program, host, t, functionDeclaration, groupedReferences); });
+ return { renameFilename: undefined, renameLocation: undefined, edits: edits };
+ }
+ return { edits: [] }; // TODO: GH#30113
+ }
+ function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) {
+ var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); });
+ changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ",
+ // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter
+ indentation: 0,
+ leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll,
+ trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include
+ });
+ var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); });
+ for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) {
+ var call = functionCalls_1[_i];
+ if (call.arguments && call.arguments.length) {
+ var newArgument = ts.getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true);
+ changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include });
+ }
+ }
+ }
+ function getGroupedReferences(functionDeclaration, program, cancellationToken) {
+ var functionNames = getFunctionNames(functionDeclaration);
+ var classNames = ts.isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : [];
+ var names = ts.deduplicate(functionNames.concat(classNames), ts.equateValues);
+ var checker = program.getTypeChecker();
+ var references = ts.flatMap(names, /*mapfn*/ function (/*mapfn*/ name) { return ts.FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken); });
+ var groupedReferences = groupReferences(references);
+ if (!ts.every(groupedReferences.declarations, function (decl) { return ts.contains(names, decl); })) {
+ groupedReferences.valid = false;
+ }
+ return groupedReferences;
+ function groupReferences(referenceEntries) {
+ var classReferences = { accessExpressions: [], typeUsages: [] };
+ var groupedReferences = { functionCalls: [], declarations: [], classReferences: classReferences, valid: true };
+ var functionSymbols = ts.map(functionNames, checker.getSymbolAtLocation);
+ var classSymbols = ts.map(classNames, checker.getSymbolAtLocation);
+ var isConstructor = ts.isConstructorDeclaration(functionDeclaration);
+ for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) {
+ var entry = referenceEntries_1[_i];
+ if (entry.kind !== 1 /* Node */) {
+ groupedReferences.valid = false;
+ continue;
+ }
+ if (ts.contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ var call = entryToFunctionCall(entry);
+ if (call) {
+ groupedReferences.functionCalls.push(call);
+ continue;
+ }
+ }
+ // if the refactored function is a constructor, we must also check if the references to its class are valid
+ if (isConstructor && ts.contains(classSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) {
+ var decl = entryToDeclaration(entry);
+ if (decl) {
+ groupedReferences.declarations.push(decl);
+ continue;
+ }
+ var accessExpression = entryToAccessExpression(entry);
+ if (accessExpression) {
+ classReferences.accessExpressions.push(accessExpression);
+ continue;
+ }
+ // Only class declarations are allowed to be used as a type (in a heritage clause),
+ // otherwise `findAllReferences` might not be able to track constructor calls.
+ if (ts.isClassDeclaration(functionDeclaration.parent)) {
+ var type = entryToType(entry);
+ if (type) {
+ classReferences.typeUsages.push(type);
+ continue;
+ }
+ }
+ }
+ groupedReferences.valid = false;
+ }
+ return groupedReferences;
+ }
+ }
+ function symbolComparer(a, b) {
+ return ts.getSymbolTarget(a) === ts.getSymbolTarget(b);
+ }
+ function entryToDeclaration(entry) {
+ if (ts.isDeclaration(entry.node.parent)) {
+ return entry.node;
+ }
+ return undefined;
+ }
+ function entryToFunctionCall(entry) {
+ if (entry.node.parent) {
+ var functionReference = entry.node;
+ var parent = functionReference.parent;
+ switch (parent.kind) {
+ // Function call (foo(...) or super(...))
+ case 191 /* CallExpression */:
+ var callExpression = ts.tryCast(parent, ts.isCallExpression);
+ if (callExpression && callExpression.expression === functionReference) {
+ return callExpression;
+ }
+ break;
+ // Constructor call (new Foo(...))
+ case 192 /* NewExpression */:
+ var newExpression = ts.tryCast(parent, ts.isNewExpression);
+ if (newExpression && newExpression.expression === functionReference) {
+ return newExpression;
+ }
+ break;
+ // Method call (x.foo(...))
+ case 189 /* PropertyAccessExpression */:
+ var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
+ if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) {
+ var callExpression_1 = ts.tryCast(propertyAccessExpression.parent, ts.isCallExpression);
+ if (callExpression_1 && callExpression_1.expression === propertyAccessExpression) {
+ return callExpression_1;
+ }
+ }
+ break;
+ // Method call (x["foo"](...))
+ case 190 /* ElementAccessExpression */:
+ var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
+ if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) {
+ var callExpression_2 = ts.tryCast(elementAccessExpression.parent, ts.isCallExpression);
+ if (callExpression_2 && callExpression_2.expression === elementAccessExpression) {
+ return callExpression_2;
+ }
+ }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function entryToAccessExpression(entry) {
+ if (entry.node.parent) {
+ var reference = entry.node;
+ var parent = reference.parent;
+ switch (parent.kind) {
+ // `C.foo`
+ case 189 /* PropertyAccessExpression */:
+ var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression);
+ if (propertyAccessExpression && propertyAccessExpression.expression === reference) {
+ return propertyAccessExpression;
+ }
+ break;
+ // `C["foo"]`
+ case 190 /* ElementAccessExpression */:
+ var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression);
+ if (elementAccessExpression && elementAccessExpression.expression === reference) {
+ return elementAccessExpression;
+ }
+ break;
+ }
+ }
+ return undefined;
+ }
+ function entryToType(entry) {
+ var reference = entry.node;
+ if (ts.getMeaningFromLocation(reference) === 2 /* Type */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) {
+ return reference;
+ }
+ return undefined;
+ }
+ function getFunctionDeclarationAtPosition(file, startPosition, checker) {
+ var node = ts.getTouchingToken(file, startPosition);
+ var functionDeclaration = ts.getContainingFunction(node);
+ if (functionDeclaration
+ && isValidFunctionDeclaration(functionDeclaration, checker)
+ && ts.rangeContainsRange(functionDeclaration, node)
+ && !(functionDeclaration.body && ts.rangeContainsRange(functionDeclaration.body, node)))
+ return functionDeclaration;
+ return undefined;
+ }
+ function isValidFunctionDeclaration(functionDeclaration, checker) {
+ if (!isValidParameterNodeArray(functionDeclaration.parameters))
+ return false;
+ switch (functionDeclaration.kind) {
+ case 239 /* FunctionDeclaration */:
+ case 156 /* MethodDeclaration */:
+ return !!functionDeclaration.name && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration);
+ case 157 /* Constructor */:
+ if (ts.isClassDeclaration(functionDeclaration.parent)) {
+ return !!functionDeclaration.body && !!functionDeclaration.parent.name && !checker.isImplementationOfOverload(functionDeclaration);
+ }
+ else {
+ return isValidVariableDeclaration(functionDeclaration.parent.parent) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration);
+ }
+ case 196 /* FunctionExpression */:
+ case 197 /* ArrowFunction */:
+ return isValidVariableDeclaration(functionDeclaration.parent);
+ }
+ return false;
+ }
+ function isValidParameterNodeArray(parameters) {
+ return getRefactorableParametersLength(parameters) >= minimumParameterLength && ts.every(parameters, isValidParameterDeclaration);
+ }
+ function isValidParameterDeclaration(paramDeclaration) {
+ return !paramDeclaration.modifiers && !paramDeclaration.decorators && ts.isIdentifier(paramDeclaration.name);
+ }
+ function isValidVariableDeclaration(node) {
+ return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113
+ }
+ function hasThisParameter(parameters) {
+ return parameters.length > 0 && ts.isThis(parameters[0].name);
+ }
+ function getRefactorableParametersLength(parameters) {
+ if (hasThisParameter(parameters)) {
+ return parameters.length - 1;
+ }
+ return parameters.length;
+ }
+ function getRefactorableParameters(parameters) {
+ if (hasThisParameter(parameters)) {
+ parameters = ts.createNodeArray(parameters.slice(1), parameters.hasTrailingComma);
+ }
+ return parameters;
+ }
+ function createNewArgument(functionDeclaration, functionArguments) {
+ var parameters = getRefactorableParameters(functionDeclaration.parameters);
+ var hasRestParameter = ts.isRestParameter(ts.last(parameters));
+ var nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments;
+ var properties = ts.map(nonRestArguments, function (arg, i) {
+ var property = ts.createPropertyAssignment(getParameterName(parameters[i]), arg);
+ ts.suppressLeadingAndTrailingTrivia(property.initializer);
+ copyComments(arg, property);
+ return property;
+ });
+ if (hasRestParameter && functionArguments.length >= parameters.length) {
+ var restArguments = functionArguments.slice(parameters.length - 1);
+ var restProperty = ts.createPropertyAssignment(getParameterName(ts.last(parameters)), ts.createArrayLiteral(restArguments));
+ properties.push(restProperty);
+ }
+ var objectLiteral = ts.createObjectLiteral(properties, /*multiLine*/ false);
+ return objectLiteral;
+ }
+ function createNewParameters(functionDeclaration, program, host) {
+ var refactorableParameters = getRefactorableParameters(functionDeclaration.parameters);
+ var bindingElements = ts.map(refactorableParameters, createBindingElementFromParameterDeclaration);
+ var objectParameterName = ts.createObjectBindingPattern(bindingElements);
+ var objectParameterType = createParameterTypeNode(refactorableParameters);
+ var checker = program.getTypeChecker();
+ var objectInitializer;
+ // If every parameter in the original function was optional, add an empty object initializer to the new object parameter
+ if (ts.every(refactorableParameters, checker.isOptionalParameter)) {
+ objectInitializer = ts.createObjectLiteral();
+ }
+ var objectParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, objectParameterName,
+ /*questionToken*/ undefined, objectParameterType, objectInitializer);
+ if (hasThisParameter(functionDeclaration.parameters)) {
+ var thisParameter = functionDeclaration.parameters[0];
+ var newThisParameter = ts.createParameter(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined,
+ /*dotDotDotToken*/ undefined, thisParameter.name,
+ /*questionToken*/ undefined, thisParameter.type);
+ ts.suppressLeadingAndTrailingTrivia(newThisParameter.name);
+ copyComments(thisParameter.name, newThisParameter.name);
+ if (thisParameter.type) {
+ ts.suppressLeadingAndTrailingTrivia(newThisParameter.type);
+ copyComments(thisParameter.type, newThisParameter.type);
+ }
+ return ts.createNodeArray([newThisParameter, objectParameter]);
+ }
+ return ts.createNodeArray([objectParameter]);
+ function createParameterTypeNode(parameters) {
+ var members = ts.map(parameters, createPropertySignatureFromParameterDeclaration);
+ var typeNode = ts.addEmitFlags(ts.createTypeLiteralNode(members), 1 /* SingleLine */);
+ return typeNode;
+ }
+ function createPropertySignatureFromParameterDeclaration(parameterDeclaration) {
+ var parameterType = parameterDeclaration.type;
+ if (!parameterType && (parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration))) {
+ parameterType = getTypeNode(parameterDeclaration);
+ }
+ var propertySignature = ts.createPropertySignature(
+ /*modifiers*/ undefined, getParameterName(parameterDeclaration), parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration) ? ts.createToken(56 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType,
+ /*initializer*/ undefined);
+ ts.suppressLeadingAndTrailingTrivia(propertySignature);
+ copyComments(parameterDeclaration.name, propertySignature.name);
+ if (parameterDeclaration.type && propertySignature.type) {
+ copyComments(parameterDeclaration.type, propertySignature.type);
+ }
+ return propertySignature;
+ }
+ function getTypeNode(node) {
+ var checker = program.getTypeChecker();
+ var type = checker.getTypeAtLocation(node);
+ return ts.getTypeNodeIfAccessible(type, node, program, host);
+ }
+ }
+ function createBindingElementFromParameterDeclaration(parameterDeclaration) {
+ var element = ts.createBindingElement(
+ /*dotDotDotToken*/ undefined,
+ /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer);
+ ts.suppressLeadingAndTrailingTrivia(element);
+ if (parameterDeclaration.initializer && element.initializer) {
+ copyComments(parameterDeclaration.initializer, element.initializer);
+ }
+ return element;
+ }
+ function copyComments(sourceNode, targetNode) {
+ var sourceFile = sourceNode.getSourceFile();
+ var text = sourceFile.text;
+ if (hasLeadingLineBreak(sourceNode, text)) {
+ ts.copyLeadingComments(sourceNode, targetNode, sourceFile);
+ }
+ else {
+ ts.copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile);
+ }
+ ts.copyTrailingComments(sourceNode, targetNode, sourceFile);
+ }
+ function hasLeadingLineBreak(node, text) {
+ var start = node.getFullStart();
+ var end = node.getStart();
+ for (var i = start; i < end; i++) {
+ if (text.charCodeAt(i) === 10 /* lineFeed */)
+ return true;
+ }
+ return false;
+ }
+ function getParameterName(paramDeclaration) {
+ return ts.getTextOfIdentifierOrLiteral(paramDeclaration.name);
+ }
+ function getClassNames(constructorDeclaration) {
+ switch (constructorDeclaration.parent.kind) {
+ case 240 /* ClassDeclaration */:
+ var classDeclaration = constructorDeclaration.parent;
+ return [classDeclaration.name];
+ case 209 /* ClassExpression */:
+ var classExpression = constructorDeclaration.parent;
+ var variableDeclaration = constructorDeclaration.parent.parent;
+ var className = classExpression.name;
+ if (className)
+ return [className, variableDeclaration.name];
+ return [variableDeclaration.name];
+ }
+ }
+ function getFunctionNames(functionDeclaration) {
+ switch (functionDeclaration.kind) {
+ case 239 /* FunctionDeclaration */:
+ case 156 /* MethodDeclaration */:
+ return [functionDeclaration.name];
+ case 157 /* Constructor */:
+ var ctrKeyword = ts.findChildOfKind(functionDeclaration, 124 /* ConstructorKeyword */, functionDeclaration.getSourceFile());
+ if (functionDeclaration.parent.kind === 209 /* ClassExpression */) {
+ var variableDeclaration = functionDeclaration.parent.parent;
+ return [variableDeclaration.name, ctrKeyword];
+ }
+ return [ctrKeyword];
+ case 197 /* ArrowFunction */:
+ return [functionDeclaration.parent.name];
+ case 196 /* FunctionExpression */:
+ if (functionDeclaration.name)
+ return [functionDeclaration.name, functionDeclaration.parent.name];
+ return [functionDeclaration.parent.name];
+ default:
+ return ts.Debug.assertNever(functionDeclaration);
+ }
+ }
+ })(convertToNamedParameters = refactor.convertToNamedParameters || (refactor.convertToNamedParameters = {}));
+ })(refactor = ts.refactor || (ts.refactor = {}));
+})(ts || (ts = {}));
var ts;
(function (ts) {
/** The version of the language service API */
@@ -118253,7 +119897,7 @@ var ts;
if (!children.length) {
return undefined;
}
- var child = ts.find(children, function (kid) { return kid.kind < 283 /* FirstJSDocNode */ || kid.kind > 305 /* LastJSDocNode */; });
+ var child = ts.find(children, function (kid) { return kid.kind < 288 /* FirstJSDocNode */ || kid.kind > 310 /* LastJSDocNode */; });
return child.kind < 148 /* FirstNode */ ?
child :
child.getFirstToken(sourceFile);
@@ -118323,11 +119967,11 @@ var ts;
}
}
function createSyntaxList(nodes, parent) {
- var list = createNode(306 /* SyntaxList */, nodes.pos, nodes.end, parent);
+ var list = createNode(311 /* SyntaxList */, nodes.pos, nodes.end, parent);
list._children = [];
var pos = nodes.pos;
- for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) {
- var node = nodes_7[_i];
+ for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
+ var node = nodes_1[_i];
addSyntheticNodes(list._children, pos, node.pos, parent);
list._children.push(node);
pos = node.end;
@@ -118571,8 +120215,8 @@ var ts;
return ts.emptyArray;
var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations);
if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) {
- for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) {
- var declaration = declarations_14[_i];
+ for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
+ var declaration = declarations_4[_i];
var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217
// TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs
if (inheritedDocs)
@@ -119324,14 +120968,14 @@ var ts;
var typeChecker = program.getTypeChecker();
var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker);
if (!symbol || typeChecker.isUnknownSymbol(symbol)) {
- var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined;
- return type_7 && {
+ var type_2 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined;
+ return type_2 && {
kind: "" /* unknown */,
kindModifiers: "" /* none */,
textSpan: ts.createTextSpanFromNode(node, sourceFile),
- displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }),
- documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined,
- tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined
+ displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_2, ts.getContainerNode(node)); }),
+ documentation: type_2.symbol ? type_2.symbol.getDocumentationComment(typeChecker) : undefined,
+ tags: type_2.symbol ? type_2.symbol.getJsDocTags() : undefined
};
}
var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) {
diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js
index 1503cb0420af9..f655e83d64931 100644
--- a/lib/typingsInstaller.js
+++ b/lib/typingsInstaller.js
@@ -14,31 +14,6 @@ and limitations under the License.
***************************************************************************** */
-"use strict";
-var __extends = (this && this.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
-})();
-var __assign = (this && this.__assign) || function () {
- __assign = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
@@ -82,6 +57,19 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
+var __extends = (this && this.__extends) || (function () {
+ var extendStatics = function (d, b) {
+ extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
+ return extendStatics(d, b);
+ };
+ return function (d, b) {
+ extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+ };
+})();
var ts;
(function (ts) {
// WARNING: The script `configureNightly.ts` uses a regexp to parse out these values.
@@ -825,7 +813,7 @@ var ts;
}
/**
* Deduplicates an unsorted array.
- * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates.
+ * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates.
* @param comparer An optional `Comparer` used to sort entries before comparison, though the
* result will remain in the original order in `array`.
*/
@@ -1041,6 +1029,21 @@ var ts;
} };
}
ts.arrayIterator = arrayIterator;
+ function arrayReverseIterator(array) {
+ var i = array.length;
+ return {
+ next: function () {
+ if (i === 0) {
+ return { value: undefined, done: true };
+ }
+ else {
+ i--;
+ return { value: array[i], done: false };
+ }
+ }
+ };
+ }
+ ts.arrayReverseIterator = arrayReverseIterator;
/**
* Stable sort of an array. Elements equal to each other maintain their relative position in the array.
*/
@@ -2880,47 +2883,53 @@ var ts;
SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment";
// Enum
SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember";
+ // Unparsed
+ SyntaxKind[SyntaxKind["UnparsedPrologue"] = 279] = "UnparsedPrologue";
+ SyntaxKind[SyntaxKind["UnparsedPrepend"] = 280] = "UnparsedPrepend";
+ SyntaxKind[SyntaxKind["UnparsedText"] = 281] = "UnparsedText";
+ SyntaxKind[SyntaxKind["UnparsedInternalText"] = 282] = "UnparsedInternalText";
+ SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 283] = "UnparsedSyntheticReference";
// Top-level nodes
- SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile";
- SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle";
- SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource";
- SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles";
+ SyntaxKind[SyntaxKind["SourceFile"] = 284] = "SourceFile";
+ SyntaxKind[SyntaxKind["Bundle"] = 285] = "Bundle";
+ SyntaxKind[SyntaxKind["UnparsedSource"] = 286] = "UnparsedSource";
+ SyntaxKind[SyntaxKind["InputFiles"] = 287] = "InputFiles";
// JSDoc nodes
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression";
+ SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 288] = "JSDocTypeExpression";
// The * type
- SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType";
+ SyntaxKind[SyntaxKind["JSDocAllType"] = 289] = "JSDocAllType";
// The ? type
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature";
- SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag";
- SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag";
- SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag";
+ SyntaxKind[SyntaxKind["JSDocUnknownType"] = 290] = "JSDocUnknownType";
+ SyntaxKind[SyntaxKind["JSDocNullableType"] = 291] = "JSDocNullableType";
+ SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 292] = "JSDocNonNullableType";
+ SyntaxKind[SyntaxKind["JSDocOptionalType"] = 293] = "JSDocOptionalType";
+ SyntaxKind[SyntaxKind["JSDocFunctionType"] = 294] = "JSDocFunctionType";
+ SyntaxKind[SyntaxKind["JSDocVariadicType"] = 295] = "JSDocVariadicType";
+ SyntaxKind[SyntaxKind["JSDocComment"] = 296] = "JSDocComment";
+ SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 297] = "JSDocTypeLiteral";
+ SyntaxKind[SyntaxKind["JSDocSignature"] = 298] = "JSDocSignature";
+ SyntaxKind[SyntaxKind["JSDocTag"] = 299] = "JSDocTag";
+ SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 300] = "JSDocAugmentsTag";
+ SyntaxKind[SyntaxKind["JSDocClassTag"] = 301] = "JSDocClassTag";
+ SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 302] = "JSDocCallbackTag";
+ SyntaxKind[SyntaxKind["JSDocEnumTag"] = 303] = "JSDocEnumTag";
+ SyntaxKind[SyntaxKind["JSDocParameterTag"] = 304] = "JSDocParameterTag";
+ SyntaxKind[SyntaxKind["JSDocReturnTag"] = 305] = "JSDocReturnTag";
+ SyntaxKind[SyntaxKind["JSDocThisTag"] = 306] = "JSDocThisTag";
+ SyntaxKind[SyntaxKind["JSDocTypeTag"] = 307] = "JSDocTypeTag";
+ SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 308] = "JSDocTemplateTag";
+ SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 309] = "JSDocTypedefTag";
+ SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 310] = "JSDocPropertyTag";
// Synthesized list
- SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList";
+ SyntaxKind[SyntaxKind["SyntaxList"] = 311] = "SyntaxList";
// Transformation nodes
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker";
+ SyntaxKind[SyntaxKind["NotEmittedStatement"] = 312] = "NotEmittedStatement";
+ SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 313] = "PartiallyEmittedExpression";
+ SyntaxKind[SyntaxKind["CommaListExpression"] = 314] = "CommaListExpression";
+ SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 315] = "MergeDeclarationMarker";
+ SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 316] = "EndOfDeclarationMarker";
// Enum value count
- SyntaxKind[SyntaxKind["Count"] = 312] = "Count";
+ SyntaxKind[SyntaxKind["Count"] = 317] = "Count";
// Markers
SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment";
SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment";
@@ -2947,10 +2956,10 @@ var ts;
SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator";
SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator";
SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode";
+ SyntaxKind[SyntaxKind["FirstJSDocNode"] = 288] = "FirstJSDocNode";
+ SyntaxKind[SyntaxKind["LastJSDocNode"] = 310] = "LastJSDocNode";
+ SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 299] = "FirstJSDocTagNode";
+ SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 310] = "LastJSDocTagNode";
/* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword";
/* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword";
})(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
@@ -3568,6 +3577,7 @@ var ts;
InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
InferenceFlags[InferenceFlags["NoFixing"] = 4] = "NoFixing";
+ InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 8] = "SkippedGenericFunction";
})(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
/**
* Ternary values are defined such that
@@ -3827,6 +3837,7 @@ var ts;
Extension["Js"] = ".js";
Extension["Jsx"] = ".jsx";
Extension["Json"] = ".json";
+ Extension["TsBuildInfo"] = ".tsbuildinfo";
})(Extension = ts.Extension || (ts.Extension = {}));
/* @internal */
var TransformFlags;
@@ -3984,6 +3995,20 @@ var ts;
EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
})(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
+ /*@internal*/
+ var BundleFileSectionKind;
+ (function (BundleFileSectionKind) {
+ BundleFileSectionKind["Prologue"] = "prologue";
+ BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
+ BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
+ BundleFileSectionKind["Reference"] = "reference";
+ BundleFileSectionKind["Type"] = "type";
+ BundleFileSectionKind["Lib"] = "lib";
+ BundleFileSectionKind["Prepend"] = "prepend";
+ BundleFileSectionKind["Text"] = "text";
+ BundleFileSectionKind["Internal"] = "internal";
+ // comments?
+ })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
var ListFormat;
(function (ListFormat) {
ListFormat[ListFormat["None"] = 0] = "None";
@@ -4391,6 +4416,8 @@ var ts;
: FileWatcherEventKind.Changed;
}
ts.getFileWatcherEventKind = getFileWatcherEventKind;
+ /*@internal*/
+ ts.ignoredPaths = ["/node_modules/.", "/.git"];
/**
* Watch the directory recursively using host provided method to watch child directories
* that means if this is recursive watcher, watch the children directories as well
@@ -4415,6 +4442,8 @@ var ts;
else {
directoryWatcher = {
watcher: host.watchDirectory(dirName, function (fileName) {
+ if (isIgnoredPath(fileName))
+ return;
// Call the actual callback
callbackCache.forEach(function (callbacks, rootDirName) {
if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
@@ -4464,7 +4493,7 @@ var ts;
var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
// Filter our the symbolic link directories since those arent included in recursive watch
// which is same behaviour when recursive: true is passed to fs.watch
- return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
+ return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
}) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
return newChildWatches || ts.emptyArray;
/**
@@ -4481,6 +4510,16 @@ var ts;
(newChildWatches || (newChildWatches = [])).push(childWatcher);
}
}
+ function isIgnoredPath(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
+ }
+ function isInPath(path, searchPath) {
+ if (ts.stringContains(path, searchPath))
+ return true;
+ if (host.useCaseSensitiveFileNames)
+ return false;
+ return ts.stringContains(toCanonicalFilePath(path), searchPath);
+ }
}
ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher;
function getNodeMajorVersion() {
@@ -5846,6 +5885,7 @@ var ts;
Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."),
Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."),
Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."),
+ Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."),
The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."),
Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."),
File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."),
@@ -6113,6 +6153,16 @@ var ts;
Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."),
Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."),
Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."),
+ Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"),
+ Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
+ A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"),
+ A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"),
+ Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"),
+ Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"),
+ Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
+ Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."),
+ Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"),
+ Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"),
The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"),
The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."),
The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."),
@@ -6329,6 +6379,7 @@ var ts;
Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"),
Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"),
Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"),
+ Convert_to_named_parameters: diag(95075, ts.DiagnosticCategory.Message, "Convert_to_named_parameters_95075", "Convert to named parameters"),
};
})(ts || (ts = {}));
var ts;
@@ -6816,16 +6867,20 @@ var ts;
return pos;
}
var shebangTriviaRegex = /^#!.*/;
+ /*@internal*/
function isShebangTrivia(text, pos) {
// Shebangs check must only be done at the start of the file
ts.Debug.assert(pos === 0);
return shebangTriviaRegex.test(text);
}
+ ts.isShebangTrivia = isShebangTrivia;
+ /*@internal*/
function scanShebangTrivia(text, pos) {
var shebang = shebangTriviaRegex.exec(text)[0];
pos = pos + shebang.length;
return pos;
}
+ ts.scanShebangTrivia = scanShebangTrivia;
/**
* Invokes a callback for each comment range following the provided position.
*
@@ -8535,7 +8590,7 @@ var ts;
}
}
function getSourceFileOfNode(node) {
- while (node && node.kind !== 279 /* SourceFile */) {
+ while (node && node.kind !== 284 /* SourceFile */) {
node = node.parent;
}
return node;
@@ -8681,7 +8736,7 @@ var ts;
// the syntax list itself considers them as normal trivia. Therefore if we simply skip
// trivia for the list, we may have skipped the JSDocComment as well. So we should process its
// first child to determine the actual position of its first token.
- if (node.kind === 306 /* SyntaxList */ && node._children.length > 0) {
+ if (node.kind === 311 /* SyntaxList */ && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -8700,7 +8755,7 @@ var ts;
}
ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
function isJSDocTypeExpressionOrChild(node) {
- return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
+ return node.kind === 288 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent));
}
function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
if (includeTrivia === void 0) { includeTrivia = false; }
@@ -8827,7 +8882,7 @@ var ts;
return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body);
}
function isBlockScopedContainerTopLevel(node) {
- return node.kind === 279 /* SourceFile */ ||
+ return node.kind === 284 /* SourceFile */ ||
node.kind === 244 /* ModuleDeclaration */ ||
ts.isFunctionLike(node);
}
@@ -8845,7 +8900,7 @@ var ts;
// - defined in the top level scope and source file is an external module
// - defined inside ambient module declaration located in the top level scope and source file not an external module
switch (node.parent.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.isExternalModule(node.parent);
case 245 /* ModuleBlock */:
return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
@@ -8863,7 +8918,7 @@ var ts;
ts.isEffectiveExternalModule = isEffectiveExternalModule;
function isBlockScope(node, parentNode) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 274 /* CatchClause */:
case 244 /* ModuleDeclaration */:
@@ -8888,9 +8943,9 @@ var ts;
ts.isBlockScope = isBlockScope;
function isDeclarationWithTypeParameters(node) {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
- case 293 /* JSDocSignature */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 298 /* JSDocSignature */:
return true;
default:
ts.assertType(node);
@@ -8906,12 +8961,12 @@ var ts;
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 240 /* ClassDeclaration */:
case 209 /* ClassExpression */:
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 157 /* Constructor */:
@@ -9056,7 +9111,7 @@ var ts;
function getErrorSpanForNode(sourceFile, node) {
var errorNode = node;
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
if (pos_1 === sourceFile.text.length) {
// file is empty - return span for the beginning of the file
@@ -9231,7 +9286,7 @@ var ts;
return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
case 150 /* TypeParameter */:
return node === parent.constraint;
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return node === parent.constraint;
case 154 /* PropertyDeclaration */:
case 153 /* PropertySignature */:
@@ -9491,7 +9546,7 @@ var ts;
}
ts.getContainingClass = getContainingClass;
function getThisContainer(node, includeArrowFunctions) {
- ts.Debug.assert(node.kind !== 279 /* SourceFile */);
+ ts.Debug.assert(node.kind !== 284 /* SourceFile */);
while (true) {
node = node.parent;
if (!node) {
@@ -9545,7 +9600,7 @@ var ts;
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 243 /* EnumDeclaration */:
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return node;
}
}
@@ -10253,7 +10308,7 @@ var ts;
}
ts.isJSDocConstructSignature = isJSDocConstructSignature;
function isJSDocTypeAlias(node) {
- return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 309 /* JSDocTypedefTag */ || node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocTypeAlias = isJSDocTypeAlias;
function isTypeAlias(node) {
@@ -10397,7 +10452,7 @@ var ts;
ts.hasRestParameter = hasRestParameter;
function isRestParameter(node) {
var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
- return node.dotDotDotToken !== undefined || !!type && type.kind === 290 /* JSDocVariadicType */;
+ return node.dotDotDotToken !== undefined || !!type && type.kind === 295 /* JSDocVariadicType */;
}
ts.isRestParameter = isRestParameter;
var AssignmentKind;
@@ -10882,7 +10937,7 @@ var ts;
|| kind === 158 /* GetAccessor */
|| kind === 159 /* SetAccessor */
|| kind === 244 /* ModuleDeclaration */
- || kind === 279 /* SourceFile */;
+ || kind === 284 /* SourceFile */;
}
ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
function nodeIsSynthesized(range) {
@@ -10959,7 +11014,7 @@ var ts;
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return 0;
case 208 /* SpreadElement */:
return 1;
@@ -11277,6 +11332,9 @@ var ts;
lineStart = true;
}
}
+ function getTextPosWithWriteLine() {
+ return lineStart ? output.length : (output.length + newLine.length);
+ }
reset();
return {
write: write,
@@ -11305,7 +11363,8 @@ var ts;
writeStringLiteral: write,
writeSymbol: function (s, _) { return write(s); },
writeTrailingSemicolon: write,
- writeComment: write
+ writeComment: write,
+ getTextPosWithWriteLine: getTextPosWithWriteLine
};
}
ts.createTextWriter = createTextWriter;
@@ -11596,7 +11655,7 @@ var ts;
ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
/** template tags are only available when a typedef isn't already using them */
function isNonTypeAliasTemplate(tag) {
- return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
+ return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 296 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
}
/**
* Gets the effective type annotation of the value parameter of a set accessor. If the node
@@ -12568,19 +12627,29 @@ var ts;
|| kind === 96 /* NullKeyword */
|| kind === 132 /* NeverKeyword */
|| kind === 211 /* ExpressionWithTypeArguments */
- || kind === 284 /* JSDocAllType */
- || kind === 285 /* JSDocUnknownType */
- || kind === 286 /* JSDocNullableType */
- || kind === 287 /* JSDocNonNullableType */
- || kind === 288 /* JSDocOptionalType */
- || kind === 289 /* JSDocFunctionType */
- || kind === 290 /* JSDocVariadicType */;
+ || kind === 289 /* JSDocAllType */
+ || kind === 290 /* JSDocUnknownType */
+ || kind === 291 /* JSDocNullableType */
+ || kind === 292 /* JSDocNonNullableType */
+ || kind === 293 /* JSDocOptionalType */
+ || kind === 294 /* JSDocFunctionType */
+ || kind === 295 /* JSDocVariadicType */;
}
ts.isTypeNodeKind = isTypeNodeKind;
function isAccessExpression(node) {
return node.kind === 189 /* PropertyAccessExpression */ || node.kind === 190 /* ElementAccessExpression */;
}
ts.isAccessExpression = isAccessExpression;
+ function isBundleFileTextLike(section) {
+ switch (section.kind) {
+ case "text" /* Text */:
+ case "internal" /* Internal */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isBundleFileTextLike = isBundleFileTextLike;
})(ts || (ts = {}));
(function (ts) {
function getDefaultLibFileName(options) {
@@ -13042,8 +13111,8 @@ var ts;
switch (declaration.kind) {
case 72 /* Identifier */:
return declaration;
- case 305 /* JSDocPropertyTag */:
- case 299 /* JSDocParameterTag */: {
+ case 310 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */: {
var name = declaration.name;
if (name.kind === 148 /* QualifiedName */) {
return name.right;
@@ -13067,7 +13136,7 @@ var ts;
return undefined;
}
}
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return getNameOfJSDocTypedef(declaration);
case 254 /* ExportAssignment */: {
var expression = declaration.expression;
@@ -13271,7 +13340,7 @@ var ts;
return ts.emptyArray;
}
if (ts.isJSDocTypeAlias(node)) {
- ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */);
+ ts.Debug.assert(node.parent.kind === 296 /* JSDocComment */);
return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
}
if (node.typeParameters) {
@@ -13543,7 +13612,7 @@ var ts;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 308 /* PartiallyEmittedExpression */) {
+ while (node.kind === 313 /* PartiallyEmittedExpression */) {
node = node.expression;
}
return node;
@@ -13890,108 +13959,128 @@ var ts;
ts.isEnumMember = isEnumMember;
// Top-level nodes
function isSourceFile(node) {
- return node.kind === 279 /* SourceFile */;
+ return node.kind === 284 /* SourceFile */;
}
ts.isSourceFile = isSourceFile;
function isBundle(node) {
- return node.kind === 280 /* Bundle */;
+ return node.kind === 285 /* Bundle */;
}
ts.isBundle = isBundle;
function isUnparsedSource(node) {
- return node.kind === 281 /* UnparsedSource */;
+ return node.kind === 286 /* UnparsedSource */;
}
ts.isUnparsedSource = isUnparsedSource;
+ function isUnparsedPrepend(node) {
+ return node.kind === 280 /* UnparsedPrepend */;
+ }
+ ts.isUnparsedPrepend = isUnparsedPrepend;
+ function isUnparsedTextLike(node) {
+ switch (node.kind) {
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ ts.isUnparsedTextLike = isUnparsedTextLike;
+ function isUnparsedNode(node) {
+ return isUnparsedTextLike(node) ||
+ node.kind === 279 /* UnparsedPrologue */ ||
+ node.kind === 283 /* UnparsedSyntheticReference */;
+ }
+ ts.isUnparsedNode = isUnparsedNode;
// JSDoc
function isJSDocTypeExpression(node) {
- return node.kind === 283 /* JSDocTypeExpression */;
+ return node.kind === 288 /* JSDocTypeExpression */;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 284 /* JSDocAllType */;
+ return node.kind === 289 /* JSDocAllType */;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 285 /* JSDocUnknownType */;
+ return node.kind === 290 /* JSDocUnknownType */;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 286 /* JSDocNullableType */;
+ return node.kind === 291 /* JSDocNullableType */;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 287 /* JSDocNonNullableType */;
+ return node.kind === 292 /* JSDocNonNullableType */;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 288 /* JSDocOptionalType */;
+ return node.kind === 293 /* JSDocOptionalType */;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 289 /* JSDocFunctionType */;
+ return node.kind === 294 /* JSDocFunctionType */;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 290 /* JSDocVariadicType */;
+ return node.kind === 295 /* JSDocVariadicType */;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 291 /* JSDocComment */;
+ return node.kind === 296 /* JSDocComment */;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 295 /* JSDocAugmentsTag */;
+ return node.kind === 300 /* JSDocAugmentsTag */;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 296 /* JSDocClassTag */;
+ return node.kind === 301 /* JSDocClassTag */;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocEnumTag(node) {
- return node.kind === 298 /* JSDocEnumTag */;
+ return node.kind === 303 /* JSDocEnumTag */;
}
ts.isJSDocEnumTag = isJSDocEnumTag;
function isJSDocThisTag(node) {
- return node.kind === 301 /* JSDocThisTag */;
+ return node.kind === 306 /* JSDocThisTag */;
}
ts.isJSDocThisTag = isJSDocThisTag;
function isJSDocParameterTag(node) {
- return node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 300 /* JSDocReturnTag */;
+ return node.kind === 305 /* JSDocReturnTag */;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 302 /* JSDocTypeTag */;
+ return node.kind === 307 /* JSDocTypeTag */;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 303 /* JSDocTemplateTag */;
+ return node.kind === 308 /* JSDocTemplateTag */;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 304 /* JSDocTypedefTag */;
+ return node.kind === 309 /* JSDocTypedefTag */;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */;
+ return node.kind === 310 /* JSDocPropertyTag */;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */;
+ return node.kind === 310 /* JSDocPropertyTag */ || node.kind === 304 /* JSDocParameterTag */;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 292 /* JSDocTypeLiteral */;
+ return node.kind === 297 /* JSDocTypeLiteral */;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
function isJSDocCallbackTag(node) {
- return node.kind === 297 /* JSDocCallbackTag */;
+ return node.kind === 302 /* JSDocCallbackTag */;
}
ts.isJSDocCallbackTag = isJSDocCallbackTag;
function isJSDocSignature(node) {
- return node.kind === 293 /* JSDocSignature */;
+ return node.kind === 298 /* JSDocSignature */;
}
ts.isJSDocSignature = isJSDocSignature;
})(ts || (ts = {}));
@@ -14002,7 +14091,7 @@ var ts;
(function (ts) {
/* @internal */
function isSyntaxList(n) {
- return n.kind === 306 /* SyntaxList */;
+ return n.kind === 311 /* SyntaxList */;
}
ts.isSyntaxList = isSyntaxList;
/* @internal */
@@ -14154,11 +14243,11 @@ var ts;
switch (kind) {
case 155 /* MethodSignature */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 166 /* ConstructorType */:
return true;
default:
@@ -14449,8 +14538,8 @@ var ts;
case 208 /* SpreadElement */:
case 212 /* AsExpression */:
case 210 /* OmittedExpression */:
- case 309 /* CommaListExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 314 /* CommaListExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -14464,12 +14553,12 @@ var ts;
ts.isAssertionExpression = isAssertionExpression;
/* @internal */
function isPartiallyEmittedExpression(node) {
- return node.kind === 308 /* PartiallyEmittedExpression */;
+ return node.kind === 313 /* PartiallyEmittedExpression */;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
/* @internal */
function isNotEmittedStatement(node) {
- return node.kind === 307 /* NotEmittedStatement */;
+ return node.kind === 312 /* NotEmittedStatement */;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
/* @internal */
@@ -14580,9 +14669,9 @@ var ts;
|| kind === 242 /* TypeAliasDeclaration */
|| kind === 150 /* TypeParameter */
|| kind === 237 /* VariableDeclaration */
- || kind === 304 /* JSDocTypedefTag */
- || kind === 297 /* JSDocCallbackTag */
- || kind === 305 /* JSDocPropertyTag */;
+ || kind === 309 /* JSDocTypedefTag */
+ || kind === 302 /* JSDocCallbackTag */
+ || kind === 310 /* JSDocPropertyTag */;
}
function isDeclarationStatementKind(kind) {
return kind === 239 /* FunctionDeclaration */
@@ -14617,14 +14706,14 @@ var ts;
|| kind === 219 /* VariableStatement */
|| kind === 224 /* WhileStatement */
|| kind === 231 /* WithStatement */
- || kind === 307 /* NotEmittedStatement */
- || kind === 311 /* EndOfDeclarationMarker */
- || kind === 310 /* MergeDeclarationMarker */;
+ || kind === 312 /* NotEmittedStatement */
+ || kind === 316 /* EndOfDeclarationMarker */
+ || kind === 315 /* MergeDeclarationMarker */;
}
/* @internal */
function isDeclaration(node) {
if (node.kind === 150 /* TypeParameter */) {
- return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node);
+ return (node.parent && node.parent.kind !== 308 /* JSDocTemplateTag */) || ts.isInJSFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -14719,18 +14808,18 @@ var ts;
/** True if node is of some JSDoc syntax kind. */
/* @internal */
function isJSDocNode(node) {
- return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */;
+ return node.kind >= 288 /* FirstJSDocNode */ && node.kind <= 310 /* LastJSDocNode */;
}
ts.isJSDocNode = isJSDocNode;
/** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node) {
- return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
+ return node.kind === 296 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
}
ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
// TODO: determine what this does before making it public.
/* @internal */
function isJSDocTag(node) {
- return node.kind >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */;
+ return node.kind >= 299 /* FirstJSDocTagNode */ && node.kind <= 310 /* LastJSDocTagNode */;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -15047,6 +15136,10 @@ var ts;
return !!(compilerOptions.declaration || compilerOptions.composite);
}
ts.getEmitDeclarations = getEmitDeclarations;
+ function isIncrementalCompilation(options) {
+ return !!(options.incremental || options.composite);
+ }
+ ts.isIncrementalCompilation = isIncrementalCompilation;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
}
@@ -16331,7 +16424,7 @@ var ts;
var SourceFileConstructor;
// tslint:enable variable-name
function createNode(kind, pos, end) {
- if (kind === 279 /* SourceFile */) {
+ if (kind === 284 /* SourceFile */) {
return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else if (kind === 72 /* Identifier */) {
@@ -16582,7 +16675,7 @@ var ts;
case 218 /* Block */:
case 245 /* ModuleBlock */:
return visitNodes(cbNode, cbNodes, node.statements);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return visitNodes(cbNode, cbNodes, node.statements) ||
visitNode(cbNode, node.endOfFileToken);
case 219 /* VariableStatement */:
@@ -16731,7 +16824,7 @@ var ts;
return visitNode(cbNode, node.expression);
case 258 /* MissingDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return visitNodes(cbNode, cbNodes, node.elements);
case 260 /* JsxElement */:
return visitNode(cbNode, node.openingElement) ||
@@ -16760,60 +16853,60 @@ var ts;
return visitNode(cbNode, node.tagName);
case 171 /* OptionalType */:
case 172 /* RestType */:
- case 283 /* JSDocTypeExpression */:
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 288 /* JSDocOptionalType */:
- case 290 /* JSDocVariadicType */:
+ case 288 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 293 /* JSDocOptionalType */:
+ case 295 /* JSDocVariadicType */:
return visitNode(cbNode, node.type);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return visitNodes(cbNode, cbNodes, node.tags);
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return visitNode(cbNode, node.tagName) ||
(node.isNameFirst
? visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression)
: visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name));
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.class);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.constraint) ||
visitNodes(cbNode, cbNodes, node.typeParameters);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return visitNode(cbNode, node.tagName) ||
(node.typeExpression &&
- node.typeExpression.kind === 283 /* JSDocTypeExpression */
+ node.typeExpression.kind === 288 /* JSDocTypeExpression */
? visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName)
: visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression));
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return visitNode(cbNode, node.tagName) ||
visitNode(cbNode, node.typeExpression);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return ts.forEach(node.typeParameters, cbNode) ||
ts.forEach(node.parameters, cbNode) ||
visitNode(cbNode, node.type);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return ts.forEach(node.jsDocPropertyTags, cbNode);
- case 294 /* JSDocTag */:
- case 296 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
return visitNode(cbNode, node.tagName);
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
}
@@ -17187,7 +17280,7 @@ var ts;
function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
// code from createNode is inlined here so createNode won't have to deal with special case of creating source files
// this is quite rare comparing to other nodes and createNode should be as fast as possible
- var sourceFile = new SourceFileConstructor(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
+ var sourceFile = new SourceFileConstructor(284 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
nodeCount++;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
@@ -18387,9 +18480,9 @@ var ts;
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(284 /* JSDocAllType */);
+ var result = createNode(289 /* JSDocAllType */);
if (postFixEquals) {
- return createPostfixType(288 /* JSDocOptionalType */, result);
+ return createPostfixType(293 /* JSDocOptionalType */, result);
}
else {
nextToken();
@@ -18397,7 +18490,7 @@ var ts;
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(287 /* JSDocNonNullableType */);
+ var result = createNode(292 /* JSDocNonNullableType */);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -18421,18 +18514,18 @@ var ts;
token() === 30 /* GreaterThanToken */ ||
token() === 59 /* EqualsToken */ ||
token() === 50 /* BarToken */) {
- var result = createNode(285 /* JSDocUnknownType */, pos);
+ var result = createNode(290 /* JSDocUnknownType */, pos);
return finishNode(result);
}
else {
- var result = createNode(286 /* JSDocNullableType */, pos);
+ var result = createNode(291 /* JSDocNullableType */, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(289 /* JSDocFunctionType */);
+ var result = createNodeWithJSDoc(294 /* JSDocFunctionType */);
nextToken();
fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
return finishNode(result);
@@ -18456,12 +18549,12 @@ var ts;
var type = parseTypeOrTypePredicate();
scanner.setInJSDocType(false);
if (dotdotdot) {
- var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos);
+ var variadic = createNode(295 /* JSDocVariadicType */, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 59 /* EqualsToken */) {
- return createPostfixType(288 /* JSDocOptionalType */, type);
+ return createPostfixType(293 /* JSDocOptionalType */, type);
}
return type;
}
@@ -18833,7 +18926,7 @@ var ts;
return finishNode(node);
}
var type = parseType();
- if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) {
+ if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 291 /* JSDocNullableType */ && type.pos === type.type.pos) {
type.kind = 171 /* OptionalType */;
}
return type;
@@ -19020,14 +19113,14 @@ var ts;
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 52 /* ExclamationToken */:
- type = createPostfixType(287 /* JSDocNonNullableType */, type);
+ type = createPostfixType(292 /* JSDocNonNullableType */, type);
break;
case 56 /* QuestionToken */:
// If not in JSDoc and next token is start of a type we have a conditional type
if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
return type;
}
- type = createPostfixType(286 /* JSDocNullableType */, type);
+ type = createPostfixType(291 /* JSDocNullableType */, type);
break;
case 22 /* OpenBracketToken */:
parseExpected(22 /* OpenBracketToken */);
@@ -21964,7 +22057,7 @@ var ts;
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
// Parses out a JSDoc type expression.
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(283 /* JSDocTypeExpression */);
+ var result = createNode(288 /* JSDocTypeExpression */);
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -22127,7 +22220,7 @@ var ts;
}
}
function createJSDocComment() {
- var result = createNode(291 /* JSDocComment */, start);
+ var result = createNode(296 /* JSDocComment */, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
@@ -22294,7 +22387,7 @@ var ts;
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(start, tagName) {
- var result = createNode(294 /* JSDocTag */, start);
+ var result = createNode(299 /* JSDocTag */, start);
result.tagName = tagName;
return finishNode(result);
}
@@ -22353,8 +22446,8 @@ var ts;
typeExpression = tryParseTypeExpression();
}
var result = target === 1 /* Property */ ?
- createNode(305 /* JSDocPropertyTag */, start) :
- createNode(299 /* JSDocParameterTag */, start);
+ createNode(310 /* JSDocPropertyTag */, start) :
+ createNode(304 /* JSDocParameterTag */, start);
var comment = parseTagComments(indent + scanner.getStartPos() - start);
var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
if (nestedTypeLiteral) {
@@ -22371,18 +22464,18 @@ var ts;
}
function parseNestedTypeLiteral(typeExpression, name, target, indent) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(288 /* JSDocTypeExpression */, scanner.getTokenPos());
var child = void 0;
var jsdocTypeLiteral = void 0;
var start_2 = scanner.getStartPos();
var children = void 0;
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
- if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) {
+ if (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 169 /* ArrayType */) {
jsdocTypeLiteral.isArrayType = true;
@@ -22393,25 +22486,25 @@ var ts;
}
}
function parseReturnTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 305 /* JSDocReturnTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(300 /* JSDocReturnTag */, start);
+ var result = createNode(305 /* JSDocReturnTag */, start);
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(start, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 307 /* JSDocTypeTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(302 /* JSDocTypeTag */, start);
+ var result = createNode(307 /* JSDocTypeTag */, start);
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
return finishNode(result);
}
function parseAugmentsTag(start, tagName) {
- var result = createNode(295 /* JSDocAugmentsTag */, start);
+ var result = createNode(300 /* JSDocAugmentsTag */, start);
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
return finishNode(result);
@@ -22438,19 +22531,19 @@ var ts;
return node;
}
function parseClassTag(start, tagName) {
- var tag = createNode(296 /* JSDocClassTag */, start);
+ var tag = createNode(301 /* JSDocClassTag */, start);
tag.tagName = tagName;
return finishNode(tag);
}
function parseThisTag(start, tagName) {
- var tag = createNode(301 /* JSDocThisTag */, start);
+ var tag = createNode(306 /* JSDocThisTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
return finishNode(tag);
}
function parseEnumTag(start, tagName) {
- var tag = createNode(298 /* JSDocEnumTag */, start);
+ var tag = createNode(303 /* JSDocEnumTag */, start);
tag.tagName = tagName;
tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
skipWhitespace();
@@ -22459,7 +22552,7 @@ var ts;
function parseTypedefTag(start, tagName, indent) {
var typeExpression = tryParseTypeExpression();
skipWhitespaceOrAsterisk();
- var typedefTag = createNode(304 /* JSDocTypedefTag */, start);
+ var typedefTag = createNode(309 /* JSDocTypedefTag */, start);
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace();
typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
@@ -22473,9 +22566,9 @@ var ts;
var childTypeTag = void 0;
while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start);
+ jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start);
}
- if (child.kind === 302 /* JSDocTypeTag */) {
+ if (child.kind === 307 /* JSDocTypeTag */) {
if (childTypeTag) {
break;
}
@@ -22521,14 +22614,14 @@ var ts;
return typeNameOrNamespaceName;
}
function parseCallbackTag(start, tagName, indent) {
- var callbackTag = createNode(297 /* JSDocCallbackTag */, start);
+ var callbackTag = createNode(302 /* JSDocCallbackTag */, start);
callbackTag.tagName = tagName;
callbackTag.fullName = parseJSDocTypeNameWithNamespace();
callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
skipWhitespace();
callbackTag.comment = parseTagComments(indent);
var child;
- var jsdocSignature = createNode(293 /* JSDocSignature */, start);
+ var jsdocSignature = createNode(298 /* JSDocSignature */, start);
jsdocSignature.parameters = [];
while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
@@ -22536,7 +22629,7 @@ var ts;
var returnTag = tryParse(function () {
if (parseOptionalJsdoc(58 /* AtToken */)) {
var tag = parseTag(indent);
- if (tag && tag.kind === 300 /* JSDocReturnTag */) {
+ if (tag && tag.kind === 305 /* JSDocReturnTag */) {
return tag;
}
}
@@ -22581,7 +22674,7 @@ var ts;
case 58 /* AtToken */:
if (canParseTag) {
var child = tryParseChildTag(target, indent);
- if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) &&
+ if (child && (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) &&
target !== 4 /* CallbackParameter */ &&
name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
@@ -22651,7 +22744,7 @@ var ts;
skipWhitespace();
typeParameters.push(typeParameter);
} while (parseOptionalJsdoc(27 /* CommaToken */));
- var result = createNode(303 /* JSDocTemplateTag */, start);
+ var result = createNode(308 /* JSDocTemplateTag */, start);
result.tagName = tagName;
result.constraint = constraint;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -23737,6 +23830,22 @@ var ts;
category: ts.Diagnostics.Basic_Options,
description: ts.Diagnostics.Enable_project_compilation,
},
+ {
+ name: "incremental",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_incremental_compilation,
+ },
+ {
+ name: "tsBuildInfoFile",
+ type: "string",
+ isFilePath: true,
+ paramType: ts.Diagnostics.FILE,
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
+ },
{
name: "removeComments",
type: "boolean",
@@ -27455,7 +27564,7 @@ var ts;
return "__constructor" /* Constructor */;
case 165 /* FunctionType */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return "__call" /* Call */;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
@@ -27464,7 +27573,7 @@ var ts;
return "__index" /* Index */;
case 255 /* ExportDeclaration */:
return "__export" /* ExportStar */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// json file should behave as
// module.exports = ...
return "export=" /* ExportEquals */;
@@ -27475,12 +27584,12 @@ var ts;
}
ts.Debug.fail("Unknown binary declaration kind");
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
case 151 /* Parameter */:
// Parameters with names are handled at the top of this function. Parameters
// without names can only come from JSDocFunctionTypes.
- ts.Debug.assert(node.parent.kind === 289 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
+ ts.Debug.assert(node.parent.kind === 294 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
var functionType = node.parent;
var index = functionType.parameters.indexOf(node);
return "arg" + index;
@@ -27719,7 +27828,7 @@ var ts;
if (hasExplicitReturn)
node.flags |= 256 /* HasExplicitReturn */;
}
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
node.flags |= emitFlags;
}
if (currentReturnTarget) {
@@ -27863,12 +27972,12 @@ var ts;
case 191 /* CallExpression */:
bindCallExpressionFlow(node);
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
bindJSDocTypeAlias(node);
break;
// In source files and blocks, bind functions first to match hoisting that occurs at runtime
- case 279 /* SourceFile */: {
+ case 284 /* SourceFile */: {
bindEachFunctionsFirst(node.statements);
bind(node.endOfFileToken);
break;
@@ -28555,7 +28664,7 @@ var ts;
case 243 /* EnumDeclaration */:
case 188 /* ObjectLiteralExpression */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 268 /* JsxAttributes */:
return 1 /* IsContainer */;
case 241 /* InterfaceDeclaration */:
@@ -28564,7 +28673,7 @@ var ts;
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
return 1 /* IsContainer */ | 32 /* HasLocals */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
case 156 /* MethodDeclaration */:
if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
@@ -28577,8 +28686,8 @@ var ts;
case 158 /* GetAccessor */:
case 159 /* SetAccessor */:
case 160 /* CallSignature */:
- case 293 /* JSDocSignature */:
- case 289 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
case 165 /* FunctionType */:
case 161 /* ConstructSignature */:
case 162 /* IndexSignature */:
@@ -28632,7 +28741,7 @@ var ts;
// handlers to take care of declaring these child members.
case 244 /* ModuleDeclaration */:
return declareModuleMember(node, symbolFlags, symbolExcludes);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return declareSourceFileMember(node, symbolFlags, symbolExcludes);
case 209 /* ClassExpression */:
case 240 /* ClassDeclaration */:
@@ -28640,7 +28749,7 @@ var ts;
case 243 /* EnumDeclaration */:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 188 /* ObjectLiteralExpression */:
case 241 /* InterfaceDeclaration */:
case 268 /* JsxAttributes */:
@@ -28654,7 +28763,7 @@ var ts;
case 166 /* ConstructorType */:
case 160 /* CallSignature */:
case 161 /* ConstructSignature */:
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
case 162 /* IndexSignature */:
case 156 /* MethodDeclaration */:
case 155 /* MethodSignature */:
@@ -28664,9 +28773,9 @@ var ts;
case 239 /* FunctionDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
- case 289 /* JSDocFunctionType */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 294 /* JSDocFunctionType */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 242 /* TypeAliasDeclaration */:
case 181 /* MappedType */:
// All the children of these container types are never visible through another
@@ -28689,8 +28798,8 @@ var ts;
: declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
function hasExportDeclarations(node) {
- var body = node.kind === 279 /* SourceFile */ ? node : node.body;
- if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
+ var body = node.kind === 284 /* SourceFile */ ? node : node.body;
+ if (body && (body.kind === 284 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) {
for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
var stat = _a[_i];
if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) {
@@ -28824,7 +28933,7 @@ var ts;
case 244 /* ModuleDeclaration */:
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (ts.isExternalOrCommonJsModule(container)) {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
@@ -28962,7 +29071,7 @@ var ts;
function checkStrictModeFunctionDeclaration(node) {
if (languageVersion < 2 /* ES2015 */) {
// Report error if function is not top level function declaration
- if (blockScopeContainer.kind !== 279 /* SourceFile */ &&
+ if (blockScopeContainer.kind !== 284 /* SourceFile */ &&
blockScopeContainer.kind !== 244 /* ModuleDeclaration */ &&
!ts.isFunctionLike(blockScopeContainer)) {
// We check first if the name is inside class declaration or class expression; if so give explicit message
@@ -29237,12 +29346,12 @@ var ts;
case 159 /* SetAccessor */:
return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */);
case 165 /* FunctionType */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
case 166 /* ConstructorType */:
return bindFunctionOrConstructorType(node);
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
case 181 /* MappedType */:
return bindAnonymousTypeWorker(node);
case 188 /* ObjectLiteralExpression */:
@@ -29301,7 +29410,7 @@ var ts;
return bindExportDeclaration(node);
case 254 /* ExportAssignment */:
return bindExportAssignment(node);
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
updateStrictModeStatementList(node.statements);
return bindSourceFileIfExternalModule();
case 218 /* Block */:
@@ -29311,22 +29420,22 @@ var ts;
// falls through
case 245 /* ModuleBlock */:
return updateStrictModeStatementList(node.statements);
- case 299 /* JSDocParameterTag */:
- if (node.parent.kind === 293 /* JSDocSignature */) {
+ case 304 /* JSDocParameterTag */:
+ if (node.parent.kind === 298 /* JSDocSignature */) {
return bindParameter(node);
}
- if (node.parent.kind !== 292 /* JSDocTypeLiteral */) {
+ if (node.parent.kind !== 297 /* JSDocTypeLiteral */) {
break;
}
// falls through
- case 305 /* JSDocPropertyTag */:
+ case 310 /* JSDocPropertyTag */:
var propTag = node;
- var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ?
+ var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 293 /* JSDocOptionalType */ ?
4 /* Property */ | 16777216 /* Optional */ :
4 /* Property */;
return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
}
}
@@ -29498,7 +29607,7 @@ var ts;
var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
// this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
if (thisContainer.commonJsModuleIndicator) {
declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
@@ -29515,7 +29624,7 @@ var ts;
if (node.expression.kind === 100 /* ThisKeyword */) {
bindThisPropertyAssignment(node);
}
- else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) {
+ else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 284 /* SourceFile */) {
if (ts.isPrototypeAccess(node.expression)) {
bindPrototypePropertyAssignment(node, node.parent);
}
@@ -29552,7 +29661,7 @@ var ts;
}
function bindObjectDefinePropertyAssignment(node) {
var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
- var isToplevel = node.parent.parent.kind === 279 /* SourceFile */;
+ var isToplevel = node.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false);
bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
}
@@ -29619,8 +29728,8 @@ var ts;
function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) {
var namespaceSymbol = lookupSymbolForPropertyAccess(name);
var isToplevel = ts.isBinaryExpression(propertyAccess.parent)
- ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */
- : propertyAccess.parent.parent.kind === 279 /* SourceFile */;
+ ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 284 /* SourceFile */
+ : propertyAccess.parent.parent.kind === 284 /* SourceFile */;
namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty);
bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
}
@@ -29758,7 +29867,7 @@ var ts;
}
}
function bindParameter(node) {
- if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) {
+ if (node.kind === 304 /* JSDocParameterTag */ && container.kind !== 298 /* JSDocSignature */) {
return;
}
if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) {
@@ -30501,7 +30610,7 @@ var ts;
break;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
// These nodes are TypeScript syntax.
transformFlags |= 3 /* AssertTypeScript */;
excludeFlags = 536872257 /* OuterExpressionExcludes */;
@@ -30702,7 +30811,7 @@ var ts;
transformFlags |= 192 /* AssertES2015 */;
}
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) {
transformFlags |= 192 /* AssertES2015 */;
}
@@ -30782,7 +30891,7 @@ var ts;
return 637666625 /* BindingPatternExcludes */;
case 194 /* TypeAssertionExpression */:
case 212 /* AsExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
case 195 /* ParenthesizedExpression */:
case 98 /* SuperKeyword */:
return 536872257 /* OuterExpressionExcludes */;
@@ -31193,10 +31302,10 @@ var ts;
isContextSensitive: isContextSensitive,
getFullyQualifiedName: getFullyQualifiedName,
getResolvedSignature: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 0 /* Normal */);
},
getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) {
- return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true);
+ return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16 /* IsForSignatureHelp */);
},
getConstantValue: function (nodeIn) {
var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
@@ -31323,10 +31432,10 @@ var ts;
},
getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
};
- function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) {
+ function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
apparentArgumentCount = argumentCount;
- var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined;
+ var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
apparentArgumentCount = undefined;
return res;
}
@@ -31601,9 +31710,11 @@ var ts;
var CheckMode;
(function (CheckMode) {
CheckMode[CheckMode["Normal"] = 0] = "Normal";
- CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive";
+ CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
- CheckMode[CheckMode["Contextual"] = 3] = "Contextual";
+ CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
+ CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
+ CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
})(CheckMode || (CheckMode = {}));
var CallbackCheck;
(function (CallbackCheck) {
@@ -31959,7 +32070,7 @@ var ts;
return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 });
}
function isGlobalSourceFile(node) {
- return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
+ return node.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
}
function getSymbol(symbols, name, meaning) {
if (meaning) {
@@ -32133,7 +32244,7 @@ var ts;
// - parameters are only in the scope of function body
// This restriction does not apply to JSDoc comment types because they are parented
// at a higher level than type parameters would normally be
- if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) {
+ if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 296 /* JSDocComment */) {
useResult = result.flags & 262144 /* TypeParameter */
// type parameters are visible in parameter list, return type and type parameter list
? lastLocation === location.type ||
@@ -32175,14 +32286,14 @@ var ts;
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
isInExternalModule = true;
// falls through
case 244 /* ModuleDeclaration */:
var moduleExports = getSymbolOfNode(location).exports;
- if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) {
+ if (location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location)) {
// It's an external module. First see if the module has an export default and if the local
// name of that export default matches.
if (result = moduleExports.get("default" /* Default */)) {
@@ -32354,8 +32465,8 @@ var ts;
location = location.parent;
}
break;
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
// js type aliases do not resolve names from their host, so skip past it
location = ts.getJSDocHost(location);
break;
@@ -32374,7 +32485,7 @@ var ts;
}
if (!result) {
if (lastLocation) {
- ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */);
+ ts.Debug.assert(lastLocation.kind === 284 /* SourceFile */);
if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
return lastLocation.symbol;
}
@@ -33230,7 +33341,7 @@ var ts;
function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) {
var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
if (!dontResolveAlias && symbol) {
- if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) {
+ if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 284 /* SourceFile */)) {
var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
? "allowSyntheticDefaultImports"
: "esModuleInterop";
@@ -33581,7 +33692,7 @@ var ts;
}
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location)) {
break;
}
@@ -33821,10 +33932,10 @@ var ts;
return node && getSymbolOfNode(node);
}
function hasExternalModuleSymbol(declaration) {
- return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isAmbientModule(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
- return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
+ return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
}
function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
var aliasesToMakeVisible;
@@ -34281,7 +34392,7 @@ var ts;
var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
(symbol.parent || // is exported function symbol
ts.forEach(symbol.declarations, function (declaration) {
- return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
+ return declaration.parent.kind === 284 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */;
}));
if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
// typeof is allowed only for static/non local functions
@@ -34647,7 +34758,7 @@ var ts;
var savedContextFlags = context.flags;
context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
- type.symbol.declarations[0] &&
+ type.symbol.declarations && type.symbol.declarations[0] &&
ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
typeParameterShadowsNameInScope(type, context);
var name = shouldUseGeneratedName
@@ -34666,7 +34777,7 @@ var ts;
function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */);
if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) {
- parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */);
+ parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 304 /* JSDocParameterTag */);
}
var parameterType = getTypeOfSymbol(parameterSymbol);
if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
@@ -34824,7 +34935,7 @@ var ts;
return top;
}
function getSpecifierForModuleSymbol(symbol, context) {
- var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */);
+ var file = ts.getDeclarationOfKind(symbol, 284 /* SourceFile */);
if (file && file.moduleName !== undefined) {
// Use the amd name if it is available
return file.moduleName;
@@ -35077,7 +35188,7 @@ var ts;
ts.isExternalModuleAugmentation(node.parent.parent);
}
function isDefaultBindingContext(location) {
- return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location);
+ return location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location);
}
function getNameOfSymbolFromNameType(symbol, context) {
var nameType = symbol.nameType;
@@ -35154,8 +35265,8 @@ var ts;
return false;
function determineIfDeclarationIsVisible() {
switch (node.kind) {
- case 297 /* JSDocCallbackTag */:
- case 304 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
// Top-level jsdoc type aliases are considered exported
// First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file
return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
@@ -35182,7 +35293,7 @@ var ts;
var parent = getDeclarationContainer(node);
// If the node is not exported or it is not ambient module element (except import declaration)
if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
- !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
+ !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 284 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) {
return isGlobalSourceFile(parent);
}
// Exported members/ambient module elements (exception import declaration) are visible if parent is visible
@@ -35224,7 +35335,7 @@ var ts;
// Type parameters are always visible
case 150 /* TypeParameter */:
// Source file and namespace export are always visible
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 247 /* NamespaceExportDeclaration */:
return true;
// Export assignments do not create name bindings outside the module
@@ -36334,15 +36445,15 @@ var ts;
case 155 /* MethodSignature */:
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
case 239 /* FunctionDeclaration */:
case 156 /* MethodDeclaration */:
case 196 /* FunctionExpression */:
case 197 /* ArrowFunction */:
case 242 /* TypeAliasDeclaration */:
- case 303 /* JSDocTemplateTag */:
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 308 /* JSDocTemplateTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
case 181 /* MappedType */:
case 175 /* ConditionalType */:
var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
@@ -38334,10 +38445,10 @@ var ts;
function isJSDocOptionalParameter(node) {
return ts.isInJSFile(node) && (
// node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
- node.type && node.type.kind === 288 /* JSDocOptionalType */
+ node.type && node.type.kind === 293 /* JSDocOptionalType */
|| ts.getJSDocParameterTags(node).some(function (_a) {
var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}));
}
function tryFindAmbientModule(moduleName, withAugmentations) {
@@ -38371,7 +38482,7 @@ var ts;
return false;
}
var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */;
}
function createIdentifierTypePredicate(parameterName, parameterIndex, type) {
return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
@@ -38702,8 +38813,21 @@ var ts;
}
return undefined;
}
- function getSignatureInstantiation(signature, typeArguments, isJavascript) {
- return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
+ var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
+ if (inferredTypeParameters) {
+ var returnSignature = getSingleCallSignature(getReturnTypeOfSignature(instantiatedSignature));
+ if (returnSignature) {
+ var newReturnSignature = cloneSignature(returnSignature);
+ newReturnSignature.typeParameters = inferredTypeParameters;
+ newReturnSignature.target = returnSignature.target;
+ newReturnSignature.mapper = returnSignature.mapper;
+ var newInstantiatedSignature = cloneSignature(instantiatedSignature);
+ newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
+ return newInstantiatedSignature;
+ }
+ }
+ return instantiatedSignature;
}
function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
@@ -39075,7 +39199,7 @@ var ts;
}
function getTypeReferenceTypeWorker(node, symbol, typeArguments) {
if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
- if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
+ if (symbol.valueDeclaration && symbol.valueDeclaration.parent && ts.isBinaryExpression(symbol.valueDeclaration.parent)) {
var jsdocType = getJSDocTypeReference(node, symbol, typeArguments);
if (jsdocType) {
return jsdocType;
@@ -39111,7 +39235,7 @@ var ts;
}
function getConstrainedTypeVariable(typeVariable, node) {
var constraints;
- while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) {
+ while (node && !ts.isStatement(node) && node.kind !== 296 /* JSDocComment */) {
var parent = node.parent;
if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) {
var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType);
@@ -40684,8 +40808,8 @@ var ts;
function getTypeFromTypeNode(node) {
switch (node.kind) {
case 120 /* AnyKeyword */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
return anyType;
case 143 /* UnknownKeyword */:
return unknownType;
@@ -40732,23 +40856,23 @@ var ts;
return getTypeFromUnionTypeNode(node);
case 174 /* IntersectionType */:
return getTypeFromIntersectionTypeNode(node);
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return getTypeFromJSDocNullableTypeNode(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return addOptionality(getTypeFromTypeNode(node.type));
case 177 /* ParenthesizedType */:
case 172 /* RestType */:
- case 287 /* JSDocNonNullableType */:
- case 283 /* JSDocTypeExpression */:
+ case 292 /* JSDocNonNullableType */:
+ case 288 /* JSDocTypeExpression */:
return getTypeFromTypeNode(node.type);
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return getTypeFromJSDocVariadicType(node);
case 165 /* FunctionType */:
case 166 /* ConstructorType */:
case 168 /* TypeLiteral */:
- case 292 /* JSDocTypeLiteral */:
- case 289 /* JSDocFunctionType */:
- case 293 /* JSDocSignature */:
+ case 297 /* JSDocTypeLiteral */:
+ case 294 /* JSDocFunctionType */:
+ case 298 /* JSDocSignature */:
return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
case 179 /* TypeOperator */:
return getTypeFromTypeOperatorNode(node);
@@ -41686,7 +41810,7 @@ var ts;
return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation);
}
// recreate a tuple from the elements, if possible
- var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true);
+ var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
if (isTupleLikeType(tupleizedType)) {
return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation);
}
@@ -44109,7 +44233,7 @@ var ts;
return;
}
break;
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
return;
case 239 /* FunctionDeclaration */:
@@ -46390,7 +46514,7 @@ var ts;
return ts.findAncestor(node.parent, function (node) {
return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
node.kind === 245 /* ModuleBlock */ ||
- node.kind === 279 /* SourceFile */ ||
+ node.kind === 284 /* SourceFile */ ||
node.kind === 154 /* PropertyDeclaration */;
});
}
@@ -46511,7 +46635,7 @@ var ts;
// to the constructor in the initializer, we will need to substitute that
// binding with an alias as the class name is not in scope.
var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
- while (container.kind !== 279 /* SourceFile */) {
+ while (container.kind !== 284 /* SourceFile */) {
if (container.parent === declaration) {
if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
@@ -46934,7 +47058,7 @@ var ts;
}
function getTypeForThisExpressionFromJSDoc(node) {
var jsdocType = ts.getJSDocType(node);
- if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) {
+ if (jsdocType && jsdocType.kind === 294 /* JSDocFunctionType */) {
var jsDocFunctionType = jsdocType;
if (jsDocFunctionType.parameters.length > 0 &&
jsDocFunctionType.parameters[0].name &&
@@ -49536,23 +49660,34 @@ var ts;
// Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) {
var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
- var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature;
+ // We clone the contextualMapper to avoid fixing. For example, when the source signature is (x: T) => T[] and
+ // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
+ // for T but leave it possible to later infer '[any]' back to A.
+ var restType = getEffectiveRestType(contextualSignature);
+ var mapper = contextualMapper && restType && restType.flags & 262144 /* TypeParameter */ ? cloneTypeMapper(contextualMapper) : contextualMapper;
+ var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
forEachMatchingParameterType(sourceSignature, signature, function (source, target) {
// Type parameters from outer context referenced by source type are fixed by instantiation of the source type
inferTypes(context.inferences, source, target);
});
if (!contextualMapper) {
inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */);
+ var signaturePredicate = getTypePredicateOfSignature(signature);
+ var contextualPredicate = getTypePredicateOfSignature(sourceSignature);
+ if (signaturePredicate && contextualPredicate && signaturePredicate.kind === contextualPredicate.kind &&
+ (signaturePredicate.kind === 0 /* This */ || signaturePredicate.parameterIndex === contextualPredicate.parameterIndex)) {
+ inferTypes(context.inferences, contextualPredicate.type, signaturePredicate.type, 8 /* ReturnType */);
+ }
}
return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
}
- function inferJsxTypeArguments(node, signature, excludeArgument, context) {
+ function inferJsxTypeArguments(node, signature, checkMode, context) {
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context);
+ var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
inferTypes(context.inferences, checkAttrType, paramType);
return getInferredTypes(context);
}
- function inferTypeArguments(node, signature, args, excludeArgument, context) {
+ function inferTypeArguments(node, signature, args, checkMode, context) {
// Clear out all the inference results from the last time inferTypeArguments was called on this context
for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) {
var inference = _a[_i];
@@ -49565,7 +49700,7 @@ var ts;
}
}
if (ts.isJsxOpeningLikeElement(node)) {
- return inferJsxTypeArguments(node, signature, excludeArgument, context);
+ return inferJsxTypeArguments(node, signature, checkMode, context);
}
// If a contextual type is available, infer from that type to the return type of the call expression. For
// example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression
@@ -49609,10 +49744,7 @@ var ts;
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- // For context sensitive arguments we pass the identityMapper, which is a signal to treat all
- // context sensitive function expressions as wildcards
- var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context;
- var argType = checkExpressionWithContextualType(arg, paramType, mapper);
+ var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
inferTypes(context.inferences, argType, paramType);
}
}
@@ -49636,7 +49768,7 @@ var ts;
// and the argument are ...x forms.
return arg.kind === 215 /* SyntheticExpression */ ?
createArrayType(arg.type) :
- getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context));
+ getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
}
}
var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType;
@@ -49644,7 +49776,7 @@ var ts;
var types = [];
var spreadIndex = -1;
for (var i = index; i < argCount; i++) {
- var argType = checkExpressionWithContextualType(args[i], contextualType, context);
+ var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
if (spreadIndex < 0 && isSpreadArgument(args[i])) {
spreadIndex = i - index;
}
@@ -49694,19 +49826,18 @@ var ts;
* @param node a JSX opening-like element we are trying to figure its call signature
* @param signature a candidate signature we are trying whether it is a call signature
* @param relation a relationship to check parameter and argument type
- * @param excludeArgument
*/
- function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors) {
// Stateless function components can have maximum of three arguments: "props", "context", and "updater".
// However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
// can be specified by users through attributes property.
var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
- var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined);
+ var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined, checkMode);
return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes);
}
- function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) {
+ function checkApplicableSignature(node, args, signature, relation, checkMode, reportErrors) {
if (ts.isJsxOpeningLikeElement(node)) {
- return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors);
+ return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors);
}
var thisType = getThisTypeOfSignature(signature);
if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) {
@@ -49728,11 +49859,11 @@ var ts;
var arg = args[i];
if (arg.kind !== 210 /* OmittedExpression */) {
var paramType = getTypeAtPosition(signature, i);
- var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined);
- // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter),
+ var argType = checkExpressionWithContextualType(arg, paramType, /*contextualMapper*/ undefined, checkMode);
+ // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
// we obtain the regular type of any object literal arguments because we may not have inferred complete
// parameter types yet and therefore excess property checks may yield false positives (see #17041).
- var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType;
+ var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) {
return false;
}
@@ -49937,7 +50068,7 @@ var ts;
}
return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
}
- function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) {
+ function resolveCall(node, signatures, candidatesOutArray, checkMode, fallbackError) {
var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */;
var isDecorator = node.kind === 152 /* Decorator */;
var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
@@ -49973,7 +50104,7 @@ var ts;
// For a decorator, no arguments are susceptible to contextual typing due to the fact
// decorators are applied to a declaration by the emitter, and not to an expression.
var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
- var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined;
+ var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
// The following variables are captured and modified by calls to chooseOverload.
// If overload resolution or type argument inference fails, we want to report the
// best error possible. The best error is one which says that an argument was not
@@ -50001,7 +50132,7 @@ var ts;
var result;
// If we are in signature help, a trailing comma indicates that we intend to provide another argument,
// so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
- var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma;
+ var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma;
// Section 4.12.1:
// if the candidate list contains one or more signatures for which the type of each argument
// expression is a subtype of each corresponding parameter type, the return type of the first
@@ -50027,12 +50158,7 @@ var ts;
// skip the checkApplicableSignature check.
if (reportErrors) {
if (candidateForArgumentError) {
- // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...]
- // The importance of excludeArgument is to prevent us from typing function expression parameters
- // in arguments too early. If possible, we'd like to only type them once we know the correct
- // overload. However, this matters for the case where the call is correct. When the call is
- // an error, we don't need to exclude any arguments, although it would cause no harm to do so.
- checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true);
+ checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, 0 /* Normal */, /*reportErrors*/ true);
}
else if (candidateForArgumentArityError) {
diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
@@ -50064,7 +50190,7 @@ var ts;
if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
return undefined;
}
- if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false)) {
candidateForArgumentError = candidate;
return undefined;
}
@@ -50088,9 +50214,10 @@ var ts;
}
else {
inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
+ typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
+ argCheckMode |= inferenceContext.flags & 8 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
}
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// If the original signature has a generic rest type, instantiation may produce a
// signature with different arity and we need to perform another arity check.
if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -50101,21 +50228,21 @@ var ts;
else {
checkCandidate = candidate;
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
}
continue;
}
- if (excludeArgument) {
+ if (argCheckMode) {
// If one or more context sensitive arguments were excluded, we start including
// them now (and keeping do so for any subsequent candidates) and perform a second
// round of type inference and applicability checking for this particular candidate.
- excludeArgument = undefined;
+ argCheckMode = 0 /* Normal */;
if (inferenceContext) {
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext);
- checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration));
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
+ checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
// If the original signature has a generic rest type, instantiation may produce a
// signature with different arity and we need to perform another arity check.
if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
@@ -50123,7 +50250,7 @@ var ts;
continue;
}
}
- if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) {
+ if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) {
// Give preference to error candidates that have no rest parameters (as they are more specific)
if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) {
candidateForArgumentError = checkCandidate;
@@ -50137,20 +50264,6 @@ var ts;
return undefined;
}
}
- function getExcludeArgument(args) {
- var excludeArgument;
- // We do not need to call `getEffectiveArgumentCount` here as it only
- // applies when calculating the number of arguments for a decorator.
- for (var i = 0; i < args.length; i++) {
- if (isContextSensitive(args[i])) {
- if (!excludeArgument) {
- excludeArgument = new Array(args.length);
- }
- excludeArgument[i] = true;
- }
- }
- return excludeArgument;
- }
// No signature was applicable. We have already reported the errors for the invalid signature.
// If this is a type resolution session, e.g. Language Service, try to get better information than anySignature.
function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
@@ -50239,7 +50352,7 @@ var ts;
}
function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
- var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext);
+ var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
return createSignatureInstantiation(candidate, typeArgumentTypes);
}
function getLongestCandidateIndex(candidates, argsCount) {
@@ -50258,7 +50371,7 @@ var ts;
}
return maxParamsIndex;
}
- function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveCallExpression(node, candidatesOutArray, checkMode) {
if (node.expression.kind === 98 /* SuperKeyword */) {
var superType = checkSuperExpression(node.expression);
if (isTypeAny(superType)) {
@@ -50274,7 +50387,7 @@ var ts;
var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
if (baseTypeNode) {
var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
- return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, baseConstructors, candidatesOutArray, checkMode);
}
}
return resolveUntypedCall(node);
@@ -50324,12 +50437,31 @@ var ts;
}
return resolveErrorCall(node);
}
+ // When a call to a generic function is an argument to an outer call to a generic function for which
+ // inference is in process, we have a choice to make. If the inner call relies on inferences made from
+ // its contextual type to its return type, deferring the inner call processing allows the best possible
+ // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
+ // the inner call, the inner call should be processed early. There's no sure way to know which choice is
+ // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
+ // If no type arguments are specified in the inner call and at least one call signature is generic and
+ // returns a function type, we choose to defer processing. This narrowly permits function composition
+ // operators to flow inferences through return types, but otherwise processes calls right away. We
+ // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
+ // propagated out and eventually turned into silentNeverType (a type that is assignable to anything and
+ // from which we never make inferences).
+ if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
+ skippedGenericFunction(node, checkMode);
+ return resolvingSignature;
+ }
// If the function is explicitly marked with `@class`, then it must be constructed.
if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
+ }
+ function isGenericFunctionReturningFunction(signature) {
+ return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
}
/**
* TS 1.0 spec: 4.12
@@ -50341,7 +50473,7 @@ var ts;
return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
!numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
}
- function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveNewExpression(node, candidatesOutArray, checkMode) {
if (node.arguments && languageVersion < 1 /* ES5 */) {
var spreadIndex = getSpreadArgumentIndex(node.arguments);
if (spreadIndex >= 0) {
@@ -50389,7 +50521,7 @@ var ts;
error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
return resolveErrorCall(node);
}
- return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, constructSignatures, candidatesOutArray, checkMode);
}
// If expressionType's apparent type is an object type with no construct signatures but
// one or more call signatures, the expression is processed as a function call. A compile-time
@@ -50397,7 +50529,7 @@ var ts;
// operation is Any. It is an error to have a Void this type.
var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
if (callSignatures.length) {
- var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode);
if (!noImplicitAny) {
if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
@@ -50494,7 +50626,7 @@ var ts;
addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead));
}
}
- function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
var tagType = checkExpression(node.tag);
var apparentType = getApparentType(tagType);
if (apparentType === errorType) {
@@ -50510,7 +50642,7 @@ var ts;
invocationError(node, apparentType, 0 /* Call */);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode);
}
/**
* Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
@@ -50535,7 +50667,7 @@ var ts;
/**
* Resolves a decorator as if it were a call expression.
*/
- function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveDecorator(node, candidatesOutArray, checkMode) {
var funcType = checkExpression(node.expression);
var apparentType = getApparentType(funcType);
if (apparentType === errorType) {
@@ -50560,7 +50692,7 @@ var ts;
invocationErrorRecovery(apparentType, 0 /* Call */, diag);
return resolveErrorCall(node);
}
- return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage);
+ return resolveCall(node, callSignatures, candidatesOutArray, checkMode, headMessage);
}
function createSignatureForJSXIntrinsic(node, result) {
var namespace = getJsxNamespaceAt(node);
@@ -50579,11 +50711,11 @@ var ts;
/*hasRestparameter*/ false,
/*hasLiteralTypes*/ false);
}
- function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
if (isJsxIntrinsicIdentifier(node.tagName)) {
var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
var fakeSignature = createSignatureForJSXIntrinsic(node, result);
- checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes);
+ checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
return fakeSignature;
}
var exprTypes = checkExpression(node.tagName);
@@ -50600,7 +50732,7 @@ var ts;
error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
return resolveErrorCall(node);
}
- return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp);
+ return resolveCall(node, signatures, candidatesOutArray, checkMode);
}
/**
* Sometimes, we have a decorator that could accept zero arguments,
@@ -50614,19 +50746,19 @@ var ts;
signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
});
}
- function resolveSignature(node, candidatesOutArray, isForSignatureHelp) {
+ function resolveSignature(node, candidatesOutArray, checkMode) {
switch (node.kind) {
case 191 /* CallExpression */:
- return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveCallExpression(node, candidatesOutArray, checkMode);
case 192 /* NewExpression */:
- return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveNewExpression(node, candidatesOutArray, checkMode);
case 193 /* TaggedTemplateExpression */:
- return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp);
+ return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
case 152 /* Decorator */:
- return resolveDecorator(node, candidatesOutArray, isForSignatureHelp);
+ return resolveDecorator(node, candidatesOutArray, checkMode);
case 262 /* JsxOpeningElement */:
case 261 /* JsxSelfClosingElement */:
- return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp);
+ return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
}
throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
}
@@ -50637,8 +50769,7 @@ var ts;
* the function will fill it up with appropriate candidate signatures
* @return a signature of the call-like expression or undefined if one can't be found
*/
- function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) {
- if (isForSignatureHelp === void 0) { isForSignatureHelp = false; }
+ function getResolvedSignature(node, candidatesOutArray, checkMode) {
var links = getNodeLinks(node);
// If getResolvedSignature has already been called, we will have cached the resolvedSignature.
// However, it is possible that either candidatesOutArray was not passed in the first time,
@@ -50649,11 +50780,15 @@ var ts;
return cached;
}
links.resolvedSignature = resolvingSignature;
- var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp);
- // If signature resolution originated in control flow type analysis (for example to compute the
- // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
- // types from the control flow analysis.
- links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
+ // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
+ // resolution should be deferred.
+ if (result !== resolvingSignature) {
+ // If signature resolution originated in control flow type analysis (for example to compute the
+ // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
+ // types from the control flow analysis.
+ links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
+ }
return result;
}
/**
@@ -50729,10 +50864,15 @@ var ts;
* @param node The call/new expression to be checked.
* @returns On success, the expression's signature's return type. On failure, anyType.
*/
- function checkCallExpression(node) {
+ function checkCallExpression(node, checkMode) {
if (!checkGrammarTypeArguments(node, node.typeArguments))
checkGrammarArguments(node.arguments);
- var signature = getResolvedSignature(node);
+ var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
+ if (signature === resolvingSignature) {
+ // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
+ // returns a function type. We defer checking and return anyFunctionType.
+ return silentNeverType;
+ }
if (node.expression.kind === 98 /* SuperKeyword */) {
return voidType;
}
@@ -50976,7 +51116,7 @@ var ts;
if (isTupleType(restType)) {
var associatedNames = restType.target.associatedNames;
var index = pos - paramCount;
- return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index;
+ return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
}
return restParameter.escapedName;
}
@@ -51184,7 +51324,7 @@ var ts;
var functionFlags = ts.getFunctionFlags(func);
var type;
if (func.body.kind !== 218 /* Block */) {
- type = checkExpressionCached(func.body, checkMode);
+ type = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -51362,7 +51502,7 @@ var ts;
ts.forEachReturnStatement(func.body, function (returnStatement) {
var expr = returnStatement.expression;
if (expr) {
- var type = checkExpressionCached(expr, checkMode);
+ var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
if (functionFlags & 2 /* Async */) {
// From within an async function you can return either a non-promise value or a promise. Any
// Promise/A+ compatible implementation will always assimilate any foreign promise, so the
@@ -51455,7 +51595,7 @@ var ts;
ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
checkNodeDeferred(node);
// The identityMapper object is used to indicate that function expressions are wildcards
- if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) {
+ if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
// Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) {
var links_1 = getNodeLinks(node);
@@ -51492,7 +51632,7 @@ var ts;
var signature = getSignaturesOfType(type, 0 /* Call */)[0];
if (isContextSensitive(node)) {
var contextualMapper = getContextualMapper(node);
- if (checkMode === 2 /* Inferential */) {
+ if (checkMode && checkMode & 2 /* Inferential */) {
inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper);
}
var instantiatedContextualSignature = contextualMapper === identityMapper ?
@@ -52414,15 +52554,13 @@ var ts;
}
return node;
}
- function checkExpressionWithContextualType(node, contextualType, contextualMapper) {
+ function checkExpressionWithContextualType(node, contextualType, contextualMapper, checkMode) {
var context = getContextNode(node);
var saveContextualType = context.contextualType;
var saveContextualMapper = context.contextualMapper;
context.contextualType = contextualType;
context.contextualMapper = contextualMapper;
- var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ :
- contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */;
- var type = checkExpression(node, checkMode);
+ var type = checkExpression(node, checkMode | 1 /* Contextual */ | (contextualMapper ? 2 /* Inferential */ : 0));
// We strip literal freshness when an appropriate contextual type is present such that contextually typed
// literals always preserve their literal types (otherwise they might widen during type inference). An alternative
// here would be to not mark contextually typed literals as fresh in the first place.
@@ -52435,7 +52573,7 @@ var ts;
function checkExpressionCached(node, checkMode) {
var links = getNodeLinks(node);
if (!links.resolvedType) {
- if (checkMode) {
+ if (checkMode && checkMode !== 0 /* Normal */) {
return checkExpression(node, checkMode);
}
// When computing a type that we're going to cache, we need to ignore any ongoing control flow
@@ -52532,20 +52670,122 @@ var ts;
return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
}
function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
- if (checkMode === 2 /* Inferential */) {
+ if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
var signature = getSingleCallSignature(type);
if (signature && signature.typeParameters) {
+ if (checkMode & 8 /* SkipGenericFunctions */) {
+ skippedGenericFunction(node, checkMode);
+ return anyFunctionType;
+ }
var contextualType = getApparentTypeOfContextualType(node);
if (contextualType) {
var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType));
if (contextualSignature && !contextualSignature.typeParameters) {
- return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node)));
+ var context = getContextualMapper(node);
+ // We have an expression that is an argument of a generic function for which we are performing
+ // type argument inference. The expression is of a function type with a single generic call
+ // signature and a contextual function type with a single non-generic call signature. Now check
+ // if the outer function returns a function type with a single non-generic call signature and
+ // if some of the outer function type parameters have no inferences so far. If so, we can
+ // potentially add inferred type parameters to the outer function return type.
+ var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature));
+ if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
+ // Instantiate the expression type with its own type parameters as type arguments. This
+ // ensures that the type parameters are not erased to type any during type inference such
+ // that they can be inferred as actual types.
+ var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
+ var strippedType = getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters));
+ // Infer from the stripped expression type to the contextual type starting with an empty
+ // set of inference candidates.
+ var inferences = ts.map(context.typeParameters, createInferenceInfo);
+ inferTypes(inferences, strippedType, contextualType);
+ // If we produced some inference candidates and if the type parameters for which we produced
+ // candidates do not already have existing inferences, we adopt the new inference candidates and
+ // add the type parameters of the expression type to the set of inferred type parameters for
+ // the outer function return type.
+ if (ts.some(inferences, hasInferenceCandidates) && !hasOverlappingInferences(context.inferences, inferences)) {
+ mergeInferences(context.inferences, inferences);
+ context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
+ return strippedType;
+ }
+ }
+ return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
}
}
}
}
return type;
}
+ function skippedGenericFunction(node, checkMode) {
+ if (checkMode & 2 /* Inferential */) {
+ // We have skipped a generic function during inferential typing. Obtain the inference context and
+ // indicate this has occurred such that we know a second pass of inference is be needed.
+ var context = getContextualMapper(node);
+ context.flags |= 8 /* SkippedGenericFunction */;
+ }
+ }
+ function hasInferenceCandidates(info) {
+ return !!(info.candidates || info.contraCandidates);
+ }
+ function hasOverlappingInferences(a, b) {
+ for (var i = 0; i < a.length; i++) {
+ if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
+ return true;
+ }
+ }
+ return false;
+ }
+ function mergeInferences(target, source) {
+ for (var i = 0; i < target.length; i++) {
+ if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
+ target[i] = source[i];
+ }
+ }
+ }
+ function getUniqueTypeParameters(context, typeParameters) {
+ var result = [];
+ var oldTypeParameters;
+ var newTypeParameters;
+ for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
+ var tp = typeParameters_2[_i];
+ var name = tp.symbol.escapedName;
+ if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
+ var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
+ var symbol = createSymbol(262144 /* TypeParameter */, newName);
+ var newTypeParameter = createTypeParameter(symbol);
+ newTypeParameter.target = tp;
+ oldTypeParameters = ts.append(oldTypeParameters, tp);
+ newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
+ result.push(newTypeParameter);
+ }
+ else {
+ result.push(tp);
+ }
+ }
+ if (newTypeParameters) {
+ var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
+ for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
+ var tp = newTypeParameters_1[_a];
+ tp.mapper = mapper;
+ }
+ }
+ return result;
+ }
+ function hasTypeParameterByName(typeParameters, name) {
+ return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
+ }
+ function getUniqueTypeParameterName(typeParameters, baseName) {
+ var len = baseName.length;
+ while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
+ len--;
+ var s = baseName.slice(0, len);
+ for (var index = 1; true; index++) {
+ var augmentedName = (s + index);
+ if (!hasTypeParameterByName(typeParameters, augmentedName)) {
+ return augmentedName;
+ }
+ }
+ }
/**
* Returns the type of an expression. Unlike checkExpression, this function is simply concerned
* with computing the type and may not fully check all contained sub-expressions for errors.
@@ -52585,7 +52825,7 @@ var ts;
}
var saveContextualType = node.contextualType;
node.contextualType = anyType;
- var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */);
+ var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
node.contextualType = saveContextualType;
return type;
}
@@ -52677,7 +52917,7 @@ var ts;
}
/* falls through */
case 192 /* NewExpression */:
- return checkCallExpression(node);
+ return checkCallExpression(node, checkMode);
case 193 /* TaggedTemplateExpression */:
return checkTaggedTemplateExpression(node);
case 195 /* ParenthesizedExpression */:
@@ -52936,7 +53176,7 @@ var ts;
checkAsyncFunctionReturnType(node, returnTypeNode);
}
}
- if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) {
+ if (node.kind !== 162 /* IndexSignature */ && node.kind !== 294 /* JSDocFunctionType */) {
registerForUnusedIdentifiersCheck(node);
}
}
@@ -53692,8 +53932,8 @@ var ts;
case 241 /* InterfaceDeclaration */:
case 242 /* TypeAliasDeclaration */:
// A jsdoc typedef and callback are, by definition, type aliases
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return 2 /* ExportType */;
case 244 /* ModuleDeclaration */:
return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
@@ -53702,7 +53942,7 @@ var ts;
case 240 /* ClassDeclaration */:
case 243 /* EnumDeclaration */:
return 2 /* ExportType */ | 1 /* ExportValue */;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
case 254 /* ExportAssignment */:
// Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
@@ -54343,7 +54583,7 @@ var ts;
checkUnusedClassMembers(node, addDiagnostic);
checkUnusedTypeParameters(node, addDiagnostic);
break;
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 244 /* ModuleDeclaration */:
case 218 /* Block */:
case 246 /* CaseBlock */:
@@ -54436,8 +54676,8 @@ var ts;
return;
var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
var seenParentsWithEveryUnused = new ts.NodeSet();
- for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
- var typeParameter = typeParameters_2[_i];
+ for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
+ var typeParameter = typeParameters_3[_i];
if (!isTypeParameterUnused(typeParameter))
continue;
var name = ts.idText(typeParameter.name);
@@ -54690,7 +54930,7 @@ var ts;
}
// In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
var parent = getDeclarationContainer(node);
- if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
+ if (parent.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
// If the declaration happens to be in external module, report error that require and exports are reserved keywords
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
@@ -54705,7 +54945,7 @@ var ts;
}
// In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
var parent = getDeclarationContainer(node);
- if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
+ if (parent.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) {
// If the declaration happens to be in external module, report error that Promise is a reserved identifier.
error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name));
}
@@ -54762,7 +55002,7 @@ var ts;
(container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) ||
container.kind === 245 /* ModuleBlock */ ||
container.kind === 244 /* ModuleDeclaration */ ||
- container.kind === 279 /* SourceFile */);
+ container.kind === 284 /* SourceFile */);
// here we know that function scoped variable is shadowed by block scoped one
// if they are defined in the same scope - binder has already reported redeclaration error
// otherwise if variable has an initializer - show error that initialization will fail
@@ -56612,7 +56852,7 @@ var ts;
return false;
}
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule) {
error(moduleName, node.kind === 255 /* ExportDeclaration */ ?
ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
@@ -56743,7 +56983,7 @@ var ts;
var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ &&
!node.moduleSpecifier && node.flags & 4194304 /* Ambient */;
- if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
+ if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
}
}
@@ -56760,7 +57000,7 @@ var ts;
}
}
function checkGrammarModuleElementContext(node, errorMessage) {
- var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
+ var isInAppropriateContext = node.parent.kind === 284 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */;
if (!isInAppropriateContext) {
grammarErrorOnFirstToken(node, errorMessage);
}
@@ -56789,7 +57029,7 @@ var ts;
// If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
return;
}
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
if (node.isExportEquals) {
error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
@@ -56959,32 +57199,32 @@ var ts;
return checkInferType(node);
case 183 /* ImportType */:
return checkImportType(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return checkJSDocAugmentsTag(node);
- case 304 /* JSDocTypedefTag */:
- case 297 /* JSDocCallbackTag */:
+ case 309 /* JSDocTypedefTag */:
+ case 302 /* JSDocCallbackTag */:
return checkJSDocTypeAliasTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return checkJSDocTemplateTag(node);
- case 302 /* JSDocTypeTag */:
+ case 307 /* JSDocTypeTag */:
return checkJSDocTypeTag(node);
- case 299 /* JSDocParameterTag */:
+ case 304 /* JSDocParameterTag */:
return checkJSDocParameterTag(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
checkJSDocFunctionType(node);
// falls through
- case 287 /* JSDocNonNullableType */:
- case 286 /* JSDocNullableType */:
- case 284 /* JSDocAllType */:
- case 285 /* JSDocUnknownType */:
- case 292 /* JSDocTypeLiteral */:
+ case 292 /* JSDocNonNullableType */:
+ case 291 /* JSDocNullableType */:
+ case 289 /* JSDocAllType */:
+ case 290 /* JSDocUnknownType */:
+ case 297 /* JSDocTypeLiteral */:
checkJSDocTypeIsInJsFile(node);
ts.forEachChild(node, checkSourceElement);
return;
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
checkJSDocVariadicType(node);
return;
- case 283 /* JSDocTypeExpression */:
+ case 288 /* JSDocTypeExpression */:
return checkSourceElement(node.type);
case 180 /* IndexedAccessType */:
return checkIndexedAccessType(node);
@@ -57292,7 +57532,7 @@ var ts;
copySymbols(location.locals, meaning);
}
switch (location.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
if (!ts.isExternalOrCommonJsModule(location))
break;
// falls through
@@ -57511,10 +57751,10 @@ var ts;
return entityNameSymbol;
}
}
- if (entityName.parent.kind === 299 /* JSDocParameterTag */) {
+ if (entityName.parent.kind === 304 /* JSDocParameterTag */) {
return ts.getParameterSymbolFromJSDoc(entityName.parent);
}
- if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) {
+ if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 308 /* JSDocTemplateTag */) {
ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true.
var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
return typeParameter && typeParameter.symbol;
@@ -57556,7 +57796,7 @@ var ts;
return undefined;
}
function getSymbolAtLocation(node) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
}
var parent = node.parent;
@@ -57898,7 +58138,7 @@ var ts;
}
var parentSymbol_1 = getParentOfSymbol(symbol);
if (parentSymbol_1) {
- if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) {
+ if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 284 /* SourceFile */) {
var symbolFile = parentSymbol_1.valueDeclaration;
var referenceFile = ts.getSourceFileOfNode(node);
// If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
@@ -58013,7 +58253,7 @@ var ts;
}
function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
- if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
+ if (node === undefined || node.parent.kind !== 284 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
// parent is not source file or it is not reference to internal module
return false;
}
@@ -58442,7 +58682,7 @@ var ts;
break;
}
}
- if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
+ if (current.valueDeclaration && current.valueDeclaration.kind === 284 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
return false;
}
// check that at least one declaration of top level symbol originates from type declaration file
@@ -58475,7 +58715,7 @@ var ts;
if (!moduleSymbol) {
return undefined;
}
- return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */);
+ return ts.getDeclarationOfKind(moduleSymbol, 284 /* SourceFile */);
}
function initializeTypeChecker() {
// Bind all source files and propagate errors
@@ -58707,7 +58947,7 @@ var ts;
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
}
else if (flags & 128 /* Abstract */) {
@@ -58730,7 +58970,7 @@ var ts;
else if (flags & 256 /* Async */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
}
- else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
}
else if (node.kind === 151 /* Parameter */) {
@@ -58775,7 +59015,7 @@ var ts;
flags |= 1 /* Export */;
break;
case 80 /* DefaultKeyword */:
- var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent;
+ var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent;
if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
}
@@ -58898,7 +59138,7 @@ var ts;
case 151 /* Parameter */:
return false;
default:
- if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
return false;
}
switch (node.kind) {
@@ -59821,7 +60061,7 @@ var ts;
// to prevent noisiness. So use a bit on the block to indicate if
// this has already been reported, and don't report if it has.
//
- if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) {
+ if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) {
var links_2 = getNodeLinks(node.parent);
// Check if the containing block ever report this error
if (!links_2.hasReportedStatementInAmbientContext) {
@@ -61875,14 +62115,14 @@ var ts;
// JSDoc
/* @internal */
function createJSDocTypeExpression(type) {
- var node = createSynthesizedNode(283 /* JSDocTypeExpression */);
+ var node = createSynthesizedNode(288 /* JSDocTypeExpression */);
node.type = type;
return node;
}
ts.createJSDocTypeExpression = createJSDocTypeExpression;
/* @internal */
function createJSDocTypeTag(typeExpression, comment) {
- var tag = createJSDocTag(302 /* JSDocTypeTag */, "type");
+ var tag = createJSDocTag(307 /* JSDocTypeTag */, "type");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61890,7 +62130,7 @@ var ts;
ts.createJSDocTypeTag = createJSDocTypeTag;
/* @internal */
function createJSDocReturnTag(typeExpression, comment) {
- var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns");
+ var tag = createJSDocTag(305 /* JSDocReturnTag */, "returns");
tag.typeExpression = typeExpression;
tag.comment = comment;
return tag;
@@ -61898,7 +62138,7 @@ var ts;
ts.createJSDocReturnTag = createJSDocReturnTag;
/* @internal */
function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
- var tag = createJSDocTag(299 /* JSDocParameterTag */, "param");
+ var tag = createJSDocTag(304 /* JSDocParameterTag */, "param");
tag.typeExpression = typeExpression;
tag.name = name;
tag.isBracketed = isBracketed;
@@ -61908,7 +62148,7 @@ var ts;
ts.createJSDocParamTag = createJSDocParamTag;
/* @internal */
function createJSDocComment(comment, tags) {
- var node = createSynthesizedNode(291 /* JSDocComment */);
+ var node = createSynthesizedNode(296 /* JSDocComment */);
node.comment = comment;
node.tags = tags;
return node;
@@ -62167,7 +62407,7 @@ var ts;
(typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
(libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
(hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
- var updated = createSynthesizedNode(279 /* SourceFile */);
+ var updated = createSynthesizedNode(284 /* SourceFile */);
updated.flags |= node.flags;
updated.statements = createNodeArray(statements);
updated.endOfFileToken = node.endOfFileToken;
@@ -62251,7 +62491,7 @@ var ts;
* @param original The original statement.
*/
function createNotEmittedStatement(original) {
- var node = createSynthesizedNode(307 /* NotEmittedStatement */);
+ var node = createSynthesizedNode(312 /* NotEmittedStatement */);
node.original = original;
setTextRange(node, original);
return node;
@@ -62263,7 +62503,7 @@ var ts;
*/
/* @internal */
function createEndOfDeclarationMarker(original) {
- var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */);
+ var node = createSynthesizedNode(316 /* EndOfDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -62275,7 +62515,7 @@ var ts;
*/
/* @internal */
function createMergeDeclarationMarker(original) {
- var node = createSynthesizedNode(310 /* MergeDeclarationMarker */);
+ var node = createSynthesizedNode(315 /* MergeDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -62290,7 +62530,7 @@ var ts;
* @param location The location for the expression. Defaults to the positions from "original" if provided.
*/
function createPartiallyEmittedExpression(expression, original) {
- var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */);
+ var node = createSynthesizedNode(313 /* PartiallyEmittedExpression */);
node.expression = expression;
node.original = original;
setTextRange(node, original);
@@ -62306,7 +62546,7 @@ var ts;
ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
function flattenCommaElements(node) {
if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
- if (node.kind === 309 /* CommaListExpression */) {
+ if (node.kind === 314 /* CommaListExpression */) {
return node.elements;
}
if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
@@ -62316,7 +62556,7 @@ var ts;
return node;
}
function createCommaList(elements) {
- var node = createSynthesizedNode(309 /* CommaListExpression */);
+ var node = createSynthesizedNode(314 /* CommaListExpression */);
node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
return node;
}
@@ -62329,33 +62569,197 @@ var ts;
ts.updateCommaList = updateCommaList;
function createBundle(sourceFiles, prepends) {
if (prepends === void 0) { prepends = ts.emptyArray; }
- var node = ts.createNode(280 /* Bundle */);
+ var node = ts.createNode(285 /* Bundle */);
node.prepends = prepends;
node.sourceFiles = sourceFiles;
return node;
}
ts.createBundle = createBundle;
- function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, map) {
- var node = ts.createNode(281 /* UnparsedSource */);
+ var allUnscopedEmitHelpers;
+ function getAllUnscopedEmitHelpers() {
+ return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
+ ts.valuesHelper,
+ ts.readHelper,
+ ts.spreadHelper,
+ ts.restHelper,
+ ts.decorateHelper,
+ ts.metadataHelper,
+ ts.paramHelper,
+ ts.awaiterHelper,
+ ts.assignHelper,
+ ts.awaitHelper,
+ ts.asyncGeneratorHelper,
+ ts.asyncDelegator,
+ ts.asyncValues,
+ ts.extendsHelper,
+ ts.templateObjectHelper,
+ ts.generatorHelper,
+ ts.importStarHelper,
+ ts.importDefaultHelper
+ ], function (helper) { return helper.name; }));
+ }
+ function createUnparsedSource() {
+ var node = ts.createNode(286 /* UnparsedSource */);
+ node.prologues = ts.emptyArray;
+ node.referencedFiles = ts.emptyArray;
+ node.libReferenceDirectives = ts.emptyArray;
+ node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
+ return node;
+ }
+ function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
+ var node = createUnparsedSource();
+ var stripInternal;
+ var bundleFileInfo;
if (!ts.isString(textOrInputFiles)) {
ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
- node.fileName = mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath;
+ node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
Object.defineProperties(node, {
text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
});
+ if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
+ node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
+ ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
+ stripInternal = mapTextOrStripInternal;
+ bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
+ if (node.oldFileOfCurrentEmit) {
+ parseOldFileOfCurrentEmit(node, ts.Debug.assertDefined(bundleFileInfo));
+ return node;
+ }
+ }
}
else {
+ node.fileName = "";
node.text = textOrInputFiles;
node.sourceMapPath = mapPathOrType;
- node.sourceMapText = map;
+ node.sourceMapText = mapTextOrStripInternal;
}
+ ts.Debug.assert(!node.oldFileOfCurrentEmit);
+ parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
return node;
}
ts.createUnparsedSourceFile = createUnparsedSourceFile;
- function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapText) {
- var node = ts.createNode(282 /* InputFiles */);
+ function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
+ var prologues;
+ var helpers;
+ var referencedFiles;
+ var typeReferenceDirectives;
+ var libReferenceDirectives;
+ var texts;
+ for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "prologue" /* Prologue */:
+ (prologues || (prologues = [])).push(createUnparsedNode(section, node));
+ break;
+ case "emitHelpers" /* EmitHelpers */:
+ (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ node.hasNoDefaultLib = true;
+ break;
+ case "reference" /* Reference */:
+ (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "type" /* Type */:
+ (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
+ break;
+ case "lib" /* Lib */:
+ (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case "prepend" /* Prepend */:
+ var prependNode = createUnparsedNode(section, node);
+ var prependTexts = void 0;
+ for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
+ var text = _c[_b];
+ if (!stripInternal || text.kind !== "internal" /* Internal */) {
+ (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
+ }
+ }
+ prependNode.texts = prependTexts || ts.emptyArray;
+ (texts || (texts = [])).push(prependNode);
+ break;
+ case "internal" /* Internal */:
+ if (stripInternal)
+ break;
+ // falls through
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.prologues = prologues || ts.emptyArray;
+ node.helpers = helpers;
+ node.referencedFiles = referencedFiles || ts.emptyArray;
+ node.typeReferenceDirectives = typeReferenceDirectives;
+ node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
+ node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
+ }
+ function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
+ ts.Debug.assert(!!node.oldFileOfCurrentEmit);
+ var texts;
+ var syntheticReferences;
+ for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
+ var section = _a[_i];
+ switch (section.kind) {
+ case "internal" /* Internal */:
+ case "text" /* Text */:
+ (texts || (texts = [])).push(createUnparsedNode(section, node));
+ break;
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
+ break;
+ // Ignore
+ case "prologue" /* Prologue */:
+ case "emitHelpers" /* EmitHelpers */:
+ case "prepend" /* Prepend */:
+ break;
+ default:
+ ts.Debug.assertNever(section);
+ }
+ }
+ node.texts = texts || ts.emptyArray;
+ node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
+ node.syntheticReferences = syntheticReferences;
+ return node;
+ }
+ function mapBundleFileSectionKindToSyntaxKind(kind) {
+ switch (kind) {
+ case "prologue" /* Prologue */: return 279 /* UnparsedPrologue */;
+ case "prepend" /* Prepend */: return 280 /* UnparsedPrepend */;
+ case "internal" /* Internal */: return 282 /* UnparsedInternalText */;
+ case "text" /* Text */: return 281 /* UnparsedText */;
+ case "emitHelpers" /* EmitHelpers */:
+ case "no-default-lib" /* NoDefaultLib */:
+ case "reference" /* Reference */:
+ case "type" /* Type */:
+ case "lib" /* Lib */:
+ return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
+ default:
+ return ts.Debug.assertNever(kind);
+ }
+ }
+ function createUnparsedNode(section, parent) {
+ var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ return node;
+ }
+ function createUnparsedSyntheticReference(section, parent) {
+ var node = ts.createNode(283 /* UnparsedSyntheticReference */, section.pos, section.end);
+ node.parent = parent;
+ node.data = section.data;
+ node.section = section;
+ return node;
+ }
+ function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
+ var node = ts.createNode(287 /* InputFiles */);
if (!ts.isString(javascriptTextOrReadFileText)) {
var cache_1 = ts.createMap();
var textGetter_1 = function (path) {
@@ -62372,15 +62776,25 @@ var ts;
var result = textGetter_1(path);
return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
};
+ var buildInfo_1;
+ var getAndCacheBuildInfo_1 = function (getText) {
+ if (buildInfo_1 === undefined) {
+ var result = getText();
+ buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
+ }
+ return buildInfo_1 || undefined;
+ };
node.javascriptPath = declarationTextOrJavascriptPath;
node.javascriptMapPath = javascriptMapPath;
node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
node.declarationMapPath = declarationMapPath;
+ node.buildInfoPath = declarationMapTextOrBuildInfoPath;
Object.defineProperties(node, {
javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
- declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } } // TODO:: if there is inline sourceMap in dtsFile, use that
+ declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
+ buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
});
}
else {
@@ -62389,7 +62803,12 @@ var ts;
node.javascriptMapText = javascriptMapTextOrDeclarationPath;
node.declarationText = declarationTextOrJavascriptPath;
node.declarationMapPath = declarationMapPath;
- node.declarationMapText = declarationMapText;
+ node.declarationMapText = declarationMapTextOrBuildInfoPath;
+ node.javascriptPath = javascriptPath;
+ node.declarationPath = declarationPath,
+ node.buildInfoPath = buildInfoPath;
+ node.buildInfo = buildInfo;
+ node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
}
return node;
}
@@ -62527,7 +62946,7 @@ var ts;
// To avoid holding onto transformation artifacts, we keep track of any
// parse tree node we are annotating. This allows us to clean them up after
// all transformations have completed.
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
return node.emitNode = { annotatedNodes: [node] };
}
var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
@@ -62973,38 +63392,38 @@ var ts;
return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
}
ts.getHelperName = getHelperName;
- var valuesHelper = {
+ ts.valuesHelper = {
name: "typescript:values",
scoped: false,
text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };"
};
function createValuesHelper(context, expression, location) {
- context.requestEmitHelper(valuesHelper);
+ context.requestEmitHelper(ts.valuesHelper);
return ts.setTextRange(ts.createCall(getHelperName("__values"),
/*typeArguments*/ undefined, [expression]), location);
}
ts.createValuesHelper = createValuesHelper;
- var readHelper = {
+ ts.readHelper = {
name: "typescript:read",
scoped: false,
text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };"
};
function createReadHelper(context, iteratorRecord, count, location) {
- context.requestEmitHelper(readHelper);
+ context.requestEmitHelper(ts.readHelper);
return ts.setTextRange(ts.createCall(getHelperName("__read"),
/*typeArguments*/ undefined, count !== undefined
? [iteratorRecord, ts.createLiteral(count)]
: [iteratorRecord]), location);
}
ts.createReadHelper = createReadHelper;
- var spreadHelper = {
+ ts.spreadHelper = {
name: "typescript:spread",
scoped: false,
text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };"
};
function createSpreadHelper(context, argumentList, location) {
- context.requestEmitHelper(readHelper);
- context.requestEmitHelper(spreadHelper);
+ context.requestEmitHelper(ts.readHelper);
+ context.requestEmitHelper(ts.spreadHelper);
return ts.setTextRange(ts.createCall(getHelperName("__spread"),
/*typeArguments*/ undefined, argumentList), location);
}
@@ -63850,7 +64269,7 @@ var ts;
case 190 /* ElementAccessExpression */:
case 189 /* PropertyAccessExpression */:
case 213 /* NonNullExpression */:
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
node = node.expression;
continue;
}
@@ -63866,7 +64285,7 @@ var ts;
ts.parenthesizeConciseBody = parenthesizeConciseBody;
function isCommaSequence(node) {
return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
- node.kind === 309 /* CommaListExpression */;
+ node.kind === 314 /* CommaListExpression */;
}
ts.isCommaSequence = isCommaSequence;
var OuterExpressionKinds;
@@ -63885,7 +64304,7 @@ var ts;
case 212 /* AsExpression */:
case 213 /* NonNullExpression */:
return (kinds & 2 /* Assertions */) !== 0;
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0;
}
return false;
@@ -63922,7 +64341,7 @@ var ts;
case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
- case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
+ case 313 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
}
}
/**
@@ -64714,12 +65133,12 @@ var ts;
case 278 /* EnumMember */:
return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
default:
// No need to visit nodes with no children.
@@ -64775,7 +65194,7 @@ var ts;
case 220 /* EmptyStatement */:
case 210 /* OmittedExpression */:
case 236 /* DebuggerStatement */:
- case 307 /* NotEmittedStatement */:
+ case 312 /* NotEmittedStatement */:
// No need to visit nodes with no children.
break;
// Names
@@ -65152,14 +65571,14 @@ var ts;
result = reduceNode(node.initializer, cbNode, result);
break;
// Top-level nodes
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
result = reduceNodes(node.statements, cbNodes, result);
break;
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
result = reduceNodes(node.elements, cbNodes, result);
break;
default:
@@ -65440,7 +65859,7 @@ var ts;
}
exit();
}
- function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) {
+ function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
var _a;
ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
@@ -65450,6 +65869,14 @@ var ts;
var nameIndexToNewNameIndexMap;
var mappingIterator = decodeMappings(map.mappings);
for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) {
+ if (end && (raw.generatedLine > end.line ||
+ (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
+ break;
+ }
+ if (start && (raw.generatedLine < start.line ||
+ (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
+ continue;
+ }
// Then reencode all the updated mappings into the overall map
var newSourceIndex = void 0;
var newSourceLine = void 0;
@@ -65478,8 +65905,10 @@ var ts;
}
}
}
- var newGeneratedLine = raw.generatedLine + generatedLine;
- var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter;
+ var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
+ var newGeneratedLine = rawGeneratedLine + generatedLine;
+ var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
+ var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
}
exit();
@@ -65962,7 +66391,7 @@ var ts;
function chainBundle(transformSourceFile) {
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
+ return node.kind === 284 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
}
function transformBundle(node) {
return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
@@ -66623,7 +67052,7 @@ var ts;
function makeAssignmentElement(name) {
return name;
}
- var restHelper = {
+ ts.restHelper = {
name: "typescript:rest",
scoped: false,
text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };"
@@ -66632,7 +67061,7 @@ var ts;
* `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
*/
function createRestCall(context, value, elements, computedTempVariables, location) {
- context.requestEmitHelper(restHelper);
+ context.requestEmitHelper(ts.restHelper);
var propertyNames = [];
var computedTempVariableOffset = 0;
for (var i = 0; i < elements.length - 1; i++) {
@@ -66733,14 +67162,14 @@ var ts;
var pendingExpressions;
return transformSourceFileOrBundle;
function transformSourceFileOrBundle(node) {
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* Bundle */) {
return transformBundle(node);
}
return transformSourceFile(node);
}
function transformBundle(node) {
return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
- if (prepend.kind === 282 /* InputFiles */) {
+ if (prepend.kind === 287 /* InputFiles */) {
return ts.createUnparsedSourceFile(prepend, "js");
}
return prepend;
@@ -66789,7 +67218,7 @@ var ts;
*/
function onBeforeVisitNode(node) {
switch (node.kind) {
- case 279 /* SourceFile */:
+ case 284 /* SourceFile */:
case 246 /* CaseBlock */:
case 245 /* ModuleBlock */:
case 218 /* Block */:
@@ -69020,7 +69449,7 @@ var ts;
// enums in any other scope are emitted as a `let` declaration.
var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
- ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
+ ], currentLexicalScope.kind === 284 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
ts.setOriginalNode(statement, node);
recordEmittedDeclarationInScope(node);
if (isFirstEmittedDeclarationInScope(node)) {
@@ -69585,7 +70014,7 @@ var ts;
// If we are nested within a namespace declaration, we may need to qualifiy
// an identifier that is exported from a merged namespace.
var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
- if (container && container.kind !== 279 /* SourceFile */) {
+ if (container && container.kind !== 284 /* SourceFile */) {
var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) ||
(applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */);
if (substitute) {
@@ -69636,39 +70065,39 @@ var ts;
argumentsArray.push(descriptor);
}
}
- context.requestEmitHelper(decorateHelper);
+ context.requestEmitHelper(ts.decorateHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"),
/*typeArguments*/ undefined, argumentsArray), location);
}
- var decorateHelper = {
+ ts.decorateHelper = {
name: "typescript:decorate",
scoped: false,
priority: 2,
text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };"
};
function createMetadataHelper(context, metadataKey, metadataValue) {
- context.requestEmitHelper(metadataHelper);
+ context.requestEmitHelper(ts.metadataHelper);
return ts.createCall(ts.getHelperName("__metadata"),
/*typeArguments*/ undefined, [
ts.createLiteral(metadataKey),
metadataValue
]);
}
- var metadataHelper = {
+ ts.metadataHelper = {
name: "typescript:metadata",
scoped: false,
priority: 3,
text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };"
};
function createParamHelper(context, expression, parameterOffset, location) {
- context.requestEmitHelper(paramHelper);
+ context.requestEmitHelper(ts.paramHelper);
return ts.setTextRange(ts.createCall(ts.getHelperName("__param"),
/*typeArguments*/ undefined, [
ts.createLiteral(parameterOffset),
expression
]), location);
}
- var paramHelper = {
+ ts.paramHelper = {
name: "typescript:param",
scoped: false,
priority: 4,
@@ -70219,14 +70648,14 @@ var ts;
], 2 /* Const */));
}
ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
- var awaiterHelper = {
+ ts.awaiterHelper = {
name: "typescript:awaiter",
scoped: false,
priority: 5,
text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };"
};
function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) {
- context.requestEmitHelper(awaiterHelper);
+ context.requestEmitHelper(ts.awaiterHelper);
var generatorFunc = ts.createFunctionExpression(
/*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */),
/*name*/ undefined,
@@ -70858,7 +71287,7 @@ var ts;
}
}
ts.transformES2018 = transformES2018;
- var assignHelper = {
+ ts.assignHelper = {
name: "typescript:assign",
scoped: false,
priority: 1,
@@ -70869,28 +71298,28 @@ var ts;
return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"),
/*typeArguments*/ undefined, attributesSegments);
}
- context.requestEmitHelper(assignHelper);
+ context.requestEmitHelper(ts.assignHelper);
return ts.createCall(ts.getHelperName("__assign"),
/*typeArguments*/ undefined, attributesSegments);
}
ts.createAssignHelper = createAssignHelper;
- var awaitHelper = {
+ ts.awaitHelper = {
name: "typescript:await",
scoped: false,
text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
};
function createAwaitHelper(context, expression) {
- context.requestEmitHelper(awaitHelper);
+ context.requestEmitHelper(ts.awaitHelper);
return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]);
}
- var asyncGeneratorHelper = {
+ ts.asyncGeneratorHelper = {
name: "typescript:asyncGenerator",
scoped: false,
text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };"
};
function createAsyncGeneratorHelper(context, generatorFunc) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncGeneratorHelper);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncGeneratorHelper);
// Mark this node as originally an async function
(generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */;
return ts.createCall(ts.getHelperName("__asyncGenerator"),
@@ -70900,24 +71329,24 @@ var ts;
generatorFunc
]);
}
- var asyncDelegator = {
+ ts.asyncDelegator = {
name: "typescript:asyncDelegator",
scoped: false,
text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };"
};
function createAsyncDelegatorHelper(context, expression, location) {
- context.requestEmitHelper(awaitHelper);
- context.requestEmitHelper(asyncDelegator);
+ context.requestEmitHelper(ts.awaitHelper);
+ context.requestEmitHelper(ts.asyncDelegator);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"),
/*typeArguments*/ undefined, [expression]), location);
}
- var asyncValues = {
+ ts.asyncValues = {
name: "typescript:asyncValues",
scoped: false,
text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };"
};
function createAsyncValuesHelper(context, expression, location) {
- context.requestEmitHelper(asyncValues);
+ context.requestEmitHelper(ts.asyncValues);
return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"),
/*typeArguments*/ undefined, [expression]), location);
}
@@ -74729,7 +75158,7 @@ var ts;
}
ts.transformES2015 = transformES2015;
function createExtendsHelper(context, name) {
- context.requestEmitHelper(extendsHelper);
+ context.requestEmitHelper(ts.extendsHelper);
return ts.createCall(ts.getHelperName("__extends"),
/*typeArguments*/ undefined, [
name,
@@ -74737,20 +75166,20 @@ var ts;
]);
}
function createTemplateObjectHelper(context, cooked, raw) {
- context.requestEmitHelper(templateObjectHelper);
+ context.requestEmitHelper(ts.templateObjectHelper);
return ts.createCall(ts.getHelperName("__makeTemplateObject"),
/*typeArguments*/ undefined, [
cooked,
raw
]);
}
- var extendsHelper = {
+ ts.extendsHelper = {
name: "typescript:extends",
scoped: false,
priority: 0,
text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();"
};
- var templateObjectHelper = {
+ ts.templateObjectHelper = {
name: "typescript:makeTemplateObject",
scoped: false,
priority: 0,
@@ -77444,7 +77873,7 @@ var ts;
}
ts.transformGenerators = transformGenerators;
function createGeneratorHelper(context, body) {
- context.requestEmitHelper(generatorHelper);
+ context.requestEmitHelper(ts.generatorHelper);
return ts.createCall(ts.getHelperName("__generator"),
/*typeArguments*/ undefined, [ts.createThis(), body]);
}
@@ -77507,7 +77936,7 @@ var ts;
// entering a finally block.
//
// For examples of how these are used, see the comments in ./transformers/generators.ts
- var generatorHelper = {
+ ts.generatorHelper = {
name: "typescript:generator",
scoped: false,
priority: 6,
@@ -77540,7 +77969,7 @@ var ts;
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* SourceFile */); // Restore state when substituting nodes in a file.
var moduleInfoMap = []; // The ExternalModuleInfo for each file.
var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
var currentSourceFile; // The current file.
@@ -77882,9 +78311,9 @@ var ts;
return visitFunctionDeclaration(node);
case 240 /* ClassDeclaration */:
return visitClassDeclaration(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
@@ -78042,7 +78471,7 @@ var ts;
}
var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]);
}
return promise;
@@ -78056,7 +78485,7 @@ var ts;
var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
if (compilerOptions.esModuleInterop) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
}
var func;
@@ -78090,11 +78519,11 @@ var ts;
return innerExpr;
}
if (ts.getImportNeedsImportStarHelper(node)) {
- context.requestEmitHelper(importStarHelper);
+ context.requestEmitHelper(ts.importStarHelper);
return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
}
if (ts.getImportNeedsImportDefaultHelper(node)) {
- context.requestEmitHelper(importDefaultHelper);
+ context.requestEmitHelper(ts.importDefaultHelper);
return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
}
return innerExpr;
@@ -78663,7 +79092,7 @@ var ts;
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
currentSourceFile = node;
currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
noSubstitution = [];
@@ -78751,7 +79180,7 @@ var ts;
}
if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)),
/*location*/ node);
}
@@ -78877,13 +79306,13 @@ var ts;
text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
};
// emit helper for `import * as Name from "foo"`
- var importStarHelper = {
+ ts.importStarHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};"
};
// emit helper for `import Name from "foo"`
- var importDefaultHelper = {
+ ts.importDefaultHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
@@ -78906,7 +79335,7 @@ var ts;
context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols.
context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
- context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file.
+ context.enableEmitNotification(284 /* SourceFile */); // Restore state when substituting nodes in a file.
var moduleInfoMap = []; // The ExternalModuleInfo for each file.
var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
var exportFunctionsMap = []; // The export function associated with a source file.
@@ -79476,7 +79905,7 @@ var ts;
function shouldHoistVariableDeclarationList(node) {
// hoist only non-block scoped declarations or block scoped declarations parented by source file
return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
- && (enclosingBlockScopedContainer.kind === 279 /* SourceFile */
+ && (enclosingBlockScopedContainer.kind === 284 /* SourceFile */
|| (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
}
/**
@@ -79819,9 +80248,9 @@ var ts;
return visitCatchClause(node);
case 218 /* Block */:
return visitBlock(node);
- case 310 /* MergeDeclarationMarker */:
+ case 315 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 311 /* EndOfDeclarationMarker */:
+ case 316 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return destructuringAndImportCallVisitor(node);
@@ -80069,7 +80498,7 @@ var ts;
}
else if (ts.isIdentifier(node)) {
var container = resolver.getReferencedExportContainer(node);
- return container !== undefined && container.kind === 279 /* SourceFile */;
+ return container !== undefined && container.kind === 284 /* SourceFile */;
}
else {
return false;
@@ -80102,7 +80531,7 @@ var ts;
* @param emitCallback A callback used to emit the node in the printer.
*/
function onEmitNode(hint, node, emitCallback) {
- if (node.kind === 279 /* SourceFile */) {
+ if (node.kind === 284 /* SourceFile */) {
var id = ts.getOriginalNodeId(node);
currentSourceFile = node;
moduleInfo = moduleInfoMap[id];
@@ -80311,7 +80740,7 @@ var ts;
|| resolver.getReferencedValueDeclaration(name);
if (valueDeclaration) {
var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
- if (exportContainer && exportContainer.kind === 279 /* SourceFile */) {
+ if (exportContainer && exportContainer.kind === 284 /* SourceFile */) {
exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
}
exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
@@ -80350,7 +80779,7 @@ var ts;
var previousOnSubstituteNode = context.onSubstituteNode;
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
- context.enableEmitNotification(279 /* SourceFile */);
+ context.enableEmitNotification(284 /* SourceFile */);
context.enableSubstitution(72 /* Identifier */);
var currentSourceFile;
return ts.chainBundle(transformSourceFile);
@@ -80780,6 +81209,9 @@ var ts;
case 241 /* InterfaceDeclaration */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
break;
+ case 181 /* MappedType */:
+ diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
+ break;
case 166 /* ConstructorType */:
case 161 /* ConstructSignature */:
diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
@@ -80863,6 +81295,15 @@ var ts;
return result.diagnostics;
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
+ function isInternalDeclaration(node, currentSourceFile) {
+ var parseTreeNode = ts.getParseTreeNode(node);
+ var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
+ return !!ts.forEach(leadingCommentRanges, function (range) {
+ var comment = currentSourceFile.text.substring(range.pos, range.end);
+ return ts.stringContains(comment, "@internal");
+ });
+ }
+ ts.isInternalDeclaration = isInternalDeclaration;
var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
2048 /* WriteClassExpressionAsTypeLiteral */ |
4096 /* UseTypeOfFunction */ |
@@ -80991,10 +81432,10 @@ var ts;
}
}
function transformRoot(node) {
- if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
+ if (node.kind === 284 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) {
return node;
}
- if (node.kind === 280 /* Bundle */) {
+ if (node.kind === 285 /* Bundle */) {
isBundledEmit = true;
refs = ts.createMap();
libs = ts.createMap();
@@ -81024,9 +81465,15 @@ var ts;
var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
}), ts.mapDefined(node.prepends, function (prepend) {
- if (prepend.kind === 282 /* InputFiles */) {
- return ts.createUnparsedSourceFile(prepend, "dts");
- }
+ if (prepend.kind === 287 /* InputFiles */) {
+ var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
+ hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
+ collectReferences(sourceFile, refs);
+ recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
+ collectLibs(sourceFile, libs);
+ return sourceFile;
+ }
+ return prepend;
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
@@ -81118,7 +81565,7 @@ var ts;
}
}
function collectReferences(sourceFile, ret) {
- if (noResolve || ts.isSourceFileJS(sourceFile))
+ if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
return ret;
ts.forEach(sourceFile.referencedFiles, function (f) {
var elem = ts.tryResolveScriptReference(host, sourceFile, f);
@@ -81846,18 +82293,8 @@ var ts;
}
errorNameNode = undefined;
}
- function hasInternalAnnotation(range) {
- var comment = currentSourceFile.text.substring(range.pos, range.end);
- return ts.stringContains(comment, "@internal");
- }
function shouldStripInternal(node) {
- if (stripInternal && node) {
- var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile);
- if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) {
- return true;
- }
- }
- return false;
+ return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
}
function isScopeMarker(node) {
return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
@@ -81879,7 +82316,7 @@ var ts;
function ensureModifierFlags(node, privateDeclaration) {
var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
- var parentIsFile = node.parent.kind === 279 /* SourceFile */;
+ var parentIsFile = node.parent.kind === 284 /* SourceFile */;
if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */);
additions = 0 /* None */;
@@ -82096,7 +82533,7 @@ var ts;
* @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
*/
function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
- var enabledSyntaxKindFeatures = new Array(312 /* Count */);
+ var enabledSyntaxKindFeatures = new Array(317 /* Count */);
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
@@ -82356,10 +82793,14 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- var infoExtension = ".tsbundleinfo";
var brackets = createBracketsMap();
var syntheticParent = { pos: -1, end: -1 };
/*@internal*/
+ function isBuildInfoFile(file) {
+ return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
+ }
+ ts.isBuildInfoFile = isBuildInfoFile;
+ /*@internal*/
/**
* Iterates over the source files that are expected to have an emit output.
*
@@ -82369,13 +82810,14 @@ var ts;
* If an array, the full list of source files to emit.
* Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
*/
- function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) {
+ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles, onlyBuildInfo, includeBuildInfo) {
if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; }
var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
- if (sourceFiles.length) {
- var bundle = ts.createBundle(sourceFiles, host.getPrependNodes());
+ var prepends = host.getPrependNodes();
+ if (sourceFiles.length || prepends.length) {
+ var bundle = ts.createBundle(sourceFiles, prepends);
var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
if (result) {
return result;
@@ -82383,31 +82825,61 @@ var ts;
}
}
else {
- for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
- var sourceFile = sourceFiles_1[_a];
- var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
- if (result) {
- return result;
+ if (!onlyBuildInfo) {
+ for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
+ var sourceFile = sourceFiles_1[_a];
+ var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
+ if (result) {
+ return result;
+ }
}
}
+ if (includeBuildInfo) {
+ var buildInfoPath = getOutputPathForBuildInfo(host.getCompilerOptions());
+ if (buildInfoPath)
+ return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
+ }
}
}
ts.forEachEmittedFile = forEachEmittedFile;
/*@internal*/
+ function getOutputPathForBuildInfo(options) {
+ var configFile = options.configFilePath;
+ if (!configFile || !ts.isIncrementalCompilation(options))
+ return undefined;
+ if (options.tsBuildInfoFile)
+ return options.tsBuildInfoFile;
+ var outPath = options.outFile || options.out;
+ var buildInfoExtensionLess;
+ if (outPath) {
+ buildInfoExtensionLess = ts.removeFileExtension(outPath);
+ }
+ else {
+ var configFileExtensionLess = ts.removeFileExtension(configFile);
+ buildInfoExtensionLess = options.outDir ?
+ options.rootDir ?
+ ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
+ ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
+ configFileExtensionLess;
+ }
+ return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
+ }
+ ts.getOutputPathForBuildInfo = getOutputPathForBuildInfo;
+ /*@internal*/
function getOutputPathsForBundle(options, forceDtsPaths) {
var outPath = options.outFile || options.out;
var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath };
+ var buildInfoPath = getOutputPathForBuildInfo(options);
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
}
ts.getOutputPathsForBundle = getOutputPathsForBundle;
/*@internal*/
function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
var options = host.getCompilerOptions();
- if (sourceFile.kind === 280 /* Bundle */) {
+ if (sourceFile.kind === 285 /* Bundle */) {
return getOutputPathsForBundle(options, forceDtsPaths);
}
else {
@@ -82421,19 +82893,13 @@ var ts;
var isJs = ts.isSourceFileJS(sourceFile);
var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined };
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
}
}
ts.getOutputPathsFor = getOutputPathsFor;
function getSourceMapFilePath(jsFilePath, options) {
return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
}
- function createDefaultBundleInfo() {
- return {
- originalOffset: -1,
- totalLength: -1
- };
- }
// JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
// So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
// For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
@@ -82458,7 +82924,7 @@ var ts;
ts.getOutputExtension = getOutputExtension;
/*@internal*/
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
- function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) {
+ function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers, onlyBuildInfo) {
var compilerOptions = host.getCompilerOptions();
var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
@@ -82466,12 +82932,12 @@ var ts;
var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
var writer = ts.createTextWriter(newLine);
var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit;
- var bundleInfo = createDefaultBundleInfo();
+ var bundleBuildInfo;
var emitSkipped = false;
var exportedModulesFromDeclarationEmit;
// Emit each output file
enter();
- forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles);
+ forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles, onlyBuildInfo, !targetSourceFile);
exit();
return {
emitSkipped: emitSkipped,
@@ -82481,9 +82947,16 @@ var ts;
exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
};
function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
- var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath;
- emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
+ var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
+ bundleBuildInfo = {
+ commonSourceDirectory: host.getCommonSourceDirectory(),
+ sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return file.fileName; })
+ };
+ }
+ emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
+ emitBuildInfo(bundleBuildInfo, buildInfoPath);
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
if (jsFilePath) {
@@ -82492,8 +82965,8 @@ var ts;
if (sourceMapFilePath) {
emittedFilesList.push(sourceMapFilePath);
}
- if (bundleInfoPath) {
- emittedFilesList.push(bundleInfoPath);
+ if (buildInfoPath) {
+ emittedFilesList.push(buildInfoPath);
}
}
if (declarationFilePath) {
@@ -82504,8 +82977,21 @@ var ts;
}
}
}
- function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) {
- if (emitOnlyDtsFiles || !jsFilePath) {
+ function emitBuildInfo(bundle, buildInfoPath) {
+ // Write build information if applicable
+ if (!buildInfoPath || targetSourceFile || emitSkipped)
+ return;
+ var program = host.getProgramBuildInfo();
+ if (!bundle && !program)
+ return;
+ if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
+ emitSkipped = true;
+ return;
+ }
+ ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: ts.version }), /*writeByteOrderMark*/ false);
+ }
+ function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) {
+ if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
return;
}
// Make sure not to write js file and source map file if any of them cannot be written
@@ -82525,6 +83011,7 @@ var ts;
inlineSourceMap: compilerOptions.inlineSourceMap,
inlineSources: compilerOptions.inlineSources,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
+ writeBundleFileInfo: !!bundleBuildInfo
};
// Create a printer to print the nodes
var printer = createPrinter(printerOptions, {
@@ -82535,12 +83022,14 @@ var ts;
substituteNode: transform.substituteNode,
});
ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
- printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions);
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
// Clean up emit nodes on parse tree
transform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.js = printer.bundleFileInfo;
}
function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) {
- if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
+ if (!sourceFileOrBundle || !(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) {
return;
}
var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
@@ -82569,6 +83058,8 @@ var ts;
inlineSourceMap: compilerOptions.inlineSourceMap,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
onlyPrintJsDocStyle: true,
+ writeBundleFileInfo: !!bundleBuildInfo,
+ recordInternalSection: !!bundleBuildInfo
};
var declarationPrinter = createPrinter(printerOptions, {
// resolver hooks
@@ -82581,18 +83072,20 @@ var ts;
emitSkipped = emitSkipped || declBlocked;
if (!declBlocked || emitOnlyDtsFiles) {
ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
- printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, {
+ printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
sourceMap: compilerOptions.declarationMap,
sourceRoot: compilerOptions.sourceRoot,
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
});
- if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) {
+ if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 284 /* SourceFile */) {
var sourceFile = declarationTransform.transformed[0];
exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
}
}
declarationTransform.dispose();
+ if (bundleBuildInfo)
+ bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
}
function collectLinkedAliases(node) {
if (ts.isExportAssignment(node)) {
@@ -82607,16 +83100,16 @@ var ts;
}
ts.forEachChild(node, collectLinkedAliases);
}
- function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) {
- var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined;
- var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined;
+ function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
+ var bundle = sourceFileOrBundle.kind === 285 /* Bundle */ ? sourceFileOrBundle : undefined;
+ var sourceFile = sourceFileOrBundle.kind === 284 /* SourceFile */ ? sourceFileOrBundle : undefined;
var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
var sourceMapGenerator;
if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
}
if (bundle) {
- printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator);
+ printer.writeBundle(bundle, writer, sourceMapGenerator);
}
else {
printer.writeFile(sourceFile, writer, sourceMapGenerator);
@@ -82645,18 +83138,12 @@ var ts;
}
// Write the output file
ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
- // Write bundled offset information if applicable
- if (bundleInfoPath) {
- bundleInfo.totalLength = writer.getTextPos();
- ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false);
- }
// Reset state
writer.clear();
- bundleInfo = createDefaultBundleInfo();
}
function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
- && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
+ && (sourceFileOrBundle.kind !== 284 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
}
function getSourceRoot(mapOptions) {
// Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
@@ -82713,6 +83200,166 @@ var ts;
}
}
ts.emitFiles = emitFiles;
+ /*@internal*/
+ function getBuildInfoText(buildInfo) {
+ return JSON.stringify(buildInfo, undefined, 2);
+ }
+ ts.getBuildInfoText = getBuildInfoText;
+ /*@internal*/
+ function getBuildInfo(buildInfoText) {
+ return JSON.parse(buildInfoText);
+ }
+ ts.getBuildInfo = getBuildInfo;
+ /*@internal*/
+ ts.notImplementedResolver = {
+ hasGlobalName: ts.notImplemented,
+ getReferencedExportContainer: ts.notImplemented,
+ getReferencedImportDeclaration: ts.notImplemented,
+ getReferencedDeclarationWithCollidingName: ts.notImplemented,
+ isDeclarationWithCollidingName: ts.notImplemented,
+ isValueAliasDeclaration: ts.notImplemented,
+ isReferencedAliasDeclaration: ts.notImplemented,
+ isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
+ getNodeCheckFlags: ts.notImplemented,
+ isDeclarationVisible: ts.notImplemented,
+ isLateBound: function (_node) { return false; },
+ collectLinkedAliases: ts.notImplemented,
+ isImplementationOfOverload: ts.notImplemented,
+ isRequiredInitializedParameter: ts.notImplemented,
+ isOptionalUninitializedParameterProperty: ts.notImplemented,
+ isExpandoFunctionDeclaration: ts.notImplemented,
+ getPropertiesOfContainerFunction: ts.notImplemented,
+ createTypeOfDeclaration: ts.notImplemented,
+ createReturnTypeOfSignatureDeclaration: ts.notImplemented,
+ createTypeOfExpression: ts.notImplemented,
+ createLiteralConstValue: ts.notImplemented,
+ isSymbolAccessible: ts.notImplemented,
+ isEntityNameVisible: ts.notImplemented,
+ // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
+ getConstantValue: ts.notImplemented,
+ getReferencedValueDeclaration: ts.notImplemented,
+ getTypeReferenceSerializationKind: ts.notImplemented,
+ isOptionalParameter: ts.notImplemented,
+ moduleExportsSomeValue: ts.notImplemented,
+ isArgumentsLocalBinding: ts.notImplemented,
+ getExternalModuleFileFromDeclaration: ts.notImplemented,
+ getTypeReferenceDirectivesForEntityName: ts.notImplemented,
+ getTypeReferenceDirectivesForSymbol: ts.notImplemented,
+ isLiteralConstDeclaration: ts.notImplemented,
+ getJsxFactoryEntity: ts.notImplemented,
+ getAllAccessorDeclarations: ts.notImplemented,
+ getSymbolOfExternalModuleSpecifier: ts.notImplemented,
+ isBindingCapturedByNode: ts.notImplemented,
+ };
+ function createSourceFilesFromBundleBuildInfo(bundle) {
+ var sourceFiles = bundle.sourceFiles.map(function (fileName) {
+ var sourceFile = ts.createNode(284 /* SourceFile */, 0, 0);
+ sourceFile.fileName = fileName;
+ sourceFile.text = "";
+ sourceFile.statements = ts.createNodeArray();
+ return sourceFile;
+ });
+ var jsBundle = ts.Debug.assertDefined(bundle.js);
+ ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
+ var sourceFile = sourceFiles[prologueInfo.file];
+ sourceFile.text = prologueInfo.text;
+ sourceFile.end = prologueInfo.text.length;
+ sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
+ var statement = ts.createNode(221 /* ExpressionStatement */, directive.pos, directive.end);
+ statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
+ statement.expression.text = directive.expression.text;
+ return statement;
+ }));
+ });
+ return sourceFiles;
+ }
+ /*@internal*/
+ function emitUsingBuildInfo(config, host, getCommandLine) {
+ var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
+ var buildInfoText = host.readFile(ts.Debug.assertDefined(buildInfoPath));
+ if (!buildInfoText)
+ return buildInfoPath;
+ var jsFileText = host.readFile(ts.Debug.assertDefined(jsFilePath));
+ if (!jsFileText)
+ return jsFilePath;
+ var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
+ // error if no source map or for now if inline sourcemap
+ if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
+ return sourceMapFilePath || "inline sourcemap decoding";
+ // read declaration text
+ var declarationText = declarationFilePath && host.readFile(declarationFilePath);
+ if (declarationFilePath && !declarationText)
+ return declarationFilePath;
+ var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
+ // error if no source map or for now if inline sourcemap
+ if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
+ return declarationMapPath || "inline sourcemap decoding";
+ var buildInfo = getBuildInfo(buildInfoText);
+ if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
+ return buildInfoPath;
+ var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo,
+ /*onlyOwnText*/ true);
+ var outputFiles = [];
+ var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
+ var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle);
+ var emitHost = {
+ getPrependNodes: ts.memoize(function () { return prependNodes.concat([ownPrependInput]); }),
+ getCanonicalFileName: host.getCanonicalFileName,
+ getCommonSourceDirectory: function () { return buildInfo.bundle.commonSourceDirectory; },
+ getCompilerOptions: function () { return config.options; },
+ getCurrentDirectory: function () { return host.getCurrentDirectory(); },
+ getNewLine: function () { return host.getNewLine(); },
+ getSourceFile: function () { return undefined; },
+ getSourceFileByPath: function () { return undefined; },
+ getSourceFiles: function () { return sourceFilesForJsEmit; },
+ getLibFileFromReference: ts.notImplemented,
+ isSourceFileFromExternalLibrary: ts.returnFalse,
+ writeFile: function (name, text, writeByteOrderMark) {
+ switch (name) {
+ case jsFilePath:
+ if (jsFileText === text)
+ return;
+ break;
+ case sourceMapFilePath:
+ if (sourceMapText === text)
+ return;
+ break;
+ case buildInfoPath:
+ var newBuildInfo = getBuildInfo(text);
+ newBuildInfo.program = buildInfo.program;
+ // Update sourceFileInfo
+ var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
+ newBuildInfo.bundle.js.sources = js.sources;
+ if (dts) {
+ newBuildInfo.bundle.dts.sources = dts.sources;
+ }
+ newBuildInfo.bundle.sourceFiles = sourceFiles;
+ outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
+ return;
+ case declarationFilePath:
+ if (declarationText === text)
+ return;
+ break;
+ case declarationMapPath:
+ if (declarationMapText === text)
+ return;
+ break;
+ default:
+ ts.Debug.fail("Unexpected path: " + name);
+ }
+ outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
+ },
+ isEmitBlocked: ts.returnFalse,
+ readFile: function (f) { return host.readFile(f); },
+ fileExists: function (f) { return host.fileExists(f); },
+ directoryExists: host.directoryExists && (function (f) { return host.directoryExists(f); }),
+ useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
+ getProgramBuildInfo: function () { return undefined; }
+ };
+ emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, /*emitOnlyDtsFiles*/ false, ts.getTransformers(config.options));
+ return outputFiles;
+ }
+ ts.emitUsingBuildInfo = emitUsingBuildInfo;
var PipelinePhase;
(function (PipelinePhase) {
PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
@@ -82741,6 +83388,10 @@ var ts;
var ownWriter; // Reusable `EmitTextWriter` for basic printing.
var write = writeBase;
var isOwnFileEmit;
+ var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
+ var recordInternalSection = printerOptions.recordInternalSection;
+ var sourceFileTextPos = 0;
+ var sourceFileTextKind = "text" /* Text */;
// Source Maps
var sourceMapsDisabled = true;
var sourceMapGenerator;
@@ -82766,7 +83417,8 @@ var ts;
writeNode: writeNode,
writeList: writeList,
writeFile: writeFile,
- writeBundle: writeBundle
+ writeBundle: writeBundle,
+ bundleFileInfo: bundleFileInfo
};
function printNode(hint, node, sourceFile) {
switch (hint) {
@@ -82781,9 +83433,9 @@ var ts;
break;
}
switch (node.kind) {
- case 279 /* SourceFile */: return printFile(node);
- case 280 /* Bundle */: return printBundle(node);
- case 281 /* UnparsedSource */: return printUnparsedSource(node);
+ case 284 /* SourceFile */: return printFile(node);
+ case 285 /* Bundle */: return printBundle(node);
+ case 286 /* UnparsedSource */: return printUnparsedSource(node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
@@ -82793,7 +83445,7 @@ var ts;
return endPrint();
}
function printBundle(bundle) {
- writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined);
+ writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
return endPrint();
}
function printFile(sourceFile) {
@@ -82821,7 +83473,49 @@ var ts;
reset();
writer = previousWriter;
}
- function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) {
+ function getTextPosWithWriteLine() {
+ return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
+ }
+ function updateOrPushBundleFileTextLike(pos, end, kind) {
+ var last = ts.lastOrUndefined(bundleFileInfo.sections);
+ if (last && last.kind === kind) {
+ last.end = end;
+ }
+ else {
+ bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
+ }
+ }
+ function recordBundleFileInternalSectionStart(node) {
+ if (recordInternalSection &&
+ bundleFileInfo &&
+ currentSourceFile &&
+ (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
+ ts.isInternalDeclaration(node, currentSourceFile) &&
+ sourceFileTextKind !== "internal" /* Internal */) {
+ var prevSourceFileTextKind = sourceFileTextKind;
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = "internal" /* Internal */;
+ return prevSourceFileTextKind;
+ }
+ return undefined;
+ }
+ function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
+ if (prevSourceFileTextKind) {
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = prevSourceFileTextKind;
+ }
+ }
+ function recordBundleFileTextLikeSection(end) {
+ if (sourceFileTextPos < end) {
+ updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
+ return true;
+ }
+ return false;
+ }
+ function writeBundle(bundle, output, sourceMapGenerator) {
+ var _a;
isOwnFileEmit = false;
var previousWriter = writer;
setWriter(output, sourceMapGenerator);
@@ -82829,18 +83523,49 @@ var ts;
emitPrologueDirectivesIfNeeded(bundle);
emitHelpers(bundle);
emitSyntheticTripleSlashReferencesIfNeeded(bundle);
- for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) {
- var prepend = _b[_a];
+ for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
+ var prepend = _c[_b];
writeLine();
+ var pos = writer.getTextPos();
+ var savedSections = bundleFileInfo && bundleFileInfo.sections;
+ if (savedSections)
+ bundleFileInfo.sections = [];
print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
+ if (bundleFileInfo) {
+ var newSections = bundleFileInfo.sections;
+ bundleFileInfo.sections = savedSections;
+ if (prepend.oldFileOfCurrentEmit)
+ (_a = bundleFileInfo.sections).push.apply(_a, newSections);
+ else {
+ newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prepend" /* Prepend */, data: prepend.fileName, texts: newSections });
+ }
+ }
}
- if (bundleInfo) {
- bundleInfo.originalOffset = writer.getTextPos();
- }
- for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) {
- var sourceFile = _d[_c];
+ sourceFileTextPos = getTextPosWithWriteLine();
+ for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
+ var sourceFile = _e[_d];
print(0 /* SourceFile */, sourceFile, sourceFile);
}
+ if (bundleFileInfo && bundle.sourceFiles.length) {
+ var end = writer.getTextPos();
+ if (recordBundleFileTextLikeSection(end)) {
+ // Store prologues
+ var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
+ if (prologues) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.prologues = prologues;
+ }
+ // Store helpes
+ var helpers = getHelpersFromBundledSourceFiles(bundle);
+ if (helpers) {
+ if (!bundleFileInfo.sources)
+ bundleFileInfo.sources = {};
+ bundleFileInfo.sources.helpers = helpers;
+ }
+ }
+ }
reset();
writer = previousWriter;
}
@@ -82910,8 +83635,10 @@ var ts;
function emit(node) {
if (node === undefined)
return;
+ var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
var pipelinePhase = getPipelinePhase(0 /* Notification */, node);
pipelinePhase(4 /* Unspecified */, node);
+ recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
}
function emitIdentifierName(node) {
if (node === undefined)
@@ -82938,12 +83665,12 @@ var ts;
}
// falls through
case 2 /* Comments */:
- if (!commentsDisabled && node.kind !== 279 /* SourceFile */) {
+ if (!commentsDisabled && node.kind !== 284 /* SourceFile */) {
return pipelineEmitWithComments;
}
// falls through
case 3 /* SourceMaps */:
- if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) {
+ if (!sourceMapsDisabled && node.kind !== 284 /* SourceFile */ && !ts.isInJsonFile(node)) {
return pipelineEmitWithSourceMap;
}
// falls through
@@ -82980,8 +83707,16 @@ var ts;
case 16 /* TemplateMiddle */:
case 17 /* TemplateTail */:
return emitLiteral(node);
- case 281 /* UnparsedSource */:
- return emitUnparsedSource(node);
+ case 286 /* UnparsedSource */:
+ case 280 /* UnparsedPrepend */:
+ return emitUnparsedSourceOrPrepend(node);
+ case 279 /* UnparsedPrologue */:
+ return writeUnparsedNode(node);
+ case 281 /* UnparsedText */:
+ case 282 /* UnparsedInternalText */:
+ return emitUnparsedTextLike(node);
+ case 283 /* UnparsedSyntheticReference */:
+ return emitUnparsedSyntheticReference(node);
// Identifiers
case 72 /* Identifier */:
return emitIdentifier(node);
@@ -83025,7 +83760,7 @@ var ts;
return emitTypeReference(node);
case 165 /* FunctionType */:
return emitFunctionType(node);
- case 289 /* JSDocFunctionType */:
+ case 294 /* JSDocFunctionType */:
return emitJSDocFunctionType(node);
case 166 /* ConstructorType */:
return emitConstructorType(node);
@@ -83063,20 +83798,20 @@ var ts;
return emitLiteralType(node);
case 183 /* ImportType */:
return emitImportTypeNode(node);
- case 284 /* JSDocAllType */:
+ case 289 /* JSDocAllType */:
writePunctuation("*");
return;
- case 285 /* JSDocUnknownType */:
+ case 290 /* JSDocUnknownType */:
writePunctuation("?");
return;
- case 286 /* JSDocNullableType */:
+ case 291 /* JSDocNullableType */:
return emitJSDocNullableType(node);
- case 287 /* JSDocNonNullableType */:
+ case 292 /* JSDocNonNullableType */:
return emitJSDocNonNullableType(node);
- case 288 /* JSDocOptionalType */:
+ case 293 /* JSDocOptionalType */:
return emitJSDocOptionalType(node);
case 172 /* RestType */:
- case 290 /* JSDocVariadicType */:
+ case 295 /* JSDocVariadicType */:
return emitRestOrJSDocVariadicType(node);
// Binding patterns
case 184 /* ObjectBindingPattern */:
@@ -83214,30 +83949,30 @@ var ts;
case 278 /* EnumMember */:
return emitEnumMember(node);
// JSDoc nodes (only used in codefixes currently)
- case 299 /* JSDocParameterTag */:
- case 305 /* JSDocPropertyTag */:
+ case 304 /* JSDocParameterTag */:
+ case 310 /* JSDocPropertyTag */:
return emitJSDocPropertyLikeTag(node);
- case 300 /* JSDocReturnTag */:
- case 302 /* JSDocTypeTag */:
- case 301 /* JSDocThisTag */:
- case 298 /* JSDocEnumTag */:
+ case 305 /* JSDocReturnTag */:
+ case 307 /* JSDocTypeTag */:
+ case 306 /* JSDocThisTag */:
+ case 303 /* JSDocEnumTag */:
return emitJSDocSimpleTypedTag(node);
- case 295 /* JSDocAugmentsTag */:
+ case 300 /* JSDocAugmentsTag */:
return emitJSDocAugmentsTag(node);
- case 303 /* JSDocTemplateTag */:
+ case 308 /* JSDocTemplateTag */:
return emitJSDocTemplateTag(node);
- case 304 /* JSDocTypedefTag */:
+ case 309 /* JSDocTypedefTag */:
return emitJSDocTypedefTag(node);
- case 297 /* JSDocCallbackTag */:
+ case 302 /* JSDocCallbackTag */:
return emitJSDocCallbackTag(node);
- case 293 /* JSDocSignature */:
+ case 298 /* JSDocSignature */:
return emitJSDocSignature(node);
- case 292 /* JSDocTypeLiteral */:
+ case 297 /* JSDocTypeLiteral */:
return emitJSDocTypeLiteral(node);
- case 296 /* JSDocClassTag */:
- case 294 /* JSDocTag */:
+ case 301 /* JSDocClassTag */:
+ case 299 /* JSDocTag */:
return emitJSDocSimpleTag(node);
- case 291 /* JSDocComment */:
+ case 296 /* JSDocComment */:
return emitJSDoc(node);
// Transformation nodes (ignored)
}
@@ -83336,9 +84071,9 @@ var ts;
case 264 /* JsxFragment */:
return emitJsxFragment(node);
// Transformation nodes
- case 308 /* PartiallyEmittedExpression */:
+ case 313 /* PartiallyEmittedExpression */:
return emitPartiallyEmittedExpression(node);
- case 309 /* CommaListExpression */:
+ case 314 /* CommaListExpression */:
return emitCommaList(node);
}
}
@@ -83354,22 +84089,45 @@ var ts;
var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node);
pipelinePhase(hint, substituteNode(hint, node));
}
+ function getHelpersFromBundledSourceFiles(bundle) {
+ var result;
+ if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
+ return undefined;
+ }
+ var bundledHelpers = ts.createMap();
+ for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
+ var sourceFile = _b[_a];
+ var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
+ var helpers = getSortedEmitHelpers(sourceFile);
+ if (!helpers)
+ continue;
+ for (var _c = 0, helpers_3 = helpers; _c < helpers_3.length; _c++) {
+ var helper = helpers_3[_c];
+ if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
+ bundledHelpers.set(helper.name, true);
+ (result || (result = [])).push(helper.name);
+ }
+ }
+ }
+ return result;
+ }
function emitHelpers(node) {
var helpersEmitted = false;
- var bundle = node.kind === 280 /* Bundle */ ? node : undefined;
+ var bundle = node.kind === 285 /* Bundle */ ? node : undefined;
if (bundle && moduleKind === ts.ModuleKind.None) {
return;
}
- var numNodes = bundle ? bundle.sourceFiles.length : 1;
+ var numPrepends = bundle ? bundle.prepends.length : 0;
+ var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
for (var i = 0; i < numNodes; i++) {
- var currentNode = bundle ? bundle.sourceFiles[i] : node;
- var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile;
- var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined;
- var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit;
- var helpers = ts.getEmitHelpers(currentNode);
+ var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
+ var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
+ var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined);
+ var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
+ var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
if (helpers) {
- for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) {
- var helper = _b[_a];
+ for (var _a = 0, helpers_4 = helpers; _a < helpers_4.length; _a++) {
+ var helper = helpers_4[_a];
if (!helper.scoped) {
// Skip the helper if it can be skipped and the noEmitHelpers compiler
// option is set, or if it can be imported and the importHelpers compiler
@@ -83389,18 +84147,25 @@ var ts;
// Skip the helper if it is scoped and we are emitting bundled helpers
continue;
}
+ var pos = getTextPosWithWriteLine();
if (typeof helper.text === "string") {
writeLines(helper.text);
}
else {
writeLines(helper.text(makeFileLevelOptimisticUniqueName));
}
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
helpersEmitted = true;
}
}
}
return helpersEmitted;
}
+ function getSortedEmitHelpers(node) {
+ var helpers = ts.getEmitHelpers(node);
+ return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
+ }
//
// Literals/Pseudo-literals
//
@@ -83427,8 +84192,42 @@ var ts;
}
}
// SyntaxKind.UnparsedSource
- function emitUnparsedSource(unparsed) {
- writer.rawWrite(unparsed.text);
+ // SyntaxKind.UnparsedPrepend
+ function emitUnparsedSourceOrPrepend(unparsed) {
+ for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
+ var text = _b[_a];
+ writeLine();
+ emit(text);
+ }
+ }
+ // SyntaxKind.UnparsedPrologue
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ // SyntaxKind.UnparsedSyntheticReference
+ function writeUnparsedNode(unparsed) {
+ writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
+ }
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ function emitUnparsedTextLike(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 281 /* UnparsedText */ ?
+ "text" /* Text */ :
+ "internal" /* Internal */);
+ }
+ }
+ // SyntaxKind.UnparsedSyntheticReference
+ function emitUnparsedSyntheticReference(unparsed) {
+ var pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ var section = ts.clone(unparsed.section);
+ section.pos = pos;
+ section.end = writer.getTextPos();
+ bundleFileInfo.sections.push(section);
+ }
}
//
// Identifiers
@@ -83483,7 +84282,7 @@ var ts;
emit(node.dotDotDotToken);
emitNodeWithWriter(node.name, writeParameter);
emit(node.questionToken);
- if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) {
+ if (node.parent && node.parent.kind === 294 /* JSDocFunctionType */ && !node.name) {
emit(node.type);
}
else {
@@ -84363,7 +85162,7 @@ var ts;
}
function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
// Emit all the prologue directives (like "use strict").
- var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true);
+ var statementOffset = emitPrologueDirectives(body.statements);
var pos = writer.getTextPos();
emitHelpers(body);
if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
@@ -84768,7 +85567,7 @@ var ts;
}
}
if (node.tags) {
- if (node.tags.length === 1 && node.tags[0].kind === 302 /* JSDocTypeTag */ && !node.comment) {
+ if (node.tags.length === 1 && node.tags[0].kind === 307 /* JSDocTypeTag */ && !node.comment) {
writeSpace();
emit(node.tags[0]);
}
@@ -84802,7 +85601,7 @@ var ts;
function emitJSDocTypedefTag(tag) {
emitJSDocTagName(tag.tagName);
if (tag.typeExpression) {
- if (tag.typeExpression.kind === 283 /* JSDocTypeExpression */) {
+ if (tag.typeExpression.kind === 288 /* JSDocTypeExpression */) {
emitJSDocTypeExpression(tag.typeExpression);
}
else {
@@ -84821,7 +85620,7 @@ var ts;
emit(tag.fullName);
}
emitJSDocComment(tag.comment);
- if (tag.typeExpression && tag.typeExpression.kind === 292 /* JSDocTypeLiteral */) {
+ if (tag.typeExpression && tag.typeExpression.kind === 297 /* JSDocTypeLiteral */) {
emitJSDocTypeLiteral(tag.typeExpression);
}
}
@@ -84908,6 +85707,16 @@ var ts;
}
function emitSyntheticTripleSlashReferencesIfNeeded(node) {
emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
+ for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
+ for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
+ var ref = _d[_c];
+ emit(ref);
+ writeLine();
+ }
+ }
+ }
}
function emitTripleSlashDirectivesIfNeeded(node) {
if (node.isDeclarationFile)
@@ -84915,7 +85724,10 @@ var ts;
}
function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
if (hasNoDefaultLib) {
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
writeLine();
}
if (currentSourceFile && currentSourceFile.moduleName) {
@@ -84936,17 +85748,26 @@ var ts;
}
for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
var directive = files_1[_c];
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
writeLine();
}
for (var _d = 0, types_19 = types; _d < types_19.length; _d++) {
var directive = types_19[_d];
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
writeLine();
}
for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
var directive = libs_1[_e];
+ var pos = writer.getTextPos();
writeComment("/// ");
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
writeLine();
}
}
@@ -84971,16 +85792,22 @@ var ts;
* Emits any prologue directives at the start of a Statement list, returning the
* number of prologue directives written to the output.
*/
- function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) {
+ function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
+ var needsToSetSourceFile = !!sourceFile;
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (ts.isPrologueDirective(statement)) {
var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
if (shouldEmitPrologueDirective) {
- if (startWithNewLine || i > 0) {
- writeLine();
+ if (needsToSetSourceFile) {
+ needsToSetSourceFile = false;
+ setSourceFile(sourceFile);
}
+ writeLine();
+ var pos = writer.getTextPos();
emit(statement);
+ if (recordBundleFileSection && bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
if (seenPrologueDirectives) {
seenPrologueDirectives.set(statement.expression.text, true);
}
@@ -84993,23 +85820,70 @@ var ts;
}
return statements.length;
}
+ function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
+ for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
+ var prologue = prologues_1[_a];
+ if (!seenPrologueDirectives.has(prologue.data)) {
+ writeLine();
+ var pos = writer.getTextPos();
+ emit(prologue);
+ if (bundleFileInfo)
+ bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
+ if (seenPrologueDirectives) {
+ seenPrologueDirectives.set(prologue.data, true);
+ }
+ }
+ }
+ }
function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
if (ts.isSourceFile(sourceFileOrBundle)) {
- setSourceFile(sourceFileOrBundle);
- emitPrologueDirectives(sourceFileOrBundle.statements);
+ emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
}
else {
var seenPrologueDirectives = ts.createMap();
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
- setSourceFile(sourceFile);
- emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives);
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
+ emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
}
setSourceFile(undefined);
}
}
+ function getPrologueDirectivesFromBundledSourceFiles(bundle) {
+ var seenPrologueDirectives = ts.createMap();
+ var prologues;
+ for (var index = 0; index < bundle.sourceFiles.length; index++) {
+ var sourceFile = bundle.sourceFiles[index];
+ var directives = void 0;
+ var end = 0;
+ for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
+ var statement = _b[_a];
+ if (!ts.isPrologueDirective(statement))
+ break;
+ if (seenPrologueDirectives.has(statement.expression.text))
+ continue;
+ seenPrologueDirectives.set(statement.expression.text, true);
+ (directives || (directives = [])).push({
+ pos: statement.pos,
+ end: statement.end,
+ expression: {
+ pos: statement.expression.pos,
+ end: statement.expression.end,
+ text: statement.expression.text
+ }
+ });
+ end = end < statement.end ? statement.end : end;
+ }
+ if (directives)
+ (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
+ }
+ return prologues;
+ }
function emitShebangIfNeeded(sourceFileOrBundle) {
- if (ts.isSourceFile(sourceFileOrBundle)) {
+ if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
var shebang = ts.getShebang(sourceFileOrBundle.text);
if (shebang) {
writeComment(shebang);
@@ -85018,11 +85892,18 @@ var ts;
}
}
else {
- for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ ts.Debug.assertNode(prepend, ts.isUnparsedSource);
+ if (emitShebangIfNeeded(prepend)) {
+ return true;
+ }
+ }
+ for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
// Emit only the first encountered shebang
if (emitShebangIfNeeded(sourceFile)) {
- break;
+ return true;
}
}
}
@@ -85225,6 +86106,7 @@ var ts;
}
// Emit each child.
var previousSibling = void 0;
+ var previousSourceFileTextKind = void 0;
var shouldDecreaseIndentAfterEmit = false;
for (var i = 0; i < count; i++) {
var child = children[start + i];
@@ -85245,6 +86127,7 @@ var ts;
emitLeadingCommentsOfPosition(previousSibling.end);
}
writeDelimiter(format);
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write either a line terminator or whitespace to separate the elements.
if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) {
// If a synthesized node in a single-line list starts on a new
@@ -85261,6 +86144,7 @@ var ts;
}
}
// Emit this child.
+ previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
if (shouldEmitInterveningComments) {
if (emitTrailingCommentsOfPosition) {
var commentRange = ts.getCommentRange(child);
@@ -85295,6 +86179,7 @@ var ts;
if (format & 128 /* Indented */) {
decreaseIndent();
}
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write the closing line terminator or closing whitespace.
if (shouldWriteClosingLineTerminator(parentNode, children, format)) {
writeLine();
@@ -85396,7 +86281,6 @@ var ts;
if (line.length) {
writeLine();
write(line);
- writer.rawWrite(newLine);
}
}
}
@@ -85910,7 +86794,7 @@ var ts;
hasWrittenComment = false;
var emitFlags = ts.getEmitFlags(node);
var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
- var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */;
+ var isEmittedNode = node.kind !== 312 /* NotEmittedStatement */;
// We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
// It is expensive to walk entire tree just to set one kind of node to have no comments.
var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
@@ -86170,19 +87054,28 @@ var ts;
return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
}
// Source Maps
+ function getParsedSourceMap(node) {
+ if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
+ node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
+ }
+ return node.parsedSourceMap || undefined;
+ }
function pipelineEmitWithSourceMap(hint, node) {
var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node);
- if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) {
- var parsed = ts.tryParseRawSourceMap(node.sourceMapText);
- if (parsed) {
- sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath);
+ if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
+ pipelinePhase(hint, node);
+ }
+ else if (ts.isUnparsedNode(node)) {
+ var parsed = getParsedSourceMap(node.parent);
+ if (parsed && sourceMapGenerator) {
+ sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
}
pipelinePhase(hint, node);
}
else {
var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
var emitFlags = ts.getEmitFlags(node);
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 16 /* NoLeadingSourceMap */) === 0
&& pos >= 0) {
emitSourcePos(source, skipSourceTrivia(source, pos));
@@ -86195,7 +87088,7 @@ var ts;
else {
pipelinePhase(hint, node);
}
- if (node.kind !== 307 /* NotEmittedStatement */
+ if (node.kind !== 312 /* NotEmittedStatement */
&& (emitFlags & 32 /* NoTrailingSourceMap */) === 0
&& end >= 0) {
emitSourcePos(source, end);
@@ -86843,7 +87736,8 @@ var ts;
var value = readFileCache.get(key);
if (value !== undefined)
return value !== false ? value : undefined; // could be .d.ts from output
- if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) {
+ // Cache json or buildInfo
+ if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
return originalReadFile.call(host, fileName);
}
return setReadFileCache(key, fileName);
@@ -86874,7 +87768,7 @@ var ts;
var key = toPath(fileName);
fileExistsCache.delete(key);
var value = readFileCache.get(key);
- if (value && value !== data) {
+ if (value !== undefined && value !== data) {
readFileCache.delete(key);
sourceFileCache.delete(key);
}
@@ -87429,7 +88323,8 @@ var ts;
getProjectReferenceRedirect: getProjectReferenceRedirect,
getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
- forEachResolvedProjectReference: forEachResolvedProjectReference
+ forEachResolvedProjectReference: forEachResolvedProjectReference,
+ emitBuildInfo: emitBuildInfo
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -87856,7 +88751,20 @@ var ts;
return false;
// Before falling back to the host
return host.fileExists(f);
- } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } });
+ } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); } });
+ }
+ function emitBuildInfo(writeFileCallback) {
+ ts.Debug.assert(!options.out && !options.outFile);
+ ts.performance.mark("beforeEmit");
+ var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback),
+ /*targetSourceFile*/ undefined,
+ /*emitOnlyDtsFiles*/ false,
+ /*transformers*/ undefined,
+ /*declaraitonTransformers*/ undefined,
+ /*onlyBuildInfo*/ true);
+ ts.performance.mark("afterEmit");
+ ts.performance.measure("Emit", "beforeEmit", "afterEmit");
+ return emitResult;
}
function getResolvedProjectReferences() {
return resolvedProjectReferences;
@@ -87865,28 +88773,11 @@ var ts;
return projectReferences;
}
function getPrependNodes() {
- if (!projectReferences) {
- return ts.emptyArray;
- }
- var nodes = [];
- for (var i = 0; i < projectReferences.length; i++) {
- var ref = projectReferences[i];
- var resolvedRefOpts = resolvedProjectReferences[i].commandLine;
- if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
- var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
- // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
- if (!out)
- continue;
- var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
- var node = ts.createInputFiles(function (fileName) {
- var path = toPath(fileName);
- var sourceFile = getSourceFileByPath(path);
- return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
- }, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath);
- nodes.push(node);
- }
- }
- return nodes;
+ return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
+ var path = toPath(fileName);
+ var sourceFile = getSourceFileByPath(path);
+ return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
+ });
}
function isSourceFileFromExternalLibrary(file) {
return !!sourceFilesFoundSearchingNodeModules.get(file.path);
@@ -87958,8 +88849,7 @@ var ts;
var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
ts.performance.mark("beforeEmit");
var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers);
- var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217
- emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
+ var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations);
ts.performance.mark("afterEmit");
ts.performance.measure("Emit", "beforeEmit", "afterEmit");
return emitResult;
@@ -88961,6 +89851,14 @@ var ts;
if (options.declaration === false) {
createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
}
+ if (options.incremental === false) {
+ createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
+ }
+ }
+ if (options.tsBuildInfoFile) {
+ if (!ts.isIncrementalCompilation(options)) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
+ }
}
verifyProjectReferences();
// List of collected files is complete; validate exhautiveness if this is a project with a file list
@@ -89155,6 +90053,7 @@ var ts;
}
}
function verifyProjectReferences() {
+ var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getOutputPathForBuildInfo(options) : undefined;
forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
var parentFile = parent && parent.sourceFile;
@@ -89181,6 +90080,10 @@ var ts;
createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
}
}
+ if (!parent && buildInfoPath && buildInfoPath === ts.getOutputPathForBuildInfo(options)) {
+ createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
+ hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
+ }
});
}
function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
@@ -89330,6 +90233,27 @@ var ts;
};
}
ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
+ /* @internal */
+ function createPrependNodes(projectReferences, getCommandLine, readFile) {
+ if (!projectReferences)
+ return ts.emptyArray;
+ var nodes;
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = getCommandLine(ref, i);
+ if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
+ var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
+ // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
+ if (!out)
+ continue;
+ var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
+ var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
+ (nodes || (nodes = [])).push(node);
+ }
+ }
+ return nodes || ts.emptyArray;
+ }
+ ts.createPrependNodes = createPrependNodes;
function resolveProjectReferencePath(hostOrRef, ref) {
var passedInRef = ref ? ref : hostOrRef;
return ts.resolveConfigFileProjectName(passedInRef.path);
@@ -89873,11 +90797,14 @@ var ts;
var affectedSignatures = oldState.currentAffectedFilesSignatures;
ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
}
+ var changedFilesSet = oldState.changedFilesSet;
if (canCopySemanticDiagnostics) {
- ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
+ ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
}
// Copy old state's changed files set
- ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet);
+ if (changedFilesSet) {
+ ts.copyEntries(changedFilesSet, state.changedFilesSet);
+ }
if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit;
state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
@@ -89915,7 +90842,7 @@ var ts;
// Unchanged file copy diagnostics
var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
if (diagnostics) {
- state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics);
+ state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics);
if (!state.semanticDiagnosticsFromOldState) {
state.semanticDiagnosticsFromOldState = ts.createMap();
}
@@ -89923,8 +90850,45 @@ var ts;
}
}
});
+ if (oldCompilerOptions &&
+ (oldCompilerOptions.outDir !== compilerOptions.outDir ||
+ oldCompilerOptions.declarationDir !== compilerOptions.declarationDir ||
+ (oldCompilerOptions.outFile || oldCompilerOptions.out) !== (compilerOptions.outFile || compilerOptions.out))) {
+ // Add all files to affectedFilesPendingEmit since emit changed
+ state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, newProgram.getSourceFiles().map(function (f) { return f.path; }));
+ if (state.affectedFilesPendingEmitIndex === undefined) {
+ state.affectedFilesPendingEmitIndex = 0;
+ }
+ ts.Debug.assert(state.seenAffectedFiles === undefined);
+ state.seenAffectedFiles = ts.createMap();
+ }
return state;
}
+ function convertToDiagnostics(diagnostics, newProgram) {
+ if (!diagnostics.length)
+ return ts.emptyArray;
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToDiagnosticRelatedInformation(diagnostic, newProgram) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && newProgram.getSourceFileByPath(file), messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToDiagnosticMessageChain(messageText, newProgram) });
+ }
+ function convertToDiagnosticMessageChain(diagnostic, newProgram) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToDiagnosticMessageChain(diagnostic.next, newProgram) });
+ }
/**
* Releases program and other related not needed properties
*/
@@ -90144,8 +91108,11 @@ var ts;
* This is called after completing operation on the next affected file.
* The operations here are postponed to ensure that cancellation during the iteration is handled correctly
*/
- function doneWithAffectedFile(state, affected, isPendingEmit) {
- if (affected === state.program) {
+ function doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit) {
+ if (isBuildInfoEmit) {
+ state.emittedBuildInfo = true;
+ }
+ else if (affected === state.program) {
state.changedFilesSet.clear();
state.programEmitComplete = true;
}
@@ -90162,8 +91129,8 @@ var ts;
/**
* Returns the result with affected file
*/
- function toAffectedFileResult(state, result, affected, isPendingEmit) {
- doneWithAffectedFile(state, affected, isPendingEmit);
+ function toAffectedFileResult(state, result, affected, isPendingEmit, isBuildInfoEmit) {
+ doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit);
return { result: result, affected: affected };
}
/**
@@ -90186,6 +91153,77 @@ var ts;
}
return diagnostics;
}
+ /**
+ * Gets the program information to be emitted in buildInfo so that we can use it to create new program
+ */
+ function getProgramBuildInfo(state) {
+ if (state.compilerOptions.outFile || state.compilerOptions.out)
+ return undefined;
+ var fileInfos = {};
+ state.fileInfos.forEach(function (value, key) {
+ var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
+ fileInfos[key] = signature === undefined ? value : { version: value.version, signature: signature };
+ });
+ var result = { fileInfos: fileInfos, options: state.compilerOptions };
+ if (state.referencedMap) {
+ var referencedMap_1 = {};
+ state.referencedMap.forEach(function (value, key) {
+ referencedMap_1[key] = ts.arrayFrom(value.keys());
+ });
+ result.referencedMap = referencedMap_1;
+ }
+ if (state.exportedModulesMap) {
+ var exportedModulesMap_1 = {};
+ state.exportedModulesMap.forEach(function (value, key) {
+ var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
+ // Not in temporary cache, use existing value
+ if (newValue === undefined)
+ exportedModulesMap_1[key] = ts.arrayFrom(value.keys());
+ // Value in cache and has updated value map, use that
+ else if (newValue)
+ exportedModulesMap_1[key] = ts.arrayFrom(newValue.keys());
+ });
+ result.exportedModulesMap = exportedModulesMap_1;
+ }
+ if (state.semanticDiagnosticsPerFile) {
+ var semanticDiagnosticsPerFile_1 = [];
+ // Currently not recording actual errors since those mean no emit for tsc --build
+ state.semanticDiagnosticsPerFile.forEach(function (value, key) { return semanticDiagnosticsPerFile_1.push(value.length ?
+ [
+ key,
+ state.hasReusableDiagnostic ?
+ value :
+ convertToReusableDiagnostics(value)
+ ] :
+ key); });
+ result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile_1;
+ }
+ return result;
+ }
+ function convertToReusableDiagnostics(diagnostics) {
+ ts.Debug.assert(!!diagnostics.length);
+ return diagnostics.map(function (diagnostic) {
+ var result = convertToReusableDiagnosticRelatedInformation(diagnostic);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ var relatedInformation = diagnostic.relatedInformation;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r); }) :
+ ts.emptyArray :
+ undefined;
+ return result;
+ });
+ }
+ function convertToReusableDiagnosticRelatedInformation(diagnostic) {
+ var file = diagnostic.file, messageText = diagnostic.messageText;
+ return __assign({}, diagnostic, { file: file && file.path, messageText: messageText === undefined || ts.isString(messageText) ?
+ messageText :
+ convertToReusableDiagnosticMessageChain(messageText) });
+ }
+ function convertToReusableDiagnosticMessageChain(diagnostic) {
+ return __assign({}, diagnostic, { next: diagnostic.next && convertToReusableDiagnosticMessageChain(diagnostic.next) });
+ }
var BuilderProgramKind;
(function (BuilderProgramKind) {
BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
@@ -90242,6 +91280,7 @@ var ts;
var computeHash = host.createHash || ts.generateDjb2Hash;
var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
var backupState;
+ newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state); };
// To ensure that we arent storing any references to old program or new program without state
newProgram = undefined; // TODO: GH#18217
oldProgram = undefined;
@@ -90285,7 +91324,16 @@ var ts;
if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
affected = getNextAffectedFilePendingEmit(state);
if (!affected) {
- return undefined;
+ if (state.emittedBuildInfo) {
+ return undefined;
+ }
+ var affected_1 = ts.Debug.assertDefined(state.program);
+ return toAffectedFileResult(state,
+ // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
+ // Otherwise just affected file
+ affected_1.emitBuildInfo(writeFile || host.writeFile, cancellationToken), affected_1,
+ /*isPendingEmitFile*/ false,
+ /*isBuildInfoEmit*/ true);
}
isPendingEmitFile = true;
}
@@ -90418,6 +91466,53 @@ var ts;
}
}
ts.createBuilderProgram = createBuilderProgram;
+ function getMapOfReferencedSet(mapLike) {
+ if (!mapLike)
+ return undefined;
+ var map = ts.createMap();
+ // Copies keys/values from template. Note that for..in will not throw if
+ // template is undefined, and instead will just exit the loop.
+ for (var key in mapLike) {
+ if (ts.hasProperty(mapLike, key)) {
+ map.set(key, ts.arrayToSet(mapLike[key]));
+ }
+ }
+ return map;
+ }
+ function createBuildProgramUsingProgramBuildInfo(program) {
+ var fileInfos = ts.createMapFromTemplate(program.fileInfos);
+ var state = {
+ fileInfos: fileInfos,
+ compilerOptions: program.options,
+ referencedMap: getMapOfReferencedSet(program.referencedMap),
+ exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap),
+ semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return ts.isString(value) ? value : value[0]; }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }),
+ hasReusableDiagnostic: true
+ };
+ return {
+ getState: function () { return state; },
+ backupState: ts.noop,
+ restoreState: ts.noop,
+ getProgram: ts.notImplemented,
+ getProgramOrUndefined: function () { return undefined; },
+ releaseProgram: ts.noop,
+ getCompilerOptions: function () { return state.compilerOptions; },
+ getSourceFile: ts.notImplemented,
+ getSourceFiles: ts.notImplemented,
+ getOptionsDiagnostics: ts.notImplemented,
+ getGlobalDiagnostics: ts.notImplemented,
+ getConfigFileParsingDiagnostics: ts.notImplemented,
+ getSyntacticDiagnostics: ts.notImplemented,
+ getDeclarationDiagnostics: ts.notImplemented,
+ getSemanticDiagnostics: ts.notImplemented,
+ emit: ts.notImplemented,
+ getAllDependencies: ts.notImplemented,
+ getCurrentDirectory: ts.notImplemented,
+ emitNextAffectedFile: ts.notImplemented,
+ getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
+ };
+ }
+ ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
return {
getState: ts.notImplemented,
@@ -90437,7 +91532,7 @@ var ts;
getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
getAllDependencies: ts.notImplemented,
- getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); }
+ getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
};
function getProgram() {
return ts.Debug.assertDefined(state.program);
@@ -90463,10 +91558,10 @@ var ts;
/*@internal*/
var ts;
(function (ts) {
- function isPathInNodeModulesStartingWithDot(path) {
- return ts.stringContains(path, "/node_modules/.");
+ function isPathIgnored(path) {
+ return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); });
}
- ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot;
+ ts.isPathIgnored = isPathIgnored;
ts.maxNumberOfFilesToIterateForInvalidation = 256;
function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
var filesWithChangedSetOfUnresolvedImports;
@@ -90988,7 +92083,7 @@ var ts;
}
else {
// If something to do with folder/file starting with "." in node_modules folder, skip it
- if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (isPathIgnored(fileOrDirectoryPath))
return false;
// Some file or directory in the watching directory is created
// Return early if it does not have any of the watching extension or not the custom failed lookup path
@@ -91465,6 +92560,8 @@ var ts;
case ".jsx" /* Jsx */:
case ".json" /* Json */:
return ext;
+ case ".tsbuildinfo" /* TsBuildInfo */:
+ return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
default:
return ts.Debug.assertNever(ext);
}
@@ -91746,7 +92843,7 @@ var ts;
writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; },
createHash: ts.maybeBind(system, system.createHash),
- createProgram: createProgram
+ createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
};
}
ts.createProgramHost = createProgramHost;
@@ -91756,7 +92853,7 @@ var ts;
function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
var writeFileName = function (s) { return system.write(s + system.newLine); };
- var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram);
+ var result = createProgramHost(system, createProgram);
ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
result.afterProgramCreate = function (builderProgram) {
var compilerOptions = builderProgram.getCompilerOptions();
@@ -92185,7 +93282,7 @@ var ts;
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
nextSourceFileVersion(fileOrDirectoryPath);
- if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath))
+ if (ts.isPathIgnored(fileOrDirectoryPath))
return;
// If the the added or created file or directory is not supported file name, ignore the file
// But when watched directory is added/removed, we need to reload the file list
@@ -92239,16 +93336,23 @@ var ts;
* This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
*/
UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
- UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf";
- UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream";
- UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate";
- UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked";
- UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream";
+ /**
+ * The project appears out of date because its upstream inputs are newer than its outputs,
+ * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
+ * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
+ */
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
+ UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
+ UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
+ UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
+ UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
+ UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
+ UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
/**
* Projects with no outputs (i.e. "solution" files)
*/
- UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly";
+ UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
})(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
function createFileMap(toPath) {
// tslint:disable-next-line:no-null-keyword
@@ -92329,24 +93433,18 @@ var ts;
}
return outputs;
}
- function getOutFileOutputs(project) {
- var out = project.options.outFile || project.options.out;
- if (!out) {
- return ts.Debug.fail("outFile must be set");
- }
+ function getOutFileOutputs(project, ignoreBuildInfo) {
+ ts.Debug.assert(!!project.options.outFile || !!project.options.out, "outFile must be set");
+ var _a = ts.getOutputPathsForBundle(project.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
var outputs = [];
- outputs.push(out);
- if (project.options.sourceMap) {
- outputs.push(out + ".map");
- }
- if (ts.getEmitDeclarations(project.options)) {
- var dts = ts.changeExtension(out, ".d.ts" /* Dts */);
- outputs.push(dts);
- if (project.options.declarationMap) {
- outputs.push(dts + ".map");
- }
- }
- return outputs;
+ var addOutput = function (path) { return path && (outputs || (outputs = [])).push(path); };
+ addOutput(jsFilePath);
+ addOutput(sourceMapFilePath);
+ addOutput(declarationFilePath);
+ addOutput(declarationMapPath);
+ if (!ignoreBuildInfo)
+ addOutput(buildInfoPath);
+ return outputs || ts.emptyArray;
}
function rootDirOfOptions(opts, configFileName) {
return opts.rootDir || ts.getDirectoryPath(configFileName);
@@ -92379,14 +93477,14 @@ var ts;
}
function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
host.reportErrorSummary = reportErrorSummary;
return host;
}
ts.createSolutionBuilderHost = createSolutionBuilderHost;
function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
if (system === void 0) { system = ts.sys; }
- var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus);
+ var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
var watchHost = ts.createWatchHost(system, reportWatchStatus);
ts.copyProperties(host, watchHost);
return host;
@@ -92420,7 +93518,18 @@ var ts;
var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; });
var originalGetSourceFile = compilerHost.getSourceFile;
var computeHash = host.createHash || ts.generateDjb2Hash;
- updateGetSourceFile();
+ compilerHost.getSourceFile = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
+ if (result) {
+ result.version = computeHash.call(host, result.text);
+ }
+ return result;
+ };
+ var buildInfoChecked = createFileMap(toPath);
// Watch state
var builderPrograms = createFileMap(toPath);
var diagnostics = createFileMap(toPath);
@@ -92458,6 +93567,7 @@ var ts;
projectStatus.clear();
missingRoots.clear();
globalDependencyGraph = undefined;
+ buildInfoChecked.clear();
diagnostics.clear();
projectPendingBuild.clear();
projectErrorsReported.clear();
@@ -92472,29 +93582,6 @@ var ts;
ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); });
ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher);
builderPrograms.clear();
- updateGetSourceFile();
- }
- function updateGetSourceFile() {
- if (options.watch) {
- if (compilerHost.getSourceFile === originalGetSourceFile) {
- compilerHost.getSourceFile = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args));
- if (result && options.watch) {
- result.version = computeHash.call(host, result.text);
- }
- return result;
- };
- }
- }
- else {
- if (compilerHost.getSourceFile !== originalGetSourceFile) {
- compilerHost.getSourceFile = originalGetSourceFile;
- }
- }
}
function isParsedCommandLine(entry) {
return !!entry.options;
@@ -92726,25 +93813,28 @@ var ts;
upstreamProjectName: ref.path
};
}
- // If the upstream project's newest file is older than our oldest output, we
- // can't be out of date because of it
- if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
- continue;
- }
- // If the upstream project has only change .d.ts files, and we've built
- // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
- if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
- pseudoUpToDate = true;
- upstreamChangedProject = ref.path;
- continue;
+ // Check oldest output file name only if there is no missing output file name
+ if (!missingOutputFileName) {
+ // If the upstream project's newest file is older than our oldest output, we
+ // can't be out of date because of it
+ if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
+ continue;
+ }
+ // If the upstream project has only change .d.ts files, and we've built
+ // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
+ if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
+ pseudoUpToDate = true;
+ upstreamChangedProject = ref.path;
+ continue;
+ }
+ // We have an output older than an upstream output - we are out of date
+ ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
+ return {
+ type: UpToDateStatusType.OutOfDateWithUpstream,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerProjectName: ref.path
+ };
}
- // We have an output older than an upstream output - we are out of date
- ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
- return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: oldestOutputFileName,
- newerProjectName: ref.path
- };
}
}
if (missingOutputFileName !== undefined) {
@@ -92760,9 +93850,23 @@ var ts;
newerInputFileName: newestInputFileName
};
}
+ if (!buildInfoChecked.hasKey(project.options.configFilePath)) {
+ buildInfoChecked.setValue(project.options.configFilePath, true);
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath) {
+ var value = readFileWithCache(buildInfoPath);
+ var buildInfo = value && ts.getBuildInfo(value);
+ if (buildInfo && buildInfo.version !== ts.version) {
+ return {
+ type: UpToDateStatusType.TsVersionOutputOfDate,
+ version: buildInfo.version
+ };
+ }
+ }
+ }
if (usesPrepend && pseudoUpToDate) {
return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
+ type: UpToDateStatusType.OutOfDateWithPrepend,
outOfDateOutputFileName: oldestOutputFileName,
newerProjectName: upstreamChangedProject
};
@@ -92896,7 +94000,9 @@ var ts;
updateOutputTimestamps(proj);
return;
}
- var buildResult = buildSingleProject(resolved);
+ var buildResult = status.type === UpToDateStatusType.OutOfDateWithPrepend ?
+ updateBundle(resolved) : // Fake that files have been built by manipulating prepend and existing output
+ buildSingleProject(resolved); // Actual build
if (buildResult & BuildResultFlags.AnyErrors)
return;
var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue;
@@ -92912,17 +94018,26 @@ var ts;
// If declaration output is changed, build the project
// otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
var status_1 = projectStatus.getValue(project);
- if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
- if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) {
+ if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
+ if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes || status_1.type === UpToDateStatusType.OutOfDateWithPrepend)) {
projectStatus.setValue(project, {
type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: status_1.oldestOutputFileName,
+ outOfDateOutputFileName: status_1.type === UpToDateStatusType.OutOfDateWithPrepend ? status_1.outOfDateOutputFileName : status_1.oldestOutputFileName,
newerProjectName: resolved
});
}
}
else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) {
- status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
+ if (prepend) {
+ projectStatus.setValue(project, {
+ type: UpToDateStatusType.OutOfDateWithPrepend,
+ outOfDateOutputFileName: status_1.oldestOutputFileName,
+ newerProjectName: resolved
+ });
+ }
+ else {
+ status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
+ }
}
addProjToQueue(project);
}
@@ -92979,8 +94094,7 @@ var ts;
}
if (options.verbose)
reportStatus(ts.Diagnostics.Building_project_0, proj);
- var resultFlags = BuildResultFlags.None;
- resultFlags |= BuildResultFlags.DeclarationOutputUnchanged;
+ var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
var configFile = parseConfigFile(proj);
if (!configFile) {
// Failed to read the config file
@@ -92996,8 +94110,7 @@ var ts;
}
// TODO: handle resolve module name to cache result in project reference redirect
projectCompilerOptions = configFile.options;
- var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences);
- projectCompilerOptions = baseCompilerOptions;
+ var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, getOldProgram(proj, configFile), configFile.errors, configFile.projectReferences);
// Don't emit anything in the presence of syntactic errors or options diagnostics
var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics());
if (syntaxDiagnostics.length) {
@@ -93058,12 +94171,14 @@ var ts;
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
function buildErrors(diagnostics, errorFlags, errorType) {
resultFlags |= errorFlags;
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
}
}
@@ -93076,9 +94191,67 @@ var ts;
builderPrograms.setValue(proj, program);
}
}
+ function getOldProgram(proj, parsed) {
+ var value = builderPrograms.getValue(proj);
+ if (value)
+ return value;
+ var buildInfoPath = ts.getOutputPathForBuildInfo(parsed.options);
+ if (!buildInfoPath)
+ return undefined;
+ var content = readFileWithCache(buildInfoPath);
+ if (!content)
+ return undefined;
+ var buildInfo = ts.getBuildInfo(content);
+ if (buildInfo.version !== ts.version)
+ return undefined;
+ return buildInfo.program && ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program);
+ }
+ function updateBundle(proj) {
+ if (options.dry) {
+ reportStatus(ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, proj);
+ return BuildResultFlags.Success;
+ }
+ if (options.verbose)
+ reportStatus(ts.Diagnostics.Updating_output_of_project_0, proj);
+ // Update js, and source map
+ var config = ts.Debug.assertDefined(parseConfigFile(proj));
+ projectCompilerOptions = config.options;
+ var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) { return parseConfigFile(resolveProjectName(ref.path)); });
+ if (ts.isString(outputFiles)) {
+ reportStatus(ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, proj, relName(outputFiles));
+ return buildSingleProject(proj);
+ }
+ // Actual Emit
+ ts.Debug.assert(!!outputFiles.length);
+ var emitterDiagnostics = ts.createDiagnosticCollection();
+ var emittedOutputs = createFileMap(toPath);
+ outputFiles.forEach(function (_a) {
+ var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
+ emittedOutputs.setValue(name, true);
+ ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
+ });
+ var emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
+ reportAndStoreErrors(proj, emitDiagnostics);
+ projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Emit errors" });
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged | BuildResultFlags.EmitErrors;
+ }
+ // Update timestamps for dts
+ var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(config, minimumDate, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
+ var status = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
+ oldestOutputFileName: outputFiles[0].name
+ };
+ diagnostics.removeKey(proj);
+ projectStatus.setValue(proj, status);
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged;
+ }
function updateOutputTimestamps(proj) {
if (options.dry) {
- return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath);
+ return reportStatus(ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
}
var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime });
@@ -93205,7 +94378,9 @@ var ts;
// Do nothing
continue;
}
- var buildResult = buildSingleProject(next);
+ var buildResult = status.type === UpToDateStatusType.OutOfDateWithPrepend && !options.force ?
+ updateBundle(next) : // Fake that files have been built by manipulating prepend and existing output
+ buildSingleProject(next); // Actual build
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
@@ -93267,6 +94442,9 @@ var ts;
var inputFile = _a[_i];
outputs.push.apply(outputs, getOutputFileNames(inputFile, project));
}
+ var buildInfoPath = ts.getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath)
+ outputs.push(buildInfoPath);
return outputs;
}
}
@@ -93298,6 +94476,8 @@ var ts;
}
// Don't report anything for "up to date because it was already built" -- too verbose
break;
+ case UpToDateStatusType.OutOfDateWithPrepend:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(configFileName), relName(status.newerProjectName));
case UpToDateStatusType.UpToDateWithUpstreamTypes:
return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName));
case UpToDateStatusType.UpstreamOutOfDate:
@@ -93306,6 +94486,8 @@ var ts;
return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName));
case UpToDateStatusType.Unbuildable:
return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason);
+ case UpToDateStatusType.TsVersionOutputOfDate:
+ return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(configFileName), status.version, ts.version);
case UpToDateStatusType.ContainerOnly:
// Don't report status on "solution" projects
case UpToDateStatusType.ComputingUpstream:
@@ -93455,8 +94637,6 @@ var ts;
}
}
})(ts || (ts = {}));
-//# sourceMappingURL=compiler.js.map
-"use strict";
/* @internal */
var ts;
(function (ts) {
@@ -93797,8 +94977,6 @@ var ts;
JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
})(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
})(ts || (ts = {}));
-//# sourceMappingURL=jsTyping.js.map
-"use strict";
var ts;
(function (ts) {
var server;
@@ -94275,7 +95453,6 @@ var ts;
})(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
-//# sourceMappingURL=typingsInstallerCore.js.map
var ts;
(function (ts) {
var server;
diff --git a/src/cancellationToken/tsconfig.json b/src/cancellationToken/tsconfig.json
index 6d9e0af772410..6d27fe45cf37f 100644
--- a/src/cancellationToken/tsconfig.json
+++ b/src/cancellationToken/tsconfig.json
@@ -7,6 +7,7 @@
"declaration": false,
"declarationMap": false,
"removeComments": true,
+ "incremental": false,
"module": "commonjs",
"types": [
"node"
diff --git a/src/compiler/builder.ts b/src/compiler/builder.ts
index c95a8270052b6..a97e07b132b77 100644
--- a/src/compiler/builder.ts
+++ b/src/compiler/builder.ts
@@ -1,5 +1,80 @@
/*@internal*/
namespace ts {
+ export interface ReusableDiagnostic extends ReusableDiagnosticRelatedInformation {
+ /** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */
+ reportsUnnecessary?: {};
+ source?: string;
+ relatedInformation?: ReusableDiagnosticRelatedInformation[];
+ }
+
+ export interface ReusableDiagnosticRelatedInformation {
+ category: DiagnosticCategory;
+ code: number;
+ file: Path | undefined;
+ start: number | undefined;
+ length: number | undefined;
+ messageText: string | ReusableDiagnosticMessageChain;
+ }
+
+ export interface ReusableDiagnosticMessageChain {
+ messageText: string;
+ category: DiagnosticCategory;
+ code: number;
+ next?: ReusableDiagnosticMessageChain;
+ }
+
+ export interface ReusableBuilderProgramState extends ReusableBuilderState {
+ /**
+ * Cache of semantic diagnostics for files with their Path being the key
+ */
+ semanticDiagnosticsPerFile?: ReadonlyMap | ReadonlyArray> | undefined;
+ /**
+ * The map has key by source file's path that has been changed
+ */
+ changedFilesSet?: ReadonlyMap;
+ /**
+ * Set of affected files being iterated
+ */
+ affectedFiles?: ReadonlyArray | undefined;
+ /**
+ * Current changed file for iterating over affected files
+ */
+ currentChangedFilePath?: Path | undefined;
+ /**
+ * Map of file signatures, with key being file path, calculated while getting current changed file's affected files
+ * These will be committed whenever the iteration through affected files of current changed file is complete
+ */
+ currentAffectedFilesSignatures?: ReadonlyMap | undefined;
+ /**
+ * Newly computed visible to outside referencedSet
+ */
+ currentAffectedFilesExportedModulesMap?: Readonly | undefined;
+ /**
+ * True if the semantic diagnostics were copied from the old state
+ */
+ semanticDiagnosticsFromOldState?: Map;
+ /**
+ * program corresponding to this state
+ */
+ program?: Program | undefined;
+ /**
+ * compilerOptions for the program
+ */
+ compilerOptions: CompilerOptions;
+ /**
+ * Files pending to be emitted
+ */
+ affectedFilesPendingEmit?: ReadonlyArray | undefined;
+ /**
+ * Current index to retrieve pending affected file
+ */
+ affectedFilesPendingEmitIndex?: number | undefined;
+ /*
+ * true if semantic diagnostics are ReusableDiagnostic instead of Diagnostic
+ */
+ hasReusableDiagnostic?: true;
+ }
+
/**
* State to store the changed files, affected files and cache semantic diagnostics
*/
@@ -62,6 +137,10 @@ namespace ts {
* Current index to retrieve pending affected file
*/
affectedFilesPendingEmitIndex: number | undefined;
+ /**
+ * true if build info is emitted
+ */
+ emittedBuildInfo?: boolean;
/**
* Already seen affected files
*/
@@ -80,7 +159,7 @@ namespace ts {
/**
* Create the state so that we can iterate on changedFiles/affected files
*/
- function createBuilderProgramState(newProgram: Program, getCanonicalFileName: GetCanonicalFileName, oldState?: Readonly): BuilderProgramState {
+ function createBuilderProgramState(newProgram: Program, getCanonicalFileName: GetCanonicalFileName, oldState?: Readonly): BuilderProgramState {
const state = BuilderState.create(newProgram, getCanonicalFileName, oldState) as BuilderProgramState;
state.program = newProgram;
const compilerOptions = newProgram.getCompilerOptions();
@@ -102,12 +181,15 @@ namespace ts {
const affectedSignatures = oldState!.currentAffectedFilesSignatures;
Debug.assert(!oldState!.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
}
+ const changedFilesSet = oldState!.changedFilesSet;
if (canCopySemanticDiagnostics) {
- Debug.assert(!forEachKey(oldState!.changedFilesSet, path => oldState!.semanticDiagnosticsPerFile!.has(path)), "Semantic diagnostics shouldnt be available for changed files");
+ Debug.assert(!changedFilesSet || !forEachKey(changedFilesSet, path => oldState!.semanticDiagnosticsPerFile!.has(path)), "Semantic diagnostics shouldnt be available for changed files");
}
// Copy old state's changed files set
- copyEntries(oldState!.changedFilesSet, state.changedFilesSet);
+ if (changedFilesSet) {
+ copyEntries(changedFilesSet, state.changedFilesSet);
+ }
if (!compilerOptions.outFile && !compilerOptions.out && oldState!.affectedFilesPendingEmit) {
state.affectedFilesPendingEmit = oldState!.affectedFilesPendingEmit;
state.affectedFilesPendingEmitIndex = oldState!.affectedFilesPendingEmitIndex;
@@ -145,7 +227,7 @@ namespace ts {
// Unchanged file copy diagnostics
const diagnostics = oldState!.semanticDiagnosticsPerFile!.get(sourceFilePath);
if (diagnostics) {
- state.semanticDiagnosticsPerFile!.set(sourceFilePath, diagnostics);
+ state.semanticDiagnosticsPerFile!.set(sourceFilePath, oldState!.hasReusableDiagnostic ? convertToDiagnostics(diagnostics as ReadonlyArray, newProgram) : diagnostics as ReadonlyArray);
if (!state.semanticDiagnosticsFromOldState) {
state.semanticDiagnosticsFromOldState = createMap();
}
@@ -154,9 +236,56 @@ namespace ts {
}
});
+ if (oldCompilerOptions &&
+ (oldCompilerOptions.outDir !== compilerOptions.outDir ||
+ oldCompilerOptions.declarationDir !== compilerOptions.declarationDir ||
+ (oldCompilerOptions.outFile || oldCompilerOptions.out) !== (compilerOptions.outFile || compilerOptions.out))) {
+ // Add all files to affectedFilesPendingEmit since emit changed
+ state.affectedFilesPendingEmit = concatenate(state.affectedFilesPendingEmit, newProgram.getSourceFiles().map(f => f.path));
+ if (state.affectedFilesPendingEmitIndex === undefined) {
+ state.affectedFilesPendingEmitIndex = 0;
+ }
+ Debug.assert(state.seenAffectedFiles === undefined);
+ state.seenAffectedFiles = createMap();
+ }
+
return state;
}
+ function convertToDiagnostics(diagnostics: ReadonlyArray, newProgram: Program): ReadonlyArray {
+ if (!diagnostics.length) return emptyArray;
+ return diagnostics.map(diagnostic => {
+ const result: Diagnostic = convertToDiagnosticRelatedInformation(diagnostic, newProgram);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ const { relatedInformation } = diagnostic;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(r => convertToDiagnosticRelatedInformation(r, newProgram)) :
+ emptyArray :
+ undefined;
+ return result;
+ });
+ }
+
+ function convertToDiagnosticRelatedInformation(diagnostic: ReusableDiagnosticRelatedInformation, newProgram: Program): DiagnosticRelatedInformation {
+ const { file, messageText } = diagnostic;
+ return {
+ ...diagnostic,
+ file: file && newProgram.getSourceFileByPath(file),
+ messageText: messageText === undefined || isString(messageText) ?
+ messageText :
+ convertToDiagnosticMessageChain(messageText, newProgram)
+ };
+ }
+
+ function convertToDiagnosticMessageChain(diagnostic: ReusableDiagnosticMessageChain, newProgram: Program): DiagnosticMessageChain {
+ return {
+ ...diagnostic,
+ next: diagnostic.next && convertToDiagnosticMessageChain(diagnostic.next, newProgram)
+ };
+ }
+
/**
* Releases program and other related not needed properties
*/
@@ -397,8 +526,11 @@ namespace ts {
* This is called after completing operation on the next affected file.
* The operations here are postponed to ensure that cancellation during the iteration is handled correctly
*/
- function doneWithAffectedFile(state: BuilderProgramState, affected: SourceFile | Program, isPendingEmit?: boolean) {
- if (affected === state.program) {
+ function doneWithAffectedFile(state: BuilderProgramState, affected: SourceFile | Program, isPendingEmit?: boolean, isBuildInfoEmit?: boolean) {
+ if (isBuildInfoEmit) {
+ state.emittedBuildInfo = true;
+ }
+ else if (affected === state.program) {
state.changedFilesSet.clear();
state.programEmitComplete = true;
}
@@ -416,8 +548,8 @@ namespace ts {
/**
* Returns the result with affected file
*/
- function toAffectedFileResult(state: BuilderProgramState, result: T, affected: SourceFile | Program, isPendingEmit?: boolean): AffectedFileResult {
- doneWithAffectedFile(state, affected, isPendingEmit);
+ function toAffectedFileResult(state: BuilderProgramState, result: T, affected: SourceFile | Program, isPendingEmit?: boolean, isBuildInfoEmit?: boolean): AffectedFileResult {
+ doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit);
return { result, affected };
}
@@ -443,6 +575,100 @@ namespace ts {
return diagnostics;
}
+ export type ProgramBuildInfoDiagnostic = string | [string, ReadonlyArray];
+ export interface ProgramBuildInfo {
+ fileInfos: MapLike;
+ options: CompilerOptions;
+ referencedMap?: MapLike;
+ exportedModulesMap?: MapLike;
+ semanticDiagnosticsPerFile?: ProgramBuildInfoDiagnostic[];
+ }
+
+ /**
+ * Gets the program information to be emitted in buildInfo so that we can use it to create new program
+ */
+ function getProgramBuildInfo(state: Readonly): ProgramBuildInfo | undefined {
+ if (state.compilerOptions.outFile || state.compilerOptions.out) return undefined;
+ const fileInfos: MapLike = {};
+ state.fileInfos.forEach((value, key) => {
+ const signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
+ fileInfos[key] = signature === undefined ? value : { version: value.version, signature };
+ });
+
+ const result: ProgramBuildInfo = { fileInfos, options: state.compilerOptions };
+ if (state.referencedMap) {
+ const referencedMap: MapLike = {};
+ state.referencedMap.forEach((value, key) => {
+ referencedMap[key] = arrayFrom(value.keys());
+ });
+ result.referencedMap = referencedMap;
+ }
+
+ if (state.exportedModulesMap) {
+ const exportedModulesMap: MapLike = {};
+ state.exportedModulesMap.forEach((value, key) => {
+ const newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
+ // Not in temporary cache, use existing value
+ if (newValue === undefined) exportedModulesMap[key] = arrayFrom(value.keys());
+ // Value in cache and has updated value map, use that
+ else if (newValue) exportedModulesMap[key] = arrayFrom(newValue.keys());
+ });
+ result.exportedModulesMap = exportedModulesMap;
+ }
+
+ if (state.semanticDiagnosticsPerFile) {
+ const semanticDiagnosticsPerFile: ProgramBuildInfoDiagnostic[] = [];
+ // Currently not recording actual errors since those mean no emit for tsc --build
+ state.semanticDiagnosticsPerFile.forEach((value, key) => semanticDiagnosticsPerFile.push(
+ value.length ?
+ [
+ key,
+ state.hasReusableDiagnostic ?
+ value as ReadonlyArray :
+ convertToReusableDiagnostics(value as ReadonlyArray)
+ ] :
+ key
+ ));
+ result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile;
+ }
+
+ return result;
+ }
+
+ function convertToReusableDiagnostics(diagnostics: ReadonlyArray): ReadonlyArray {
+ Debug.assert(!!diagnostics.length);
+ return diagnostics.map(diagnostic => {
+ const result: ReusableDiagnostic = convertToReusableDiagnosticRelatedInformation(diagnostic);
+ result.reportsUnnecessary = diagnostic.reportsUnnecessary;
+ result.source = diagnostic.source;
+ const { relatedInformation } = diagnostic;
+ result.relatedInformation = relatedInformation ?
+ relatedInformation.length ?
+ relatedInformation.map(r => convertToReusableDiagnosticRelatedInformation(r)) :
+ emptyArray :
+ undefined;
+ return result;
+ });
+ }
+
+ function convertToReusableDiagnosticRelatedInformation(diagnostic: DiagnosticRelatedInformation): ReusableDiagnosticRelatedInformation {
+ const { file, messageText } = diagnostic;
+ return {
+ ...diagnostic,
+ file: file && file.path,
+ messageText: messageText === undefined || isString(messageText) ?
+ messageText :
+ convertToReusableDiagnosticMessageChain(messageText)
+ };
+ }
+
+ function convertToReusableDiagnosticMessageChain(diagnostic: DiagnosticMessageChain): ReusableDiagnosticMessageChain {
+ return {
+ ...diagnostic,
+ next: diagnostic.next && convertToReusableDiagnosticMessageChain(diagnostic.next)
+ };
+ }
+
export enum BuilderProgramKind {
SemanticDiagnosticsBuilderProgram,
EmitAndSemanticDiagnosticsBuilderProgram
@@ -508,6 +734,7 @@ namespace ts {
const computeHash = host.createHash || generateDjb2Hash;
let state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
let backupState: BuilderProgramState | undefined;
+ newProgram.getProgramBuildInfo = () => getProgramBuildInfo(state);
// To ensure that we arent storing any references to old program or new program without state
newProgram = undefined!; // TODO: GH#18217
@@ -556,7 +783,20 @@ namespace ts {
if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
affected = getNextAffectedFilePendingEmit(state);
if (!affected) {
- return undefined;
+ if (state.emittedBuildInfo) {
+ return undefined;
+ }
+
+ const affected = Debug.assertDefined(state.program);
+ return toAffectedFileResult(
+ state,
+ // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
+ // Otherwise just affected file
+ affected.emitBuildInfo(writeFile || host.writeFile, cancellationToken),
+ affected,
+ /*isPendingEmitFile*/ false,
+ /*isBuildInfoEmit*/ true
+ );
}
isPendingEmitFile = true;
}
@@ -712,6 +952,53 @@ namespace ts {
}
}
+ function getMapOfReferencedSet(mapLike: MapLike> | undefined): ReadonlyMap | undefined {
+ if (!mapLike) return undefined;
+ const map = createMap();
+ // Copies keys/values from template. Note that for..in will not throw if
+ // template is undefined, and instead will just exit the loop.
+ for (const key in mapLike) {
+ if (hasProperty(mapLike, key)) {
+ map.set(key, arrayToSet(mapLike[key]));
+ }
+ }
+ return map;
+ }
+
+ export function createBuildProgramUsingProgramBuildInfo(program: ProgramBuildInfo): EmitAndSemanticDiagnosticsBuilderProgram & SemanticDiagnosticsBuilderProgram {
+ const fileInfos = createMapFromTemplate(program.fileInfos);
+ const state: ReusableBuilderProgramState = {
+ fileInfos,
+ compilerOptions: program.options,
+ referencedMap: getMapOfReferencedSet(program.referencedMap),
+ exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap),
+ semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && arrayToMap(program.semanticDiagnosticsPerFile, value => isString(value) ? value : value[0], value => isString(value) ? emptyArray : value[1]),
+ hasReusableDiagnostic: true
+ };
+ return {
+ getState: () => state,
+ backupState: noop,
+ restoreState: noop,
+ getProgram: notImplemented,
+ getProgramOrUndefined: () => undefined,
+ releaseProgram: noop,
+ getCompilerOptions: () => state.compilerOptions,
+ getSourceFile: notImplemented,
+ getSourceFiles: notImplemented,
+ getOptionsDiagnostics: notImplemented,
+ getGlobalDiagnostics: notImplemented,
+ getConfigFileParsingDiagnostics: notImplemented,
+ getSyntacticDiagnostics: notImplemented,
+ getDeclarationDiagnostics: notImplemented,
+ getSemanticDiagnostics: notImplemented,
+ emit: notImplemented,
+ getAllDependencies: notImplemented,
+ getCurrentDirectory: notImplemented,
+ emitNextAffectedFile: notImplemented,
+ getSemanticDiagnosticsOfNextAffectedFile: notImplemented,
+ };
+ }
+
export function createRedirectedBuilderProgram(state: { program: Program | undefined; compilerOptions: CompilerOptions; }, configFileParsingDiagnostics: ReadonlyArray): BuilderProgram {
return {
getState: notImplemented,
@@ -731,7 +1018,7 @@ namespace ts {
getSemanticDiagnostics: (sourceFile, cancellationToken) => getProgram().getSemanticDiagnostics(sourceFile, cancellationToken),
emit: (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) => getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers),
getAllDependencies: notImplemented,
- getCurrentDirectory: () => getProgram().getCurrentDirectory()
+ getCurrentDirectory: () => getProgram().getCurrentDirectory(),
};
function getProgram() {
@@ -764,7 +1051,7 @@ namespace ts {
*/
export interface BuilderProgram {
/*@internal*/
- getState(): BuilderProgramState;
+ getState(): ReusableBuilderProgramState;
/*@internal*/
backupState(): void;
/*@internal*/
diff --git a/src/compiler/builderState.ts b/src/compiler/builderState.ts
index a394ff562013d..ff21d76ad8e76 100644
--- a/src/compiler/builderState.ts
+++ b/src/compiler/builderState.ts
@@ -25,6 +25,24 @@ namespace ts {
}
}
+ export interface ReusableBuilderState {
+ /**
+ * Information of the file eg. its version, signature etc
+ */
+ fileInfos: ReadonlyMap;
+ /**
+ * Contains the map of ReferencedSet=Referenced files of the file if module emit is enabled
+ * Otherwise undefined
+ * Thus non undefined value indicates, module emit
+ */
+ readonly referencedMap?: ReadonlyMap | undefined;
+ /**
+ * Contains the map of exported modules ReferencedSet=exported module files from the file if module emit is enabled
+ * Otherwise undefined
+ */
+ readonly exportedModulesMap?: ReadonlyMap | undefined;
+ }
+
export interface BuilderState {
/**
* Information of the file eg. its version, signature etc
@@ -196,14 +214,14 @@ namespace ts.BuilderState {
/**
* Returns true if oldState is reusable, that is the emitKind = module/non module has not changed
*/
- export function canReuseOldState(newReferencedMap: ReadonlyMap | undefined, oldState: Readonly | undefined) {
+ export function canReuseOldState(newReferencedMap: ReadonlyMap | undefined, oldState: Readonly | undefined) {
return oldState && !oldState.referencedMap === !newReferencedMap;
}
/**
* Creates the state of file references and signature for the new program from oldState if it is safe
*/
- export function create(newProgram: Program, getCanonicalFileName: GetCanonicalFileName, oldState?: Readonly): BuilderState {
+ export function create(newProgram: Program, getCanonicalFileName: GetCanonicalFileName, oldState?: Readonly): BuilderState {
const fileInfos = createMap();
const referencedMap = newProgram.getCompilerOptions().module !== ModuleKind.None ? createMap() : undefined;
const exportedModulesMap = referencedMap ? createMap() : undefined;
diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts
index e82c2895ad077..3c4b0577fb664 100644
--- a/src/compiler/commandLineParser.ts
+++ b/src/compiler/commandLineParser.ts
@@ -331,6 +331,22 @@ namespace ts {
category: Diagnostics.Basic_Options,
description: Diagnostics.Enable_project_compilation,
},
+ {
+ name: "incremental",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: Diagnostics.Basic_Options,
+ description: Diagnostics.Enable_incremental_compilation,
+ },
+ {
+ name: "tsBuildInfoFile",
+ type: "string",
+ isFilePath: true,
+ paramType: Diagnostics.FILE,
+ isTSConfigOnly: true,
+ category: Diagnostics.Basic_Options,
+ description: Diagnostics.Specify_file_to_store_incremental_compilation_information,
+ },
{
name: "removeComments",
type: "boolean",
@@ -1427,6 +1443,7 @@ namespace ts {
return _tsconfigRootOptions;
}
+ /*@internal*/
interface JsonConversionNotifier {
/**
* Notifies parent option object is being set with the optionKey and a valid optionValue
diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json
index 4bde97af3e7bf..53094bf188852 100644
--- a/src/compiler/diagnosticMessages.json
+++ b/src/compiler/diagnosticMessages.json
@@ -3936,7 +3936,6 @@
"category": "Message",
"code": 6353
},
-
"Project '{0}' is up to date with .d.ts files from its dependencies": {
"category": "Message",
"code": 6354
@@ -4009,6 +4008,46 @@
"category": "Message",
"code": 6371
},
+ "Project '{0}' is out of date because output of its dependency '{1}' has changed": {
+ "category": "Message",
+ "code": 6372
+ },
+ "Updating output of project '{0}'...": {
+ "category": "Message",
+ "code": 6373
+ },
+ "A non-dry build would update timestamps for output of project '{0}'": {
+ "category": "Message",
+ "code": 6374
+ },
+ "A non-dry build would update output of project '{0}'": {
+ "category": "Message",
+ "code": 6375
+ },
+ "Cannot update output of project '{0}' because there was error reading file '{1}'": {
+ "category": "Message",
+ "code": 6376
+ },
+ "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'": {
+ "category": "Error",
+ "code": 6377
+ },
+ "Enable incremental compilation": {
+ "category": "Message",
+ "code": 6378
+ },
+ "Composite projects may not disable incremental compilation.": {
+ "category": "Error",
+ "code": 6379
+ },
+ "Specify file to store incremental compilation information": {
+ "category": "Message",
+ "code": 6380
+ },
+ "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'": {
+ "category": "Message",
+ "code": 6381
+ },
"The expected type comes from property '{0}' which is declared here on type '{1}'": {
"category": "Message",
diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts
index 8baeae5d84a27..e55e768bab31f 100644
--- a/src/compiler/emitter.ts
+++ b/src/compiler/emitter.ts
@@ -1,8 +1,12 @@
namespace ts {
- const infoExtension = ".tsbundleinfo";
const brackets = createBracketsMap();
const syntheticParent: TextRange = { pos: -1, end: -1 };
+ /*@internal*/
+ export function isBuildInfoFile(file: string) {
+ return fileExtensionIs(file, Extension.TsBuildInfo);
+ }
+
/*@internal*/
/**
* Iterates over the source files that are expected to have an emit output.
@@ -14,14 +18,17 @@ namespace ts {
* Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
*/
export function forEachEmittedFile(
- host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFileOrBundle: SourceFile | Bundle) => T,
+ host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFileOrBundle: SourceFile | Bundle | undefined) => T,
sourceFilesOrTargetSourceFile?: ReadonlyArray | SourceFile,
- emitOnlyDtsFiles = false) {
+ emitOnlyDtsFiles = false,
+ onlyBuildInfo?: boolean,
+ includeBuildInfo?: boolean) {
const sourceFiles = isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile);
const options = host.getCompilerOptions();
if (options.outFile || options.out) {
- if (sourceFiles.length) {
- const bundle = createBundle(sourceFiles, host.getPrependNodes());
+ const prepends = host.getPrependNodes();
+ if (sourceFiles.length || prepends.length) {
+ const bundle = createBundle(sourceFiles, prepends);
const result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
if (result) {
return result;
@@ -29,15 +36,42 @@ namespace ts {
}
}
else {
- for (const sourceFile of sourceFiles) {
- const result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
- if (result) {
- return result;
+ if (!onlyBuildInfo) {
+ for (const sourceFile of sourceFiles) {
+ const result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile);
+ if (result) {
+ return result;
+ }
}
}
+ if (includeBuildInfo) {
+ const buildInfoPath = getOutputPathForBuildInfo(host.getCompilerOptions());
+ if (buildInfoPath) return action({ buildInfoPath }, /*sourceFileOrBundle*/ undefined);
+ }
}
}
+ /*@internal*/
+ export function getOutputPathForBuildInfo(options: CompilerOptions) {
+ const configFile = options.configFilePath;
+ if (!configFile || !isIncrementalCompilation(options)) return undefined;
+ if (options.tsBuildInfoFile) return options.tsBuildInfoFile;
+ const outPath = options.outFile || options.out;
+ let buildInfoExtensionLess: string;
+ if (outPath) {
+ buildInfoExtensionLess = removeFileExtension(outPath);
+ }
+ else {
+ const configFileExtensionLess = removeFileExtension(configFile);
+ buildInfoExtensionLess = options.outDir ?
+ options.rootDir ?
+ resolvePath(options.outDir, getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
+ combinePaths(options.outDir, getBaseFileName(configFileExtensionLess)) :
+ configFileExtensionLess;
+ }
+ return buildInfoExtensionLess + Extension.TsBuildInfo;
+ }
+
/*@internal*/
export function getOutputPathsForBundle(options: CompilerOptions, forceDtsPaths: boolean): EmitFileNames {
const outPath = options.outFile || options.out!;
@@ -45,8 +79,8 @@ namespace ts {
const sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
const declarationFilePath = (forceDtsPaths || getEmitDeclarations(options)) ? removeFileExtension(outPath) + Extension.Dts : undefined;
const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- const bundleInfoPath = options.references && jsFilePath ? (removeFileExtension(jsFilePath) + infoExtension) : undefined;
- return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, bundleInfoPath };
+ const buildInfoPath = getOutputPathForBuildInfo(options);
+ return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath };
}
/*@internal*/
@@ -66,7 +100,7 @@ namespace ts {
const isJs = isSourceFileJS(sourceFile);
const declarationFilePath = ((forceDtsPaths || getEmitDeclarations(options)) && !isJs) ? getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, bundleInfoPath: undefined };
+ return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath: undefined };
}
}
@@ -74,13 +108,6 @@ namespace ts {
return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
}
- function createDefaultBundleInfo(): BundleInfo {
- return {
- originalOffset: -1,
- totalLength: -1
- };
- }
-
// JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
// So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
// For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
@@ -106,7 +133,7 @@ namespace ts {
/*@internal*/
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
- export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile, emitOnlyDtsFiles?: boolean, transformers?: TransformerFactory[], declarationTransformers?: TransformerFactory[]): EmitResult {
+ export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile | undefined, emitOnlyDtsFiles?: boolean, transformers?: TransformerFactory[], declarationTransformers?: TransformerFactory[], onlyBuildInfo?: boolean): EmitResult {
const compilerOptions = host.getCompilerOptions();
const sourceMapDataList: SourceMapEmitResult[] | undefined = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
const emittedFilesList: string[] | undefined = compilerOptions.listEmittedFiles ? [] : undefined;
@@ -114,13 +141,13 @@ namespace ts {
const newLine = getNewLineCharacter(compilerOptions, () => host.getNewLine());
const writer = createTextWriter(newLine);
const { enter, exit } = performance.createTimer("printTime", "beforePrint", "afterPrint");
- let bundleInfo: BundleInfo = createDefaultBundleInfo();
+ let bundleBuildInfo: BundleBuildInfo | undefined;
let emitSkipped = false;
let exportedModulesFromDeclarationEmit: ExportedModulesFromDeclarationEmit | undefined;
// Emit each output file
enter();
- forEachEmittedFile(host, emitSourceFileOrBundle, getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles);
+ forEachEmittedFile(host, emitSourceFileOrBundle, getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles, onlyBuildInfo, !targetSourceFile);
exit();
@@ -132,9 +159,16 @@ namespace ts {
exportedModulesFromDeclarationEmit
};
- function emitSourceFileOrBundle({ jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, bundleInfoPath }: EmitFileNames, sourceFileOrBundle: SourceFile | Bundle) {
- emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
+ function emitSourceFileOrBundle({ jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath }: EmitFileNames, sourceFileOrBundle: SourceFile | Bundle | undefined) {
+ if (buildInfoPath && sourceFileOrBundle && isBundle(sourceFileOrBundle)) {
+ bundleBuildInfo = {
+ commonSourceDirectory: host.getCommonSourceDirectory(),
+ sourceFiles: sourceFileOrBundle.sourceFiles.map(file => file.fileName)
+ };
+ }
+ emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
+ emitBuildInfo(bundleBuildInfo, buildInfoPath);
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
@@ -144,8 +178,8 @@ namespace ts {
if (sourceMapFilePath) {
emittedFilesList.push(sourceMapFilePath);
}
- if (bundleInfoPath) {
- emittedFilesList.push(bundleInfoPath);
+ if (buildInfoPath) {
+ emittedFilesList.push(buildInfoPath);
}
}
if (declarationFilePath) {
@@ -157,8 +191,20 @@ namespace ts {
}
}
- function emitJsFileOrBundle(sourceFileOrBundle: SourceFile | Bundle, jsFilePath: string | undefined, sourceMapFilePath: string | undefined, bundleInfoPath: string | undefined) {
- if (emitOnlyDtsFiles || !jsFilePath) {
+ function emitBuildInfo(bundle: BundleBuildInfo | undefined, buildInfoPath: string | undefined) {
+ // Write build information if applicable
+ if (!buildInfoPath || targetSourceFile || emitSkipped) return;
+ const program = host.getProgramBuildInfo();
+ if (!bundle && !program) return;
+ if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
+ emitSkipped = true;
+ return;
+ }
+ writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle, program, version }), /*writeByteOrderMark*/ false);
+ }
+
+ function emitJsFileOrBundle(sourceFileOrBundle: SourceFile | Bundle | undefined, jsFilePath: string | undefined, sourceMapFilePath: string | undefined) {
+ if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
return;
}
@@ -180,6 +226,7 @@ namespace ts {
inlineSourceMap: compilerOptions.inlineSourceMap,
inlineSources: compilerOptions.inlineSources,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
+ writeBundleFileInfo: !!bundleBuildInfo
};
// Create a printer to print the nodes
@@ -193,14 +240,15 @@ namespace ts {
});
Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
- printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions);
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
// Clean up emit nodes on parse tree
transform.dispose();
+ if (bundleBuildInfo) bundleBuildInfo.js = printer.bundleFileInfo;
}
- function emitDeclarationFileOrBundle(sourceFileOrBundle: SourceFile | Bundle, declarationFilePath: string | undefined, declarationMapPath: string | undefined) {
- if (!(declarationFilePath && !isInJSFile(sourceFileOrBundle))) {
+ function emitDeclarationFileOrBundle(sourceFileOrBundle: SourceFile | Bundle | undefined, declarationFilePath: string | undefined, declarationMapPath: string | undefined) {
+ if (!sourceFileOrBundle || !(declarationFilePath && !isInJSFile(sourceFileOrBundle))) {
return;
}
const sourceFiles = isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
@@ -229,6 +277,8 @@ namespace ts {
inlineSourceMap: compilerOptions.inlineSourceMap,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
onlyPrintJsDocStyle: true,
+ writeBundleFileInfo: !!bundleBuildInfo,
+ recordInternalSection: !!bundleBuildInfo
};
const declarationPrinter = createPrinter(printerOptions, {
@@ -243,19 +293,26 @@ namespace ts {
emitSkipped = emitSkipped || declBlocked;
if (!declBlocked || emitOnlyDtsFiles) {
Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
- printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, {
- sourceMap: compilerOptions.declarationMap,
- sourceRoot: compilerOptions.sourceRoot,
- mapRoot: compilerOptions.mapRoot,
- extendedDiagnostics: compilerOptions.extendedDiagnostics,
- // Explicitly do not passthru either `inline` option
- });
+ printSourceFileOrBundle(
+ declarationFilePath,
+ declarationMapPath,
+ declarationTransform.transformed[0],
+ declarationPrinter,
+ {
+ sourceMap: compilerOptions.declarationMap,
+ sourceRoot: compilerOptions.sourceRoot,
+ mapRoot: compilerOptions.mapRoot,
+ extendedDiagnostics: compilerOptions.extendedDiagnostics,
+ // Explicitly do not passthru either `inline` option
+ }
+ );
if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === SyntaxKind.SourceFile) {
const sourceFile = declarationTransform.transformed[0] as SourceFile;
exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
}
}
declarationTransform.dispose();
+ if (bundleBuildInfo) bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
}
function collectLinkedAliases(node: Node) {
@@ -272,7 +329,7 @@ namespace ts {
forEachChild(node, collectLinkedAliases);
}
- function printSourceFileOrBundle(jsFilePath: string, sourceMapFilePath: string | undefined, sourceFileOrBundle: SourceFile | Bundle, bundleInfoPath: string | undefined, printer: Printer, mapOptions: SourceMapOptions) {
+ function printSourceFileOrBundle(jsFilePath: string, sourceMapFilePath: string | undefined, sourceFileOrBundle: SourceFile | Bundle, printer: Printer, mapOptions: SourceMapOptions) {
const bundle = sourceFileOrBundle.kind === SyntaxKind.Bundle ? sourceFileOrBundle : undefined;
const sourceFile = sourceFileOrBundle.kind === SyntaxKind.SourceFile ? sourceFileOrBundle : undefined;
const sourceFiles = bundle ? bundle.sourceFiles : [sourceFile!];
@@ -288,7 +345,7 @@ namespace ts {
}
if (bundle) {
- printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator);
+ printer.writeBundle(bundle, writer, sourceMapGenerator);
}
else {
printer.writeFile(sourceFile!, writer, sourceMapGenerator);
@@ -327,16 +384,8 @@ namespace ts {
// Write the output file
writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
- // Write bundled offset information if applicable
- if (bundleInfoPath) {
- bundleInfo.totalLength = writer.getTextPos();
- writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false);
- }
-
// Reset state
writer.clear();
-
- bundleInfo = createDefaultBundleInfo();
}
interface SourceMapOptions {
@@ -412,6 +461,182 @@ namespace ts {
}
}
+ /*@internal*/
+ export function getBuildInfoText(buildInfo: BuildInfo) {
+ return JSON.stringify(buildInfo, undefined, 2);
+ }
+
+ /*@internal*/
+ export function getBuildInfo(buildInfoText: string) {
+ return JSON.parse(buildInfoText) as BuildInfo;
+ }
+
+ /*@internal*/
+ export const notImplementedResolver: EmitResolver = {
+ hasGlobalName: notImplemented,
+ getReferencedExportContainer: notImplemented,
+ getReferencedImportDeclaration: notImplemented,
+ getReferencedDeclarationWithCollidingName: notImplemented,
+ isDeclarationWithCollidingName: notImplemented,
+ isValueAliasDeclaration: notImplemented,
+ isReferencedAliasDeclaration: notImplemented,
+ isTopLevelValueImportEqualsWithEntityName: notImplemented,
+ getNodeCheckFlags: notImplemented,
+ isDeclarationVisible: notImplemented,
+ isLateBound: (_node): _node is LateBoundDeclaration => false,
+ collectLinkedAliases: notImplemented,
+ isImplementationOfOverload: notImplemented,
+ isRequiredInitializedParameter: notImplemented,
+ isOptionalUninitializedParameterProperty: notImplemented,
+ isExpandoFunctionDeclaration: notImplemented,
+ getPropertiesOfContainerFunction: notImplemented,
+ createTypeOfDeclaration: notImplemented,
+ createReturnTypeOfSignatureDeclaration: notImplemented,
+ createTypeOfExpression: notImplemented,
+ createLiteralConstValue: notImplemented,
+ isSymbolAccessible: notImplemented,
+ isEntityNameVisible: notImplemented,
+ // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
+ getConstantValue: notImplemented,
+ getReferencedValueDeclaration: notImplemented,
+ getTypeReferenceSerializationKind: notImplemented,
+ isOptionalParameter: notImplemented,
+ moduleExportsSomeValue: notImplemented,
+ isArgumentsLocalBinding: notImplemented,
+ getExternalModuleFileFromDeclaration: notImplemented,
+ getTypeReferenceDirectivesForEntityName: notImplemented,
+ getTypeReferenceDirectivesForSymbol: notImplemented,
+ isLiteralConstDeclaration: notImplemented,
+ getJsxFactoryEntity: notImplemented,
+ getAllAccessorDeclarations: notImplemented,
+ getSymbolOfExternalModuleSpecifier: notImplemented,
+ isBindingCapturedByNode: notImplemented,
+ };
+
+ /*@internal*/
+ /** File that isnt present resulting in error or output files */
+ export type EmitUsingBuildInfoResult = string | ReadonlyArray;
+
+ /*@internal*/
+ export interface EmitUsingBuildInfoHost extends ModuleResolutionHost {
+ getCurrentDirectory(): string;
+ getCanonicalFileName(fileName: string): string;
+ useCaseSensitiveFileNames(): boolean;
+ getNewLine(): string;
+ }
+
+ function createSourceFilesFromBundleBuildInfo(bundle: BundleBuildInfo): ReadonlyArray {
+ const sourceFiles = bundle.sourceFiles.map(fileName => {
+ const sourceFile = createNode(SyntaxKind.SourceFile, 0, 0) as SourceFile;
+ sourceFile.fileName = fileName;
+ sourceFile.text = "";
+ sourceFile.statements = createNodeArray();
+ return sourceFile;
+ });
+ const jsBundle = Debug.assertDefined(bundle.js);
+ forEach(jsBundle.sources && jsBundle.sources.prologues, prologueInfo => {
+ const sourceFile = sourceFiles[prologueInfo.file];
+ sourceFile.text = prologueInfo.text;
+ sourceFile.end = prologueInfo.text.length;
+ sourceFile.statements = createNodeArray(prologueInfo.directives.map(directive => {
+ const statement = createNode(SyntaxKind.ExpressionStatement, directive.pos, directive.end) as PrologueDirective;
+ statement.expression = createNode(SyntaxKind.StringLiteral, directive.expression.pos, directive.expression.end) as StringLiteral;
+ statement.expression.text = directive.expression.text;
+ return statement;
+ }));
+ });
+ return sourceFiles;
+ }
+
+ /*@internal*/
+ export function emitUsingBuildInfo(config: ParsedCommandLine, host: EmitUsingBuildInfoHost, getCommandLine: (ref: ProjectReference) => ParsedCommandLine | undefined): EmitUsingBuildInfoResult {
+ const { buildInfoPath, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath } = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false);
+ const buildInfoText = host.readFile(Debug.assertDefined(buildInfoPath));
+ if (!buildInfoText) return buildInfoPath!;
+ const jsFileText = host.readFile(Debug.assertDefined(jsFilePath));
+ if (!jsFileText) return jsFilePath!;
+ const sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
+ // error if no source map or for now if inline sourcemap
+ if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap) return sourceMapFilePath || "inline sourcemap decoding";
+ // read declaration text
+ const declarationText = declarationFilePath && host.readFile(declarationFilePath);
+ if (declarationFilePath && !declarationText) return declarationFilePath;
+ const declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
+ // error if no source map or for now if inline sourcemap
+ if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap) return declarationMapPath || "inline sourcemap decoding";
+
+ const buildInfo = getBuildInfo(buildInfoText);
+ if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts)) return buildInfoPath!;
+ const ownPrependInput = createInputFiles(
+ jsFileText,
+ declarationText!,
+ sourceMapFilePath,
+ sourceMapText,
+ declarationMapPath,
+ declarationMapText,
+ jsFilePath,
+ declarationFilePath,
+ buildInfoPath,
+ buildInfo,
+ /*onlyOwnText*/ true
+ );
+ const outputFiles: OutputFile[] = [];
+ const prependNodes = createPrependNodes(config.projectReferences, getCommandLine, f => host.readFile(f));
+ const sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle);
+ const emitHost: EmitHost = {
+ getPrependNodes: memoize(() => [...prependNodes, ownPrependInput]),
+ getCanonicalFileName: host.getCanonicalFileName,
+ getCommonSourceDirectory: () => buildInfo.bundle!.commonSourceDirectory,
+ getCompilerOptions: () => config.options,
+ getCurrentDirectory: () => host.getCurrentDirectory(),
+ getNewLine: () => host.getNewLine(),
+ getSourceFile: () => undefined,
+ getSourceFileByPath: () => undefined,
+ getSourceFiles: () => sourceFilesForJsEmit,
+ getLibFileFromReference: notImplemented,
+ isSourceFileFromExternalLibrary: returnFalse,
+ writeFile: (name, text, writeByteOrderMark) => {
+ switch (name) {
+ case jsFilePath:
+ if (jsFileText === text) return;
+ break;
+ case sourceMapFilePath:
+ if (sourceMapText === text) return;
+ break;
+ case buildInfoPath:
+ const newBuildInfo = getBuildInfo(text);
+ newBuildInfo.program = buildInfo.program;
+ // Update sourceFileInfo
+ const { js, dts, sourceFiles } = buildInfo.bundle!;
+ newBuildInfo.bundle!.js!.sources = js!.sources;
+ if (dts) {
+ newBuildInfo.bundle!.dts!.sources = dts.sources;
+ }
+ newBuildInfo.bundle!.sourceFiles = sourceFiles;
+ outputFiles.push({ name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark });
+ return;
+ case declarationFilePath:
+ if (declarationText === text) return;
+ break;
+ case declarationMapPath:
+ if (declarationMapText === text) return;
+ break;
+ default:
+ Debug.fail(`Unexpected path: ${name}`);
+ }
+ outputFiles.push({ name, text, writeByteOrderMark });
+ },
+ isEmitBlocked: returnFalse,
+ readFile: f => host.readFile(f),
+ fileExists: f => host.fileExists(f),
+ directoryExists: host.directoryExists && (f => host.directoryExists!(f)),
+ useCaseSensitiveFileNames: () => host.useCaseSensitiveFileNames(),
+ getProgramBuildInfo: () => undefined
+ };
+ emitFiles(notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, /*emitOnlyDtsFiles*/ false, getTransformers(config.options));
+ return outputFiles;
+ }
+
const enum PipelinePhase {
Notification,
Substitution,
@@ -449,6 +674,10 @@ namespace ts {
let ownWriter: EmitTextWriter; // Reusable `EmitTextWriter` for basic printing.
let write = writeBase;
let isOwnFileEmit: boolean;
+ const bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } as BundleFileInfo : undefined;
+ const recordInternalSection = printerOptions.recordInternalSection;
+ let sourceFileTextPos = 0;
+ let sourceFileTextKind: BundleFileTextLikeKind = BundleFileSectionKind.Text;
// Source Maps
let sourceMapsDisabled = true;
@@ -478,7 +707,8 @@ namespace ts {
writeNode,
writeList,
writeFile,
- writeBundle
+ writeBundle,
+ bundleFileInfo
};
function printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string {
@@ -508,7 +738,7 @@ namespace ts {
}
function printBundle(bundle: Bundle): string {
- writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined);
+ writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
return endPrint();
}
@@ -546,7 +776,53 @@ namespace ts {
writer = previousWriter;
}
- function writeBundle(bundle: Bundle, bundleInfo: BundleInfo | undefined, output: EmitTextWriter, sourceMapGenerator: SourceMapGenerator | undefined) {
+ function getTextPosWithWriteLine() {
+ return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
+ }
+
+ function updateOrPushBundleFileTextLike(pos: number, end: number, kind: BundleFileTextLikeKind) {
+ const last = lastOrUndefined(bundleFileInfo!.sections);
+ if (last && last.kind === kind) {
+ last.end = end;
+ }
+ else {
+ bundleFileInfo!.sections.push({ pos, end, kind });
+ }
+ }
+
+ function recordBundleFileInternalSectionStart(node: Node) {
+ if (recordInternalSection &&
+ bundleFileInfo &&
+ currentSourceFile &&
+ (isDeclaration(node) || isVariableStatement(node)) &&
+ isInternalDeclaration(node, currentSourceFile) &&
+ sourceFileTextKind !== BundleFileSectionKind.Internal) {
+ const prevSourceFileTextKind = sourceFileTextKind;
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = BundleFileSectionKind.Internal;
+ return prevSourceFileTextKind;
+ }
+ return undefined;
+ }
+
+ function recordBundleFileInternalSectionEnd(prevSourceFileTextKind: ReturnType) {
+ if (prevSourceFileTextKind) {
+ recordBundleFileTextLikeSection(writer.getTextPos());
+ sourceFileTextPos = getTextPosWithWriteLine();
+ sourceFileTextKind = prevSourceFileTextKind;
+ }
+ }
+
+ function recordBundleFileTextLikeSection(end: number) {
+ if (sourceFileTextPos < end) {
+ updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
+ return true;
+ }
+ return false;
+ }
+
+ function writeBundle(bundle: Bundle, output: EmitTextWriter, sourceMapGenerator: SourceMapGenerator | undefined) {
isOwnFileEmit = false;
const previousWriter = writer;
setWriter(output, sourceMapGenerator);
@@ -557,16 +833,44 @@ namespace ts {
for (const prepend of bundle.prepends) {
writeLine();
+ const pos = writer.getTextPos();
+ const savedSections = bundleFileInfo && bundleFileInfo.sections;
+ if (savedSections) bundleFileInfo!.sections = [];
print(EmitHint.Unspecified, prepend, /*sourceFile*/ undefined);
+ if (bundleFileInfo) {
+ const newSections = bundleFileInfo.sections;
+ bundleFileInfo.sections = savedSections!;
+ if (prepend.oldFileOfCurrentEmit) bundleFileInfo.sections.push(...newSections);
+ else {
+ newSections.forEach(section => Debug.assert(isBundleFileTextLike(section)));
+ bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: BundleFileSectionKind.Prepend, data: (prepend as UnparsedSource).fileName, texts: newSections as BundleFileTextLike[] });
+ }
+ }
}
- if (bundleInfo) {
- bundleInfo.originalOffset = writer.getTextPos();
- }
-
+ sourceFileTextPos = getTextPosWithWriteLine();
for (const sourceFile of bundle.sourceFiles) {
print(EmitHint.SourceFile, sourceFile, sourceFile);
}
+ if (bundleFileInfo && bundle.sourceFiles.length) {
+ const end = writer.getTextPos();
+ if (recordBundleFileTextLikeSection(end)) {
+ // Store prologues
+ const prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
+ if (prologues) {
+ if (!bundleFileInfo.sources) bundleFileInfo.sources = {};
+ bundleFileInfo.sources.prologues = prologues;
+ }
+
+ // Store helpes
+ const helpers = getHelpersFromBundledSourceFiles(bundle);
+ if (helpers) {
+ if (!bundleFileInfo.sources) bundleFileInfo.sources = {};
+ bundleFileInfo.sources.helpers = helpers;
+ }
+ }
+ }
+
reset();
writer = previousWriter;
}
@@ -647,8 +951,10 @@ namespace ts {
function emit(node: Node | undefined) {
if (node === undefined) return;
+ const prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
const pipelinePhase = getPipelinePhase(PipelinePhase.Notification, node);
pipelinePhase(EmitHint.Unspecified, node);
+ recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
}
function emitIdentifierName(node: Identifier | undefined) {
@@ -725,7 +1031,19 @@ namespace ts {
return emitLiteral(node);
case SyntaxKind.UnparsedSource:
- return emitUnparsedSource(node);
+ case SyntaxKind.UnparsedPrepend:
+ return emitUnparsedSourceOrPrepend(node);
+
+ case SyntaxKind.UnparsedPrologue:
+ return writeUnparsedNode(node);
+
+ case SyntaxKind.UnparsedText:
+ case SyntaxKind.UnparsedInternalText:
+ return emitUnparsedTextLike(node);
+
+ case SyntaxKind.UnparsedSyntheticReference:
+ return emitUnparsedSyntheticReference(node);
+
// Identifiers
case SyntaxKind.Identifier:
@@ -1127,22 +1445,43 @@ namespace ts {
pipelinePhase(hint, substituteNode(hint, node));
}
+ function getHelpersFromBundledSourceFiles(bundle: Bundle): string[] | undefined {
+ let result: string[] | undefined;
+ if (moduleKind === ModuleKind.None || printerOptions.noEmitHelpers) {
+ return undefined;
+ }
+ const bundledHelpers = createMap();
+ for (const sourceFile of bundle.sourceFiles) {
+ const shouldSkip = getExternalHelpersModuleName(sourceFile) !== undefined;
+ const helpers = getSortedEmitHelpers(sourceFile);
+ if (!helpers) continue;
+ for (const helper of helpers) {
+ if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
+ bundledHelpers.set(helper.name, true);
+ (result || (result = [])).push(helper.name);
+ }
+ }
+ }
+
+ return result;
+ }
+
function emitHelpers(node: Node) {
let helpersEmitted = false;
const bundle = node.kind === SyntaxKind.Bundle ? node : undefined;
if (bundle && moduleKind === ModuleKind.None) {
return;
}
-
- const numNodes = bundle ? bundle.sourceFiles.length : 1;
+ const numPrepends = bundle ? bundle.prepends.length : 0;
+ const numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
for (let i = 0; i < numNodes; i++) {
- const currentNode = bundle ? bundle.sourceFiles[i] : node;
- const sourceFile = isSourceFile(currentNode) ? currentNode : currentSourceFile!;
- const shouldSkip = printerOptions.noEmitHelpers || getExternalHelpersModuleName(sourceFile) !== undefined;
- const shouldBundle = isSourceFile(currentNode) && !isOwnFileEmit;
- const helpers = getEmitHelpers(currentNode);
+ const currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
+ const sourceFile = isSourceFile(currentNode) ? currentNode : isUnparsedSource(currentNode) ? undefined : currentSourceFile!;
+ const shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && getExternalHelpersModuleName(sourceFile) !== undefined);
+ const shouldBundle = (isSourceFile(currentNode) || isUnparsedSource(currentNode)) && !isOwnFileEmit;
+ const helpers = isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
if (helpers) {
- for (const helper of stableSort(helpers, compareEmitHelpers)) {
+ for (const helper of helpers) {
if (!helper.scoped) {
// Skip the helper if it can be skipped and the noEmitHelpers compiler
// option is set, or if it can be imported and the importHelpers compiler
@@ -1163,13 +1502,14 @@ namespace ts {
// Skip the helper if it is scoped and we are emitting bundled helpers
continue;
}
-
+ const pos = getTextPosWithWriteLine();
if (typeof helper.text === "string") {
writeLines(helper.text);
}
else {
writeLines(helper.text(makeFileLevelOptimisticUniqueName));
}
+ if (bundleFileInfo) bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: BundleFileSectionKind.EmitHelpers, data: helper.name });
helpersEmitted = true;
}
}
@@ -1178,6 +1518,11 @@ namespace ts {
return helpersEmitted;
}
+ function getSortedEmitHelpers(node: Node) {
+ const helpers = getEmitHelpers(node);
+ return helpers && stableSort(helpers, compareEmitHelpers);
+ }
+
//
// Literals/Pseudo-literals
//
@@ -1207,8 +1552,48 @@ namespace ts {
}
// SyntaxKind.UnparsedSource
- function emitUnparsedSource(unparsed: UnparsedSource) {
- writer.rawWrite(unparsed.text);
+ // SyntaxKind.UnparsedPrepend
+ function emitUnparsedSourceOrPrepend(unparsed: UnparsedSource | UnparsedPrepend) {
+ for (const text of unparsed.texts) {
+ writeLine();
+ emit(text);
+ }
+ }
+
+ // SyntaxKind.UnparsedPrologue
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ // SyntaxKind.UnparsedSyntheticReference
+ function writeUnparsedNode(unparsed: UnparsedNode) {
+ writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
+ }
+
+ // SyntaxKind.UnparsedText
+ // SyntaxKind.UnparsedInternal
+ function emitUnparsedTextLike(unparsed: UnparsedTextLike) {
+ const pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ updateOrPushBundleFileTextLike(
+ pos,
+ writer.getTextPos(),
+ unparsed.kind === SyntaxKind.UnparsedText ?
+ BundleFileSectionKind.Text :
+ BundleFileSectionKind.Internal
+ );
+ }
+ }
+
+ // SyntaxKind.UnparsedSyntheticReference
+ function emitUnparsedSyntheticReference(unparsed: UnparsedSyntheticReference) {
+ const pos = getTextPosWithWriteLine();
+ writeUnparsedNode(unparsed);
+ if (bundleFileInfo) {
+ const section = clone(unparsed.section);
+ section.pos = pos;
+ section.end = writer.getTextPos();
+ bundleFileInfo.sections.push(section);
+ }
}
//
@@ -2294,7 +2679,7 @@ namespace ts {
function emitBlockFunctionBodyWorker(body: Block, emitBlockFunctionBodyOnSingleLine?: boolean) {
// Emit all the prologue directives (like "use strict").
- const statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true);
+ const statementOffset = emitPrologueDirectives(body.statements);
const pos = writer.getTextPos();
emitHelpers(body);
if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
@@ -2916,6 +3301,14 @@ namespace ts {
function emitSyntheticTripleSlashReferencesIfNeeded(node: Bundle) {
emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
+ for (const prepend of node.prepends) {
+ if (isUnparsedSource(prepend) && prepend.syntheticReferences) {
+ for (const ref of prepend.syntheticReferences) {
+ emit(ref);
+ writeLine();
+ }
+ }
+ }
}
function emitTripleSlashDirectivesIfNeeded(node: SourceFile) {
@@ -2924,7 +3317,9 @@ namespace ts {
function emitTripleSlashDirectives(hasNoDefaultLib: boolean, files: ReadonlyArray, types: ReadonlyArray, libs: ReadonlyArray) {
if (hasNoDefaultLib) {
+ const pos = writer.getTextPos();
writeComment(`/// `);
+ if (bundleFileInfo) bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: BundleFileSectionKind.NoDefaultLib });
writeLine();
}
if (currentSourceFile && currentSourceFile.moduleName) {
@@ -2943,15 +3338,21 @@ namespace ts {
}
}
for (const directive of files) {
+ const pos = writer.getTextPos();
writeComment(`/// `);
+ if (bundleFileInfo) bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: BundleFileSectionKind.Reference, data: directive.fileName });
writeLine();
}
for (const directive of types) {
+ const pos = writer.getTextPos();
writeComment(`/// `);
+ if (bundleFileInfo) bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: BundleFileSectionKind.Type, data: directive.fileName });
writeLine();
}
for (const directive of libs) {
+ const pos = writer.getTextPos();
writeComment(`/// `);
+ if (bundleFileInfo) bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: BundleFileSectionKind.Lib, data: directive.fileName });
writeLine();
}
}
@@ -2981,16 +3382,21 @@ namespace ts {
* Emits any prologue directives at the start of a Statement list, returning the
* number of prologue directives written to the output.
*/
- function emitPrologueDirectives(statements: ReadonlyArray, startWithNewLine?: boolean, seenPrologueDirectives?: Map): number {
+ function emitPrologueDirectives(statements: ReadonlyArray, sourceFile?: SourceFile, seenPrologueDirectives?: Map, recordBundleFileSection?: true): number {
+ let needsToSetSourceFile = !!sourceFile;
for (let i = 0; i < statements.length; i++) {
const statement = statements[i];
if (isPrologueDirective(statement)) {
const shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
if (shouldEmitPrologueDirective) {
- if (startWithNewLine || i > 0) {
- writeLine();
+ if (needsToSetSourceFile) {
+ needsToSetSourceFile = false;
+ setSourceFile(sourceFile!);
}
+ writeLine();
+ const pos = writer.getTextPos();
emit(statement);
+ if (recordBundleFileSection && bundleFileInfo) bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: BundleFileSectionKind.Prologue, data: statement.expression.text });
if (seenPrologueDirectives) {
seenPrologueDirectives.set(statement.expression.text, true);
}
@@ -3005,23 +3411,65 @@ namespace ts {
return statements.length;
}
+ function emitUnparsedPrologues(prologues: ReadonlyArray, seenPrologueDirectives: Map) {
+ for (const prologue of prologues) {
+ if (!seenPrologueDirectives.has(prologue.data)) {
+ writeLine();
+ const pos = writer.getTextPos();
+ emit(prologue);
+ if (bundleFileInfo) bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: BundleFileSectionKind.Prologue, data: prologue.data });
+ if (seenPrologueDirectives) {
+ seenPrologueDirectives.set(prologue.data, true);
+ }
+ }
+ }
+ }
+
function emitPrologueDirectivesIfNeeded(sourceFileOrBundle: Bundle | SourceFile) {
if (isSourceFile(sourceFileOrBundle)) {
- setSourceFile(sourceFileOrBundle);
- emitPrologueDirectives(sourceFileOrBundle.statements);
+ emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
}
else {
const seenPrologueDirectives = createMap();
+ for (const prepend of sourceFileOrBundle.prepends) {
+ emitUnparsedPrologues((prepend as UnparsedSource).prologues, seenPrologueDirectives);
+ }
for (const sourceFile of sourceFileOrBundle.sourceFiles) {
- setSourceFile(sourceFile);
- emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives);
+ emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
}
setSourceFile(undefined);
}
}
- function emitShebangIfNeeded(sourceFileOrBundle: Bundle | SourceFile) {
- if (isSourceFile(sourceFileOrBundle)) {
+ function getPrologueDirectivesFromBundledSourceFiles(bundle: Bundle): SourceFilePrologueInfo[] | undefined {
+ const seenPrologueDirectives = createMap();
+ let prologues: SourceFilePrologueInfo[] | undefined;
+ for (let index = 0; index < bundle.sourceFiles.length; index++) {
+ const sourceFile = bundle.sourceFiles[index];
+ let directives: SourceFilePrologueDirective[] | undefined;
+ let end = 0;
+ for (const statement of sourceFile.statements) {
+ if (!isPrologueDirective(statement)) break;
+ if (seenPrologueDirectives.has(statement.expression.text)) continue;
+ seenPrologueDirectives.set(statement.expression.text, true);
+ (directives || (directives = [])).push({
+ pos: statement.pos,
+ end: statement.end,
+ expression: {
+ pos: statement.expression.pos,
+ end: statement.expression.end,
+ text: statement.expression.text
+ }
+ });
+ end = end < statement.end ? statement.end : end;
+ }
+ if (directives) (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives });
+ }
+ return prologues;
+ }
+
+ function emitShebangIfNeeded(sourceFileOrBundle: Bundle | SourceFile | UnparsedSource) {
+ if (isSourceFile(sourceFileOrBundle) || isUnparsedSource(sourceFileOrBundle)) {
const shebang = getShebang(sourceFileOrBundle.text);
if (shebang) {
writeComment(shebang);
@@ -3030,10 +3478,16 @@ namespace ts {
}
}
else {
+ for (const prepend of sourceFileOrBundle.prepends) {
+ Debug.assertNode(prepend, isUnparsedSource);
+ if (emitShebangIfNeeded(prepend as UnparsedSource)) {
+ return true;
+ }
+ }
for (const sourceFile of sourceFileOrBundle.sourceFiles) {
// Emit only the first encountered shebang
if (emitShebangIfNeeded(sourceFile)) {
- break;
+ return true;
}
}
}
@@ -3260,6 +3714,7 @@ namespace ts {
// Emit each child.
let previousSibling: Node | undefined;
+ let previousSourceFileTextKind: ReturnType;
let shouldDecreaseIndentAfterEmit = false;
for (let i = 0; i < count; i++) {
const child = children![start + i];
@@ -3281,6 +3736,7 @@ namespace ts {
emitLeadingCommentsOfPosition(previousSibling.end);
}
writeDelimiter(format);
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
// Write either a line terminator or whitespace to separate the elements.
if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) {
@@ -3300,6 +3756,7 @@ namespace ts {
}
// Emit this child.
+ previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
if (shouldEmitInterveningComments) {
if (emitTrailingCommentsOfPosition) {
const commentRange = getCommentRange(child);
@@ -3342,6 +3799,8 @@ namespace ts {
decreaseIndent();
}
+ recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
+
// Write the closing line terminator or closing whitespace.
if (shouldWriteClosingLineTerminator(parentNode, children!, format)) {
writeLine();
@@ -3467,7 +3926,6 @@ namespace ts {
if (line.length) {
writeLine();
write(line);
- writer.rawWrite(newLine);
}
}
}
@@ -4337,16 +4795,29 @@ namespace ts {
// Source Maps
+ function getParsedSourceMap(node: UnparsedSource) {
+ if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
+ node.parsedSourceMap = tryParseRawSourceMap(node.sourceMapText) || false;
+ }
+ return node.parsedSourceMap || undefined;
+ }
+
function pipelineEmitWithSourceMap(hint: EmitHint, node: Node) {
const pipelinePhase = getNextPipelinePhase(PipelinePhase.SourceMaps, node);
- if (isUnparsedSource(node) && node.sourceMapText !== undefined) {
- const parsed = tryParseRawSourceMap(node.sourceMapText);
- if (parsed) {
- sourceMapGenerator!.appendSourceMap(
+ if (isUnparsedSource(node) || isUnparsedPrepend(node)) {
+ pipelinePhase(hint, node);
+ }
+ else if (isUnparsedNode(node)) {
+ const parsed = getParsedSourceMap(node.parent);
+ if (parsed && sourceMapGenerator) {
+ sourceMapGenerator.appendSourceMap(
writer.getLine(),
writer.getColumn(),
parsed,
- node.sourceMapPath!);
+ node.parent.sourceMapPath!,
+ node.parent.getLineAndCharacterOfPosition(node.pos),
+ node.parent.getLineAndCharacterOfPosition(node.end)
+ );
}
pipelinePhase(hint, node);
}
diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts
index f303dcb47a637..a3bffb785a8fc 100644
--- a/src/compiler/factory.ts
+++ b/src/compiler/factory.ts
@@ -143,8 +143,8 @@ namespace ts {
export function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; // tslint:disable-line unified-signatures
export function updateIdentifier(node: Identifier, typeArguments?: NodeArray | undefined): Identifier {
return node.typeArguments !== typeArguments
- ? updateNode(createIdentifier(idText(node), typeArguments), node)
- : node;
+ ? updateNode(createIdentifier(idText(node), typeArguments), node)
+ : node;
}
let nextAutoGenerateId = 0;
@@ -2629,27 +2629,204 @@ namespace ts {
return node;
}
+ let allUnscopedEmitHelpers: ReadonlyMap | undefined;
+ function getAllUnscopedEmitHelpers() {
+ return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = arrayToMap([
+ valuesHelper,
+ readHelper,
+ spreadHelper,
+ restHelper,
+ decorateHelper,
+ metadataHelper,
+ paramHelper,
+ awaiterHelper,
+ assignHelper,
+ awaitHelper,
+ asyncGeneratorHelper,
+ asyncDelegator,
+ asyncValues,
+ extendsHelper,
+ templateObjectHelper,
+ generatorHelper,
+ importStarHelper,
+ importDefaultHelper
+ ], helper => helper.name));
+ }
+
+ function createUnparsedSource() {
+ const node = createNode(SyntaxKind.UnparsedSource);
+ node.prologues = emptyArray;
+ node.referencedFiles = emptyArray;
+ node.libReferenceDirectives = emptyArray;
+ node.getLineAndCharacterOfPosition = pos => getLineAndCharacterOfPosition(node, pos);
+ return node;
+ }
+
export function createUnparsedSourceFile(text: string): UnparsedSource;
- export function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts"): UnparsedSource;
+ export function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts", stripInternal?: boolean): UnparsedSource;
export function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource;
- export function createUnparsedSourceFile(textOrInputFiles: string | InputFiles, mapPathOrType?: string, map?: string): UnparsedSource {
- const node = createNode(SyntaxKind.UnparsedSource);
+ export function createUnparsedSourceFile(textOrInputFiles: string | InputFiles, mapPathOrType?: string, mapTextOrStripInternal?: string | boolean): UnparsedSource {
+ const node = createUnparsedSource();
+ let stripInternal: boolean | undefined;
+ let bundleFileInfo: BundleFileInfo | undefined;
if (!isString(textOrInputFiles)) {
Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
- node.fileName = mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath;
+ node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
Object.defineProperties(node, {
text: { get() { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
sourceMapText: { get() { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
});
+
+
+ if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
+ node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
+ Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
+ stripInternal = mapTextOrStripInternal as boolean | undefined;
+ bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
+ if (node.oldFileOfCurrentEmit) {
+ parseOldFileOfCurrentEmit(node, Debug.assertDefined(bundleFileInfo));
+ return node;
+ }
+ }
}
else {
+ node.fileName = "";
node.text = textOrInputFiles;
node.sourceMapPath = mapPathOrType;
- node.sourceMapText = map;
+ node.sourceMapText = mapTextOrStripInternal as string;
+ }
+ Debug.assert(!node.oldFileOfCurrentEmit);
+ parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
+ return node;
+ }
+
+ function parseUnparsedSourceFile(node: UnparsedSource, bundleFileInfo: BundleFileInfo | undefined, stripInternal: boolean | undefined) {
+ let prologues: UnparsedPrologue[] | undefined;
+ let helpers: UnscopedEmitHelper[] | undefined;
+ let referencedFiles: FileReference[] | undefined;
+ let typeReferenceDirectives: string[] | undefined;
+ let libReferenceDirectives: FileReference[] | undefined;
+ let texts: UnparsedSourceText[] | undefined;
+
+ for (const section of bundleFileInfo ? bundleFileInfo.sections : emptyArray) {
+ switch (section.kind) {
+ case BundleFileSectionKind.Prologue:
+ (prologues || (prologues = [])).push(createUnparsedNode(section, node) as UnparsedPrologue);
+ break;
+ case BundleFileSectionKind.EmitHelpers:
+ (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data)!);
+ break;
+ case BundleFileSectionKind.NoDefaultLib:
+ node.hasNoDefaultLib = true;
+ break;
+ case BundleFileSectionKind.Reference:
+ (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case BundleFileSectionKind.Type:
+ (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
+ break;
+ case BundleFileSectionKind.Lib:
+ (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
+ break;
+ case BundleFileSectionKind.Prepend:
+ const prependNode = createUnparsedNode(section, node) as UnparsedPrepend;
+ let prependTexts: UnparsedTextLike[] | undefined;
+ for (const text of section.texts) {
+ if (!stripInternal || text.kind !== BundleFileSectionKind.Internal) {
+ (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node) as UnparsedTextLike);
+ }
+ }
+ prependNode.texts = prependTexts || emptyArray;
+ (texts || (texts = [])).push(prependNode);
+ break;
+ case BundleFileSectionKind.Internal:
+ if (stripInternal) break;
+ // falls through
+ case BundleFileSectionKind.Text:
+ (texts || (texts = [])).push(createUnparsedNode(section, node) as UnparsedTextLike);
+ break;
+ default:
+ Debug.assertNever(section);
+ }
+ }
+
+ node.prologues = prologues || emptyArray;
+ node.helpers = helpers;
+ node.referencedFiles = referencedFiles || emptyArray;
+ node.typeReferenceDirectives = typeReferenceDirectives;
+ node.libReferenceDirectives = libReferenceDirectives || emptyArray;
+ node.texts = texts || [createUnparsedNode({ kind: BundleFileSectionKind.Text, pos: 0, end: node.text.length }, node)];
+ }
+
+ function parseOldFileOfCurrentEmit(node: UnparsedSource, bundleFileInfo: BundleFileInfo) {
+ Debug.assert(!!node.oldFileOfCurrentEmit);
+ let texts: UnparsedTextLike[] | undefined;
+ let syntheticReferences: UnparsedSyntheticReference[] | undefined;
+ for (const section of bundleFileInfo.sections) {
+ switch (section.kind) {
+ case BundleFileSectionKind.Internal:
+ case BundleFileSectionKind.Text:
+ (texts || (texts = [])).push(createUnparsedNode(section, node) as UnparsedTextLike);
+ break;
+
+ case BundleFileSectionKind.NoDefaultLib:
+ case BundleFileSectionKind.Reference:
+ case BundleFileSectionKind.Type:
+ case BundleFileSectionKind.Lib:
+ (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
+ break;
+
+ // Ignore
+ case BundleFileSectionKind.Prologue:
+ case BundleFileSectionKind.EmitHelpers:
+ case BundleFileSectionKind.Prepend:
+ break;
+
+ default:
+ Debug.assertNever(section);
+ }
}
+ node.texts = texts || emptyArray;
+ node.helpers = map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, name => getAllUnscopedEmitHelpers().get(name)!);
+ node.syntheticReferences = syntheticReferences;
+ return node;
+ }
+
+ function mapBundleFileSectionKindToSyntaxKind(kind: BundleFileSectionKind): SyntaxKind {
+ switch (kind) {
+ case BundleFileSectionKind.Prologue: return SyntaxKind.UnparsedPrologue;
+ case BundleFileSectionKind.Prepend: return SyntaxKind.UnparsedPrepend;
+ case BundleFileSectionKind.Internal: return SyntaxKind.UnparsedInternalText;
+ case BundleFileSectionKind.Text: return SyntaxKind.UnparsedText;
+
+ case BundleFileSectionKind.EmitHelpers:
+ case BundleFileSectionKind.NoDefaultLib:
+ case BundleFileSectionKind.Reference:
+ case BundleFileSectionKind.Type:
+ case BundleFileSectionKind.Lib:
+ return Debug.fail(`BundleFileSectionKind: ${kind} not yet mapped to SyntaxKind`);
+
+ default:
+ return Debug.assertNever(kind);
+ }
+ }
+
+ function createUnparsedNode(section: BundleFileSection, parent: UnparsedSource): UnparsedNode {
+ const node = createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end) as UnparsedNode;
+ node.parent = parent;
+ node.data = section.data;
return node;
}
+
+ function createUnparsedSyntheticReference(section: BundleFileHasNoDefaultLib | BundleFileReference, parent: UnparsedSource) {
+ const node = createNode(SyntaxKind.UnparsedSyntheticReference, section.pos, section.end) as UnparsedSyntheticReference;
+ node.parent = parent;
+ node.data = section.data;
+ node.section = section;
+ return node;
+ }
+
export function createInputFiles(
javascriptText: string,
declarationText: string
@@ -2660,6 +2837,7 @@ namespace ts {
javascriptMapPath: string | undefined,
declarationPath: string,
declarationMapPath: string | undefined,
+ buildInfoPath: string | undefined
): InputFiles;
export function createInputFiles(
javascriptText: string,
@@ -2669,13 +2847,32 @@ namespace ts {
declarationMapPath: string | undefined,
declarationMapText: string | undefined
): InputFiles;
+ /*@internal*/
+ export function createInputFiles(
+ javascriptText: string,
+ declarationText: string,
+ javascriptMapPath: string | undefined,
+ javascriptMapText: string | undefined,
+ declarationMapPath: string | undefined,
+ declarationMapText: string | undefined,
+ javascriptPath: string | undefined,
+ declarationPath: string | undefined,
+ buildInfoPath?: string | undefined,
+ buildInfo?: BuildInfo,
+ oldFileOfCurrentEmit?: boolean
+ ): InputFiles;
export function createInputFiles(
javascriptTextOrReadFileText: string | ((path: string) => string | undefined),
declarationTextOrJavascriptPath: string,
javascriptMapPath?: string,
javascriptMapTextOrDeclarationPath?: string,
declarationMapPath?: string,
- declarationMapText?: string
+ declarationMapTextOrBuildInfoPath?: string,
+ javascriptPath?: string | undefined,
+ declarationPath?: string | undefined,
+ buildInfoPath?: string | undefined,
+ buildInfo?: BuildInfo,
+ oldFileOfCurrentEmit?: boolean
): InputFiles {
const node = createNode(SyntaxKind.InputFiles);
if (!isString(javascriptTextOrReadFileText)) {
@@ -2693,15 +2890,25 @@ namespace ts {
const result = textGetter(path);
return result !== undefined ? result : `/* Input file ${path} was missing */\r\n`;
};
+ let buildInfo: BuildInfo | false;
+ const getAndCacheBuildInfo = (getText: () => string | undefined) => {
+ if (buildInfo === undefined) {
+ const result = getText();
+ buildInfo = result !== undefined ? getBuildInfo(result) : false;
+ }
+ return buildInfo || undefined;
+ };
node.javascriptPath = declarationTextOrJavascriptPath;
node.javascriptMapPath = javascriptMapPath;
node.declarationPath = Debug.assertDefined(javascriptMapTextOrDeclarationPath);
node.declarationMapPath = declarationMapPath;
+ node.buildInfoPath = declarationMapTextOrBuildInfoPath;
Object.defineProperties(node, {
javascriptText: { get() { return definedTextGetter(declarationTextOrJavascriptPath); } },
javascriptMapText: { get() { return textGetter(javascriptMapPath); } }, // TODO:: if there is inline sourceMap in jsFile, use that
declarationText: { get() { return definedTextGetter(Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
- declarationMapText: { get() { return textGetter(declarationMapPath); } } // TODO:: if there is inline sourceMap in dtsFile, use that
+ declarationMapText: { get() { return textGetter(declarationMapPath); } }, // TODO:: if there is inline sourceMap in dtsFile, use that
+ buildInfo: { get() { return getAndCacheBuildInfo(() => textGetter(declarationMapTextOrBuildInfoPath)); } }
});
}
else {
@@ -2710,7 +2917,12 @@ namespace ts {
node.javascriptMapText = javascriptMapTextOrDeclarationPath;
node.declarationText = declarationTextOrJavascriptPath;
node.declarationMapPath = declarationMapPath;
- node.declarationMapText = declarationMapText;
+ node.declarationMapText = declarationMapTextOrBuildInfoPath;
+ node.javascriptPath = javascriptPath;
+ node.declarationPath = declarationPath,
+ node.buildInfoPath = buildInfoPath;
+ node.buildInfo = buildInfo;
+ node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
}
return node;
}
@@ -3372,7 +3584,7 @@ namespace ts {
return setEmitFlags(createIdentifier(name), EmitFlags.HelperName | EmitFlags.AdviseOnEmitNode);
}
- const valuesHelper: EmitHelper = {
+ export const valuesHelper: UnscopedEmitHelper = {
name: "typescript:values",
scoped: false,
text: `
@@ -3400,7 +3612,7 @@ namespace ts {
);
}
- const readHelper: EmitHelper = {
+ export const readHelper: UnscopedEmitHelper = {
name: "typescript:read",
scoped: false,
text: `
@@ -3436,7 +3648,7 @@ namespace ts {
);
}
- const spreadHelper: EmitHelper = {
+ export const spreadHelper: UnscopedEmitHelper = {
name: "typescript:spread",
scoped: false,
text: `
diff --git a/src/compiler/moduleSpecifiers.ts b/src/compiler/moduleSpecifiers.ts
index f5bac45f6abaa..59bb74a22c172 100644
--- a/src/compiler/moduleSpecifiers.ts
+++ b/src/compiler/moduleSpecifiers.ts
@@ -437,6 +437,8 @@ namespace ts.moduleSpecifiers {
case Extension.Jsx:
case Extension.Json:
return ext;
+ case Extension.TsBuildInfo:
+ return Debug.fail(`Extension ${Extension.TsBuildInfo} is unsupported:: FileName:: ${fileName}`);
default:
return Debug.assertNever(ext);
}
diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts
index 4aec4f5962bde..1564b78ca61d2 100644
--- a/src/compiler/parser.ts
+++ b/src/compiler/parser.ts
@@ -7762,6 +7762,7 @@ namespace ts {
}
}
+ /*@internal*/
type PragmaDiagnosticReporter = (pos: number, length: number, message: DiagnosticMessage) => void;
/*@internal*/
diff --git a/src/compiler/program.ts b/src/compiler/program.ts
index 280f46fa445a2..6801a8fa3aa79 100644
--- a/src/compiler/program.ts
+++ b/src/compiler/program.ts
@@ -203,6 +203,7 @@ namespace ts {
return compilerHost;
}
+ /*@internal*/
interface CompilerHostLikeForCache {
fileExists(fileName: string): boolean;
readFile(fileName: string, encoding?: string): string | undefined;
@@ -242,7 +243,8 @@ namespace ts {
const key = toPath(fileName);
const value = readFileCache.get(key);
if (value !== undefined) return value !== false ? value : undefined; // could be .d.ts from output
- if (!fileExtensionIs(fileName, Extension.Json)) {
+ // Cache json or buildInfo
+ if (!fileExtensionIs(fileName, Extension.Json) && !isBuildInfoFile(fileName)) {
return originalReadFile.call(host, fileName);
}
@@ -276,7 +278,7 @@ namespace ts {
fileExistsCache.delete(key);
const value = readFileCache.get(key);
- if (value && value !== data) {
+ if (value !== undefined && value !== data) {
readFileCache.delete(key);
sourceFileCache.delete(key);
}
@@ -937,7 +939,8 @@ namespace ts {
getProjectReferenceRedirect,
getResolvedProjectReferenceToRedirect,
getResolvedProjectReferenceByPath,
- forEachResolvedProjectReference
+ forEachResolvedProjectReference,
+ emitBuildInfo
};
verifyCompilerOptions();
@@ -1431,9 +1434,28 @@ namespace ts {
},
...(host.directoryExists ? { directoryExists: f => host.directoryExists!(f) } : {}),
useCaseSensitiveFileNames: () => host.useCaseSensitiveFileNames(),
+ getProgramBuildInfo: () => program.getProgramBuildInfo && program.getProgramBuildInfo()
};
}
+ function emitBuildInfo(writeFileCallback?: WriteFileCallback): EmitResult {
+ Debug.assert(!options.out && !options.outFile);
+ performance.mark("beforeEmit");
+ const emitResult = emitFiles(
+ notImplementedResolver,
+ getEmitHost(writeFileCallback),
+ /*targetSourceFile*/ undefined,
+ /*emitOnlyDtsFiles*/ false,
+ /*transformers*/ undefined,
+ /*declaraitonTransformers*/ undefined,
+ /*onlyBuildInfo*/ true
+ );
+
+ performance.mark("afterEmit");
+ performance.measure("Emit", "beforeEmit", "afterEmit");
+ return emitResult;
+ }
+
function getResolvedProjectReferences() {
return resolvedProjectReferences;
}
@@ -1442,30 +1464,16 @@ namespace ts {
return projectReferences;
}
- function getPrependNodes(): InputFiles[] {
- if (!projectReferences) {
- return emptyArray;
- }
-
- const nodes: InputFiles[] = [];
- for (let i = 0; i < projectReferences.length; i++) {
- const ref = projectReferences[i];
- const resolvedRefOpts = resolvedProjectReferences![i]!.commandLine;
- if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
- const out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
- // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
- if (!out) continue;
-
- const { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath } = getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true);
- const node = createInputFiles(fileName => {
- const path = toPath(fileName);
- const sourceFile = getSourceFileByPath(path);
- return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
- }, jsFilePath! , sourceMapFilePath, declarationFilePath! , declarationMapPath);
- nodes.push(node);
+ function getPrependNodes() {
+ return createPrependNodes(
+ projectReferences,
+ (_ref, index) => resolvedProjectReferences![index]!.commandLine,
+ fileName => {
+ const path = toPath(fileName);
+ const sourceFile = getSourceFileByPath(path);
+ return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
}
- }
- return nodes;
+ );
}
function isSourceFileFromExternalLibrary(file: SourceFile): boolean {
@@ -1562,7 +1570,7 @@ namespace ts {
const emitResult = emitFiles(
emitResolver,
getEmitHost(writeFileCallback),
- sourceFile!, // TODO: GH#18217
+ sourceFile,
emitOnlyDtsFiles,
transformers,
customTransformers && customTransformers.afterDeclarations
@@ -2712,6 +2720,15 @@ namespace ts {
if (options.declaration === false) {
createDiagnosticForOptionName(Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
}
+ if (options.incremental === false) {
+ createDiagnosticForOptionName(Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
+ }
+ }
+
+ if (options.tsBuildInfoFile) {
+ if (!isIncrementalCompilation(options)) {
+ createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
+ }
}
verifyProjectReferences();
@@ -2933,6 +2950,7 @@ namespace ts {
}
function verifyProjectReferences() {
+ const buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? getOutputPathForBuildInfo(options) : undefined;
forEachProjectReference(projectReferences, resolvedProjectReferences, (resolvedRef, index, parent) => {
const ref = (parent ? parent.commandLine.projectReferences : projectReferences)![index];
const parentFile = parent && parent.sourceFile as JsonSourceFile;
@@ -2959,6 +2977,10 @@ namespace ts {
createDiagnosticForReference(parentFile, index, Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
}
}
+ if (!parent && buildInfoPath && buildInfoPath === getOutputPathForBuildInfo(options)) {
+ createDiagnosticForReference(parentFile, index, Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
+ hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
+ }
});
}
@@ -3109,6 +3131,7 @@ namespace ts {
}
}
+ /*@internal*/
interface CompilerHostLike {
useCaseSensitiveFileNames(): boolean;
getCurrentDirectory(): string;
@@ -3140,6 +3163,25 @@ namespace ts {
fileExists(fileName: string): boolean;
}
+ /* @internal */
+ export function createPrependNodes(projectReferences: ReadonlyArray | undefined, getCommandLine: (ref: ProjectReference, index: number) => ParsedCommandLine | undefined, readFile: (path: string) => string | undefined) {
+ if (!projectReferences) return emptyArray;
+ let nodes: InputFiles[] | undefined;
+ for (let i = 0; i < projectReferences.length; i++) {
+ const ref = projectReferences[i];
+ const resolvedRefOpts = getCommandLine(ref, i);
+ if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
+ const out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
+ // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
+ if (!out) continue;
+
+ const { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath } = getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true);
+ const node = createInputFiles(readFile, jsFilePath!, sourceMapFilePath, declarationFilePath!, declarationMapPath, buildInfoPath);
+ (nodes || (nodes = [])).push(node);
+ }
+ }
+ return nodes || emptyArray;
+ }
/**
* Returns the target config filename of a project reference.
* Note: The file might not exist.
diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts
index d0ecc1298567e..5af23cf084fc4 100644
--- a/src/compiler/scanner.ts
+++ b/src/compiler/scanner.ts
@@ -623,13 +623,15 @@ namespace ts {
const shebangTriviaRegex = /^#!.*/;
- function isShebangTrivia(text: string, pos: number) {
+ /*@internal*/
+ export function isShebangTrivia(text: string, pos: number) {
// Shebangs check must only be done at the start of the file
Debug.assert(pos === 0);
return shebangTriviaRegex.test(text);
}
- function scanShebangTrivia(text: string, pos: number) {
+ /*@internal*/
+ export function scanShebangTrivia(text: string, pos: number) {
const shebang = shebangTriviaRegex.exec(text)![0];
pos = pos + shebang.length;
return pos;
diff --git a/src/compiler/sourcemap.ts b/src/compiler/sourcemap.ts
index c2597d688d8f3..b33536bab2a5e 100644
--- a/src/compiler/sourcemap.ts
+++ b/src/compiler/sourcemap.ts
@@ -140,7 +140,7 @@ namespace ts {
exit();
}
- function appendSourceMap(generatedLine: number, generatedCharacter: number, map: RawSourceMap, sourceMapPath: string) {
+ function appendSourceMap(generatedLine: number, generatedCharacter: number, map: RawSourceMap, sourceMapPath: string, start?: LineAndCharacter, end?: LineAndCharacter) {
Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
enter();
@@ -149,6 +149,17 @@ namespace ts {
let nameIndexToNewNameIndexMap: number[] | undefined;
const mappingIterator = decodeMappings(map.mappings);
for (let { value: raw, done } = mappingIterator.next(); !done; { value: raw, done } = mappingIterator.next()) {
+ if (end && (
+ raw.generatedLine > end.line ||
+ (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
+ break;
+ }
+
+ if (start && (
+ raw.generatedLine < start.line ||
+ (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
+ continue;
+ }
// Then reencode all the updated mappings into the overall map
let newSourceIndex: number | undefined;
let newSourceLine: number | undefined;
@@ -178,8 +189,10 @@ namespace ts {
}
}
- const newGeneratedLine = raw.generatedLine + generatedLine;
- const newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter;
+ const rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
+ const newGeneratedLine = rawGeneratedLine + generatedLine;
+ const rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
+ const newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
}
exit();
diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts
index f38d0ae506c22..f5ae4928de625 100644
--- a/src/compiler/sys.ts
+++ b/src/compiler/sys.ts
@@ -469,6 +469,66 @@ namespace ts {
}
}
+ /*@internal*/
+ interface NodeBuffer extends Uint8Array {
+ write(str: string, offset?: number, length?: number, encoding?: string): number;
+ toString(encoding?: string, start?: number, end?: number): string;
+ toJSON(): { type: "Buffer", data: any[] };
+ equals(otherBuffer: Buffer): boolean;
+ compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number;
+ copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
+ slice(start?: number, end?: number): Buffer;
+ writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
+ writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
+ writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
+ writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
+ readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
+ readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
+ readIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
+ readIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
+ readUInt8(offset: number, noAssert?: boolean): number;
+ readUInt16LE(offset: number, noAssert?: boolean): number;
+ readUInt16BE(offset: number, noAssert?: boolean): number;
+ readUInt32LE(offset: number, noAssert?: boolean): number;
+ readUInt32BE(offset: number, noAssert?: boolean): number;
+ readInt8(offset: number, noAssert?: boolean): number;
+ readInt16LE(offset: number, noAssert?: boolean): number;
+ readInt16BE(offset: number, noAssert?: boolean): number;
+ readInt32LE(offset: number, noAssert?: boolean): number;
+ readInt32BE(offset: number, noAssert?: boolean): number;
+ readFloatLE(offset: number, noAssert?: boolean): number;
+ readFloatBE(offset: number, noAssert?: boolean): number;
+ readDoubleLE(offset: number, noAssert?: boolean): number;
+ readDoubleBE(offset: number, noAssert?: boolean): number;
+ swap16(): Buffer;
+ swap32(): Buffer;
+ swap64(): Buffer;
+ writeUInt8(value: number, offset: number, noAssert?: boolean): number;
+ writeUInt16LE(value: number, offset: number, noAssert?: boolean): number;
+ writeUInt16BE(value: number, offset: number, noAssert?: boolean): number;
+ writeUInt32LE(value: number, offset: number, noAssert?: boolean): number;
+ writeUInt32BE(value: number, offset: number, noAssert?: boolean): number;
+ writeInt8(value: number, offset: number, noAssert?: boolean): number;
+ writeInt16LE(value: number, offset: number, noAssert?: boolean): number;
+ writeInt16BE(value: number, offset: number, noAssert?: boolean): number;
+ writeInt32LE(value: number, offset: number, noAssert?: boolean): number;
+ writeInt32BE(value: number, offset: number, noAssert?: boolean): number;
+ writeFloatLE(value: number, offset: number, noAssert?: boolean): number;
+ writeFloatBE(value: number, offset: number, noAssert?: boolean): number;
+ writeDoubleLE(value: number, offset: number, noAssert?: boolean): number;
+ writeDoubleBE(value: number, offset: number, noAssert?: boolean): number;
+ fill(value: any, offset?: number, end?: number): this;
+ indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
+ lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
+ entries(): IterableIterator<[number, number]>;
+ includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean;
+ keys(): IterableIterator;
+ values(): IterableIterator;
+ }
+
+ /*@internal*/
+ interface Buffer extends NodeBuffer { }
+
// TODO: GH#18217 Methods on System are often used as if they are certainly defined
export interface System {
args: string[];
diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts
index 63c340d81dc8a..1f88bfb9e4f34 100644
--- a/src/compiler/transformers/declarations.ts
+++ b/src/compiler/transformers/declarations.ts
@@ -9,6 +9,15 @@ namespace ts {
return result.diagnostics;
}
+ export function isInternalDeclaration(node: Node, currentSourceFile: SourceFile) {
+ const parseTreeNode = getParseTreeNode(node);
+ const leadingCommentRanges = parseTreeNode && getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
+ return !!forEach(leadingCommentRanges, range => {
+ const comment = currentSourceFile.text.substring(range.pos, range.end);
+ return stringContains(comment, "@internal");
+ });
+ }
+
const declarationEmitNodeBuilderFlags =
NodeBuilderFlags.MultilineObjectLiterals |
NodeBuilderFlags.WriteClassExpressionAsTypeLiteral |
@@ -61,7 +70,7 @@ namespace ts {
const { noResolve, stripInternal } = options;
return transformRoot;
- function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives: string[] | undefined): void {
+ function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives: ReadonlyArray | undefined): void {
if (!typeReferenceDirectives) {
return;
}
@@ -207,8 +216,14 @@ namespace ts {
}
), mapDefined(node.prepends, prepend => {
if (prepend.kind === SyntaxKind.InputFiles) {
- return createUnparsedSourceFile(prepend, "dts");
+ const sourceFile = createUnparsedSourceFile(prepend, "dts", stripInternal);
+ hasNoDefaultLib = hasNoDefaultLib || !!sourceFile.hasNoDefaultLib;
+ collectReferences(sourceFile, refs);
+ recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
+ collectLibs(sourceFile, libs);
+ return sourceFile;
}
+ return prepend;
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
@@ -311,8 +326,8 @@ namespace ts {
}
}
- function collectReferences(sourceFile: SourceFile, ret: Map) {
- if (noResolve || isSourceFileJS(sourceFile)) return ret;
+ function collectReferences(sourceFile: SourceFile | UnparsedSource, ret: Map) {
+ if (noResolve || (!isUnparsedSource(sourceFile) && isSourceFileJS(sourceFile))) return ret;
forEach(sourceFile.referencedFiles, f => {
const elem = tryResolveScriptReference(host, sourceFile, f);
if (elem) {
@@ -322,7 +337,7 @@ namespace ts {
return ret;
}
- function collectLibs(sourceFile: SourceFile, ret: Map) {
+ function collectLibs(sourceFile: SourceFile | UnparsedSource, ret: Map) {
forEach(sourceFile.libReferenceDirectives, ref => {
const lib = host.getLibFileFromReference(ref);
if (lib) {
@@ -1222,19 +1237,8 @@ namespace ts {
errorNameNode = undefined;
}
- function hasInternalAnnotation(range: CommentRange) {
- const comment = currentSourceFile.text.substring(range.pos, range.end);
- return stringContains(comment, "@internal");
- }
-
function shouldStripInternal(node: Node) {
- if (stripInternal && node) {
- const leadingCommentRanges = getLeadingCommentRangesOfNode(getParseTreeNode(node), currentSourceFile);
- if (forEach(leadingCommentRanges, hasInternalAnnotation)) {
- return true;
- }
- }
- return false;
+ return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
}
function isScopeMarker(node: Node) {
diff --git a/src/compiler/transformers/destructuring.ts b/src/compiler/transformers/destructuring.ts
index cde5ee290a357..b5e829ee6839d 100644
--- a/src/compiler/transformers/destructuring.ts
+++ b/src/compiler/transformers/destructuring.ts
@@ -512,7 +512,7 @@ namespace ts {
return name;
}
- const restHelper: EmitHelper = {
+ export const restHelper: UnscopedEmitHelper = {
name: "typescript:rest",
scoped: false,
text: `
diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts
index f97cec89cdf32..64d58da4ba69c 100644
--- a/src/compiler/transformers/es2015.ts
+++ b/src/compiler/transformers/es2015.ts
@@ -4383,7 +4383,7 @@ namespace ts {
);
}
- const extendsHelper: EmitHelper = {
+ export const extendsHelper: UnscopedEmitHelper = {
name: "typescript:extends",
scoped: false,
priority: 0,
@@ -4404,7 +4404,7 @@ namespace ts {
})();`
};
- const templateObjectHelper: EmitHelper = {
+ export const templateObjectHelper: UnscopedEmitHelper = {
name: "typescript:makeTemplateObject",
scoped: false,
priority: 0,
diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts
index b509c6dd00354..1b4252bc9f85d 100644
--- a/src/compiler/transformers/es2017.ts
+++ b/src/compiler/transformers/es2017.ts
@@ -750,7 +750,7 @@ namespace ts {
NodeFlags.Const));
}
- const awaiterHelper: EmitHelper = {
+ export const awaiterHelper: UnscopedEmitHelper = {
name: "typescript:awaiter",
scoped: false,
priority: 5,
diff --git a/src/compiler/transformers/es2018.ts b/src/compiler/transformers/es2018.ts
index 3087249373abd..fd7f9d325c728 100644
--- a/src/compiler/transformers/es2018.ts
+++ b/src/compiler/transformers/es2018.ts
@@ -916,7 +916,7 @@ namespace ts {
}
}
- const assignHelper: EmitHelper = {
+ export const assignHelper: UnscopedEmitHelper = {
name: "typescript:assign",
scoped: false,
priority: 1,
@@ -948,7 +948,7 @@ namespace ts {
);
}
- const awaitHelper: EmitHelper = {
+ export const awaitHelper: UnscopedEmitHelper = {
name: "typescript:await",
scoped: false,
text: `
@@ -960,7 +960,7 @@ namespace ts {
return createCall(getHelperName("__await"), /*typeArguments*/ undefined, [expression]);
}
- const asyncGeneratorHelper: EmitHelper = {
+ export const asyncGeneratorHelper: UnscopedEmitHelper = {
name: "typescript:asyncGenerator",
scoped: false,
text: `
@@ -995,7 +995,7 @@ namespace ts {
);
}
- const asyncDelegator: EmitHelper = {
+ export const asyncDelegator: UnscopedEmitHelper = {
name: "typescript:asyncDelegator",
scoped: false,
text: `
@@ -1019,7 +1019,7 @@ namespace ts {
);
}
- const asyncValues: EmitHelper = {
+ export const asyncValues: UnscopedEmitHelper = {
name: "typescript:asyncValues",
scoped: false,
text: `
diff --git a/src/compiler/transformers/generators.ts b/src/compiler/transformers/generators.ts
index 5778b47a4f8b4..83575fc4bdbd9 100644
--- a/src/compiler/transformers/generators.ts
+++ b/src/compiler/transformers/generators.ts
@@ -3240,7 +3240,7 @@ namespace ts {
// entering a finally block.
//
// For examples of how these are used, see the comments in ./transformers/generators.ts
- const generatorHelper: EmitHelper = {
+ export const generatorHelper: UnscopedEmitHelper = {
name: "typescript:generator",
scoped: false,
priority: 6,
diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts
index 1b3a623c32d21..5605c91e98760 100644
--- a/src/compiler/transformers/module/module.ts
+++ b/src/compiler/transformers/module/module.ts
@@ -1806,7 +1806,7 @@ namespace ts {
};
// emit helper for `import * as Name from "foo"`
- const importStarHelper: EmitHelper = {
+ export const importStarHelper: UnscopedEmitHelper = {
name: "typescript:commonjsimportstar",
scoped: false,
text: `
@@ -1820,7 +1820,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
};
// emit helper for `import Name from "foo"`
- const importDefaultHelper: EmitHelper = {
+ export const importDefaultHelper: UnscopedEmitHelper = {
name: "typescript:commonjsimportdefault",
scoped: false,
text: `
diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts
index 473f3ed0d14f9..15c86a63b94f1 100644
--- a/src/compiler/transformers/ts.ts
+++ b/src/compiler/transformers/ts.ts
@@ -3680,7 +3680,7 @@ namespace ts {
);
}
- const decorateHelper: EmitHelper = {
+ export const decorateHelper: UnscopedEmitHelper = {
name: "typescript:decorate",
scoped: false,
priority: 2,
@@ -3705,7 +3705,7 @@ namespace ts {
);
}
- const metadataHelper: EmitHelper = {
+ export const metadataHelper: UnscopedEmitHelper = {
name: "typescript:metadata",
scoped: false,
priority: 3,
@@ -3730,7 +3730,7 @@ namespace ts {
);
}
- const paramHelper: EmitHelper = {
+ export const paramHelper: UnscopedEmitHelper = {
name: "typescript:param",
scoped: false,
priority: 4,
diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts
index 01c4801b106ed..1ab990355b869 100644
--- a/src/compiler/tsbuild.ts
+++ b/src/compiler/tsbuild.ts
@@ -67,12 +67,19 @@ namespace ts {
* This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
*/
UpToDateWithUpstreamTypes,
+ /**
+ * The project appears out of date because its upstream inputs are newer than its outputs,
+ * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
+ * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
+ */
+ OutOfDateWithPrepend,
OutputMissing,
OutOfDateWithSelf,
OutOfDateWithUpstream,
UpstreamOutOfDate,
UpstreamBlocked,
ComputingUpstream,
+ TsVersionOutputOfDate,
/**
* Projects with no outputs (i.e. "solution" files)
@@ -83,12 +90,14 @@ namespace ts {
export type UpToDateStatus =
| Status.Unbuildable
| Status.UpToDate
+ | Status.OutOfDateWithPrepend
| Status.OutputMissing
| Status.OutOfDateWithSelf
| Status.OutOfDateWithUpstream
| Status.UpstreamOutOfDate
| Status.UpstreamBlocked
| Status.ComputingUpstream
+ | Status.TsVersionOutOfDate
| Status.ContainerOnly;
export namespace Status {
@@ -122,6 +131,15 @@ namespace ts {
oldestOutputFileName: string;
}
+ /**
+ * The project is up to date with respect to its inputs except for prepend output changed (no declaration file change in prepend).
+ */
+ export interface OutOfDateWithPrepend {
+ type: UpToDateStatusType.OutOfDateWithPrepend;
+ outOfDateOutputFileName: string;
+ newerProjectName: string;
+ }
+
/**
* One or more of the outputs of the project does not exist.
*/
@@ -165,6 +183,11 @@ namespace ts {
type: UpToDateStatusType.ComputingUpstream;
}
+ export interface TsVersionOutOfDate {
+ type: UpToDateStatusType.TsVersionOutputOfDate;
+ version: string;
+ }
+
/**
* One or more of the project's outputs is older than the newest output of
* an upstream project.
@@ -289,24 +312,18 @@ namespace ts {
return outputs;
}
- function getOutFileOutputs(project: ParsedCommandLine): ReadonlyArray {
- const out = project.options.outFile || project.options.out;
- if (!out) {
- return Debug.fail("outFile must be set");
- }
- const outputs: string[] = [];
- outputs.push(out);
- if (project.options.sourceMap) {
- outputs.push(`${out}.map`);
- }
- if (getEmitDeclarations(project.options)) {
- const dts = changeExtension(out, Extension.Dts);
- outputs.push(dts);
- if (project.options.declarationMap) {
- outputs.push(`${dts}.map`);
- }
- }
- return outputs;
+ function getOutFileOutputs(project: ParsedCommandLine, ignoreBuildInfo?: boolean): ReadonlyArray {
+ Debug.assert(!!project.options.outFile || !!project.options.out, "outFile must be set");
+ const { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath } = getOutputPathsForBundle(project.options, /*forceDtsPaths*/ false);
+
+ let outputs: string[] | undefined = [];
+ const addOutput = (path: string | undefined) => path && (outputs || (outputs = [])).push(path);
+ addOutput(jsFilePath);
+ addOutput(sourceMapFilePath);
+ addOutput(declarationFilePath);
+ addOutput(declarationMapPath);
+ if (!ignoreBuildInfo) addOutput(buildInfoPath);
+ return outputs || emptyArray;
}
function rootDirOfOptions(opts: CompilerOptions, configFileName: string) {
@@ -374,7 +391,7 @@ namespace ts {
};
}
- function createSolutionBuilderHostBase(system: System, createProgram: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter) {
+ function createSolutionBuilderHostBase(system: System, createProgram: CreateProgram | undefined, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter) {
const host = createProgramHost(system, createProgram) as SolutionBuilderHostBase;
host.getModifiedTime = system.getModifiedTime ? path => system.getModifiedTime!(path) : () => undefined;
host.setModifiedTime = system.setModifiedTime ? (path, date) => system.setModifiedTime!(path, date) : noop;
@@ -385,13 +402,13 @@ namespace ts {
}
export function createSolutionBuilderHost(system = sys, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportErrorSummary?: ReportEmitErrorSummary) {
- const host = createSolutionBuilderHostBase(system, createProgram || createAbstractBuilder as any as CreateProgram, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderHost;
+ const host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderHost;
host.reportErrorSummary = reportErrorSummary;
return host;
}
export function createSolutionBuilderWithWatchHost(system = sys, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter) {
- const host = createSolutionBuilderHostBase(system, createProgram || createEmitAndSemanticDiagnosticsBuilderProgram as any as CreateProgram, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderWithWatchHost;
+ const host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderWithWatchHost;
const watchHost = createWatchHost(system, reportWatchStatus);
copyProperties(host, watchHost);
return host;
@@ -436,7 +453,15 @@ namespace ts {
const compilerHost = createCompilerHostFromProgramHost(host, () => projectCompilerOptions);
const originalGetSourceFile = compilerHost.getSourceFile;
const computeHash = host.createHash || generateDjb2Hash;
- updateGetSourceFile();
+ compilerHost.getSourceFile = (...args) => {
+ const result = originalGetSourceFile.call(compilerHost, ...args);
+ if (result) {
+ result.version = computeHash.call(host, result.text);
+ }
+ return result;
+ };
+
+ const buildInfoChecked = createFileMap(toPath);
// Watch state
const builderPrograms = createFileMap(toPath);
@@ -483,6 +508,7 @@ namespace ts {
projectStatus.clear();
missingRoots.clear();
globalDependencyGraph = undefined;
+ buildInfoChecked.clear();
diagnostics.clear();
projectPendingBuild.clear();
@@ -498,26 +524,6 @@ namespace ts {
clearMap(allWatchedInputFiles, inputFileWatches => clearMap(inputFileWatches, closeFileWatcher));
clearMap(allWatchedConfigFiles, closeFileWatcher);
builderPrograms.clear();
- updateGetSourceFile();
- }
-
- function updateGetSourceFile() {
- if (options.watch) {
- if (compilerHost.getSourceFile === originalGetSourceFile) {
- compilerHost.getSourceFile = (...args) => {
- const result = originalGetSourceFile.call(compilerHost, ...args);
- if (result && options.watch) {
- result.version = computeHash.call(host, result.text);
- }
- return result;
- };
- }
- }
- else {
- if (compilerHost.getSourceFile !== originalGetSourceFile) {
- compilerHost.getSourceFile = originalGetSourceFile;
- }
- }
}
function isParsedCommandLine(entry: ConfigFileCacheEntry): entry is ParsedCommandLine {
@@ -806,27 +812,30 @@ namespace ts {
};
}
- // If the upstream project's newest file is older than our oldest output, we
- // can't be out of date because of it
- if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
- continue;
- }
+ // Check oldest output file name only if there is no missing output file name
+ if (!missingOutputFileName) {
+ // If the upstream project's newest file is older than our oldest output, we
+ // can't be out of date because of it
+ if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
+ continue;
+ }
- // If the upstream project has only change .d.ts files, and we've built
- // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
- if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
- pseudoUpToDate = true;
- upstreamChangedProject = ref.path;
- continue;
- }
+ // If the upstream project has only change .d.ts files, and we've built
+ // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
+ if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
+ pseudoUpToDate = true;
+ upstreamChangedProject = ref.path;
+ continue;
+ }
- // We have an output older than an upstream output - we are out of date
- Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
- return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: oldestOutputFileName,
- newerProjectName: ref.path
- };
+ // We have an output older than an upstream output - we are out of date
+ Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
+ return {
+ type: UpToDateStatusType.OutOfDateWithUpstream,
+ outOfDateOutputFileName: oldestOutputFileName,
+ newerProjectName: ref.path
+ };
+ }
}
}
@@ -845,9 +854,24 @@ namespace ts {
};
}
+ if (!buildInfoChecked.hasKey(project.options.configFilePath as ResolvedConfigFileName)) {
+ buildInfoChecked.setValue(project.options.configFilePath as ResolvedConfigFileName, true);
+ const buildInfoPath = getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath) {
+ const value = readFileWithCache(buildInfoPath);
+ const buildInfo = value && getBuildInfo(value);
+ if (buildInfo && buildInfo.version !== version) {
+ return {
+ type: UpToDateStatusType.TsVersionOutputOfDate,
+ version: buildInfo.version
+ };
+ }
+ }
+ }
+
if (usesPrepend && pseudoUpToDate) {
return {
- type: UpToDateStatusType.OutOfDateWithUpstream,
+ type: UpToDateStatusType.OutOfDateWithPrepend,
outOfDateOutputFileName: oldestOutputFileName,
newerProjectName: upstreamChangedProject!
};
@@ -996,7 +1020,9 @@ namespace ts {
return;
}
- const buildResult = buildSingleProject(resolved);
+ const buildResult = status.type === UpToDateStatusType.OutOfDateWithPrepend ?
+ updateBundle(resolved) : // Fake that files have been built by manipulating prepend and existing output
+ buildSingleProject(resolved); // Actual build
if (buildResult & BuildResultFlags.AnyErrors) return;
const { referencingProjectsMap, buildQueue } = getGlobalDependencyGraph();
@@ -1012,17 +1038,26 @@ namespace ts {
// If declaration output is changed, build the project
// otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
const status = projectStatus.getValue(project);
- if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
- if (status && (status.type === UpToDateStatusType.UpToDate || status.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) {
+ if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
+ if (status && (status.type === UpToDateStatusType.UpToDate || status.type === UpToDateStatusType.UpToDateWithUpstreamTypes || status.type === UpToDateStatusType.OutOfDateWithPrepend)) {
projectStatus.setValue(project, {
type: UpToDateStatusType.OutOfDateWithUpstream,
- outOfDateOutputFileName: status.oldestOutputFileName,
+ outOfDateOutputFileName: status.type === UpToDateStatusType.OutOfDateWithPrepend ? status.outOfDateOutputFileName : status.oldestOutputFileName,
newerProjectName: resolved
});
}
}
else if (status && status.type === UpToDateStatusType.UpToDate) {
- status.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
+ if (prepend) {
+ projectStatus.setValue(project, {
+ type: UpToDateStatusType.OutOfDateWithPrepend,
+ outOfDateOutputFileName: status.oldestOutputFileName,
+ newerProjectName: resolved
+ });
+ }
+ else {
+ status.type = UpToDateStatusType.UpToDateWithUpstreamTypes;
+ }
}
addProjToQueue(project);
}
@@ -1083,8 +1118,7 @@ namespace ts {
if (options.verbose) reportStatus(Diagnostics.Building_project_0, proj);
- let resultFlags = BuildResultFlags.None;
- resultFlags |= BuildResultFlags.DeclarationOutputUnchanged;
+ let resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
const configFile = parseConfigFile(proj);
if (!configFile) {
@@ -1106,11 +1140,10 @@ namespace ts {
configFile.fileNames,
configFile.options,
compilerHost,
- builderPrograms.getValue(proj),
+ getOldProgram(proj, configFile),
configFile.errors,
configFile.projectReferences
);
- projectCompilerOptions = baseCompilerOptions;
// Don't emit anything in the presence of syntactic errors or options diagnostics
const syntaxDiagnostics = [
@@ -1182,6 +1215,7 @@ namespace ts {
diagnostics.removeKey(proj);
projectStatus.setValue(proj, status);
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
function buildErrors(diagnostics: ReadonlyArray, errorFlags: BuildResultFlags, errorType: string) {
@@ -1189,6 +1223,7 @@ namespace ts {
reportAndStoreErrors(proj, diagnostics);
projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: `${errorType} errors` });
afterProgramCreate(proj, program);
+ projectCompilerOptions = baseCompilerOptions;
return resultFlags;
}
}
@@ -1203,9 +1238,72 @@ namespace ts {
}
}
+ function getOldProgram(proj: ResolvedConfigFileName, parsed: ParsedCommandLine) {
+ const value = builderPrograms.getValue(proj);
+ if (value) return value;
+ const buildInfoPath = getOutputPathForBuildInfo(parsed.options);
+ if (!buildInfoPath) return undefined;
+ const content = readFileWithCache(buildInfoPath);
+ if (!content) return undefined;
+ const buildInfo = getBuildInfo(content);
+ if (buildInfo.version !== version) return undefined;
+ return buildInfo.program && createBuildProgramUsingProgramBuildInfo(buildInfo.program) as any as T;
+ }
+
+ function updateBundle(proj: ResolvedConfigFileName): BuildResultFlags {
+ if (options.dry) {
+ reportStatus(Diagnostics.A_non_dry_build_would_update_output_of_project_0, proj);
+ return BuildResultFlags.Success;
+ }
+
+ if (options.verbose) reportStatus(Diagnostics.Updating_output_of_project_0, proj);
+
+ // Update js, and source map
+ const config = Debug.assertDefined(parseConfigFile(proj));
+ projectCompilerOptions = config.options;
+ const outputFiles = emitUsingBuildInfo(
+ config,
+ compilerHost,
+ ref => parseConfigFile(resolveProjectName(ref.path)));
+ if (isString(outputFiles)) {
+ reportStatus(Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, proj, relName(outputFiles));
+ return buildSingleProject(proj);
+ }
+
+ // Actual Emit
+ Debug.assert(!!outputFiles.length);
+ const emitterDiagnostics = createDiagnosticCollection();
+ const emittedOutputs = createFileMap(toPath as ToPath);
+ outputFiles.forEach(({ name, text, writeByteOrderMark }) => {
+ emittedOutputs.setValue(name, true);
+ writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
+ });
+ const emitDiagnostics = emitterDiagnostics.getDiagnostics();
+ if (emitDiagnostics.length) {
+ reportAndStoreErrors(proj, emitDiagnostics);
+ projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Emit errors" });
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged | BuildResultFlags.EmitErrors;
+ }
+
+ // Update timestamps for dts
+ const newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(config, minimumDate, Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
+
+ const status: UpToDateStatus = {
+ type: UpToDateStatusType.UpToDate,
+ newestDeclarationFileContentChangedTime,
+ oldestOutputFileName: outputFiles[0].name
+ };
+
+ diagnostics.removeKey(proj);
+ projectStatus.setValue(proj, status);
+ projectCompilerOptions = baseCompilerOptions;
+ return BuildResultFlags.DeclarationOutputUnchanged;
+ }
+
function updateOutputTimestamps(proj: ParsedCommandLine) {
if (options.dry) {
- return reportStatus(Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath!);
+ return reportStatus(Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath!);
}
const priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, Diagnostics.Updating_output_timestamps_of_project_0);
projectStatus.setValue(proj.options.configFilePath as ResolvedConfigFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime } as UpToDateStatus);
@@ -1340,7 +1438,9 @@ namespace ts {
continue;
}
- const buildResult = buildSingleProject(next);
+ const buildResult = status.type === UpToDateStatusType.OutOfDateWithPrepend && !options.force ?
+ updateBundle(next) : // Fake that files have been built by manipulating prepend and existing output
+ buildSingleProject(next); // Actual build
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
reportErrorSummary();
@@ -1407,6 +1507,8 @@ namespace ts {
for (const inputFile of project.fileNames) {
outputs.push(...getOutputFileNames(inputFile, project));
}
+ const buildInfoPath = getOutputPathForBuildInfo(project.options);
+ if (buildInfoPath) outputs.push(buildInfoPath);
return outputs;
}
}
@@ -1450,6 +1552,10 @@ namespace ts {
}
// Don't report anything for "up to date because it was already built" -- too verbose
break;
+ case UpToDateStatusType.OutOfDateWithPrepend:
+ return formatMessage(Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed,
+ relName(configFileName),
+ relName(status.newerProjectName));
case UpToDateStatusType.UpToDateWithUpstreamTypes:
return formatMessage(Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies,
relName(configFileName));
@@ -1465,6 +1571,11 @@ namespace ts {
return formatMessage(Diagnostics.Failed_to_parse_file_0_Colon_1,
relName(configFileName),
status.reason);
+ case UpToDateStatusType.TsVersionOutputOfDate:
+ return formatMessage(Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2,
+ relName(configFileName),
+ status.version,
+ version);
case UpToDateStatusType.ContainerOnly:
// Don't report status on "solution" projects
case UpToDateStatusType.ComputingUpstream:
diff --git a/src/compiler/types.ts b/src/compiler/types.ts
index 0d24db8454eb0..d14ff0b055288 100644
--- a/src/compiler/types.ts
+++ b/src/compiler/types.ts
@@ -428,6 +428,13 @@ namespace ts {
// Enum
EnumMember,
+ // Unparsed
+ UnparsedPrologue,
+ UnparsedPrepend,
+ UnparsedText,
+ UnparsedInternalText,
+ UnparsedSyntheticReference,
+
// Top-level nodes
SourceFile,
Bundle,
@@ -2775,14 +2782,66 @@ namespace ts {
declarationText: string;
declarationMapPath?: string;
declarationMapText?: string;
+ /*@internal*/ buildInfoPath?: string;
+ /*@internal*/ buildInfo?: BuildInfo;
+ /*@internal*/ oldFileOfCurrentEmit?: boolean;
}
export interface UnparsedSource extends Node {
kind: SyntaxKind.UnparsedSource;
- fileName?: string;
+ fileName: string;
text: string;
+ prologues: ReadonlyArray;
+ helpers: ReadonlyArray | undefined;
+
+ // References and noDefaultLibAre Dts only
+ referencedFiles: ReadonlyArray;
+ typeReferenceDirectives: ReadonlyArray | undefined;
+ libReferenceDirectives: ReadonlyArray;
+ hasNoDefaultLib?: boolean;
+
sourceMapPath?: string;
sourceMapText?: string;
+ syntheticReferences?: ReadonlyArray;
+ texts: ReadonlyArray;
+ /*@internal*/ oldFileOfCurrentEmit?: boolean;
+ /*@internal*/ parsedSourceMap?: RawSourceMap | false | undefined;
+ // Adding this to satisfy services, fix later
+ /*@internal*/
+ getLineAndCharacterOfPosition(pos: number): LineAndCharacter;
+ }
+
+ export type UnparsedSourceText = UnparsedPrepend | UnparsedTextLike;
+ export type UnparsedNode = UnparsedPrologue | UnparsedSourceText | UnparsedSyntheticReference;
+
+ export interface UnparsedSection extends Node {
+ kind: SyntaxKind;
+ data?: string;
+ parent: UnparsedSource;
+ }
+
+ export interface UnparsedPrologue extends UnparsedSection {
+ kind: SyntaxKind.UnparsedPrologue;
+ data: string;
+ parent: UnparsedSource;
+ }
+
+ export interface UnparsedPrepend extends UnparsedSection {
+ kind: SyntaxKind.UnparsedPrepend;
+ data: string;
+ parent: UnparsedSource;
+ texts: ReadonlyArray;
+ }
+
+ export interface UnparsedTextLike extends UnparsedSection {
+ kind: SyntaxKind.UnparsedText | SyntaxKind.UnparsedInternalText;
+ parent: UnparsedSource;
+ }
+
+ export interface UnparsedSyntheticReference extends UnparsedSection {
+ kind: SyntaxKind.UnparsedSyntheticReference;
+ parent: UnparsedSource;
+ /*@internal*/ section: BundleFileHasNoDefaultLib | BundleFileReference;
}
export interface JsonSourceFile extends SourceFile {
@@ -2935,6 +2994,8 @@ namespace ts {
/*@internal*/ getResolvedProjectReferenceToRedirect(fileName: string): ResolvedProjectReference | undefined;
/*@internal*/ forEachResolvedProjectReference(cb: (resolvedProjectReference: ResolvedProjectReference | undefined, resolvedProjectReferencePath: Path) => T | undefined): T | undefined;
/*@internal*/ getResolvedProjectReferenceByPath(projectReferencePath: Path): ResolvedProjectReference | undefined;
+ /*@internal*/ getProgramBuildInfo?(): ProgramBuildInfo | undefined;
+ /*@internal*/ emitBuildInfo(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult;
}
/* @internal */
@@ -4587,6 +4648,8 @@ namespace ts {
reactNamespace?: string;
jsxFactory?: string;
composite?: boolean;
+ incremental?: boolean;
+ tsBuildInfoFile?: string;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
@@ -4997,7 +5060,8 @@ namespace ts {
Dts = ".d.ts",
Js = ".js",
Jsx = ".jsx",
- Json = ".json"
+ Json = ".json",
+ TsBuildInfo = ".tsbuildinfo"
}
export interface ResolvedModuleWithFailedLookupLocations {
@@ -5208,6 +5272,11 @@ namespace ts {
readonly priority?: number; // Helpers with a higher priority are emitted earlier than other helpers on the node.
}
+ export interface UnscopedEmitHelper extends EmitHelper {
+ readonly scoped: false; // Indicates whether the helper MUST be emitted in the current scope.
+ readonly text: string; // ES3-compatible raw script text, or a function yielding such a string
+ }
+
/* @internal */
export type UniqueNameHandler = (baseName: string, checkFn?: (name: string) => boolean, optimistic?: boolean) => string;
@@ -5280,9 +5349,10 @@ namespace ts {
isEmitBlocked(emitFileName: string): boolean;
- getPrependNodes(): ReadonlyArray;
+ getPrependNodes(): ReadonlyArray;
writeFile: WriteFileCallback;
+ getProgramBuildInfo(): ProgramBuildInfo | undefined;
}
export interface TransformationContext {
@@ -5433,23 +5503,116 @@ namespace ts {
/*@internal*/ writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined, writer: EmitTextWriter): void;
/*@internal*/ writeList(format: ListFormat, list: NodeArray | undefined, sourceFile: SourceFile | undefined, writer: EmitTextWriter): void;
/*@internal*/ writeFile(sourceFile: SourceFile, writer: EmitTextWriter, sourceMapGenerator: SourceMapGenerator | undefined): void;
- /*@internal*/ writeBundle(bundle: Bundle, info: BundleInfo | undefined, writer: EmitTextWriter, sourceMapGenerator: SourceMapGenerator | undefined): void;
+ /*@internal*/ writeBundle(bundle: Bundle, writer: EmitTextWriter, sourceMapGenerator: SourceMapGenerator | undefined): void;
+ /*@internal*/ bundleFileInfo?: BundleFileInfo;
+ }
+
+ /*@internal*/
+ export const enum BundleFileSectionKind {
+ Prologue = "prologue",
+ EmitHelpers = "emitHelpers",
+ NoDefaultLib = "no-default-lib",
+ Reference = "reference",
+ Type = "type",
+ Lib = "lib",
+ Prepend = "prepend",
+ Text = "text",
+ Internal = "internal",
+ // comments?
+ }
+
+ /*@internal*/
+ export interface BundleFileSectionBase extends TextRange {
+ kind: BundleFileSectionKind;
+ data?: string;
+ }
+
+ /*@internal*/
+ export interface BundleFilePrologue extends BundleFileSectionBase {
+ kind: BundleFileSectionKind.Prologue;
+ data: string;
+ }
+
+ /*@internal*/
+ export interface BundleFileEmitHelpers extends BundleFileSectionBase {
+ kind: BundleFileSectionKind.EmitHelpers;
+ data: string;
+ }
+
+ /*@internal*/
+ export interface BundleFileHasNoDefaultLib extends BundleFileSectionBase {
+ kind: BundleFileSectionKind.NoDefaultLib;
+ }
+
+ /*@internal*/
+ export interface BundleFileReference extends BundleFileSectionBase {
+ kind: BundleFileSectionKind.Reference | BundleFileSectionKind.Type | BundleFileSectionKind.Lib;
+ data: string;
+ }
+
+ /*@internal*/
+ export interface BundleFilePrepend extends BundleFileSectionBase {
+ kind: BundleFileSectionKind.Prepend;
+ data: string;
+ texts: BundleFileTextLike[];
+ }
+
+ /*@internal*/
+ export type BundleFileTextLikeKind = BundleFileSectionKind.Text | BundleFileSectionKind.Internal;
+
+ /*@internal*/
+ export interface BundleFileTextLike extends BundleFileSectionBase {
+ kind: BundleFileTextLikeKind;
+ }
+
+ /*@internal*/
+ export type BundleFileSection = BundleFilePrologue | BundleFileEmitHelpers |
+ BundleFileHasNoDefaultLib | BundleFileReference | BundleFilePrepend |
+ BundleFileTextLike;
+
+ /*@internal*/
+ export interface SourceFilePrologueDirectiveExpression extends TextRange {
+ text: string;
+ }
+
+ /*@internal*/
+ export interface SourceFilePrologueDirective extends TextRange {
+ expression: SourceFilePrologueDirectiveExpression;
+ }
+
+ /*@internal*/
+ export interface SourceFilePrologueInfo {
+ file: number;
+ text: string;
+ directives: SourceFilePrologueDirective[];
+ }
+
+ /*@internal*/
+ export interface SourceFileInfo {
+ // List of helpers in own source files emitted if no prepend is present
+ helpers?: string[];
+ prologues?: SourceFilePrologueInfo[];
+ }
+
+ /*@internal*/
+ export interface BundleFileInfo {
+ sections: BundleFileSection[];
+ sources?: SourceFileInfo;
+ }
+
+ /*@internal*/
+ export interface BundleBuildInfo {
+ js?: BundleFileInfo;
+ dts?: BundleFileInfo;
+ commonSourceDirectory: string;
+ sourceFiles: ReadonlyArray;
}
- /**
- * When a bundle contains prepended content, we store a file on disk indicating where the non-prepended
- * content of that file starts. On a subsequent build where there are no upstream .d.ts changes, we
- * read the bundle info file and the original .js file to quickly re-use portion of the file
- * that didn't originate in prepended content.
- */
/* @internal */
- export interface BundleInfo {
- // The offset (in characters, i.e. suitable for .substr) at which the
- // non-prepended portion of the emitted file starts.
- originalOffset: number;
- // The total length of this bundle. Used to ensure we're pulling from
- // the same source as we originally wrote.
- totalLength: number;
+ export interface BuildInfo {
+ bundle?: BundleBuildInfo;
+ program?: ProgramBuildInfo;
+ version: string;
}
export interface PrintHandlers {
@@ -5517,6 +5680,9 @@ namespace ts {
/*@internal*/ extendedDiagnostics?: boolean;
/*@internal*/ onlyPrintJsDocStyle?: boolean;
/*@internal*/ neverAsciiEscape?: boolean;
+ /*@internal*/ writeBundleFileInfo?: boolean;
+ /*@internal*/ recordInternalSection?: boolean;
+ /*@internal*/ stripInternal?: boolean;
}
/* @internal */
@@ -5559,7 +5725,7 @@ namespace ts {
/**
* Appends a source map.
*/
- appendSourceMap(generatedLine: number, generatedCharacter: number, sourceMap: RawSourceMap, sourceMapPath: string): void;
+ appendSourceMap(generatedLine: number, generatedCharacter: number, sourceMap: RawSourceMap, sourceMapPath: string, start?: LineAndCharacter, end?: LineAndCharacter): void;
/**
* Gets the source map as a `RawSourceMap` object.
*/
@@ -5605,6 +5771,7 @@ namespace ts {
getColumn(): number;
getIndent(): number;
isAtStartOfLine(): boolean;
+ getTextPosWithWriteLine?(): number;
}
export interface GetEffectiveTypeRootsHost {
@@ -5862,6 +6029,7 @@ namespace ts {
// The above fallback to `object` when there's no args to allow `{}` (as intended), but not the number 2, for example
// TODO: Swap to `undefined` for a cleaner API once strictNullChecks is enabled
+ /* @internal */
type ConcretePragmaSpecs = typeof commentPragmas;
/* @internal */
diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts
index aa2ebe3d60c07..e04ccc13be8ab 100644
--- a/src/compiler/utilities.ts
+++ b/src/compiler/utilities.ts
@@ -2559,7 +2559,7 @@ namespace ts {
return undefined;
}
- export function tryResolveScriptReference(host: ScriptReferenceHost, sourceFile: SourceFile, reference: FileReference) {
+ export function tryResolveScriptReference(host: ScriptReferenceHost, sourceFile: SourceFile | UnparsedSource, reference: FileReference) {
if (!host.getCompilerOptions().noResolve) {
const referenceFileName = isRootedDiskPath(reference.fileName) ? reference.fileName : combinePaths(getDirectoryPath(sourceFile.fileName), reference.fileName);
return host.getSourceFile(referenceFileName);
@@ -3202,6 +3202,10 @@ namespace ts {
}
}
+ function getTextPosWithWriteLine() {
+ return lineStart ? output.length : (output.length + newLine.length);
+ }
+
reset();
return {
@@ -3231,7 +3235,8 @@ namespace ts {
writeStringLiteral: write,
writeSymbol: (s, _) => write(s),
writeTrailingSemicolon: write,
- writeComment: write
+ writeComment: write,
+ getTextPosWithWriteLine
};
}
@@ -3356,11 +3361,11 @@ namespace ts {
}
export interface EmitFileNames {
- jsFilePath: string | undefined;
- sourceMapFilePath: string | undefined;
- declarationFilePath: string | undefined;
- declarationMapPath: string | undefined;
- bundleInfoPath: string | undefined;
+ jsFilePath?: string | undefined;
+ sourceMapFilePath?: string | undefined;
+ declarationFilePath?: string | undefined;
+ declarationMapPath?: string | undefined;
+ buildInfoPath?: string | undefined;
}
/**
@@ -4596,6 +4601,16 @@ namespace ts {
export function isAccessExpression(node: Node): node is AccessExpression {
return node.kind === SyntaxKind.PropertyAccessExpression || node.kind === SyntaxKind.ElementAccessExpression;
}
+
+ export function isBundleFileTextLike(section: BundleFileSection): section is BundleFileTextLike {
+ switch (section.kind) {
+ case BundleFileSectionKind.Text:
+ case BundleFileSectionKind.Internal:
+ return true;
+ default:
+ return false;
+ }
+ }
}
namespace ts {
@@ -5988,6 +6003,26 @@ namespace ts {
return node.kind === SyntaxKind.UnparsedSource;
}
+ export function isUnparsedPrepend(node: Node): node is UnparsedPrepend {
+ return node.kind === SyntaxKind.UnparsedPrepend;
+ }
+
+ export function isUnparsedTextLike(node: Node): node is UnparsedTextLike {
+ switch (node.kind) {
+ case SyntaxKind.UnparsedText:
+ case SyntaxKind.UnparsedInternalText:
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ export function isUnparsedNode(node: Node): node is UnparsedNode {
+ return isUnparsedTextLike(node) ||
+ node.kind === SyntaxKind.UnparsedPrologue ||
+ node.kind === SyntaxKind.UnparsedSyntheticReference;
+ }
+
// JSDoc
export function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression {
@@ -6743,7 +6778,7 @@ namespace ts {
/* @internal */
export function isDeclaration(node: Node): node is NamedDeclaration {
if (node.kind === SyntaxKind.TypeParameter) {
- return node.parent.kind !== SyntaxKind.JSDocTemplateTag || isInJSFile(node);
+ return (node.parent && node.parent.kind !== SyntaxKind.JSDocTemplateTag) || isInJSFile(node);
}
return isDeclarationKind(node.kind);
@@ -7215,6 +7250,10 @@ namespace ts {
return !!(compilerOptions.declaration || compilerOptions.composite);
}
+ export function isIncrementalCompilation(options: CompilerOptions) {
+ return !!(options.incremental || options.composite);
+ }
+
export type StrictOptionName = "noImplicitAny" | "noImplicitThis" | "strictNullChecks" | "strictFunctionTypes" | "strictBindCallApply" | "strictPropertyInitialization" | "alwaysStrict";
export function getStrictOptionValue(compilerOptions: CompilerOptions, flag: StrictOptionName): boolean {
diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts
index fa2a06e4ed0a0..41ef7876d76d7 100644
--- a/src/compiler/watch.ts
+++ b/src/compiler/watch.ts
@@ -283,7 +283,7 @@ namespace ts {
/**
* Creates the watch compiler host that can be extended with config file or root file names and options host
*/
- export function createProgramHost(system: System, createProgram: CreateProgram): ProgramHost {
+ export function createProgramHost(system: System, createProgram: CreateProgram | undefined): ProgramHost {
const getDefaultLibLocation = memoize(() => getDirectoryPath(normalizePath(system.getExecutingFilePath())));
let host: DirectoryStructureHost = system;
host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!)
@@ -305,7 +305,7 @@ namespace ts {
writeFile: (path, data, writeByteOrderMark) => system.writeFile(path, data, writeByteOrderMark),
onCachedDirectoryStructureHostCreate: cacheHost => host = cacheHost || system,
createHash: maybeBind(system, system.createHash),
- createProgram
+ createProgram: createProgram || createEmitAndSemanticDiagnosticsBuilderProgram as any as CreateProgram
};
}
@@ -314,7 +314,7 @@ namespace ts {
*/
function createWatchCompilerHost(system = sys, createProgram: CreateProgram | undefined, reportDiagnostic: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHost {
const writeFileName = (s: string) => system.write(s + system.newLine);
- const result = createProgramHost(system, createProgram || createEmitAndSemanticDiagnosticsBuilderProgram as any as CreateProgram) as WatchCompilerHost;
+ const result = createProgramHost(system, createProgram) as WatchCompilerHost;
copyProperties(result, createWatchHost(system, reportWatchStatus));
result.afterProgramCreate = builderProgram => {
const compilerOptions = builderProgram.getCompilerOptions();
diff --git a/src/harness/fakes.ts b/src/harness/fakes.ts
index 093f57a112b81..31c96ac6e73c7 100644
--- a/src/harness/fakes.ts
+++ b/src/harness/fakes.ts
@@ -384,8 +384,77 @@ namespace fakes {
return text;
}
+ function compareProgramBuildInfoDiagnostic(a: ts.ProgramBuildInfoDiagnostic, b: ts.ProgramBuildInfoDiagnostic) {
+ return ts.compareStringsCaseSensitive(ts.isString(a) ? a : a[0], ts.isString(b) ? b : b[0]);
+ }
+
+ export const version = "FakeTSVersion";
+
export class SolutionBuilderHost extends CompilerHost implements ts.SolutionBuilderHost {
- createProgram = ts.createAbstractBuilder;
+ createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram;
+
+ readFile(path: string) {
+ const value = super.readFile(path);
+ if (!value || !ts.isBuildInfoFile(path)) return value;
+ const buildInfo = ts.getBuildInfo(value);
+ if (buildInfo.program) {
+ // Fix lib signatures
+ for (const path of ts.getOwnKeys(buildInfo.program.fileInfos)) {
+ if (ts.startsWith(path, "/lib/")) {
+ const currentValue = buildInfo.program.fileInfos[path];
+ ts.Debug.assert(currentValue.signature === path);
+ ts.Debug.assert(currentValue.signature === currentValue.version);
+ const text = super.readFile(path)!;
+ const signature = ts.generateDjb2Hash(text);
+ buildInfo.program.fileInfos[path] = { version: signature, signature };
+ }
+ }
+ }
+ ts.Debug.assert(buildInfo.version === version);
+ buildInfo.version = ts.version;
+ return ts.getBuildInfoText(buildInfo);
+ }
+
+ public writeFile(fileName: string, content: string, writeByteOrderMark: boolean) {
+ if (!ts.isBuildInfoFile(fileName)) return super.writeFile(fileName, content, writeByteOrderMark);
+ const buildInfo = ts.getBuildInfo(content);
+ if (buildInfo.program) {
+ // Fix lib signatures
+ for (const path of ts.getOwnKeys(buildInfo.program.fileInfos)) {
+ if (ts.startsWith(path, "/lib/")) {
+ const currentValue = buildInfo.program.fileInfos[path];
+ ts.Debug.assert(currentValue.signature === currentValue.version);
+ buildInfo.program.fileInfos[path] = { version: path, signature: path };
+ }
+ }
+
+ // reference Map
+ if (buildInfo.program.referencedMap) {
+ const referencedMap: ts.MapLike = {};
+ for (const path of ts.getOwnKeys(buildInfo.program.referencedMap).sort()) {
+ referencedMap[path] = buildInfo.program.referencedMap[path].sort();
+ }
+ buildInfo.program.referencedMap = referencedMap;
+ }
+
+ // exportedModulesMap
+ if (buildInfo.program.exportedModulesMap) {
+ const exportedModulesMap: ts.MapLike = {};
+ for (const path of ts.getOwnKeys(buildInfo.program.exportedModulesMap).sort()) {
+ exportedModulesMap[path] = buildInfo.program.exportedModulesMap[path].sort();
+ }
+ buildInfo.program.exportedModulesMap = exportedModulesMap;
+ }
+
+ // semanticDiagnosticsPerFile
+ if (buildInfo.program.semanticDiagnosticsPerFile) {
+ buildInfo.program.semanticDiagnosticsPerFile.sort(compareProgramBuildInfoDiagnostic);
+ }
+ }
+ buildInfo.version = version;
+ super.writeFile(fileName, ts.getBuildInfoText(buildInfo), writeByteOrderMark);
+ }
+
now() {
return new Date(this.sys.vfs.time());
}
diff --git a/src/harness/sourceMapRecorder.ts b/src/harness/sourceMapRecorder.ts
index d16aca21d6645..893b17ff10650 100644
--- a/src/harness/sourceMapRecorder.ts
+++ b/src/harness/sourceMapRecorder.ts
@@ -15,10 +15,10 @@ namespace Harness.SourceMapRecorder {
error?: string;
}
- export function initializeSourceMapDecoding(sourceMapData: ts.SourceMapEmitResult) {
+ export function initializeSourceMapDecoding(sourceMap: ts.RawSourceMap) {
decodingIndex = 0;
- sourceMapMappings = sourceMapData.sourceMap.mappings;
- mappings = ts.decodeMappings(sourceMapData.sourceMap.mappings);
+ sourceMapMappings = sourceMap.mappings;
+ mappings = ts.decodeMappings(sourceMap.mappings);
}
export function decodeNextEncodedSourceMapSpan(): DecodedMapping {
@@ -53,10 +53,10 @@ namespace Harness.SourceMapRecorder {
let nextJsLineToWrite: number;
let spanMarkerContinues: boolean;
- export function initializeSourceMapSpanWriter(sourceMapRecordWriter: Compiler.WriterAggregator, sourceMapData: ts.SourceMapEmitResult, currentJsFile: documents.TextDocument) {
+ export function initializeSourceMapSpanWriter(sourceMapRecordWriter: Compiler.WriterAggregator, sourceMap: ts.RawSourceMap, currentJsFile: documents.TextDocument) {
sourceMapRecorder = sourceMapRecordWriter;
- sourceMapSources = sourceMapData.sourceMap.sources;
- sourceMapNames = sourceMapData.sourceMap.names;
+ sourceMapSources = sourceMap.sources;
+ sourceMapNames = sourceMap.names;
jsFile = currentJsFile;
jsLineMap = jsFile.lineStarts;
@@ -66,14 +66,14 @@ namespace Harness.SourceMapRecorder {
nextJsLineToWrite = 0;
spanMarkerContinues = false;
- SourceMapDecoder.initializeSourceMapDecoding(sourceMapData);
+ SourceMapDecoder.initializeSourceMapDecoding(sourceMap);
sourceMapRecorder.WriteLine("===================================================================");
- sourceMapRecorder.WriteLine("JsFile: " + sourceMapData.sourceMap.file);
+ sourceMapRecorder.WriteLine("JsFile: " + sourceMap.file);
sourceMapRecorder.WriteLine("mapUrl: " + ts.tryGetSourceMappingURL(ts.getLineInfo(jsFile.text, jsLineMap)));
- sourceMapRecorder.WriteLine("sourceRoot: " + sourceMapData.sourceMap.sourceRoot);
- sourceMapRecorder.WriteLine("sources: " + sourceMapData.sourceMap.sources);
- if (sourceMapData.sourceMap.sourcesContent) {
- sourceMapRecorder.WriteLine("sourcesContent: " + JSON.stringify(sourceMapData.sourceMap.sourcesContent));
+ sourceMapRecorder.WriteLine("sourceRoot: " + sourceMap.sourceRoot);
+ sourceMapRecorder.WriteLine("sources: " + sourceMap.sources);
+ if (sourceMap.sourcesContent) {
+ sourceMapRecorder.WriteLine("sourcesContent: " + JSON.stringify(sourceMap.sourcesContent));
}
sourceMapRecorder.WriteLine("===================================================================");
}
@@ -299,7 +299,7 @@ namespace Harness.SourceMapRecorder {
}
}
- SourceMapSpanWriter.initializeSourceMapSpanWriter(sourceMapRecorder, sourceMapData, currentFile);
+ SourceMapSpanWriter.initializeSourceMapSpanWriter(sourceMapRecorder, sourceMapData.sourceMap, currentFile);
const mapper = ts.decodeMappings(sourceMapData.sourceMap.mappings);
for (let { value: decodedSourceMapping, done } = mapper.next(); !done; { value: decodedSourceMapping, done } = mapper.next()) {
const currentSourceFile = ts.isSourceMapping(decodedSourceMapping)
@@ -320,4 +320,46 @@ namespace Harness.SourceMapRecorder {
sourceMapRecorder.Close();
return sourceMapRecorder.lines.join("\r\n");
}
+
+ export function getSourceMapRecordWithVFS(fs: vfs.FileSystem, sourceMapFile: string) {
+ const sourceMapRecorder = new Compiler.WriterAggregator();
+ let prevSourceFile: documents.TextDocument | undefined;
+ const files = ts.createMap();
+ const sourceMap = ts.tryParseRawSourceMap(fs.readFileSync(sourceMapFile, "utf8"));
+ if (sourceMap) {
+ const mapDirectory = ts.getDirectoryPath(sourceMapFile);
+ const sourceRoot = sourceMap.sourceRoot ? ts.getNormalizedAbsolutePath(sourceMap.sourceRoot, mapDirectory) : mapDirectory;
+ const generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(sourceMap.file, mapDirectory);
+ const sourceFileAbsolutePaths = sourceMap.sources.map(source => ts.getNormalizedAbsolutePath(source, sourceRoot));
+ const currentFile = getFile(generatedAbsoluteFilePath);
+
+ SourceMapSpanWriter.initializeSourceMapSpanWriter(sourceMapRecorder, sourceMap, currentFile);
+ const mapper = ts.decodeMappings(sourceMap.mappings);
+ for (let { value: decodedSourceMapping, done } = mapper.next(); !done; { value: decodedSourceMapping, done } = mapper.next()) {
+ const currentSourceFile = ts.isSourceMapping(decodedSourceMapping)
+ ? getFile(sourceFileAbsolutePaths[decodedSourceMapping.sourceIndex])
+ : undefined;
+ if (currentSourceFile !== prevSourceFile) {
+ if (currentSourceFile) {
+ SourceMapSpanWriter.recordNewSourceFileSpan(decodedSourceMapping, currentSourceFile.text);
+ }
+ prevSourceFile = currentSourceFile;
+ }
+ else {
+ SourceMapSpanWriter.recordSourceMapSpan(decodedSourceMapping);
+ }
+ }
+ SourceMapSpanWriter.close(); // If the last spans werent emitted, emit them
+ }
+ sourceMapRecorder.Close();
+ return sourceMapRecorder.lines.join("\r\n");
+
+ function getFile(path: string) {
+ const existing = files.get(path);
+ if (existing) return existing;
+ const value = new documents.TextDocument(path, fs.readFileSync(path, "utf8"));
+ files.set(path, value);
+ return value;
+ }
+ }
}
diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts
index 56ae6dfdc22ac..6c1ad386a05c9 100644
--- a/src/server/editorServices.ts
+++ b/src/server/editorServices.ts
@@ -335,6 +335,7 @@ namespace ts.server {
RootOfInferredProjectFalse = "Open file was set as not inferred root",
}
+ /*@internal*/
interface ConfigFileExistenceInfo {
/**
* Cached value of existence of config file
diff --git a/src/server/tsconfig.json b/src/server/tsconfig.json
index 86d205d3bb141..3cf28ab40eebc 100644
--- a/src/server/tsconfig.json
+++ b/src/server/tsconfig.json
@@ -1,7 +1,7 @@
{
"extends": "../tsconfig-base",
"compilerOptions": {
- "removeComments": true,
+ "removeComments": false,
"outFile": "../../built/local/server.js",
"preserveConstEnums": true,
"types": [
diff --git a/src/services/codefixes/generateTypes.ts b/src/services/codefixes/generateTypes.ts
index 040d58c8e1187..53c474f5d35c0 100644
--- a/src/services/codefixes/generateTypes.ts
+++ b/src/services/codefixes/generateTypes.ts
@@ -16,6 +16,7 @@ namespace ts {
return textChanges.getNewFileText(toStatements(valueInfo, outputKind), ScriptKind.TS, formatSettings.newLineCharacter || "\n", formatting.getFormatContext(formatSettings));
}
+ /* @internal */
const enum OutputKind { ExportEquals, NamedExport, NamespaceMember, Global }
function toNamespaceMemberStatements(info: ValueInfo): ReadonlyArray {
return toStatements(info, OutputKind.NamespaceMember);
diff --git a/src/services/stringCompletions.ts b/src/services/stringCompletions.ts
index 9548397a22def..aafe90760560f 100644
--- a/src/services/stringCompletions.ts
+++ b/src/services/stringCompletions.ts
@@ -71,6 +71,7 @@ namespace ts.Completions.StringCompletions {
case Extension.Jsx: return ScriptElementKindModifier.jsxModifier;
case Extension.Ts: return ScriptElementKindModifier.tsModifier;
case Extension.Tsx: return ScriptElementKindModifier.tsxModifier;
+ case Extension.TsBuildInfo: return Debug.fail(`Extension ${Extension.TsBuildInfo} is unsupported.`);
case undefined: return ScriptElementKindModifier.none;
default:
return Debug.assertNever(extension);
diff --git a/src/testRunner/tsconfig.json b/src/testRunner/tsconfig.json
index 4e5c088025c71..d912e229b4bae 100644
--- a/src/testRunner/tsconfig.json
+++ b/src/testRunner/tsconfig.json
@@ -37,6 +37,7 @@
"runner.ts",
"unittests/services/extract/helpers.ts",
+ "unittests/tsbuild/helpers.ts",
"unittests/tscWatch/helpers.ts",
"unittests/tsserver/helpers.ts",
@@ -60,7 +61,6 @@
"unittests/semver.ts",
"unittests/shimMap.ts",
"unittests/transform.ts",
- "unittests/tsbuild.ts",
"unittests/tsbuildWatchMode.ts",
"unittests/config/commandLineParsing.ts",
"unittests/config/configurationExtension.ts",
@@ -89,6 +89,15 @@
"unittests/services/preProcessFile.ts",
"unittests/services/textChanges.ts",
"unittests/services/transpile.ts",
+ "unittests/tsbuild/amdModulesWithOut.ts",
+ "unittests/tsbuild/emptyFiles.ts",
+ "unittests/tsbuild/graphOrdering.ts",
+ "unittests/tsbuild/missingExtendedFile.ts",
+ "unittests/tsbuild/outFile.ts",
+ "unittests/tsbuild/referencesWithRootDirInParent.ts",
+ "unittests/tsbuild/resolveJsonModule.ts",
+ "unittests/tsbuild/sample.ts",
+ "unittests/tsbuild/transitiveReferences.ts",
"unittests/tscWatch/consoleClearing.ts",
"unittests/tscWatch/emit.ts",
"unittests/tscWatch/emitAndErrorUpdates.ts",
diff --git a/src/testRunner/unittests/tsbuild.ts b/src/testRunner/unittests/tsbuild.ts
deleted file mode 100644
index 707a853400436..0000000000000
--- a/src/testRunner/unittests/tsbuild.ts
+++ /dev/null
@@ -1,763 +0,0 @@
-namespace ts {
- let currentTime = 100;
-
- function getExpectedDiagnosticForProjectsInBuild(...projects: string[]): fakes.ExpectedDiagnostic {
- return [Diagnostics.Projects_in_this_build_Colon_0, projects.map(p => "\r\n * " + p).join("")];
- }
-
- export namespace Sample1 {
- tick();
- const projFs = loadProjectFromDisk("tests/projects/sample1");
-
- const allExpectedOutputs = ["/src/tests/index.js",
- "/src/core/index.js", "/src/core/index.d.ts", "/src/core/index.d.ts.map",
- "/src/logic/index.js", "/src/logic/index.js.map", "/src/logic/index.d.ts"];
-
- describe("unittests:: tsbuild - sanity check of clean build of 'sample1' project", () => {
- it("can build the sample project 'sample1' without error", () => {
- const fs = projFs.shadow();
- const host = new fakes.SolutionBuilderHost(fs);
- const builder = createSolutionBuilder(host, ["/src/tests"], { dry: false, force: false, verbose: false });
-
- host.clearDiagnostics();
- builder.buildAllProjects();
- host.assertDiagnosticMessages(/*empty*/);
-
- // Check for outputs. Not an exhaustive list
- for (const output of allExpectedOutputs) {
- assert(fs.existsSync(output), `Expect file ${output} to exist`);
- }
- });
-
- it("builds correctly when outDir is specified", () => {
- const fs = projFs.shadow();
- fs.writeFileSync("/src/logic/tsconfig.json", JSON.stringify({
- compilerOptions: { composite: true, declaration: true, sourceMap: true, outDir: "outDir" },
- references: [{ path: "../core" }]
- }));
-
- const host = new fakes.SolutionBuilderHost(fs);
- const builder = createSolutionBuilder(host, ["/src/tests"], {});
- builder.buildAllProjects();
- host.assertDiagnosticMessages(/*empty*/);
- const expectedOutputs = allExpectedOutputs.map(f => f.replace("/logic/", "/logic/outDir/"));
- // Check for outputs. Not an exhaustive list
- for (const output of expectedOutputs) {
- assert(fs.existsSync(output), `Expect file ${output} to exist`);
- }
- });
-
- it("builds correctly when declarationDir is specified", () => {
- const fs = projFs.shadow();
- fs.writeFileSync("/src/logic/tsconfig.json", JSON.stringify({
- compilerOptions: { composite: true, declaration: true, sourceMap: true, declarationDir: "out/decls" },
- references: [{ path: "../core" }]
- }));
-
- const host = new fakes.SolutionBuilderHost(fs);
- const builder = createSolutionBuilder(host, ["/src/tests"], {});
- builder.buildAllProjects();
- host.assertDiagnosticMessages(/*empty*/);
- const expectedOutputs = allExpectedOutputs.map(f => f.replace("/logic/index.d.ts", "/logic/out/decls/index.d.ts"));
- // Check for outputs. Not an exhaustive list
- for (const output of expectedOutputs) {
- assert(fs.existsSync(output), `Expect file ${output} to exist`);
- }
- });
- });
-
- describe("unittests:: tsbuild - dry builds", () => {
- it("doesn't write any files in a dry build", () => {
- const fs = projFs.shadow();
- const host = new fakes.SolutionBuilderHost(fs);
- const builder = createSolutionBuilder(host, ["/src/tests"], { dry: true, force: false, verbose: false });
- builder.buildAllProjects();
- host.assertDiagnosticMessages(
- [Diagnostics.A_non_dry_build_would_build_project_0, "/src/core/tsconfig.json"],
- [Diagnostics.A_non_dry_build_would_build_project_0, "/src/logic/tsconfig.json"],
- [Diagnostics.A_non_dry_build_would_build_project_0, "/src/tests/tsconfig.json"]
- );
-
- // Check for outputs to not be written. Not an exhaustive list
- for (const output of allExpectedOutputs) {
- assert(!fs.existsSync(output), `Expect file ${output} to not exist`);
- }
- });
-
- it("indicates that it would skip builds during a dry build", () => {
- const fs = projFs.shadow();
- const host = new fakes.SolutionBuilderHost(fs);
-
- let builder = createSolutionBuilder(host, ["/src/tests"], { dry: false, force: false, verbose: false });
- builder.buildAllProjects();
- tick();
-
- host.clearDiagnostics();
- builder = createSolutionBuilder(host, ["/src/tests"], { dry: true, force: false, verbose: false });
- builder.buildAllProjects();
- host.assertDiagnosticMessages(
- [Diagnostics.Project_0_is_up_to_date, "/src/core/tsconfig.json"],
- [Diagnostics.Project_0_is_up_to_date, "/src/logic/tsconfig.json"],
- [Diagnostics.Project_0_is_up_to_date, "/src/tests/tsconfig.json"]
- );
- });
- });
-
- describe("unittests:: tsbuild - clean builds", () => {
- it("removes all files it built", () => {
- const fs = projFs.shadow();
- const host = new fakes.SolutionBuilderHost(fs);
-
- const builder = createSolutionBuilder(host, ["/src/tests"], { dry: false, force: false, verbose: false });
- builder.buildAllProjects();
- // Verify they exist
- for (const output of allExpectedOutputs) {
- assert(fs.existsSync(output), `Expect file ${output} to exist`);
- }
- builder.cleanAllProjects();
- // Verify they are gone
- for (const output of allExpectedOutputs) {
- assert(!fs.existsSync(output), `Expect file ${output} to not exist`);
- }
- // Subsequent clean shouldn't throw / etc
- builder.cleanAllProjects();
- });
- });
-
- describe("unittests:: tsbuild - force builds", () => {
- it("always builds under --force", () => {
- const fs = projFs.shadow();
- const host = new fakes.SolutionBuilderHost(fs);
-
- const builder = createSolutionBuilder(host, ["/src/tests"], { dry: false, force: true, verbose: false });
- builder.buildAllProjects();
- let currentTime = time();
- checkOutputTimestamps(currentTime);
-
- tick();
- Debug.assert(time() !== currentTime, "Time moves on");
- currentTime = time();
- builder.buildAllProjects();
- checkOutputTimestamps(currentTime);
-
- function checkOutputTimestamps(expected: number) {
- // Check timestamps
- for (const output of allExpectedOutputs) {
- const actual = fs.statSync(output).mtimeMs;
- assert(actual === expected, `File ${output} has timestamp ${actual}, expected ${expected}`);
- }
- }
- });
- });
-
- describe("unittests:: tsbuild - can detect when and what to rebuild", () => {
- const fs = projFs.shadow();
- const host = new fakes.SolutionBuilderHost(fs);
- const builder = createSolutionBuilder(host, ["/src/tests"], { dry: false, force: false, verbose: true });
-
- it("Builds the project", () => {
- host.clearDiagnostics();
- builder.resetBuildContext();
- builder.buildAllProjects();
- host.assertDiagnosticMessages(
- getExpectedDiagnosticForProjectsInBuild("src/core/tsconfig.json", "src/logic/tsconfig.json", "src/tests/tsconfig.json"),
- [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/core/tsconfig.json", "src/core/anotherModule.js"],
- [Diagnostics.Building_project_0, "/src/core/tsconfig.json"],
- [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/logic/tsconfig.json", "src/logic/index.js"],
- [Diagnostics.Building_project_0, "/src/logic/tsconfig.json"],
- [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/tests/tsconfig.json", "src/tests/index.js"],
- [Diagnostics.Building_project_0, "/src/tests/tsconfig.json"]
- );
- tick();
- });
-
- // All three projects are up to date
- it("Detects that all projects are up to date", () => {
- host.clearDiagnostics();
- builder.resetBuildContext();
- builder.buildAllProjects();
- host.assertDiagnosticMessages(
- getExpectedDiagnosticForProjectsInBuild("src/core/tsconfig.json", "src/logic/tsconfig.json", "src/tests/tsconfig.json"),
- [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, "src/core/tsconfig.json", "src/core/anotherModule.ts", "src/core/anotherModule.js"],
- [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, "src/logic/tsconfig.json", "src/logic/index.ts", "src/logic/index.js"],
- [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, "src/tests/tsconfig.json", "src/tests/index.ts", "src/tests/index.js"]
- );
- tick();
- });
-
- // Update a file in the leaf node (tests), only it should rebuild the last one
- it("Only builds the leaf node project", () => {
- host.clearDiagnostics();
- fs.writeFileSync("/src/tests/index.ts", "const m = 10;");
- builder.resetBuildContext();
- builder.buildAllProjects();
-
- host.assertDiagnosticMessages(
- getExpectedDiagnosticForProjectsInBuild("src/core/tsconfig.json", "src/logic/tsconfig.json", "src/tests/tsconfig.json"),
- [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, "src/core/tsconfig.json", "src/core/anotherModule.ts", "src/core/anotherModule.js"],
- [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, "src/logic/tsconfig.json", "src/logic/index.ts", "src/logic/index.js"],
- [Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, "src/tests/tsconfig.json", "src/tests/index.js", "src/tests/index.ts"],
- [Diagnostics.Building_project_0, "/src/tests/tsconfig.json"]
- );
- tick();
- });
-
- // Update a file in the parent (without affecting types), should get fast downstream builds
- it("Detects type-only changes in upstream projects", () => {
- host.clearDiagnostics();
- replaceText(fs, "/src/core/index.ts", "HELLO WORLD", "WELCOME PLANET");
- builder.resetBuildContext();
- builder.buildAllProjects();
-
- host.assertDiagnosticMessages(
- getExpectedDiagnosticForProjectsInBuild("src/core/tsconfig.json", "src/logic/tsconfig.json", "src/tests/tsconfig.json"),
- [Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, "src/core/tsconfig.json", "src/core/anotherModule.js", "src/core/index.ts"],
- [Diagnostics.Building_project_0, "/src/core/tsconfig.json"],
- [Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, "src/logic/tsconfig.json"],
- [Diagnostics.Updating_output_timestamps_of_project_0, "/src/logic/tsconfig.json"],
- [Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, "src/tests/tsconfig.json"],
- [Diagnostics.Updating_output_timestamps_of_project_0, "/src/tests/tsconfig.json"]
- );
- });
- });
-
- describe("unittests:: tsbuild - downstream-blocked compilations", () => {
- it("won't build downstream projects if upstream projects have errors", () => {
- const fs = projFs.shadow();
- const host = new fakes.SolutionBuilderHost(fs);
- const builder = createSolutionBuilder(host, ["/src/tests"], { dry: false, force: false, verbose: true });
-
- // Induce an error in the middle project
- replaceText(fs, "/src/logic/index.ts", "c.multiply(10, 15)", `c.muitply()`);
- builder.buildAllProjects();
- host.assertDiagnosticMessages(
- getExpectedDiagnosticForProjectsInBuild("src/core/tsconfig.json", "src/logic/tsconfig.json", "src/tests/tsconfig.json"),
- [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/core/tsconfig.json", "src/core/anotherModule.js"],
- [Diagnostics.Building_project_0, "/src/core/tsconfig.json"],
- [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/logic/tsconfig.json", "src/logic/index.js"],
- [Diagnostics.Building_project_0, "/src/logic/tsconfig.json"],
- [Diagnostics.Property_0_does_not_exist_on_type_1, "muitply", `typeof import("/src/core/index")`],
- [Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, "src/tests/tsconfig.json", "src/logic"],
- [Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, "/src/tests/tsconfig.json", "/src/logic"]
- );
- });
- });
-
- describe("unittests:: tsbuild - project invalidation", () => {
- it("invalidates projects correctly", () => {
- const fs = projFs.shadow();
- const host = new fakes.SolutionBuilderHost(fs);
- const builder = createSolutionBuilder(host, ["/src/tests"], { dry: false, force: false, verbose: false });
-
- builder.buildAllProjects();
- host.assertDiagnosticMessages(/*empty*/);
-
- // Update a timestamp in the middle project
- tick();
- touch(fs, "/src/logic/index.ts");
- const originalWriteFile = fs.writeFileSync;
- const writtenFiles = createMap();
- fs.writeFileSync = (path, data, encoding) => {
- writtenFiles.set(path, true);
- originalWriteFile.call(fs, path, data, encoding);
- };
- // Because we haven't reset the build context, the builder should assume there's nothing to do right now
- const status = builder.getUpToDateStatusOfFile(builder.resolveProjectName("/src/logic"));
- assert.equal(status.type, UpToDateStatusType.UpToDate, "Project should be assumed to be up-to-date");
- verifyInvalidation(/*expectedToWriteTests*/ false);
-
- // Rebuild this project
- fs.writeFileSync("/src/logic/index.ts", `${fs.readFileSync("/src/logic/index.ts")}
-export class cNew {}`);
- verifyInvalidation(/*expectedToWriteTests*/ true);
-
- function verifyInvalidation(expectedToWriteTests: boolean) {
- // Rebuild this project
- tick();
- builder.invalidateProject("/src/logic");
- builder.buildInvalidatedProject();
- // The file should be updated
- assert.isTrue(writtenFiles.has("/src/logic/index.js"), "JS file should have been rebuilt");
- assert.equal(fs.statSync("/src/logic/index.js").mtimeMs, time(), "JS file should have been rebuilt");
- assert.isFalse(writtenFiles.has("/src/tests/index.js"), "Downstream JS file should *not* have been rebuilt");
- assert.isBelow(fs.statSync("/src/tests/index.js").mtimeMs, time(), "Downstream JS file should *not* have been rebuilt");
- writtenFiles.clear();
-
- // Build downstream projects should update 'tests', but not 'core'
- tick();
- builder.buildInvalidatedProject();
- if (expectedToWriteTests) {
- assert.isTrue(writtenFiles.has("/src/tests/index.js"), "Downstream JS file should have been rebuilt");
- }
- else {
- assert.equal(writtenFiles.size, 0, "Should not write any new files");
- }
- assert.equal(fs.statSync("/src/tests/index.js").mtimeMs, time(), "Downstream JS file should have new timestamp");
- assert.isBelow(fs.statSync("/src/core/index.js").mtimeMs, time(), "Upstream JS file should not have been rebuilt");
- }
- });
- });
-
- describe("unittests:: tsbuild - with resolveJsonModule option", () => {
- const projFs = loadProjectFromDisk("tests/projects/resolveJsonModuleAndComposite");
- const allExpectedOutputs = ["/src/tests/dist/src/index.js", "/src/tests/dist/src/index.d.ts", "/src/tests/dist/src/hello.json"];
-
- function verifyProjectWithResolveJsonModule(configFile: string, ...expectedDiagnosticMessages: fakes.ExpectedDiagnostic[]) {
- const fs = projFs.shadow();
- verifyProjectWithResolveJsonModuleWithFs(fs, configFile, allExpectedOutputs, ...expectedDiagnosticMessages);
- }
-
- function verifyProjectWithResolveJsonModuleWithFs(fs: vfs.FileSystem, configFile: string, allExpectedOutputs: ReadonlyArray, ...expectedDiagnosticMessages: fakes.ExpectedDiagnostic[]) {
- const host = new fakes.SolutionBuilderHost(fs);
- const builder = createSolutionBuilder(host, [configFile], { dry: false, force: false, verbose: false });
- builder.buildAllProjects();
- host.assertDiagnosticMessages(...expectedDiagnosticMessages);
- if (!expectedDiagnosticMessages.length) {
- // Check for outputs. Not an exhaustive list
- for (const output of allExpectedOutputs) {
- assert(fs.existsSync(output), `Expect file ${output} to exist`);
- }
- }
- }
-
- it("with resolveJsonModule and include only", () => {
- verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withInclude.json", [
- Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern,
- "/src/tests/src/hello.json"
- ]);
- });
-
- it("with resolveJsonModule and include of *.json along with other include", () => {
- verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withIncludeOfJson.json");
- });
-
- it("with resolveJsonModule and include of *.json along with other include and file name matches ts file", () => {
- const fs = projFs.shadow();
- fs.rimrafSync("/src/tests/src/hello.json");
- fs.writeFileSync("/src/tests/src/index.json", JSON.stringify({ hello: "world" }));
- fs.writeFileSync("/src/tests/src/index.ts", `import hello from "./index.json"
-
-export default hello.hello`);
- const allExpectedOutputs = ["/src/tests/dist/src/index.js", "/src/tests/dist/src/index.d.ts", "/src/tests/dist/src/index.json"];
- verifyProjectWithResolveJsonModuleWithFs(fs, "/src/tests/tsconfig_withIncludeOfJson.json", allExpectedOutputs);
- });
-
- it("with resolveJsonModule and files containing json file", () => {
- verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withFiles.json");
- });
-
- it("with resolveJsonModule and include and files", () => {
- verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withIncludeAndFiles.json");
- });
- });
-
- describe("unittests:: tsbuild - lists files", () => {
- it("listFiles", () => {
- const fs = projFs.shadow();
- const host = new fakes.SolutionBuilderHost(fs);
- const builder = createSolutionBuilder(host, ["/src/tests"], { listFiles: true });
- builder.buildAllProjects();
- assert.deepEqual(host.traces, [
- ...getLibs(),
- "/src/core/anotherModule.ts",
- "/src/core/index.ts",
- "/src/core/some_decl.d.ts",
- ...getLibs(),
- ...getCoreOutputs(),
- "/src/logic/index.ts",
- ...getLibs(),
- ...getCoreOutputs(),
- "/src/logic/index.d.ts",
- "/src/tests/index.ts"
- ]);
-
- function getCoreOutputs() {
- return [
- "/src/core/index.d.ts",
- "/src/core/anotherModule.d.ts"
- ];
- }
- });
-
- it("listEmittedFiles", () => {
- const fs = projFs.shadow();
- const host = new fakes.SolutionBuilderHost(fs);
- const builder = createSolutionBuilder(host, ["/src/tests"], { listEmittedFiles: true });
- builder.buildAllProjects();
- assert.deepEqual(host.traces, [
- "TSFILE: /src/core/anotherModule.js",
- "TSFILE: /src/core/anotherModule.d.ts",
- "TSFILE: /src/core/anotherModule.d.ts.map",
- "TSFILE: /src/core/index.js",
- "TSFILE: /src/core/index.d.ts",
- "TSFILE: /src/core/index.d.ts.map",
- "TSFILE: /src/logic/index.js",
- "TSFILE: /src/logic/index.js.map",
- "TSFILE: /src/logic/index.d.ts",
- "TSFILE: /src/tests/index.js",
- "TSFILE: /src/tests/index.d.ts",
- ]);
- });
- });
-
- describe("unittests:: tsbuild - with rootDir of project reference in parentDirectory", () => {
- const projFs = loadProjectFromDisk("tests/projects/projectReferenceWithRootDirInParent");
- const allExpectedOutputs = [
- "/src/dist/other/other.js", "/src/dist/other/other.d.ts",
- "/src/dist/main/a.js", "/src/dist/main/a.d.ts",
- "/src/dist/main/b.js", "/src/dist/main/b.d.ts"
- ];
- it("verify that it builds correctly", () => {
- const fs = projFs.shadow();
- const host = new fakes.SolutionBuilderHost(fs);
- const builder = createSolutionBuilder(host, ["/src/src/main", "/src/src/other"], {});
- builder.buildAllProjects();
- host.assertDiagnosticMessages(/*empty*/);
- for (const output of allExpectedOutputs) {
- assert(fs.existsSync(output), `Expect file ${output} to exist`);
- }
- });
- });
-
- describe("unittests:: tsbuild - when project reference is referenced transitively", () => {
- const projFs = loadProjectFromDisk("tests/projects/transitiveReferences");
- const allExpectedOutputs = [
- "/src/a.js", "/src/a.d.ts",
- "/src/b.js", "/src/b.d.ts",
- "/src/c.js"
- ];
- const expectedFileTraces = [
- ...getLibs(),
- "/src/a.ts",
- ...getLibs(),
- "/src/a.d.ts",
- "/src/b.ts",
- ...getLibs(),
- "/src/a.d.ts",
- "/src/b.d.ts",
- "/src/refs/a.d.ts",
- "/src/c.ts"
- ];
-
- function verifyBuild(modifyDiskLayout: (fs: vfs.FileSystem) => void, allExpectedOutputs: ReadonlyArray, expectedFileTraces: ReadonlyArray, ...expectedDiagnostics: fakes.ExpectedDiagnostic[]) {
- const fs = projFs.shadow();
- const host = new fakes.SolutionBuilderHost(fs);
- modifyDiskLayout(fs);
- const builder = createSolutionBuilder(host, ["/src/tsconfig.c.json"], { listFiles: true });
- builder.buildAllProjects();
- host.assertDiagnosticMessages(...expectedDiagnostics);
- for (const output of allExpectedOutputs) {
- assert(fs.existsSync(output), `Expect file ${output} to exist`);
- }
- assert.deepEqual(host.traces, expectedFileTraces);
- }
-
- function modifyFsBTsToNonRelativeImport(fs: vfs.FileSystem, moduleResolution: "node" | "classic") {
- fs.writeFileSync("/src/b.ts", `import {A} from 'a';
-export const b = new A();`);
- fs.writeFileSync("/src/tsconfig.b.json", JSON.stringify({
- compilerOptions: {
- composite: true,
- moduleResolution
- },
- files: ["b.ts"],
- references: [{ path: "tsconfig.a.json" }]
- }));
- }
-
- it("verify that it builds correctly", () => {
- verifyBuild(noop, allExpectedOutputs, expectedFileTraces);
- });
-
- it("verify that it builds correctly when the referenced project uses different module resolution", () => {
- verifyBuild(fs => modifyFsBTsToNonRelativeImport(fs, "classic"), allExpectedOutputs, expectedFileTraces);
- });
-
- it("verify that it build reports error about module not found with node resolution with external module name", () => {
- // Error in b build only a
- const allExpectedOutputs = ["/src/a.js", "/src/a.d.ts"];
- const expectedFileTraces = [
- ...getLibs(),
- "/src/a.ts",
- ];
- verifyBuild(fs => modifyFsBTsToNonRelativeImport(fs, "node"),
- allExpectedOutputs,
- expectedFileTraces,
- [Diagnostics.Cannot_find_module_0, "a"],
- );
- });
- });
-
- it("unittests:: tsbuild - when tsconfig extends the missing file", () => {
- const projFs = loadProjectFromDisk("tests/projects/missingExtendedConfig");
- const fs = projFs.shadow();
- const host = new fakes.SolutionBuilderHost(fs);
- const builder = createSolutionBuilder(host, ["/src/tsconfig.json"], {});
- builder.buildAllProjects();
- host.assertDiagnosticMessages(
- [Diagnostics.The_specified_path_does_not_exist_Colon_0, "/src/foobar.json"],
- [Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, "/src/tsconfig.first.json", "[\"**/*\"]", "[]"],
- [Diagnostics.The_specified_path_does_not_exist_Colon_0, "/src/foobar.json"],
- [Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, "/src/tsconfig.second.json", "[\"**/*\"]", "[]"]
- );
- });
- }
-
- export namespace OutFile {
- const outFileFs = loadProjectFromDisk("tests/projects/outfile-concat");
-
- describe("unittests:: tsbuild - baseline sectioned sourcemaps", () => {
- let fs: vfs.FileSystem | undefined;
- const actualReadFileMap = createMap();
- before(() => {
- fs = outFileFs.shadow();
- const host = new fakes.SolutionBuilderHost(fs);
- const builder = createSolutionBuilder(host, ["/src/third"], { dry: false, force: false, verbose: false });
- host.clearDiagnostics();
- const originalReadFile = host.readFile;
- host.readFile = path => {
- // Dont record libs
- if (path.startsWith("/src/")) {
- actualReadFileMap.set(path, (actualReadFileMap.get(path) || 0) + 1);
- }
- return originalReadFile.call(host, path);
- };
- builder.buildAllProjects();
- host.assertDiagnosticMessages(/*none*/);
- });
- after(() => {
- fs = undefined;
- });
- it(`Generates files matching the baseline`, () => {
- const patch = fs!.diff();
- // tslint:disable-next-line:no-null-keyword
- Harness.Baseline.runBaseline("outfile-concat.js", patch ? vfs.formatPatch(patch) : null);
- });
- it("verify readFile calls", () => {
- const expected = [
- // Configs
- "/src/third/tsconfig.json",
- "/src/second/tsconfig.json",
- "/src/first/tsconfig.json",
-
- // Source files
- "/src/third/third_part1.ts",
- "/src/second/second_part1.ts",
- "/src/second/second_part2.ts",
- "/src/first/first_PART1.ts",
- "/src/first/first_part2.ts",
- "/src/first/first_part3.ts",
-
- // outputs
- "/src/first/bin/first-output.js",
- "/src/first/bin/first-output.js.map",
- "/src/first/bin/first-output.d.ts",
- "/src/first/bin/first-output.d.ts.map",
- "/src/2/second-output.js",
- "/src/2/second-output.js.map",
- "/src/2/second-output.d.ts",
- "/src/2/second-output.d.ts.map"
- ];
-
- assert.equal(actualReadFileMap.size, expected.length, `Expected: ${JSON.stringify(expected)} \nActual: ${JSON.stringify(arrayFrom(actualReadFileMap.entries()))}`);
- expected.forEach(expectedValue => {
- const actual = actualReadFileMap.get(expectedValue);
- assert.equal(actual, 1, `Mismatch in read file call number for: ${expectedValue}\nExpected: ${JSON.stringify(expected)} \nActual: ${JSON.stringify(arrayFrom(actualReadFileMap.entries()))}`);
- });
- });
- });
-
- describe("unittests:: tsbuild - downstream prepend projects always get rebuilt", () => {
- it("", () => {
- const fs = outFileFs.shadow();
- const host = new fakes.SolutionBuilderHost(fs);
- const builder = createSolutionBuilder(host, ["/src/third"], { dry: false, force: false, verbose: false });
- builder.buildAllProjects();
- host.assertDiagnosticMessages(/*none*/);
- assert.equal(fs.statSync("src/third/thirdjs/output/third-output.js").mtimeMs, time(), "First build timestamp is correct");
- tick();
- replaceText(fs, "src/first/first_PART1.ts", "Hello", "Hola");
- tick();
- builder.resetBuildContext();
- builder.buildAllProjects();
- host.assertDiagnosticMessages(/*none*/);
- assert.equal(fs.statSync("src/third/thirdjs/output/third-output.js").mtimeMs, time(), "Second build timestamp is correct");
- });
- });
- }
-
- export namespace EmptyFiles {
- const projFs = loadProjectFromDisk("tests/projects/empty-files");
-
- const allExpectedOutputs = [
- "/src/core/index.js",
- "/src/core/index.d.ts",
- "/src/core/index.d.ts.map",
- ];
-
- describe("unittests:: tsbuild - empty files option in tsconfig", () => {
- it("has empty files diagnostic when files is empty and no references are provided", () => {
- const fs = projFs.shadow();
- const host = new fakes.SolutionBuilderHost(fs);
- const builder = createSolutionBuilder(host, ["/src/no-references"], { dry: false, force: false, verbose: false });
-
- host.clearDiagnostics();
- builder.buildAllProjects();
- host.assertDiagnosticMessages([Diagnostics.The_files_list_in_config_file_0_is_empty, "/src/no-references/tsconfig.json"]);
-
- // Check for outputs to not be written.
- for (const output of allExpectedOutputs) {
- assert(!fs.existsSync(output), `Expect file ${output} to not exist`);
- }
- });
-
- it("does not have empty files diagnostic when files is empty and references are provided", () => {
- const fs = projFs.shadow();
- const host = new fakes.SolutionBuilderHost(fs);
- const builder = createSolutionBuilder(host, ["/src/with-references"], { dry: false, force: false, verbose: false });
-
- host.clearDiagnostics();
- builder.buildAllProjects();
- host.assertDiagnosticMessages(/*empty*/);
-
- // Check for outputs to be written.
- for (const output of allExpectedOutputs) {
- assert(fs.existsSync(output), `Expect file ${output} to exist`);
- }
- });
- });
- }
-
- describe("unittests:: tsbuild - graph-ordering", () => {
- let host: fakes.SolutionBuilderHost | undefined;
- const deps: [string, string][] = [
- ["A", "B"],
- ["B", "C"],
- ["A", "C"],
- ["B", "D"],
- ["C", "D"],
- ["C", "E"],
- ["F", "E"]
- ];
-
- before(() => {
- const fs = new vfs.FileSystem(false);
- host = new fakes.SolutionBuilderHost(fs);
- writeProjects(fs, ["A", "B", "C", "D", "E", "F", "G"], deps);
- });
-
- after(() => {
- host = undefined;
- });
-
- it("orders the graph correctly - specify two roots", () => {
- checkGraphOrdering(["A", "G"], ["A", "B", "C", "D", "E", "G"]);
- });
-
- it("orders the graph correctly - multiple parts of the same graph in various orders", () => {
- checkGraphOrdering(["A"], ["A", "B", "C", "D", "E"]);
- checkGraphOrdering(["A", "C", "D"], ["A", "B", "C", "D", "E"]);
- checkGraphOrdering(["D", "C", "A"], ["A", "B", "C", "D", "E"]);
- });
-
- it("orders the graph correctly - other orderings", () => {
- checkGraphOrdering(["F"], ["F", "E"]);
- checkGraphOrdering(["E"], ["E"]);
- checkGraphOrdering(["F", "C", "A"], ["A", "B", "C", "D", "E", "F"]);
- });
-
- function checkGraphOrdering(rootNames: string[], expectedBuildSet: string[]) {
- const builder = createSolutionBuilder(host!, rootNames, { dry: true, force: false, verbose: false });
-
- const projFileNames = rootNames.map(getProjectFileName);
- const graph = builder.getBuildGraph(projFileNames);
-
- assert.sameMembers(graph.buildQueue, expectedBuildSet.map(getProjectFileName));
-
- for (const dep of deps) {
- const child = getProjectFileName(dep[0]);
- if (graph.buildQueue.indexOf(child) < 0) continue;
- const parent = getProjectFileName(dep[1]);
- assert.isAbove(graph.buildQueue.indexOf(child), graph.buildQueue.indexOf(parent), `Expecting child ${child} to be built after parent ${parent}`);
- }
- }
-
- function getProjectFileName(proj: string) {
- return `/project/${proj}/tsconfig.json` as ResolvedConfigFileName;
- }
-
- function writeProjects(fileSystem: vfs.FileSystem, projectNames: string[], deps: [string, string][]): string[] {
- const projFileNames: string[] = [];
- for (const dep of deps) {
- if (projectNames.indexOf(dep[0]) < 0) throw new Error(`Invalid dependency - project ${dep[0]} does not exist`);
- if (projectNames.indexOf(dep[1]) < 0) throw new Error(`Invalid dependency - project ${dep[1]} does not exist`);
- }
- for (const proj of projectNames) {
- fileSystem.mkdirpSync(`/project/${proj}`);
- fileSystem.writeFileSync(`/project/${proj}/${proj}.ts`, "export {}");
- const configFileName = getProjectFileName(proj);
- const configContent = JSON.stringify({
- compilerOptions: { composite: true },
- files: [`./${proj}.ts`],
- references: deps.filter(d => d[0] === proj).map(d => ({ path: `../${d[1]}` }))
- }, undefined, 2);
- fileSystem.writeFileSync(configFileName, configContent);
- projFileNames.push(configFileName);
- }
- return projFileNames;
- }
- });
-
-
- function replaceText(fs: vfs.FileSystem, path: string, oldText: string, newText: string) {
- if (!fs.statSync(path).isFile()) {
- throw new Error(`File ${path} does not exist`);
- }
- const old = fs.readFileSync(path, "utf-8");
- if (old.indexOf(oldText) < 0) {
- throw new Error(`Text "${oldText}" does not exist in file ${path}`);
- }
- const newContent = old.replace(oldText, newText);
- fs.writeFileSync(path, newContent, "utf-8");
- }
-
- function tick() {
- currentTime += 60_000;
- }
-
- function time() {
- return currentTime;
- }
-
- function touch(fs: vfs.FileSystem, path: string) {
- if (!fs.statSync(path).isFile()) {
- throw new Error(`File ${path} does not exist`);
- }
- fs.utimesSync(path, new Date(time()), new Date(time()));
- }
-
- function loadProjectFromDisk(root: string): vfs.FileSystem {
- const resolver = vfs.createResolver(Harness.IO);
- const fs = new vfs.FileSystem(/*ignoreCase*/ true, {
- files: {
- ["/lib"]: new vfs.Mount(vpath.resolve(Harness.IO.getWorkspaceRoot(), "built/local"), resolver),
- ["/src"]: new vfs.Mount(vpath.resolve(Harness.IO.getWorkspaceRoot(), root), resolver)
- },
- cwd: "/",
- meta: { defaultLibLocation: "/lib" },
- time
- });
- fs.makeReadonly();
- return fs;
- }
-
- function getLibs() {
- return [
- "/lib/lib.d.ts",
- "/lib/lib.es5.d.ts",
- "/lib/lib.dom.d.ts",
- "/lib/lib.webworker.importscripts.d.ts",
- "/lib/lib.scripthost.d.ts"
- ];
- }
-}
diff --git a/src/testRunner/unittests/tsbuild/amdModulesWithOut.ts b/src/testRunner/unittests/tsbuild/amdModulesWithOut.ts
new file mode 100644
index 0000000000000..28f80bd44cba2
--- /dev/null
+++ b/src/testRunner/unittests/tsbuild/amdModulesWithOut.ts
@@ -0,0 +1,203 @@
+namespace ts {
+ describe("unittests:: tsbuild:: outFile:: on amd modules with --out", () => {
+ let outFileFs: vfs.FileSystem;
+ const { time, tick } = getTime();
+ const enum ext { js, jsmap, dts, dtsmap, buildinfo }
+ const enum project { lib, app }
+ type OutputFile = [string, string, string, string, string];
+ function relName(path: string) { return path.slice(1); }
+ const outputFiles: [OutputFile, OutputFile] = [
+ [
+ "/src/lib/module.js",
+ "/src/lib/module.js.map",
+ "/src/lib/module.d.ts",
+ "/src/lib/module.d.ts.map",
+ "/src/lib/module.tsbuildinfo"
+ ],
+ [
+ "/src/app/module.js",
+ "/src/app/module.js.map",
+ "/src/app/module.d.ts",
+ "/src/app/module.d.ts.map",
+ "/src/app/module.tsbuildinfo"
+ ]
+ ];
+ type Sources = [string, ReadonlyArray];
+ const enum source { config, ts }
+ const sources: [Sources, Sources] = [
+ [
+ "/src/lib/tsconfig.json",
+ [
+ "/src/lib/file0.ts",
+ "/src/lib/file1.ts",
+ "/src/lib/file2.ts",
+ "/src/lib/global.ts",
+ ]
+ ],
+ [
+ "/src/app/tsconfig.json",
+ [
+ "/src/app/file3.ts",
+ "/src/app/file4.ts"
+ ]
+ ]
+ ];
+ before(() => {
+ outFileFs = loadProjectFromDisk("tests/projects/amdModulesWithOut", time);
+ });
+ after(() => {
+ outFileFs = undefined!;
+ });
+
+ interface VerifyOutFileScenarioInput {
+ scenario: string;
+ modifyFs: (fs: vfs.FileSystem) => void;
+ modifyAgainFs?: (fs: vfs.FileSystem) => void;
+ }
+
+ function verifyOutFileScenario({
+ scenario,
+ modifyFs,
+ modifyAgainFs
+ }: VerifyOutFileScenarioInput) {
+ verifyTsbuildOutput({
+ scenario,
+ projFs: () => outFileFs,
+ time,
+ tick,
+ proj: "amdModulesWithOut",
+ rootNames: ["/src/app"],
+ expectedMapFileNames: [
+ outputFiles[project.lib][ext.jsmap],
+ outputFiles[project.lib][ext.dtsmap],
+ outputFiles[project.app][ext.jsmap],
+ outputFiles[project.app][ext.dtsmap],
+ ],
+ expectedBuildInfoFilesForSectionBaselines: [
+ [outputFiles[project.lib][ext.buildinfo], outputFiles[project.lib][ext.js], outputFiles[project.lib][ext.dts]],
+ [outputFiles[project.app][ext.buildinfo], outputFiles[project.app][ext.js], outputFiles[project.app][ext.dts]]
+ ],
+ lastProjectOutputJs: outputFiles[project.app][ext.js],
+ initialBuild: {
+ modifyFs
+ },
+ incrementalDtsUnchangedBuild: {
+ modifyFs: fs => appendText(fs, relName(sources[project.lib][source.ts][1]), "console.log(x);")
+ },
+ incrementalHeaderChangedBuild: modifyAgainFs ? {
+ modifyFs: modifyAgainFs
+ } : undefined,
+ outputFiles: [
+ ...outputFiles[project.lib],
+ ...outputFiles[project.app]
+ ],
+ baselineOnly: true
+ });
+ }
+
+ describe("Prepend output with .tsbuildinfo", () => {
+ verifyOutFileScenario({
+ scenario: "modules and globals mixed in amd",
+ modifyFs: noop
+ });
+
+ // Prologues
+ describe("Prologues", () => {
+ verifyOutFileScenario({
+ scenario: "multiple prologues in all projects",
+ modifyFs: fs => {
+ enableStrict(fs, sources[project.lib][source.config]);
+ addTestPrologue(fs, sources[project.lib][source.ts][0], `"myPrologue"`);
+ addTestPrologue(fs, sources[project.lib][source.ts][2], `"myPrologueFile"`);
+ addTestPrologue(fs, sources[project.lib][source.ts][3], `"myPrologue3"`);
+ enableStrict(fs, sources[project.app][source.config]);
+ addTestPrologue(fs, sources[project.app][source.ts][0], `"myPrologue"`);
+ addTestPrologue(fs, sources[project.app][source.ts][1], `"myPrologue2";`);
+ },
+ modifyAgainFs: fs => addTestPrologue(fs, relName(sources[project.lib][source.ts][1]), `"myPrologue5"`)
+ });
+ });
+
+ // Shebang
+ describe("Shebang", () => {
+ // changes declaration because its emitted in .d.ts file
+ verifyOutFileScenario({
+ scenario: "shebang in all projects",
+ modifyFs: fs => {
+ addShebang(fs, "lib", "file0");
+ addShebang(fs, "lib", "file1");
+ addShebang(fs, "app", "file3");
+ },
+ });
+ });
+
+ // emitHelpers
+ describe("emitHelpers", () => {
+ verifyOutFileScenario({
+ scenario: "multiple emitHelpers in all projects",
+ modifyFs: fs => {
+ addSpread(fs, "lib", "file0");
+ addRest(fs, "lib", "file1");
+ addRest(fs, "app", "file3");
+ addSpread(fs, "app", "file4");
+ },
+ modifyAgainFs: fs => removeRest(fs, "lib", "file1")
+ });
+ });
+
+ // triple slash refs
+ describe("triple slash refs", () => {
+ // changes declaration because its emitted in .d.ts file
+ verifyOutFileScenario({
+ scenario: "triple slash refs in all projects",
+ modifyFs: fs => {
+ addTripleSlashRef(fs, "lib", "file0");
+ addTripleSlashRef(fs, "app", "file4");
+ }
+ });
+ });
+
+ describe("stripInternal", () => {
+ function stripInternalScenario(fs: vfs.FileSystem) {
+ const internal = "/*@internal*/";
+ replaceText(fs, sources[project.app][source.config], `"composite": true,`, `"composite": true,
+"stripInternal": true,`);
+ replaceText(fs, sources[project.lib][source.ts][0], "const", `${internal} const`);
+ appendText(fs, sources[project.lib][source.ts][1], `
+export class normalC {
+ ${internal} constructor() { }
+ ${internal} prop: string;
+ ${internal} method() { }
+ ${internal} get c() { return 10; }
+ ${internal} set c(val: number) { }
+}
+export namespace normalN {
+ ${internal} export class C { }
+ ${internal} export function foo() {}
+ ${internal} export namespace someNamespace { export class C {} }
+ ${internal} export namespace someOther.something { export class someClass {} }
+ ${internal} export import someImport = someNamespace.C;
+ ${internal} export type internalType = internalC;
+ ${internal} export const internalConst = 10;
+ ${internal} export enum internalEnum { a, b, c }
+}
+${internal} export class internalC {}
+${internal} export function internalfoo() {}
+${internal} export namespace internalNamespace { export class someClass {} }
+${internal} export namespace internalOther.something { export class someClass {} }
+${internal} export import internalImport = internalNamespace.someClass;
+${internal} export type internalType = internalC;
+${internal} export const internalConst = 10;
+${internal} export enum internalEnum { a, b, c }`);
+ }
+
+ // Verify initial + incremental edits
+ verifyOutFileScenario({
+ scenario: "stripInternal",
+ modifyFs: stripInternalScenario,
+ modifyAgainFs: fs => replaceText(fs, sources[project.lib][source.ts][1], `export const`, `/*@internal*/ export const`),
+ });
+ });
+ });
+ });
+}
diff --git a/src/testRunner/unittests/tsbuild/emptyFiles.ts b/src/testRunner/unittests/tsbuild/emptyFiles.ts
new file mode 100644
index 0000000000000..17c6644ccc66c
--- /dev/null
+++ b/src/testRunner/unittests/tsbuild/emptyFiles.ts
@@ -0,0 +1,41 @@
+namespace ts {
+ const projFs = loadProjectFromDisk("tests/projects/empty-files");
+
+ const allExpectedOutputs = [
+ "/src/core/index.js",
+ "/src/core/index.d.ts",
+ "/src/core/index.d.ts.map",
+ ];
+
+ describe("unittests:: tsbuild - empty files option in tsconfig", () => {
+ it("has empty files diagnostic when files is empty and no references are provided", () => {
+ const fs = projFs.shadow();
+ const host = new fakes.SolutionBuilderHost(fs);
+ const builder = createSolutionBuilder(host, ["/src/no-references"], { dry: false, force: false, verbose: false });
+
+ host.clearDiagnostics();
+ builder.buildAllProjects();
+ host.assertDiagnosticMessages([Diagnostics.The_files_list_in_config_file_0_is_empty, "/src/no-references/tsconfig.json"]);
+
+ // Check for outputs to not be written.
+ for (const output of allExpectedOutputs) {
+ assert(!fs.existsSync(output), `Expect file ${output} to not exist`);
+ }
+ });
+
+ it("does not have empty files diagnostic when files is empty and references are provided", () => {
+ const fs = projFs.shadow();
+ const host = new fakes.SolutionBuilderHost(fs);
+ const builder = createSolutionBuilder(host, ["/src/with-references"], { dry: false, force: false, verbose: false });
+
+ host.clearDiagnostics();
+ builder.buildAllProjects();
+ host.assertDiagnosticMessages(/*empty*/);
+
+ // Check for outputs to be written.
+ for (const output of allExpectedOutputs) {
+ assert(fs.existsSync(output), `Expect file ${output} to exist`);
+ }
+ });
+ });
+}
diff --git a/src/testRunner/unittests/tsbuild/graphOrdering.ts b/src/testRunner/unittests/tsbuild/graphOrdering.ts
new file mode 100644
index 0000000000000..bc1af3f71da94
--- /dev/null
+++ b/src/testRunner/unittests/tsbuild/graphOrdering.ts
@@ -0,0 +1,81 @@
+namespace ts {
+ describe("unittests:: tsbuild - graph-ordering", () => {
+ let host: fakes.SolutionBuilderHost | undefined;
+ const deps: [string, string][] = [
+ ["A", "B"],
+ ["B", "C"],
+ ["A", "C"],
+ ["B", "D"],
+ ["C", "D"],
+ ["C", "E"],
+ ["F", "E"]
+ ];
+
+ before(() => {
+ const fs = new vfs.FileSystem(false);
+ host = new fakes.SolutionBuilderHost(fs);
+ writeProjects(fs, ["A", "B", "C", "D", "E", "F", "G"], deps);
+ });
+
+ after(() => {
+ host = undefined;
+ });
+
+ it("orders the graph correctly - specify two roots", () => {
+ checkGraphOrdering(["A", "G"], ["A", "B", "C", "D", "E", "G"]);
+ });
+
+ it("orders the graph correctly - multiple parts of the same graph in various orders", () => {
+ checkGraphOrdering(["A"], ["A", "B", "C", "D", "E"]);
+ checkGraphOrdering(["A", "C", "D"], ["A", "B", "C", "D", "E"]);
+ checkGraphOrdering(["D", "C", "A"], ["A", "B", "C", "D", "E"]);
+ });
+
+ it("orders the graph correctly - other orderings", () => {
+ checkGraphOrdering(["F"], ["F", "E"]);
+ checkGraphOrdering(["E"], ["E"]);
+ checkGraphOrdering(["F", "C", "A"], ["A", "B", "C", "D", "E", "F"]);
+ });
+
+ function checkGraphOrdering(rootNames: string[], expectedBuildSet: string[]) {
+ const builder = createSolutionBuilder(host!, rootNames, { dry: true, force: false, verbose: false });
+
+ const projFileNames = rootNames.map(getProjectFileName);
+ const graph = builder.getBuildGraph(projFileNames);
+
+ assert.sameMembers(graph.buildQueue, expectedBuildSet.map(getProjectFileName));
+
+ for (const dep of deps) {
+ const child = getProjectFileName(dep[0]);
+ if (graph.buildQueue.indexOf(child) < 0) continue;
+ const parent = getProjectFileName(dep[1]);
+ assert.isAbove(graph.buildQueue.indexOf(child), graph.buildQueue.indexOf(parent), `Expecting child ${child} to be built after parent ${parent}`);
+ }
+ }
+
+ function getProjectFileName(proj: string) {
+ return `/project/${proj}/tsconfig.json` as ResolvedConfigFileName;
+ }
+
+ function writeProjects(fileSystem: vfs.FileSystem, projectNames: string[], deps: [string, string][]): string[] {
+ const projFileNames: string[] = [];
+ for (const dep of deps) {
+ if (projectNames.indexOf(dep[0]) < 0) throw new Error(`Invalid dependency - project ${dep[0]} does not exist`);
+ if (projectNames.indexOf(dep[1]) < 0) throw new Error(`Invalid dependency - project ${dep[1]} does not exist`);
+ }
+ for (const proj of projectNames) {
+ fileSystem.mkdirpSync(`/project/${proj}`);
+ fileSystem.writeFileSync(`/project/${proj}/${proj}.ts`, "export {}");
+ const configFileName = getProjectFileName(proj);
+ const configContent = JSON.stringify({
+ compilerOptions: { composite: true },
+ files: [`./${proj}.ts`],
+ references: deps.filter(d => d[0] === proj).map(d => ({ path: `../${d[1]}` }))
+ }, undefined, 2);
+ fileSystem.writeFileSync(configFileName, configContent);
+ projFileNames.push(configFileName);
+ }
+ return projFileNames;
+ }
+ });
+}
diff --git a/src/testRunner/unittests/tsbuild/helpers.ts b/src/testRunner/unittests/tsbuild/helpers.ts
new file mode 100644
index 0000000000000..9672da1ff79e5
--- /dev/null
+++ b/src/testRunner/unittests/tsbuild/helpers.ts
@@ -0,0 +1,435 @@
+namespace ts {
+ export function getExpectedDiagnosticForProjectsInBuild(...projects: string[]): fakes.ExpectedDiagnostic {
+ return [Diagnostics.Projects_in_this_build_Colon_0, projects.map(p => "\r\n * " + p).join("")];
+ }
+
+ export function changeCompilerVersion(host: fakes.SolutionBuilderHost) {
+ const originalReadFile = host.readFile;
+ host.readFile = path => {
+ const value = originalReadFile.call(host, path);
+ if (!value || !isBuildInfoFile(path)) return value;
+ const buildInfo = getBuildInfo(value);
+ buildInfo.version = fakes.version;
+ return getBuildInfoText(buildInfo);
+ };
+ }
+
+ export function replaceText(fs: vfs.FileSystem, path: string, oldText: string, newText: string) {
+ if (!fs.statSync(path).isFile()) {
+ throw new Error(`File ${path} does not exist`);
+ }
+ const old = fs.readFileSync(path, "utf-8");
+ if (old.indexOf(oldText) < 0) {
+ throw new Error(`Text "${oldText}" does not exist in file ${path}`);
+ }
+ const newContent = old.replace(oldText, newText);
+ fs.writeFileSync(path, newContent, "utf-8");
+ }
+
+ export function prependText(fs: vfs.FileSystem, path: string, additionalContent: string) {
+ if (!fs.statSync(path).isFile()) {
+ throw new Error(`File ${path} does not exist`);
+ }
+ const old = fs.readFileSync(path, "utf-8");
+ fs.writeFileSync(path, `${additionalContent}${old}`, "utf-8");
+ }
+
+ export function appendText(fs: vfs.FileSystem, path: string, additionalContent: string) {
+ if (!fs.statSync(path).isFile()) {
+ throw new Error(`File ${path} does not exist`);
+ }
+ const old = fs.readFileSync(path, "utf-8");
+ fs.writeFileSync(path, `${old}${additionalContent}`);
+ }
+
+ export function getTime() {
+ let currentTime = 100;
+ return { tick, time, touch };
+
+ function tick() {
+ currentTime += 60_000;
+ }
+
+ function time() {
+ return currentTime;
+ }
+
+ function touch(fs: vfs.FileSystem, path: string) {
+ if (!fs.statSync(path).isFile()) {
+ throw new Error(`File ${path} does not exist`);
+ }
+ fs.utimesSync(path, new Date(time()), new Date(time()));
+ }
+ }
+
+ export function loadProjectFromDisk(root: string, time?: vfs.FileSystemOptions["time"]): vfs.FileSystem {
+ const resolver = vfs.createResolver(Harness.IO);
+ const fs = new vfs.FileSystem(/*ignoreCase*/ true, {
+ files: {
+ ["/lib"]: new vfs.Mount(vpath.resolve(Harness.IO.getWorkspaceRoot(), "built/local"), resolver),
+ ["/src"]: new vfs.Mount(vpath.resolve(Harness.IO.getWorkspaceRoot(), root), resolver)
+ },
+ cwd: "/",
+ meta: { defaultLibLocation: "/lib" },
+ time
+ });
+ fs.makeReadonly();
+ return fs;
+ }
+
+ export function getLibs() {
+ return [
+ "/lib/lib.d.ts",
+ "/lib/lib.es5.d.ts",
+ "/lib/lib.dom.d.ts",
+ "/lib/lib.webworker.importscripts.d.ts",
+ "/lib/lib.scripthost.d.ts"
+ ];
+ }
+
+ function generateSourceMapBaselineFiles(fs: vfs.FileSystem, mapFileNames: ReadonlyArray) {
+ for (const mapFile of mapFileNames) {
+ if (!fs.existsSync(mapFile)) continue;
+ const text = Harness.SourceMapRecorder.getSourceMapRecordWithVFS(fs, mapFile);
+ fs.writeFileSync(`${mapFile}.baseline.txt`, text);
+ }
+ }
+
+ // [tsbuildinfo, js, dts]
+ export type BuildInfoSectionBaselineFiles = [string, string | undefined, string | undefined];
+ function generateBuildInfoSectionBaselineFiles(fs: vfs.FileSystem, buildInfoFileNames: ReadonlyArray) {
+ for (const [file, jsFile, dtsFile] of buildInfoFileNames) {
+ if (!fs.existsSync(file)) continue;
+
+ const buildInfo = getBuildInfo(fs.readFileSync(file, "utf8"));
+ const bundle = buildInfo.bundle;
+ if (!bundle || (!length(bundle.js && bundle.js.sections) && !length(bundle.dts && bundle.dts.sections))) continue;
+
+ // Write the baselines:
+ const baselineRecorder = new Harness.Compiler.WriterAggregator();
+ generateBundleFileSectionInfo(fs, baselineRecorder, bundle.js, jsFile);
+ generateBundleFileSectionInfo(fs, baselineRecorder, bundle.dts, dtsFile);
+ baselineRecorder.Close();
+
+ const text = baselineRecorder.lines.join("\r\n");
+ fs.writeFileSync(`${file}.baseline.txt`, text, "utf8");
+ }
+ }
+
+ function generateBundleFileSectionInfo(fs: vfs.FileSystem, baselineRecorder: Harness.Compiler.WriterAggregator, bundleFileInfo: BundleFileInfo | undefined, outFile: string | undefined) {
+ if (!length(bundleFileInfo && bundleFileInfo.sections) && !outFile) return; // Nothing to baseline
+
+ const content = outFile && fs.existsSync(outFile) ? fs.readFileSync(outFile, "utf8") : "";
+ baselineRecorder.WriteLine("======================================================================");
+ baselineRecorder.WriteLine(`File:: ${outFile}`);
+ for (const section of bundleFileInfo ? bundleFileInfo.sections : emptyArray) {
+ baselineRecorder.WriteLine("----------------------------------------------------------------------");
+ writeSectionHeader(section);
+ if (section.kind !== BundleFileSectionKind.Prepend) {
+ writeTextOfSection(section.pos, section.end);
+ }
+ else {
+ Debug.assert(section.pos === first(section.texts).pos);
+ Debug.assert(section.end === last(section.texts).end);
+ for (const text of section.texts) {
+ baselineRecorder.WriteLine(">>--------------------------------------------------------------------");
+ writeSectionHeader(text);
+ writeTextOfSection(text.pos, text.end);
+ }
+ }
+ }
+ baselineRecorder.WriteLine("======================================================================");
+
+ function writeTextOfSection(pos: number, end: number) {
+ const textLines = content.substring(pos, end).split(/\r?\n/);
+ for (const line of textLines) {
+ baselineRecorder.WriteLine(line);
+ }
+ }
+
+ function writeSectionHeader(section: BundleFileSection) {
+ baselineRecorder.WriteLine(`${section.kind}: (${section.pos}-${section.end})${section.data ? ":: " + section.data : ""}${section.kind === BundleFileSectionKind.Prepend ? " texts:: " + section.texts.length : ""}`);
+ }
+ }
+
+ interface BuildInput {
+ fs: vfs.FileSystem;
+ tick: () => void;
+ rootNames: ReadonlyArray;
+ expectedMapFileNames: ReadonlyArray;
+ expectedBuildInfoFilesForSectionBaselines?: ReadonlyArray;
+ modifyFs: (fs: vfs.FileSystem) => void;
+ }
+
+ function build({ fs, tick, rootNames, expectedMapFileNames, expectedBuildInfoFilesForSectionBaselines, modifyFs }: BuildInput) {
+ const actualReadFileMap = createMap();
+ modifyFs(fs);
+ tick();
+
+ const host = new fakes.SolutionBuilderHost(fs);
+ const builder = createSolutionBuilder(host, rootNames, { dry: false, force: false, verbose: true });
+ host.clearDiagnostics();
+ const originalReadFile = host.readFile;
+ host.readFile = path => {
+ // Dont record libs
+ if (path.startsWith("/src/")) {
+ actualReadFileMap.set(path, (actualReadFileMap.get(path) || 0) + 1);
+ }
+ return originalReadFile.call(host, path);
+ };
+ builder.buildAllProjects();
+ generateSourceMapBaselineFiles(fs, expectedMapFileNames);
+ generateBuildInfoSectionBaselineFiles(fs, expectedBuildInfoFilesForSectionBaselines || emptyArray);
+ fs.makeReadonly();
+ return { fs, actualReadFileMap, host, builder };
+ }
+
+ 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
+ Harness.Baseline.runBaseline(`tsbuild/${proj}/${subScenario.split(" ").join("-")}/${scenario.split(" ").join("-")}.js`, patch ? vfs.formatPatch(patch) : null);
+ }
+
+ function verifyReadFileCalls(actualReadFileMap: Map, expectedReadFiles: ReadonlyMap) {
+ TestFSWithWatch.verifyMapSize("readFileCalls", actualReadFileMap, arrayFrom(expectedReadFiles.keys()));
+ expectedReadFiles.forEach((expected, expectedFile) => {
+ 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)))}`);
+ });
+ }
+
+ export function getReadFilesMap(filesReadOnce: ReadonlyArray, ...filesWithTwoReadCalls: string[]) {
+ const map = arrayToMap(filesReadOnce, identity, () => 1);
+ for (const fileWithTwoReadCalls of filesWithTwoReadCalls) {
+ map.set(fileWithTwoReadCalls, 2);
+ }
+ return map;
+ }
+
+ export interface ExpectedBuildOutput {
+ expectedDiagnostics?: ReadonlyArray;
+ expectedReadFiles?: ReadonlyMap;
+ }
+
+ export interface BuildState extends ExpectedBuildOutput {
+ modifyFs: (fs: vfs.FileSystem) => void;
+ }
+
+ export interface VerifyTsBuildInput {
+ scenario: string;
+ projFs: () => vfs.FileSystem;
+ time: () => number;
+ tick: () => void;
+ proj: string;
+ rootNames: ReadonlyArray;
+ expectedMapFileNames: ReadonlyArray;
+ expectedBuildInfoFilesForSectionBaselines?: ReadonlyArray;
+ lastProjectOutputJs: string;
+ initialBuild: BuildState;
+ outputFiles?: ReadonlyArray;
+ incrementalDtsChangedBuild?: BuildState;
+ incrementalDtsUnchangedBuild?: BuildState;
+ incrementalHeaderChangedBuild?: BuildState;
+ baselineOnly?: true;
+ }
+
+ export function verifyTsbuildOutput({
+ scenario, projFs, time, tick, proj, rootNames, outputFiles, baselineOnly,
+ expectedMapFileNames, expectedBuildInfoFilesForSectionBaselines, lastProjectOutputJs,
+ initialBuild, incrementalDtsChangedBuild, incrementalDtsUnchangedBuild, incrementalHeaderChangedBuild
+ }: VerifyTsBuildInput) {
+ describe(`tsc --b ${proj}:: ${scenario}`, () => {
+ let fs: vfs.FileSystem;
+ let actualReadFileMap: Map;
+ let firstBuildTime: number;
+ let host: fakes.SolutionBuilderHost;
+ before(() => {
+ const result = build({
+ fs: projFs().shadow(),
+ tick,
+ rootNames,
+ expectedMapFileNames,
+ expectedBuildInfoFilesForSectionBaselines,
+ modifyFs: initialBuild.modifyFs,
+ });
+ ({ fs, actualReadFileMap, host } = result);
+ firstBuildTime = time();
+ });
+ after(() => {
+ fs = undefined!;
+ actualReadFileMap = undefined!;
+ host = undefined!;
+ });
+ describe("initialBuild", () => {
+ if (!baselineOnly) {
+ it(`verify diagnostics`, () => {
+ host.assertDiagnosticMessages(...(initialBuild.expectedDiagnostics || emptyArray));
+ });
+ }
+ it(`Generates files matching the baseline`, () => {
+ generateBaseline(fs, proj, scenario, "initial Build", projFs());
+ });
+ if (!baselineOnly) {
+ it("verify readFile calls", () => {
+ verifyReadFileCalls(actualReadFileMap, Debug.assertDefined(initialBuild.expectedReadFiles));
+ });
+ }
+ });
+
+ function incrementalBuild(subScenario: string, incrementalModifyFs: (fs: vfs.FileSystem) => void, incrementalExpectedDiagnostics: ReadonlyArray | undefined, incrementalExpectedReadFiles: ReadonlyMap | undefined) {
+ describe(subScenario, () => {
+ let newFs: vfs.FileSystem;
+ let actualReadFileMap: Map;
+ let host: fakes.SolutionBuilderHost;
+ before(() => {
+ assert.equal(fs.statSync(lastProjectOutputJs).mtimeMs, firstBuildTime, "First build timestamp is correct");
+ tick();
+ newFs = fs.shadow();
+ tick();
+ ({ actualReadFileMap, host } = build({
+ fs: newFs,
+ tick,
+ rootNames,
+ expectedMapFileNames,
+ expectedBuildInfoFilesForSectionBaselines,
+ modifyFs: incrementalModifyFs,
+ }));
+ assert.equal(newFs.statSync(lastProjectOutputJs).mtimeMs, time(), "Second build timestamp is correct");
+ });
+ after(() => {
+ newFs = undefined!;
+ actualReadFileMap = undefined!;
+ host = undefined!;
+ });
+ if (!baselineOnly) {
+ it(`verify diagnostics`, () => {
+ host.assertDiagnosticMessages(...(incrementalExpectedDiagnostics || emptyArray));
+ });
+ }
+ it(`Generates files matching the baseline`, () => {
+ generateBaseline(newFs, proj, scenario, subScenario, fs);
+ });
+ if (!baselineOnly) {
+ it("verify readFile calls", () => {
+ verifyReadFileCalls(actualReadFileMap, Debug.assertDefined(incrementalExpectedReadFiles));
+ });
+ }
+ it(`Verify emit output file text is same when built clean`, () => {
+ const expectedOutputFiles = Debug.assertDefined(outputFiles);
+ const { fs } = build({
+ fs: newFs.shadow(),
+ tick,
+ rootNames,
+ expectedMapFileNames: emptyArray,
+ modifyFs: fs => {
+ // Delete output files
+ for (const outputFile of expectedOutputFiles) {
+ if (fs.existsSync(outputFile)) {
+ fs.rimrafSync(outputFile);
+ }
+ }
+ },
+ });
+
+ for (const outputFile of expectedOutputFiles) {
+ const expectedText = fs.existsSync(outputFile) ? fs.readFileSync(outputFile, "utf8") : undefined;
+ const actualText = newFs.existsSync(outputFile) ? newFs.readFileSync(outputFile, "utf8") : undefined;
+ assert.equal(actualText, expectedText, `File: ${outputFile}`);
+ }
+ });
+ });
+ }
+ if (incrementalDtsChangedBuild) {
+ incrementalBuild(
+ "incremental declaration changes",
+ incrementalDtsChangedBuild.modifyFs,
+ incrementalDtsChangedBuild.expectedDiagnostics,
+ incrementalDtsChangedBuild.expectedReadFiles,
+ );
+ }
+
+ if (incrementalDtsUnchangedBuild) {
+ incrementalBuild(
+ "incremental declaration doesnt change",
+ incrementalDtsUnchangedBuild.modifyFs,
+ incrementalDtsUnchangedBuild.expectedDiagnostics,
+ incrementalDtsUnchangedBuild.expectedReadFiles
+ );
+ }
+
+ if (incrementalHeaderChangedBuild) {
+ incrementalBuild(
+ "incremental headers change without dts changes",
+ incrementalHeaderChangedBuild.modifyFs,
+ incrementalHeaderChangedBuild.expectedDiagnostics,
+ incrementalHeaderChangedBuild.expectedReadFiles
+ );
+ }
+ });
+ }
+
+ export function enableStrict(fs: vfs.FileSystem, path: string) {
+ replaceText(fs, path, `"strict": false`, `"strict": true`);
+ }
+
+ export function addTestPrologue(fs: vfs.FileSystem, path: string, prologue: string) {
+ prependText(fs, path, `${prologue}
+`);
+ }
+
+ export function addShebang(fs: vfs.FileSystem, project: string, file: string) {
+ prependText(fs, `src/${project}/${file}.ts`, `#!someshebang ${project} ${file}
+`);
+ }
+
+ export function restContent(project: string, file: string) {
+ return `function for${project}${file}Rest() {
+const { b, ...rest } = { a: 10, b: 30, yy: 30 };
+}`;
+ }
+
+ function nonrestContent(project: string, file: string) {
+ return `function for${project}${file}Rest() { }`;
+ }
+
+ export function addRest(fs: vfs.FileSystem, project: string, file: string) {
+ appendText(fs, `src/${project}/${file}.ts`, restContent(project, file));
+ }
+
+ export function removeRest(fs: vfs.FileSystem, project: string, file: string) {
+ replaceText(fs, `src/${project}/${file}.ts`, restContent(project, file), nonrestContent(project, file));
+ }
+
+ export function addStubFoo(fs: vfs.FileSystem, project: string, file: string) {
+ appendText(fs, `src/${project}/${file}.ts`, nonrestContent(project, file));
+ }
+
+ export function changeStubToRest(fs: vfs.FileSystem, project: string, file: string) {
+ replaceText(fs, `src/${project}/${file}.ts`, nonrestContent(project, file), restContent(project, file));
+ }
+
+ export function addSpread(fs: vfs.FileSystem, project: string, file: string) {
+ const path = `src/${project}/${file}.ts`;
+ const content = fs.readFileSync(path, "utf8");
+ fs.writeFileSync(path, `${content}
+function ${project}${file}Spread(...b: number[]) { }
+${project}${file}Spread(...[10, 20, 30]);`);
+
+ replaceText(fs, `src/${project}/tsconfig.json`, `"strict": false,`, `"strict": false,
+ "downlevelIteration": true,`);
+ }
+
+ export function getTripleSlashRef(project: string) {
+ return `/src/${project}/tripleRef.d.ts`;
+ }
+
+ export function addTripleSlashRef(fs: vfs.FileSystem, project: string, file: string) {
+ fs.writeFileSync(getTripleSlashRef(project), `declare class ${project}${file} { }`);
+ prependText(fs, `src/${project}/${file}.ts`, `///
+const ${file}Const = new ${project}${file}();
+`);
+ }
+}
diff --git a/src/testRunner/unittests/tsbuild/missingExtendedFile.ts b/src/testRunner/unittests/tsbuild/missingExtendedFile.ts
new file mode 100644
index 0000000000000..00e8bfec1e3e4
--- /dev/null
+++ b/src/testRunner/unittests/tsbuild/missingExtendedFile.ts
@@ -0,0 +1,17 @@
+namespace ts {
+ describe("unittests:: tsbuild:: when tsconfig extends the missing file", () => {
+ it("unittests:: tsbuild - when tsconfig extends the missing file", () => {
+ const projFs = loadProjectFromDisk("tests/projects/missingExtendedConfig");
+ const fs = projFs.shadow();
+ const host = new fakes.SolutionBuilderHost(fs);
+ const builder = createSolutionBuilder(host, ["/src/tsconfig.json"], {});
+ builder.buildAllProjects();
+ host.assertDiagnosticMessages(
+ [Diagnostics.The_specified_path_does_not_exist_Colon_0, "/src/foobar.json"],
+ [Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, "/src/tsconfig.first.json", "[\"**/*\"]", "[]"],
+ [Diagnostics.The_specified_path_does_not_exist_Colon_0, "/src/foobar.json"],
+ [Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, "/src/tsconfig.second.json", "[\"**/*\"]", "[]"]
+ );
+ });
+ });
+}
diff --git a/src/testRunner/unittests/tsbuild/outFile.ts b/src/testRunner/unittests/tsbuild/outFile.ts
new file mode 100644
index 0000000000000..e9b7cdae32626
--- /dev/null
+++ b/src/testRunner/unittests/tsbuild/outFile.ts
@@ -0,0 +1,860 @@
+namespace ts {
+ describe("unittests:: tsbuild:: outFile::", () => {
+ let outFileFs: vfs.FileSystem;
+ const enum ext { js, jsmap, dts, dtsmap, buildinfo }
+ const enum project { first, second, third }
+ type OutputFile = [string, string, string, string, string];
+ function relName(path: string) { return path.slice(1); }
+ const outputFiles: [OutputFile, OutputFile, OutputFile] = [
+ [
+ "/src/first/bin/first-output.js",
+ "/src/first/bin/first-output.js.map",
+ "/src/first/bin/first-output.d.ts",
+ "/src/first/bin/first-output.d.ts.map",
+ "/src/first/bin/first-output.tsbuildinfo"
+ ],
+ [
+ "/src/2/second-output.js",
+ "/src/2/second-output.js.map",
+ "/src/2/second-output.d.ts",
+ "/src/2/second-output.d.ts.map",
+ "/src/2/second-output.tsbuildinfo"
+ ],
+ [
+ "/src/third/thirdjs/output/third-output.js",
+ "/src/third/thirdjs/output/third-output.js.map",
+ "/src/third/thirdjs/output/third-output.d.ts",
+ "/src/third/thirdjs/output/third-output.d.ts.map",
+ "/src/third/thirdjs/output/third-output.tsbuildinfo"
+ ]
+ ];
+ const relOutputFiles = outputFiles.map(v => v.map(relName)) as [OutputFile, OutputFile, OutputFile];
+ type Sources = [string, ReadonlyArray];
+ const enum source { config, ts }
+ const enum part { one, two, three }
+ const sources: [Sources, Sources, Sources] = [
+ [
+ "/src/first/tsconfig.json",
+ [
+ "/src/first/first_PART1.ts",
+ "/src/first/first_part2.ts",
+ "/src/first/first_part3.ts"
+ ]
+ ],
+ [
+ "/src/second/tsconfig.json",
+ [
+ "/src/second/second_part1.ts",
+ "/src/second/second_part2.ts"
+ ]
+ ],
+ [
+ "/src/third/tsconfig.json",
+ [
+ "/src/third/third_part1.ts"
+ ]
+ ]
+ ];
+ const expectedMapFileNames = [
+ outputFiles[project.first][ext.jsmap],
+ outputFiles[project.first][ext.dtsmap],
+ outputFiles[project.second][ext.jsmap],
+ outputFiles[project.second][ext.dtsmap],
+ outputFiles[project.third][ext.jsmap],
+ outputFiles[project.third][ext.dtsmap]
+ ];
+ const expectedTsbuildInfoFileNames: ReadonlyArray = [
+ [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]]
+ ];
+ const relSources = sources.map(([config, sources]) => [relName(config), sources.map(relName)]) as any as [Sources, Sources, Sources];
+ const { time, tick } = getTime();
+ let expectedOutputFiles = [
+ ...outputFiles[project.first],
+ ...outputFiles[project.second],
+ ...outputFiles[project.third]
+ ];
+ let initialExpectedDiagnostics: ReadonlyArray = [
+ 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]],
+ [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relSources[project.second][source.config], relOutputFiles[project.second][ext.js]],
+ [Diagnostics.Building_project_0, sources[project.second][source.config]],
+ [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relSources[project.third][source.config], relOutputFiles[project.third][ext.js]],
+ [Diagnostics.Building_project_0, sources[project.third][source.config]]
+ ];
+ let initialExpectedReadFiles: ReadonlyMap = getReadFilesMap(
+ [
+ // Configs
+ sources[project.first][source.config],
+ sources[project.second][source.config],
+ sources[project.third][source.config],
+
+ // Source files
+ ...sources[project.first][source.ts],
+ ...sources[project.second][source.ts],
+ ...sources[project.third][source.ts],
+
+ // outputs
+ ...outputFiles[project.first],
+ ...outputFiles[project.second],
+
+ // build info
+ outputFiles[project.third][ext.buildinfo],
+ ],
+ // These are first not present and later read new contents to generate third output
+ outputFiles[project.first][ext.buildinfo],
+ outputFiles[project.second][ext.buildinfo]
+ );
+
+ let dtsChangedExpectedDiagnostics: ReadonlyArray = [
+ 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]],
+ [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relSources[project.second][source.config], relSources[project.second][source.ts][part.one], relOutputFiles[project.second][ext.js]],
+ [Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relSources[project.third][source.config], relOutputFiles[project.third][ext.js], "src/first"],
+ [Diagnostics.Building_project_0, sources[project.third][source.config]]
+ ];
+ let dtsChangedExpectedReadFiles: ReadonlyMap = getReadFilesMap(
+ [
+ // Configs
+ sources[project.first][source.config],
+ sources[project.second][source.config],
+ sources[project.third][source.config],
+
+ // Source files
+ ...sources[project.first][source.ts],
+ ...sources[project.third][source.ts],
+
+ // outputs
+ ...outputFiles[project.first],
+ ...outputFiles[project.second],
+ outputFiles[project.third][ext.dts],
+
+ // build info
+ outputFiles[project.third][ext.buildinfo],
+ ],
+ outputFiles[project.first][ext.dts], // dts changes so once read old content, and once new (to emit third)
+ outputFiles[project.first][ext.buildinfo], // since first build info changes
+ );
+
+ let dtsChangedExpectedDiagnosticsDependOrdered: ReadonlyArray = [
+ 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]],
+ [Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relSources[project.second][source.config], relOutputFiles[project.second][ext.js], "src/first"],
+ [Diagnostics.Building_project_0, sources[project.second][source.config]],
+ [Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relSources[project.third][source.config], relOutputFiles[project.third][ext.js], "src/second"],
+ [Diagnostics.Building_project_0, sources[project.third][source.config]]
+ ];
+ let dtsChangedExpectedReadFilesDependOrdered: ReadonlyMap = getDtsChangedReadFilesDependOrdered();
+
+ let dtsUnchangedExpectedDiagnostics: ReadonlyArray = [
+ 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]],
+ [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relSources[project.second][source.config], relSources[project.second][source.ts][part.one], relOutputFiles[project.second][ext.js]],
+ [Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relSources[project.third][source.config], "src/first"],
+ [Diagnostics.Updating_output_of_project_0, sources[project.third][source.config]],
+ [Diagnostics.Updating_unchanged_output_timestamps_of_project_0, sources[project.third][source.config]],
+ ];
+ let dtsUnchangedExpectedReadFiles: ReadonlyMap = getReadFilesMap(
+ [
+ // Configs
+ sources[project.first][source.config],
+ sources[project.second][source.config],
+ sources[project.third][source.config],
+
+ // Source files
+ ...sources[project.first][source.ts],
+
+ // outputs to prepend
+ ...outputFiles[project.first],
+ ...outputFiles[project.second],
+ ...outputFiles[project.third],
+ ],
+ outputFiles[project.first][ext.buildinfo], // since first build info changes
+ );
+
+ let dtsUnchangedExpectedDiagnosticsDependOrdered: ReadonlyArray = [
+ 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]],
+ [Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relSources[project.second][source.config], "src/first"],
+ [Diagnostics.Updating_output_of_project_0, sources[project.second][source.config]],
+ [Diagnostics.Updating_unchanged_output_timestamps_of_project_0, sources[project.second][source.config]],
+ [Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relSources[project.third][source.config], "src/second"],
+ [Diagnostics.Updating_output_of_project_0, sources[project.third][source.config]],
+ [Diagnostics.Updating_unchanged_output_timestamps_of_project_0, sources[project.third][source.config]],
+ ];
+ let dtsUnchangedExpectedReadFilesDependOrdered: ReadonlyMap = getDtsUnchangedExpectedReadFilesDependOrdered();
+
+ before(() => {
+ outFileFs = loadProjectFromDisk("tests/projects/outfile-concat", time);
+ });
+ after(() => {
+ outFileFs = undefined!;
+ expectedOutputFiles = undefined!;
+ initialExpectedDiagnostics = undefined!;
+ initialExpectedReadFiles = undefined!;
+ dtsChangedExpectedDiagnostics = undefined!;
+ dtsChangedExpectedReadFiles = undefined!;
+ dtsChangedExpectedDiagnosticsDependOrdered = undefined!;
+ dtsChangedExpectedReadFilesDependOrdered = undefined!;
+ dtsUnchangedExpectedDiagnostics = undefined!;
+ dtsUnchangedExpectedReadFiles = undefined!;
+ dtsUnchangedExpectedDiagnosticsDependOrdered = undefined!;
+ dtsUnchangedExpectedReadFilesDependOrdered = undefined!;
+ });
+
+ function createSolutionBuilder(host: fakes.SolutionBuilderHost) {
+ return ts.createSolutionBuilder(host, ["/src/third"], { dry: false, force: false, verbose: true });
+ }
+
+ function getInitialExpectedReadFiles(additionalSourceFiles?: ReadonlyArray) {
+ if (!additionalSourceFiles) return initialExpectedReadFiles;
+ const expectedReadFiles = cloneMap(initialExpectedReadFiles);
+ for (const path of additionalSourceFiles) {
+ expectedReadFiles.set(path, 1);
+ }
+ return expectedReadFiles;
+ }
+
+ function getDtsChangedReadFilesDependOrdered() {
+ const value = cloneMap(dtsChangedExpectedReadFiles);
+ for (const path of sources[project.second][source.ts]) {
+ value.set(path, 1);
+ }
+ value.set(outputFiles[project.second][ext.dts], 2); // dts changes so once read old content, and once new (to emit third)
+ value.set(outputFiles[project.second][ext.buildinfo], 2); // since first build info changes
+ return value;
+ }
+
+ function getDtsChangedReadFiles(dependOrdered?: boolean, additionalSourceFiles?: ReadonlyArray) {
+ const value = dependOrdered ? dtsChangedExpectedReadFilesDependOrdered : dtsChangedExpectedReadFiles;
+ if (!additionalSourceFiles) return value;
+ const expectedReadFiles = cloneMap(value);
+ for (const path of additionalSourceFiles) {
+ expectedReadFiles.set(path, 1);
+ }
+ return expectedReadFiles;
+ }
+
+ function getDtsUnchangedExpectedReadFilesDependOrdered() {
+ const value = cloneMap(dtsUnchangedExpectedReadFiles);
+ // Since this changes too
+ for (const path of outputFiles[project.second]) {
+ value.set(path, 2);
+ }
+ return value;
+ }
+
+ function getDtsUnchangedReadFiles(dependOrdered?: boolean, additionalSourceFiles?: ReadonlyArray) {
+ const value = dependOrdered ? dtsUnchangedExpectedReadFilesDependOrdered : dtsUnchangedExpectedReadFiles;
+ if (!additionalSourceFiles || additionalSourceFiles.length !== 3) return value;
+ const expectedReadFiles = cloneMap(value);
+ // Additional source Files
+ expectedReadFiles.set(additionalSourceFiles[project.first], 1);
+ return expectedReadFiles;
+ }
+
+ interface VerifyOutFileScenarioInput {
+ scenario: string;
+ modifyFs: (fs: vfs.FileSystem) => void;
+ modifyAgainFs?: (fs: vfs.FileSystem) => void;
+ additionalSourceFiles?: ReadonlyArray;
+ expectedBuildInfoFilesForSectionBaselines?: ReadonlyArray