- return parent_23.parent.parent;
+ return parent.parent.parent;
}
break;
// The context token is the closing } or " of an attribute, which means
// its parent is a JsxExpression, whose parent is a JsxAttribute,
// whose parent is a JsxOpeningLikeElement
case 9 /* StringLiteral */:
- if (parent_23 && ((parent_23.kind === 261 /* JsxAttribute */) || (parent_23.kind === 263 /* JsxSpreadAttribute */))) {
+ if (parent && ((parent.kind === 261 /* JsxAttribute */) || (parent.kind === 263 /* JsxSpreadAttribute */))) {
// Currently we parse JsxOpeningLikeElement as:
// JsxOpeningLikeElement
// attributes: JsxAttributes
// properties: NodeArray
- return parent_23.parent.parent;
+ return parent.parent.parent;
}
break;
case 18 /* CloseBraceToken */:
- if (parent_23 &&
- parent_23.kind === 264 /* JsxExpression */ &&
- parent_23.parent && parent_23.parent.kind === 261 /* JsxAttribute */) {
+ if (parent &&
+ parent.kind === 264 /* JsxExpression */ &&
+ parent.parent && parent.parent.kind === 261 /* JsxAttribute */) {
// Currently we parse JsxOpeningLikeElement as:
// JsxOpeningLikeElement
// attributes: JsxAttributes
// properties: NodeArray
// each JsxAttribute can have initializer as JsxExpression
- return parent_23.parent.parent.parent;
+ return parent.parent.parent.parent;
}
- if (parent_23 && parent_23.kind === 263 /* JsxSpreadAttribute */) {
+ if (parent && parent.kind === 263 /* JsxSpreadAttribute */) {
// Currently we parse JsxOpeningLikeElement as:
// JsxOpeningLikeElement
// attributes: JsxAttributes
// properties: NodeArray
- return parent_23.parent.parent;
+ return parent.parent.parent;
}
break;
}
@@ -87454,8 +88624,8 @@ var ts;
// TODO: Account for computed property name
// NOTE: if one only performs this step when m.name is an identifier,
// things like '__proto__' are not filtered out.
- var name_62 = ts.getNameOfDeclaration(m);
- existingName = ts.isPropertyNameLiteral(name_62) ? ts.getEscapedTextOfIdentifierOrLiteral(name_62) : undefined;
+ var name = ts.getNameOfDeclaration(m);
+ existingName = ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
}
existingMemberNames.set(existingName, true);
}
@@ -87670,7 +88840,7 @@ var ts;
function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) {
// class c { method() { } | method2() { } }
switch (location.kind) {
- case 294 /* SyntaxList */:
+ case 296 /* 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);
@@ -87707,6 +88877,10 @@ var ts;
}
function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) {
switch (triggerCharacter) {
+ case ".":
+ case "/":
+ case "@":
+ return true;
case '"':
case "'":
case "`":
@@ -87716,7 +88890,7 @@ var ts;
// Opening JSX tag
return contextToken.kind === 27 /* LessThanToken */ && contextToken.parent.kind !== 199 /* BinaryExpression */;
default:
- return ts.Debug.fail(triggerCharacter);
+ return ts.Debug.assertNever(triggerCharacter);
}
}
function isStringLiteralOrTemplate(node) {
@@ -87811,6 +88985,10 @@ var ts;
case 125 /* GetKeyword */:
case 136 /* SetKeyword */:
return getFromAllDeclarations(ts.isAccessor, [125 /* GetKeyword */, 136 /* SetKeyword */]);
+ case 121 /* AwaitKeyword */:
+ return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences);
+ case 120 /* AsyncKeyword */:
+ return highlightSpans(getAsyncAndAwaitOccurrences(node));
default:
return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent))
? highlightSpans(getModifierOccurrences(node.kind, node.parent))
@@ -87851,16 +89029,16 @@ var ts;
function getThrowStatementOwner(throwStatement) {
var child = throwStatement;
while (child.parent) {
- var parent_24 = child.parent;
- if (ts.isFunctionBlock(parent_24) || parent_24.kind === 273 /* SourceFile */) {
- return parent_24;
+ var parent = child.parent;
+ if (ts.isFunctionBlock(parent) || parent.kind === 273 /* SourceFile */) {
+ return parent;
}
// A throw-statement is only owned by a try-statement if the try-statement has
// a catch clause, and if the throw-statement occurs within the try block.
- if (ts.isTryStatement(parent_24) && parent_24.tryBlock === child && parent_24.catchClause) {
+ if (ts.isTryStatement(parent) && parent.tryBlock === child && parent.catchClause) {
return child;
}
- child = parent_24;
+ child = parent;
}
return undefined;
}
@@ -88058,6 +89236,29 @@ var ts;
});
return keywords;
}
+ function getAsyncAndAwaitOccurrences(node) {
+ var func = ts.getContainingFunction(node);
+ if (!func) {
+ return undefined;
+ }
+ var keywords = [];
+ if (func.modifiers) {
+ func.modifiers.forEach(function (modifier) {
+ pushKeywordIf(keywords, modifier, 120 /* AsyncKeyword */);
+ });
+ }
+ ts.forEachChild(func, aggregate);
+ return keywords;
+ function aggregate(node) {
+ if (ts.isAwaitExpression(node)) {
+ pushKeywordIf(keywords, node.getFirstToken(), 121 /* AwaitKeyword */);
+ }
+ // Do not cross function boundaries.
+ if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) {
+ ts.forEachChild(node, aggregate);
+ }
+ }
+ }
function getIfElseOccurrences(ifStatement, sourceFile) {
var keywords = getIfElseKeywords(ifStatement, sourceFile);
var result = [];
@@ -88178,9 +89379,10 @@ var ts;
function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) {
var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true);
var entry = bucket.get(path);
+ var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target;
if (!entry) {
// Have never seen this file with these settings. Create a new source file for it.
- var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind);
+ var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind);
entry = {
sourceFile: sourceFile,
languageServiceRefCount: 1,
@@ -88297,11 +89499,11 @@ var ts;
switch (direct.kind) {
case 186 /* CallExpression */:
if (!isAvailableThroughGlobal) {
- var parent_25 = direct.parent;
- if (exportKind === 2 /* ExportEquals */ && parent_25.kind === 231 /* VariableDeclaration */) {
- var name_63 = parent_25.name;
- if (name_63.kind === 71 /* Identifier */) {
- directImports.push(name_63);
+ var parent = direct.parent;
+ if (exportKind === 2 /* ExportEquals */ && parent.kind === 231 /* VariableDeclaration */) {
+ var name = parent.name;
+ if (name.kind === 71 /* Identifier */) {
+ directImports.push(name);
break;
}
}
@@ -88309,6 +89511,8 @@ var ts;
addIndirectUser(direct.getSourceFile());
}
break;
+ case 71 /* Identifier */: // for 'const x = require("y");
+ break; // TODO: GH#23879
case 242 /* ImportEqualsDeclaration */:
handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */));
break;
@@ -88338,6 +89542,17 @@ var ts;
directImports.push(direct);
}
break;
+ case 178 /* ImportType */:
+ if (direct.qualifier) {
+ // `import("foo").x` named import
+ directImports.push(direct);
+ }
+ else {
+ // TODO: GH#23879
+ }
+ break;
+ default:
+ ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct));
}
}
}
@@ -88415,6 +89630,9 @@ var ts;
return;
}
if (decl.kind === 178 /* ImportType */) {
+ if (decl.qualifier) { // TODO: GH#23879
+ singleReferences.push(decl.qualifier.kind === 71 /* Identifier */ ? decl.qualifier : decl.qualifier.right);
+ }
return;
}
// Ignore if there's a grammar error
@@ -88439,12 +89657,12 @@ var ts;
}
else {
// `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals
- var name_64 = importClause.name;
+ var name = importClause.name;
// If a default import has the same name as the default export, allow to rename it.
// Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that.
- if (name_64 && (!isForRename || name_64.escapedText === symbolName(exportSymbol))) {
- var defaultImportAlias = checker.getSymbolAtLocation(name_64);
- addSearch(name_64, defaultImportAlias);
+ if (name && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) {
+ var defaultImportAlias = checker.getSymbolAtLocation(name);
+ addSearch(name, defaultImportAlias);
}
// 'default' might be accessed as a named import `{ default as foo }`.
if (exportKind === 1 /* Default */) {
@@ -88469,8 +89687,8 @@ var ts;
}
for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
var element = _a[_i];
- var name_65 = element.name, propertyName = element.propertyName;
- if (!isNameMatch((propertyName || name_65).escapedText)) {
+ var name = element.name, propertyName = element.propertyName;
+ if (!isNameMatch((propertyName || name).escapedText)) {
continue;
}
if (propertyName) {
@@ -88478,16 +89696,16 @@ var ts;
singleReferences.push(propertyName);
// If renaming `{ foo as bar }`, don't touch `bar`, just `foo`.
// But do rename `foo` in ` { default as foo }` if that's the original export name.
- if (!isForRename || name_65.escapedText === exportSymbol.escapedName) {
+ if (!isForRename || name.escapedText === exportSymbol.escapedName) {
// Search locally for `bar`.
- addSearch(name_65, checker.getSymbolAtLocation(name_65));
+ addSearch(name, checker.getSymbolAtLocation(name));
}
}
else {
var localSymbol = element.kind === 251 /* ExportSpecifier */ && element.propertyName
? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol.
- : checker.getSymbolAtLocation(name_65);
- addSearch(name_65, localSymbol);
+ : checker.getSymbolAtLocation(name);
+ addSearch(name, localSymbol);
}
}
}
@@ -88500,24 +89718,18 @@ var ts;
function findNamespaceReExports(sourceFileLike, name, checker) {
var namespaceImportSymbol = checker.getSymbolAtLocation(name);
return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) {
- if (statement.kind !== 249 /* ExportDeclaration */)
+ if (!ts.isExportDeclaration(statement))
return;
- var _a = statement, exportClause = _a.exportClause, moduleSpecifier = _a.moduleSpecifier;
- if (moduleSpecifier || !exportClause)
- return;
- for (var _i = 0, _b = exportClause.elements; _i < _b.length; _i++) {
- var element = _b[_i];
- if (checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol) {
- return true;
- }
- }
+ var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier;
+ return !moduleSpecifier && exportClause &&
+ exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; });
});
}
function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
var refs = [];
var checker = program.getTypeChecker();
- for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
- var referencingFile = sourceFiles_4[_i];
+ for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
+ var referencingFile = sourceFiles_5[_i];
var searchSourceFile = searchModuleSymbol.valueDeclaration;
if (searchSourceFile.kind === 273 /* SourceFile */) {
for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
@@ -88547,8 +89759,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_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
- var sourceFile = sourceFiles_5[_i];
+ for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
+ var sourceFile = sourceFiles_6[_i];
cancellationToken.throwIfCancellationRequested();
forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
@@ -88653,6 +89865,9 @@ var ts;
else if (ts.isBinaryExpression(parent.parent)) {
return getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ true);
}
+ else if (ts.isJSDocTypedefTag(parent)) {
+ return exportInfo(symbol, 0 /* Named */);
+ }
}
function getExportAssignmentExport(ex) {
// Get the symbol for the `export =` node; its parent is the module it's the export of.
@@ -88697,7 +89912,7 @@ var ts;
// If the import has a different name than the export, do not continue searching.
// If `importedName` is undefined, do continue searching as the export is anonymous.
// (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.)
- var importedName = symbolName(importedSymbol);
+ var importedName = ts.symbolEscapedNameNoDefault(importedSymbol);
if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) {
return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport);
}
@@ -88764,15 +89979,6 @@ var ts;
return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined;
}
FindAllReferences.getExportInfo = getExportInfo;
- function symbolName(symbol) {
- if (symbol.escapedName !== "default" /* Default */) {
- return symbol.escapedName;
- }
- return ts.forEach(symbol.declarations, function (decl) {
- var name = ts.getNameOfDeclaration(decl);
- return name && name.kind === 71 /* Identifier */ && name.escapedText;
- });
- }
/** If at an export specifier, go to the symbol it refers to. */
function skipExportSpecifierSymbol(symbol, checker) {
// For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does.
@@ -88847,9 +90053,9 @@ var ts;
// 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 === 270 /* ShorthandPropertyAssignment */) {
- var result_4 = [];
- FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); });
- return result_4;
+ var result_5 = [];
+ FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); });
+ return result_5;
}
else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
// References to and accesses on the super keyword only have one possible implementation, so no
@@ -88882,8 +90088,8 @@ var ts;
case "symbol": {
var symbol = def.symbol;
var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind;
- var name_66 = 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_66, kind: kind_1, displayParts: displayParts_1 };
+ 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 };
}
case "label": {
var node_3 = def.node;
@@ -88891,13 +90097,13 @@ var ts;
}
case "keyword": {
var node_4 = def.node;
- var name_67 = ts.tokenToString(node_4.kind);
- return { node: node_4, name: name_67, kind: "keyword" /* keyword */, displayParts: [{ text: name_67, kind: "keyword" /* keyword */ }] };
+ 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 */ }] };
}
case "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;
+ 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 };
}
case "string": {
@@ -89041,6 +90247,8 @@ var ts;
case 243 /* ImportDeclaration */:
case 249 /* ExportDeclaration */:
return true;
+ case 177 /* LiteralType */:
+ return ts.isImportTypeNode(node.parent.parent);
case 186 /* CallExpression */:
return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) || ts.isImportCall(node.parent);
default:
@@ -89160,7 +90368,6 @@ var ts;
return ts.firstDefined(symbol.declarations, function (decl) {
if (!decl.parent) {
// Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here.
- ts.Debug.assert(decl.kind === 273 /* SourceFile */);
ts.Debug.fail("Unexpected symbol at " + ts.Debug.showSyntaxKind(node) + ": " + ts.Debug.showSymbol(symbol));
}
return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent)
@@ -89279,7 +90486,8 @@ var ts;
for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) {
var singleRef = singleReferences_1[_i];
// At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename.
- if (!(state.options.isForRename && (ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */)) {
+ if (hasMatchingMeaning(singleRef, state) &&
+ !(state.options.isForRename && (ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */)) {
addRef(singleRef);
}
}
@@ -89333,22 +90541,14 @@ var ts;
var bindingElement = ts.getDeclarationOfKind(symbol, 181 /* BindingElement */);
if (bindingElement &&
bindingElement.parent.kind === 179 /* ObjectBindingPattern */ &&
+ ts.isIdentifier(bindingElement.name) &&
!bindingElement.propertyName) {
return bindingElement;
}
}
function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) {
var bindingElement = getObjectBindingElementWithoutPropertyName(symbol);
- if (!bindingElement)
- return undefined;
- var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
- var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
- if (propSymbol && propSymbol.flags & 98304 /* Accessor */) {
- // See GH#16922
- ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */));
- return propSymbol.target;
- }
- return propSymbol;
+ return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement);
}
/**
* Determines the smallest scope in which a symbol may have named references.
@@ -89519,6 +90719,9 @@ var ts;
getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere);
}
}
+ function hasMatchingMeaning(referenceLocation, state) {
+ return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning);
+ }
function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) {
var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (!isValidReferencePosition(referenceLocation, search.text)) {
@@ -89534,9 +90737,8 @@ var ts;
}
return;
}
- if (!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning)) {
+ if (!hasMatchingMeaning(referenceLocation, state))
return;
- }
var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation);
if (!referenceSymbol) {
return;
@@ -90197,7 +91399,9 @@ var ts;
var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration);
// For a function, if this is the original function definition, return just sigInfo.
// If this is the original constructor definition, parent is the class.
- return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; })
+ return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; }) ||
+ // TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias
+ symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })
? [sigInfo]
: [sigInfo].concat(getDefinitionFromSymbol(typeChecker, symbol, node));
}
@@ -90252,14 +91456,14 @@ var ts;
function getReferenceAtPosition(sourceFile, position, program) {
var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position);
if (referencePath) {
- var file = ts.tryResolveScriptReference(program, sourceFile, referencePath);
- return file && { fileName: referencePath.fileName, file: file };
+ var file_15 = ts.tryResolveScriptReference(program, sourceFile, referencePath);
+ return file_15 && { fileName: referencePath.fileName, file: file_15 };
}
var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
if (typeReferenceDirective) {
var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName);
- var file = reference && program.getSourceFile(reference.resolvedFileName);
- return file && { fileName: typeReferenceDirective.fileName, file: file };
+ var file_16 = reference && program.getSourceFile(reference.resolvedFileName);
+ return file_16 && { fileName: typeReferenceDirective.fileName, file: file_16 };
}
return undefined;
}
@@ -90495,9 +91699,9 @@ var ts;
JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
function getCommentHavingNodes(declaration) {
switch (declaration.kind) {
- case 293 /* JSDocPropertyTag */:
+ case 295 /* JSDocPropertyTag */:
return [declaration];
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return [declaration.parent];
default:
return ts.getJSDocCommentsAndTags(declaration);
@@ -90518,17 +91722,17 @@ var ts;
function getCommentText(tag) {
var comment = tag.comment;
switch (tag.kind) {
- case 286 /* JSDocAugmentsTag */:
+ case 288 /* JSDocAugmentsTag */:
return withNode(tag.class);
- case 291 /* JSDocTemplateTag */:
+ case 293 /* JSDocTemplateTag */:
return withList(tag.typeParameters);
- case 290 /* JSDocTypeTag */:
+ case 292 /* JSDocTypeTag */:
return withNode(tag.typeExpression);
- case 292 /* JSDocTypedefTag */:
- case 293 /* JSDocPropertyTag */:
- case 288 /* JSDocParameterTag */:
- var name_68 = tag.name;
- return name_68 ? withNode(name_68) : comment;
+ case 294 /* JSDocTypedefTag */:
+ case 295 /* JSDocPropertyTag */:
+ case 290 /* JSDocParameterTag */:
+ var name = tag.name;
+ return name ? withNode(name) : comment;
default:
return comment;
}
@@ -90915,8 +92119,8 @@ var ts;
getTypingNamesFromSourceFileNames(fileNames);
// add typings for unresolved imports
if (unresolvedImports) {
- var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
- addInferredTypings(module, "Inferred typings from unresolved imports");
+ var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
+ addInferredTypings(module_1, "Inferred typings from unresolved imports");
}
// Add the cached typing locations for inferred typings that are already installed
packageNameToTypingLocation.forEach(function (typing, name) {
@@ -91013,8 +92217,8 @@ var ts;
if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
continue;
}
- var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
- var packageJson = result_5.config;
+ var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
+ var packageJson = result_6.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.
@@ -91114,7 +92318,7 @@ var ts;
if (!patternMatcher)
return ts.emptyArray;
var rawItems = [];
- var _loop_12 = function (sourceFile) {
+ var _loop_13 = function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) {
return "continue";
@@ -91124,9 +92328,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_12(sourceFile);
+ for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) {
+ var sourceFile = sourceFiles_7[_i];
+ _loop_13(sourceFile);
}
rawItems.sort(compareNavigateToItems);
if (maxResultCount !== undefined) {
@@ -91425,9 +92629,9 @@ var ts;
break;
case 181 /* BindingElement */:
case 231 /* VariableDeclaration */:
- var _d = node, name_69 = _d.name, initializer = _d.initializer;
- if (ts.isBindingPattern(name_69)) {
- addChildrenRecursively(name_69);
+ var _d = node, name = _d.name, initializer = _d.initializer;
+ if (ts.isBindingPattern(name)) {
+ addChildrenRecursively(name);
}
else if (initializer && isFunctionOrClassExpression(initializer)) {
if (initializer.name) {
@@ -91503,7 +92707,7 @@ var ts;
if (ts.hasJSDocNodes(node)) {
ts.forEach(node.jsDoc, function (jsDoc) {
ts.forEach(jsDoc.tags, function (tag) {
- if (tag.kind === 292 /* JSDocTypedefTag */) {
+ if (tag.kind === 294 /* JSDocTypedefTag */) {
addLeafNode(tag);
}
});
@@ -91578,6 +92782,7 @@ var ts;
}
/** Merge source into target. Source should be thrown away after this is called. */
function merge(target, source) {
+ var _a;
target.additionalNodes = target.additionalNodes || [];
target.additionalNodes.push(source.node);
if (source.additionalNodes) {
@@ -91588,7 +92793,6 @@ var ts;
mergeChildren(target.children);
sortChildren(target.children);
}
- var _a;
}
/** Recursively ensure that each NavNode's children are in sorted order. */
function sortChildren(children) {
@@ -91616,7 +92820,7 @@ var ts;
case 192 /* ArrowFunction */:
case 204 /* ClassExpression */:
return getFunctionOrClassName(node);
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return getJSDocTypedefTagName(node);
default:
return undefined;
@@ -91659,7 +92863,7 @@ var ts;
return "()";
case 159 /* IndexSignature */:
return "[]";
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return getJSDocTypedefTagName(node);
default:
return "";
@@ -91707,7 +92911,7 @@ var ts;
case 238 /* ModuleDeclaration */:
case 273 /* SourceFile */:
case 236 /* TypeAliasDeclaration */:
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return true;
case 154 /* Constructor */:
case 153 /* MethodDeclaration */:
@@ -91936,10 +93140,10 @@ var ts;
usedImports.push(importDecl);
continue;
}
- var name_70 = importClause.name, namedBindings = importClause.namedBindings;
+ var name = importClause.name, namedBindings = importClause.namedBindings;
// Default import
- if (name_70 && !isDeclarationUsed(name_70)) {
- name_70 = undefined;
+ if (name && !isDeclarationUsed(name)) {
+ name = undefined;
}
if (namedBindings) {
if (ts.isNamespaceImport(namedBindings)) {
@@ -91958,8 +93162,8 @@ var ts;
}
}
}
- if (name_70 || namedBindings) {
- usedImports.push(updateImportDeclarationAndClause(importDecl, name_70, namedBindings));
+ if (name || namedBindings) {
+ usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings));
}
}
return usedImports;
@@ -92049,8 +93253,8 @@ var ts;
importWithoutClause = importWithoutClause || importDeclaration;
continue;
}
- var _a = importDeclaration.importClause, name_71 = _a.name, namedBindings = _a.namedBindings;
- if (name_71) {
+ var _a = importDeclaration.importClause, name = _a.name, namedBindings = _a.namedBindings;
+ if (name) {
defaultImports.push(importDeclaration);
}
if (namedBindings) {
@@ -92107,21 +93311,12 @@ var ts;
}
ts.getEditsForFileRename = getEditsForFileRename;
function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) {
- var cfg = program.getCompilerOptions().configFile;
- if (!cfg)
- return;
- var oldFile = cfg.jsonObject && getFilesEntry(cfg.jsonObject, oldFilePath);
+ var configFile = program.getCompilerOptions().configFile;
+ var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath);
if (oldFile) {
- changeTracker.replaceRangeWithText(cfg, createStringRange(oldFile, cfg), newFilePath);
+ changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath);
}
}
- function getFilesEntry(cfg, fileName) {
- var filesProp = ts.find(cfg.properties, function (prop) {
- return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files";
- });
- var files = filesProp && filesProp.initializer;
- return files && ts.isArrayLiteralExpression(files) ? ts.find(files.elements, function (e) { return ts.isStringLiteral(e) && e.text === fileName; }) : undefined;
- }
function isRef(toUpdate) {
return "fileName" in toUpdate;
}
@@ -92142,7 +93337,7 @@ var ts;
if (checker.getSymbolAtLocation(importStringLiteral))
continue;
var resolved = program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
- if (ts.contains(resolved.failedLookupLocations, oldFilePath)) {
+ if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) {
result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral });
}
}
@@ -92151,11 +93346,11 @@ var ts;
}
function getPathUpdater(oldFilePath, newFilePath, host) {
// Get the relative path from old to new location, and append it on to the end of imports and normalize.
- var rel = ts.getRelativePath(newFilePath, ts.getDirectoryPath(oldFilePath), ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host)));
+ var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host)));
return function (oldPath) {
if (!ts.pathIsRelative(oldPath))
return;
- return ts.ensurePathIsRelative(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel)));
+ return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel)));
};
}
function createStringRange(node, sourceFile) {
@@ -92176,7 +93371,27 @@ var ts;
OutliningElementsCollector.collectElements = collectElements;
function addNodeOutliningSpans(sourceFile, cancellationToken, out) {
var depthRemaining = 40;
- sourceFile.forEachChild(function walk(n) {
+ var current = 0;
+ var statements = sourceFile.statements;
+ var n = statements.length;
+ while (current < n) {
+ while (current < n && !ts.isAnyImportSyntax(statements[current])) {
+ visitNonImportNode(statements[current]);
+ current++;
+ }
+ if (current === n)
+ break;
+ var firstImport = current;
+ while (current < n && ts.isAnyImportSyntax(statements[current])) {
+ addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out);
+ current++;
+ }
+ var lastImport = current - 1;
+ if (lastImport !== firstImport) {
+ out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 91 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */));
+ }
+ }
+ function visitNonImportNode(n) {
if (depthRemaining === 0)
return;
cancellationToken.throwIfCancellationRequested();
@@ -92189,17 +93404,17 @@ var ts;
depthRemaining--;
if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) {
// Consider an 'else if' to be on the same depth as the 'if'.
- walk(n.expression);
- walk(n.thenStatement);
+ visitNonImportNode(n.expression);
+ visitNonImportNode(n.thenStatement);
depthRemaining++;
- walk(n.elseStatement);
+ visitNonImportNode(n.elseStatement);
depthRemaining--;
}
else {
- n.forEachChild(walk);
+ n.forEachChild(visitNonImportNode);
}
depthRemaining++;
- });
+ }
}
function addRegionOutliningSpans(sourceFile, out) {
var regions = [];
@@ -92214,7 +93429,7 @@ var ts;
}
if (!result[1]) {
var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
- regions.push(createOutliningSpan(span, span, /*autoCollapse*/ false, result[2] || "#region"));
+ regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region"));
}
else {
var region = regions.pop();
@@ -92248,7 +93463,7 @@ var ts;
break;
case 3 /* MultiLineCommentTrivia */:
combineAndAddMultipleSingleLineComments();
- out.push(createOutliningSpanFromBounds(pos, end));
+ out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */));
singleLineCommentCount = 0;
break;
default:
@@ -92259,12 +93474,12 @@ var ts;
function combineAndAddMultipleSingleLineComments() {
// Only outline spans of two or more consecutive single line comments
if (singleLineCommentCount > 1) {
- out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd));
+ out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */));
}
}
}
- function createOutliningSpanFromBounds(pos, end) {
- return createOutliningSpan(ts.createTextSpanFromBounds(pos, end));
+ function createOutliningSpanFromBounds(pos, end, kind) {
+ return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind);
}
function getOutliningSpanForNode(n, sourceFile) {
switch (n.kind) {
@@ -92298,7 +93513,7 @@ var ts;
default:
// Block was a standalone block. In this case we want to only collapse
// the span of the block, independent of any parent span.
- return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile));
+ return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */);
}
case 239 /* ModuleBlock */:
return spanForNode(n.parent);
@@ -92330,14 +93545,14 @@ var ts;
return undefined;
}
var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd());
- return createOutliningSpan(textSpan, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse);
+ return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse);
}
}
- function createOutliningSpan(textSpan, hintSpan, autoCollapse, bannerText) {
+ function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) {
if (hintSpan === void 0) { hintSpan = textSpan; }
if (autoCollapse === void 0) { autoCollapse = false; }
if (bannerText === void 0) { bannerText = "..."; }
- return { textSpan: textSpan, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse };
+ return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse };
}
})(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {}));
})(ts || (ts = {}));
@@ -92620,13 +93835,13 @@ var ts;
// Assumes 'value' is already lowercase.
function indexOfIgnoringCase(str, value) {
var n = str.length - value.length;
- var _loop_13 = function (start) {
+ var _loop_14 = 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_13(start);
+ var state_4 = _loop_14(start);
if (typeof state_4 === "object")
return state_4.value;
}
@@ -93291,7 +94506,7 @@ var ts;
var nameToDeclarations = sourceFile.getNamedDeclarations();
var declarations = nameToDeclarations.get(name.text);
if (declarations) {
- var _loop_14 = function (declaration) {
+ var _loop_15 = function (declaration) {
var symbol = declaration.symbol;
if (symbol) {
var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration);
@@ -93305,7 +94520,7 @@ var ts;
};
for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) {
var declaration = declarations_12[_b];
- var state_5 = _loop_14(declaration);
+ var state_5 = _loop_15(declaration);
if (typeof state_5 === "object")
return state_5.value;
}
@@ -93691,13 +94906,13 @@ var ts;
for (var _b = 0, _c = sourceFile.imports; _b < _c.length; _b++) {
var moduleSpecifier = _c[_b];
var importNode = ts.importFromModuleSpecifier(moduleSpecifier);
- var name_72 = importNameForConvertToDefaultImport(importNode);
- if (!name_72)
+ var name = importNameForConvertToDefaultImport(importNode);
+ if (!name)
continue;
- var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
- var resolvedFile = module && program.getSourceFile(module.resolvedFileName);
+ var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
+ var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName);
if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) {
- diags.push(ts.createDiagnosticForNode(name_72, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
+ diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import));
}
}
}
@@ -94320,9 +95535,9 @@ var ts;
return false;
}
// If the parent is not sourceFile or module block it is local variable
- for (var parent_26 = declaration.parent; !ts.isFunctionBlock(parent_26); parent_26 = parent_26.parent) {
+ for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) {
// Reached source file or module block
- if (parent_26.kind === 273 /* SourceFile */ || parent_26.kind === 239 /* ModuleBlock */) {
+ if (parent.kind === 273 /* SourceFile */ || parent.kind === 239 /* ModuleBlock */) {
return false;
}
}
@@ -94434,7 +95649,7 @@ var ts;
return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; });
});
options = ts.cloneCompilerOptions(options);
- var _loop_15 = function (opt) {
+ var _loop_16 = function (opt) {
if (!ts.hasProperty(options, opt.name)) {
return "continue";
}
@@ -94453,7 +95668,7 @@ var ts;
};
for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) {
var opt = commandLineOptionsStringToEnum_1[_i];
- _loop_15(opt);
+ _loop_16(opt);
}
return options;
}
@@ -94857,6 +96072,7 @@ var ts;
rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */),
rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */),
rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */),
+ rule("NoSpaceBetweenImportParenInImportType", 91 /* ImportKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */),
// Special handling of unary operators.
// Prefix operators generally shouldn't have a space between
// them and their target unary expression.
@@ -95317,6 +96533,9 @@ var ts;
function isArrowFunctionContext(context) {
return context.contextNode.kind === 192 /* ArrowFunction */;
}
+ function isImportTypeContext(context) {
+ return context.contextNode.kind === 178 /* ImportType */;
+ }
function isNonJsxSameLineTokenContext(context) {
return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */;
}
@@ -95439,18 +96658,18 @@ var ts;
// This array is used only during construction of the rulesbucket in the map
var rulesBucketConstructionStateList = new Array(map.length);
for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) {
- var rule = rules_1[_i];
- var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific;
- for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) {
+ var rule_1 = rules_1[_i];
+ var specificRule = rule_1.leftTokenRange.isSpecific && rule_1.rightTokenRange.isSpecific;
+ for (var _a = 0, _b = rule_1.leftTokenRange.tokens; _a < _b.length; _a++) {
var left = _b[_a];
- for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) {
+ for (var _c = 0, _d = rule_1.rightTokenRange.tokens; _c < _d.length; _c++) {
var right = _d[_c];
var index = getRuleBucketIndex(left, right);
var rulesBucket = map[index];
if (rulesBucket === undefined) {
rulesBucket = map[index] = [];
}
- addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index);
+ addRule(rulesBucket, rule_1.rule, specificRule, rulesBucketConstructionStateList, index);
}
}
}
@@ -96757,7 +97976,7 @@ var ts;
NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace";
})(NextTokenKind || (NextTokenKind = {}));
function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) {
- var nextToken = ts.findNextToken(precedingToken, current);
+ var nextToken = ts.findNextToken(precedingToken, current, sourceFile);
if (!nextToken) {
return 0 /* Unknown */;
}
@@ -96806,9 +98025,10 @@ var ts;
}
function getContainingList(node, sourceFile) {
if (node.parent) {
+ var end = node.end;
switch (node.parent.kind) {
case 161 /* TypeReference */:
- return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end);
case 183 /* ObjectLiteralExpression */:
return node.parent.properties;
case 182 /* ArrayLiteralExpression */:
@@ -96823,22 +98043,25 @@ var ts;
case 163 /* ConstructorType */:
case 158 /* ConstructSignature */: {
var start = node.getStart(sourceFile);
- return getListIfStartEndIsInListRange(node.parent.typeParameters, start, node.getEnd()) ||
- getListIfStartEndIsInListRange(node.parent.parameters, start, node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) ||
+ getListIfStartEndIsInListRange(node.parent.parameters, start, end);
}
case 234 /* ClassDeclaration */:
- return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), end);
case 187 /* NewExpression */:
case 186 /* CallExpression */: {
var start = node.getStart(sourceFile);
- return getListIfStartEndIsInListRange(node.parent.typeArguments, start, node.getEnd()) ||
- getListIfStartEndIsInListRange(node.parent.arguments, start, node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) ||
+ getListIfStartEndIsInListRange(node.parent.arguments, start, end);
}
case 232 /* VariableDeclarationList */:
- return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end);
case 246 /* NamedImports */:
case 250 /* NamedExports */:
- return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end);
+ case 179 /* ObjectBindingPattern */:
+ case 180 /* ArrayBindingPattern */:
+ return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end);
}
}
return undefined;
@@ -97160,10 +98383,10 @@ var ts;
return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile);
}
function getAdjustedEndPosition(sourceFile, node, options) {
+ var end = node.end;
if (options.useNonAdjustedEndPosition || ts.isExpression(node)) {
- return node.getEnd();
+ return end;
}
- var end = node.getEnd();
var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))
? newEnd
@@ -97188,6 +98411,7 @@ var ts;
this.newLineCharacter = newLineCharacter;
this.formatContext = formatContext;
this.changes = [];
+ this.newFiles = [];
this.deletedNodesInLists = []; // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
this.classesWithNodesInsertedAtStart = ts.createMap(); // Set implemented as Map
}
@@ -97399,20 +98623,34 @@ var ts;
};
ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) {
var clsStart = cls.getStart(sourceFile);
- var prefix = "";
- var suffix = this.newLineCharacter;
- if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) {
- prefix = this.newLineCharacter;
- // For `class C {\n}`, don't add the trailing "\n"
- if (cls.members.length === 0 && !ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile]))) { // TODO: GH#4130 remove 'as any'
- suffix = "";
- }
- }
var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options)
+ this.formatContext.options.indentSize;
- this.insertNodeAt(sourceFile, cls.members.pos, newElement, { indentation: indentation, prefix: prefix, suffix: suffix });
+ this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls)));
+ };
+ ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) {
+ if (cls.members.length === 0) {
+ if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) {
+ // For `class C {\n}`, don't add the trailing "\n"
+ var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any'
+ return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" };
+ }
+ else {
+ return { prefix: "", suffix: this.newLineCharacter };
+ }
+ }
+ else {
+ return { prefix: this.newLineCharacter, suffix: "" };
+ }
};
ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) {
+ var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode);
+ this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
+ };
+ ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) {
+ var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes));
+ this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after));
+ };
+ ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) {
if (needSemicolonBetween(after, newNode)) {
// check if previous statement ends with semicolon
// if not - insert semicolon to preserve the code from changing the meaning due to ASI
@@ -97421,9 +98659,13 @@ var ts;
}
}
var endPosition = getAdjustedEndPosition(sourceFile, after, {});
- return this.replaceRange(sourceFile, ts.createTextRange(endPosition), newNode, this.getInsertNodeAfterOptions(after));
+ return endPosition;
};
- ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) {
+ ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) {
+ var options = this.getInsertNodeAfterOptionsWorker(after);
+ return __assign({}, options, { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix });
+ };
+ ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) {
if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) {
return { prefix: this.newLineCharacter, suffix: this.newLineCharacter };
}
@@ -97468,13 +98710,16 @@ var ts;
this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " });
}
};
+ ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) {
+ this.insertText(sourceFile, node.getStart(sourceFile), "export ");
+ };
/**
* This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range,
* i.e. arguments in arguments lists, parameters in parameter lists etc.
* Note that separators are part of the node in statements and class elements.
*/
- ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) {
- var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile);
+ ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) {
+ if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); }
if (!containingList) {
ts.Debug.fail("node is not a list element");
return this;
@@ -97600,7 +98845,15 @@ var ts;
*/
ChangeTracker.prototype.getChanges = function (validate) {
this.finishClassesWithNodesInsertedAtStart();
- return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
+ var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
+ for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) {
+ var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements;
+ changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter));
+ }
+ return changes;
+ };
+ ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) {
+ this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements });
};
return ChangeTracker;
}());
@@ -97614,15 +98867,16 @@ var ts;
return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) {
var sourceFile = changesInFile[0].sourceFile;
// order changes by start position
- var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; });
- var _loop_16 = function (i) {
+ // 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_17 = 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_16(i);
+ _loop_17(i);
}
var textChanges = normalized.map(function (c) {
return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
@@ -97631,6 +98885,11 @@ var ts;
});
}
changesToText.getTextChangesFromChanges = getTextChangesFromChanges;
+ function newFileChanges(oldFile, fileName, statements, newLineCharacter) {
+ var text = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter);
+ return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)] };
+ }
+ changesToText.newFileChanges = newFileChanges;
function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) {
if (change.kind === ChangeKind.Remove) {
return "";
@@ -97980,10 +99239,11 @@ var ts;
}
refactor_1.getEditsForRefactor = getEditsForRefactor;
})(refactor = ts.refactor || (ts.refactor = {}));
- function getRefactorContextLength(context) {
- return context.endPosition === undefined ? 0 : context.endPosition - context.startPosition;
+ function getRefactorContextSpan(_a) {
+ var startPosition = _a.startPosition, endPosition = _a.endPosition;
+ return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition);
}
- ts.getRefactorContextLength = getRefactorContextLength;
+ ts.getRefactorContextSpan = getRefactorContextSpan;
})(ts || (ts = {}));
/* @internal */
var ts;
@@ -98087,18 +99347,18 @@ var ts;
}
function transformJSDocType(node) {
switch (node.kind) {
- case 276 /* JSDocAllType */:
- case 277 /* JSDocUnknownType */:
+ case 278 /* JSDocAllType */:
+ case 279 /* JSDocUnknownType */:
return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 280 /* JSDocOptionalType */:
+ case 282 /* JSDocOptionalType */:
return transformJSDocOptionalType(node);
- case 279 /* JSDocNonNullableType */:
+ case 281 /* JSDocNonNullableType */:
return transformJSDocType(node.type);
- case 278 /* JSDocNullableType */:
+ case 280 /* JSDocNullableType */:
return transformJSDocNullableType(node);
- case 282 /* JSDocVariadicType */:
+ case 284 /* JSDocVariadicType */:
return transformJSDocVariadicType(node);
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
return transformJSDocFunctionType(node);
case 161 /* TypeReference */:
return transformJSDocTypeReference(node);
@@ -98122,7 +99382,7 @@ var ts;
}
function transformJSDocParameter(node) {
var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 282 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
+ var isRest = node.type.kind === 284 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
var name = node.name || (isRest ? "rest" : "arg" + index);
var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken;
return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
@@ -98403,7 +99663,7 @@ var ts;
var importNode = ts.importFromModuleSpecifier(moduleSpecifier);
switch (importNode.kind) {
case 242 /* ImportEqualsDeclaration */:
- changes.replaceNode(importingFile, importNode, makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier));
+ changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier));
break;
case 186 /* CallExpression */:
if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) {
@@ -98450,8 +99710,8 @@ var ts;
function forEachExportReference(sourceFile, cb) {
sourceFile.forEachChild(function recur(node) {
if (ts.isPropertyAccessExpression(node) && ts.isExportsOrModuleExportsOrAlias(sourceFile, node.expression)) {
- var parent_27 = node.parent;
- cb(node, ts.isBinaryExpression(parent_27) && parent_27.left === node && parent_27.operatorToken.kind === 58 /* EqualsToken */);
+ var parent = node.parent;
+ cb(node, ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === 58 /* EqualsToken */);
}
node.forEachChild(recur);
});
@@ -98467,7 +99727,7 @@ var ts;
case 186 /* CallExpression */: {
if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) {
// For side-effecting require() call, just make a side-effecting import.
- changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0]));
+ changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0]));
}
return false;
}
@@ -98540,27 +99800,30 @@ var ts;
changes.deleteNode(sourceFile, assignment.parent);
}
else {
- var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined;
- var changedToDefaultExport = false;
- if (!newNodes) {
- (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]);
+ var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right)
+ : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker)
+ : undefined;
+ if (replacement) {
+ changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]);
+ return replacement[1];
+ }
+ else {
+ changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default");
+ return true;
}
- changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes);
- return changedToDefaultExport;
}
}
else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
convertNamedExport(sourceFile, assignment, changes, exports);
}
return false;
- var _a;
}
/**
* Convert `module.exports = { ... }` to individual exports..
* We can't always do this if the module has interesting members -- then it will be a default export instead.
*/
function tryChangeModuleExportsObject(object) {
- return ts.mapAllOrFail(object.properties, function (prop) {
+ var statements = ts.mapAllOrFail(object.properties, function (prop) {
switch (prop.kind) {
case 155 /* GetAccessor */:
case 156 /* SetAccessor */:
@@ -98576,6 +99839,7 @@ var ts;
ts.Debug.assertNever(prop);
}
});
+ return statements && [statements, true];
}
function convertNamedExport(sourceFile, assignment, changes, exports) {
// If "originalKeywordKind" was set, this is e.g. `exports.
@@ -98596,30 +99860,6 @@ var ts;
convertExportsPropertyAssignment(assignment, sourceFile, changes);
}
}
- function convertModuleExportsToExportDefault(exported, checker) {
- var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)];
- switch (exported.kind) {
- case 191 /* FunctionExpression */:
- case 192 /* ArrowFunction */: {
- // `module.exports = function f() {}` --> `export default function f() {}`
- var fn = exported;
- return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true];
- }
- case 204 /* ClassExpression */: {
- // `module.exports = class C {}` --> `export default class C {}`
- var cls = exported;
- return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true];
- }
- case 186 /* CallExpression */:
- if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteralLike*/ true)) {
- return convertReExportAll(exported.arguments[0], checker);
- }
- // falls through
- default:
- // `module.exports = 0;` --> `export default 0;`
- return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true];
- }
- }
function convertReExportAll(reExported, checker) {
// `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";`
var moduleSpecifier = reExported.text;
@@ -98695,7 +99935,7 @@ var ts;
: makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text);
});
if (importSpecifiers) {
- return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)];
+ return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)];
}
}
// falls through -- object destructuring has an interesting pattern and must be a variable declaration
@@ -98706,7 +99946,7 @@ var ts;
*/
var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers);
return [
- makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier),
+ ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier),
makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)),
];
}
@@ -98732,16 +99972,16 @@ var ts;
// This was a use of a different symbol with the same name, due to shadowing. Ignore.
continue;
}
- var parent_28 = use.parent;
- if (ts.isPropertyAccessExpression(parent_28)) {
- var expression = parent_28.expression, propertyName = parent_28.name.text;
+ var parent = use.parent;
+ if (ts.isPropertyAccessExpression(parent)) {
+ var expression = parent.expression, propertyName = parent.name.text;
ts.Debug.assert(expression === use); // Else shouldn't have been in `collectIdentifiers`
var idName = namedBindingsNames.get(propertyName);
if (idName === undefined) {
idName = makeUniqueName(propertyName, identifiers);
namedBindingsNames.set(propertyName, idName);
}
- changes.replaceNode(file, parent_28, ts.createIdentifier(idName));
+ changes.replaceNode(file, parent, ts.createIdentifier(idName));
}
else {
needDefaultImport = true;
@@ -98755,7 +99995,7 @@ var ts;
// If it was unused, ensure that we at least import *something*.
needDefaultImport = true;
}
- return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
+ return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
}
// Identifiers helpers
function makeUniqueName(name, identifiers) {
@@ -98797,17 +100037,9 @@ var ts;
}
function makeSingleImport(localName, propertyName, moduleSpecifier) {
return propertyName === "default"
- ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier)
- : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
+ ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier)
+ : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
}
- function makeImport(name, namedImports, moduleSpecifier) {
- return makeImportDeclaration(name, namedImports, moduleSpecifier);
- }
- function makeImportDeclaration(name, namedImports, moduleSpecifier) {
- var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports));
- return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifier);
- }
- codefix.makeImportDeclaration = makeImportDeclaration;
function makeImportSpecifier(propertyName, name) {
return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name));
}
@@ -99014,11 +100246,11 @@ var ts;
if (context.symbolToken && ts.isIdentifier(context.symbolToken)) {
for (var _i = 0, existingImports_1 = existingImports; _i < existingImports_1.length; _i++) {
var declaration = existingImports_1[_i].declaration;
- var namespace = getNamespaceImportName(declaration);
- if (namespace) {
- var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace));
+ var namespace_2 = getNamespaceImportName(declaration);
+ if (namespace_2) {
+ var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace_2));
if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) {
- useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken));
+ useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace_2.text, context, context.symbolToken));
}
}
}
@@ -99119,7 +100351,7 @@ var ts;
if (global) {
return [global];
}
- var relativePath = removeExtensionAndIndexPostFix(ts.getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), moduleResolutionKind, addJsExtension);
+ var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension);
if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") {
return [relativePath];
}
@@ -99169,7 +100401,7 @@ var ts;
1 < 2 = true
In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a".
*/
- var pathFromSourceToBaseUrl = ts.getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName);
+ var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName));
var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl);
return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath];
});
@@ -99192,11 +100424,14 @@ var ts;
return symlinks.length === 0 ? [fileName] : symlinks;
}
function getRelativePathNParents(relativePath) {
- var count = 0;
- for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) {
- count++;
+ var components = ts.getPathComponents(relativePath);
+ if (components[0] || components.length === 1)
+ return 0;
+ for (var i = 1; i < components.length; i++) {
+ if (components[i] !== "..")
+ return i - 1;
}
- return count;
+ return components.length - 1;
}
function tryGetModuleNameFromAmbientModule(moduleSymbol) {
var decl = moduleSymbol.valueDeclaration;
@@ -99235,7 +100470,7 @@ var ts;
return undefined;
}
var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
- var relativePath = normalizedSourcePath !== undefined ? ts.getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath;
+ var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
return ts.removeFileExtension(relativePath);
}
function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) {
@@ -99295,7 +100530,7 @@ var ts;
return path.substring(parts.topLevelPackageNameIndex + 1);
}
else {
- return ts.getRelativePath(path, sourceDirectory, getCanonicalFileName);
+ return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, path, getCanonicalFileName));
}
}
}
@@ -99469,10 +100704,10 @@ var ts;
}
if (!ts.isUMDExportSymbol(umdSymbol)) {
// The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`.
- var parent_29 = token.parent;
- var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(parent_29);
- if ((ts.isJsxOpeningLikeElement && parent_29.tagName === token) || parent_29.kind === 259 /* JsxOpeningFragment */) {
- umdSymbol = checker.resolveName(checker.getJsxNamespace(parent_29), isNodeOpeningLikeElement ? parent_29.tagName : parent_29, 67216319 /* Value */, /*excludeGlobals*/ false);
+ var parent = token.parent;
+ var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(parent);
+ if ((ts.isJsxOpeningLikeElement && parent.tagName === token) || parent.kind === 259 /* JsxOpeningFragment */) {
+ umdSymbol = checker.resolveName(checker.getJsxNamespace(parent), isNodeOpeningLikeElement ? parent.tagName : parent, 67216319 /* Value */, /*excludeGlobals*/ false);
}
}
if (ts.isUMDExportSymbol(umdSymbol)) {
@@ -99686,9 +100921,9 @@ var ts;
}
else {
var meaning = ts.getMeaningFromLocation(node);
- var name_73 = ts.getTextOfNode(node);
- ts.Debug.assert(name_73 !== undefined, "name should be defined");
- suggestion = checker.getSuggestionForNonexistentSymbol(node, name_73, convertSemanticMeaningToSymbolFlags(meaning));
+ var name = ts.getTextOfNode(node);
+ ts.Debug.assert(name !== undefined, "name should be defined");
+ suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning));
}
return suggestion === undefined ? undefined : { node: node, suggestion: suggestion };
}
@@ -99848,7 +101083,24 @@ var ts;
/*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName,
/*questionToken*/ undefined, typeNode,
/*initializer*/ undefined);
- changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property);
+ var lastProp = getNodeToInsertPropertyAfter(classDeclaration);
+ if (lastProp) {
+ changeTracker.insertNodeAfter(classDeclarationSourceFile, lastProp, property);
+ }
+ else {
+ changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property);
+ }
+ }
+ // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration.
+ function getNodeToInsertPropertyAfter(cls) {
+ var res;
+ for (var _i = 0, _a = cls.members; _i < _a.length; _i++) {
+ var member = _a[_i];
+ if (!ts.isPropertyDeclaration(member))
+ break;
+ res = member;
+ }
+ return res;
}
function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) {
// Index signatures cannot have the static modifier.
@@ -100160,6 +101412,7 @@ var ts;
ts.Diagnostics._0_is_declared_but_never_used.code,
ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code,
ts.Diagnostics.All_imports_in_import_declaration_are_unused.code,
+ ts.Diagnostics.All_destructured_elements_are_unused.code,
];
codefix.registerCodeFix({
errorCodes: errorCodes,
@@ -100170,6 +101423,10 @@ var ts;
var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); });
return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)];
}
+ var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(t, sourceFile, context.span.start); });
+ if (delDestructure.length) {
+ return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)];
+ }
var token = getToken(sourceFile, ts.textSpanEnd(context.span));
var result = [];
var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token); });
@@ -100198,7 +101455,9 @@ var ts;
changes.deleteNode(sourceFile, importDecl);
}
else {
- tryDeleteDeclaration(changes, sourceFile, token);
+ if (!tryDeleteFullDestructure(changes, sourceFile, diag.start)) {
+ tryDeleteDeclaration(changes, sourceFile, token);
+ }
}
break;
default:
@@ -100211,6 +101470,26 @@ var ts;
var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined;
}
+ function tryDeleteFullDestructure(changes, sourceFile, pos) {
+ var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ if (startToken.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(startToken.parent))
+ return false;
+ var decl = startToken.parent.parent;
+ switch (decl.kind) {
+ case 231 /* VariableDeclaration */:
+ tryDeleteVariableDeclaration(changes, sourceFile, decl);
+ break;
+ case 148 /* Parameter */:
+ changes.deleteNodeInList(sourceFile, decl);
+ break;
+ case 181 /* BindingElement */:
+ changes.deleteNode(sourceFile, decl);
+ break;
+ default:
+ return ts.Debug.assertNever(decl);
+ }
+ return true;
+ }
function getToken(sourceFile, pos) {
var token = ts.findPrecedingToken(pos, sourceFile);
// this handles var ["computed"] = 12;
@@ -100299,6 +101578,20 @@ var ts;
changes.deleteNodeInList(sourceFile, parent);
}
break;
+ case 181 /* BindingElement */: {
+ var pattern = parent.parent;
+ switch (pattern.kind) {
+ case 180 /* ArrayBindingPattern */:
+ changes.deleteNode(sourceFile, parent); // Don't delete ','
+ break;
+ case 179 /* ObjectBindingPattern */:
+ changes.deleteNodeInList(sourceFile, parent);
+ break;
+ default:
+ return ts.Debug.assertNever(pattern);
+ }
+ break;
+ }
// handle case where 'import a = A;'
case 242 /* ImportEqualsDeclaration */:
var importEquals = ts.getAncestor(identifier, 242 /* ImportEqualsDeclaration */);
@@ -100413,7 +101706,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 === 278 /* JSDocNullableType */) {
+ if (typeNode.kind === 280 /* 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, 4096 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
@@ -100433,7 +101726,7 @@ var ts;
if (!info)
return;
var typeNode = info.typeNode, type = info.type;
- var fixedType = typeNode.kind === 278 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type;
+ var fixedType = typeNode.kind === 280 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type;
doChange(changes, sourceFile, typeNode, fixedType, checker);
});
}
@@ -101349,7 +102642,7 @@ var ts;
var opts = context.program.getCompilerOptions();
var variations = [];
// import Bluebird from "bluebird";
- variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier)));
+ variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier)));
if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) {
// import Bluebird = require("bluebird");
variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(
@@ -101575,7 +102868,7 @@ var ts;
}
}
function doChange(changes, sourceFile, info) {
- changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier));
+ changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier));
}
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
@@ -101593,7 +102886,7 @@ var ts;
* Exported for tests.
*/
function getAvailableActions(context) {
- var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) });
+ var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
var targetRange = rangeToExtract.targetRange;
if (targetRange === undefined) {
return undefined;
@@ -101662,7 +102955,7 @@ var ts;
extractSymbol.getAvailableActions = getAvailableActions;
/* Exported for tests */
function getEditsForAction(context, actionName) {
- var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) });
+ var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
var targetRange = rangeToExtract.targetRange;
var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName);
if (parsedFunctionIndexMatch) {
@@ -102797,7 +104090,7 @@ var ts;
: ts.getEnclosingBlockScopeContainer(scopes[0]);
ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
- var _loop_17 = function (i) {
+ var _loop_18 = 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
@@ -102837,7 +104130,7 @@ var ts;
}
};
for (var i = 0; i < scopes.length; i++) {
- _loop_17(i);
+ _loop_18(i);
}
return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
function hasTypeParameters(node) {
@@ -103137,21 +104430,39 @@ var ts;
return undefined;
var isJS = ts.isSourceFileJavaScript(file);
var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var isStatic = fieldInfo.isStatic, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration;
+ var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration;
+ ts.suppressLeadingAndTrailingTrivia(fieldName);
+ ts.suppressLeadingAndTrailingTrivia(declaration);
+ ts.suppressLeadingAndTrailingTrivia(container);
var isInClassLike = ts.isClassLike(container);
+ // avoid Readonly modifier because it will convert to get accessor
+ var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */;
var accessorModifiers = isInClassLike
- ? !declaration.modifiers || ts.getModifierFlags(declaration) & 8 /* Private */ ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */) : declaration.modifiers
+ ? !modifierFlags || modifierFlags & 8 /* Private */
+ ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */)
+ : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags))
: undefined;
var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 112 /* PrivateKeyword */) : undefined;
- updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers, container);
+ updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers);
var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
- var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
+ ts.suppressLeadingAndTrailingTrivia(getAccessor);
insertAccessor(changeTracker, file, getAccessor, declaration, container);
- insertAccessor(changeTracker, file, setAccessor, declaration, container);
+ if (isReadonly) {
+ // readonly modifier only existed in classLikeDeclaration
+ var constructor = ts.getFirstConstructorWithBody(container);
+ if (constructor) {
+ updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName);
+ }
+ }
+ else {
+ var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
+ ts.suppressLeadingAndTrailingTrivia(setAccessor);
+ insertAccessor(changeTracker, file, setAccessor, declaration, container);
+ }
var edits = changeTracker.getChanges();
var renameFilename = file.fileName;
var renameLocationOffset = ts.isIdentifier(fieldName) ? 0 : -1;
- var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, fieldName.text, /*isDeclaredBeforeUse*/ false);
+ var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, fieldName.text, /*preferLastLocation*/ ts.isParameter(declaration));
return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
}
function isConvertableName(name) {
@@ -103174,18 +104485,18 @@ var ts;
function getConvertibleFieldAtPosition(file, startPosition) {
var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration);
- // make sure propertyDeclaration have AccessibilityModifier or Static Modifier
- var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */;
+ // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier
+ var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */;
if (!declaration || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning)
return undefined;
var fieldName = createPropertyName(ts.getUniqueName("_" + declaration.name.text, file.text), declaration.name);
var accessorName = createPropertyName(declaration.name.text, declaration.name);
- ts.suppressLeadingAndTrailingTrivia(fieldName);
- ts.suppressLeadingAndTrailingTrivia(declaration);
return {
isStatic: ts.hasStaticModifier(declaration),
+ isReadonly: ts.hasReadonlyModifier(declaration),
type: ts.getTypeAnnotationNode(declaration),
container: declaration.kind === 148 /* Parameter */ ? declaration.parent.parent : declaration.parent,
+ originalName: declaration.name,
declaration: declaration,
fieldName: fieldName,
accessorName: accessorName,
@@ -103212,16 +104523,11 @@ var ts;
var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer);
changeTracker.replaceNode(file, declaration, property);
}
- function updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, classLikeContainer) {
- var property = ts.createProperty(declaration.decorators, modifiers, fieldName, declaration.questionToken, declaration.type, declaration.initializer);
- changeTracker.insertNodeAtClassStart(file, classLikeContainer, property);
- changeTracker.deleteNodeInList(file, declaration);
- }
function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) {
var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer);
changeTracker.replacePropertyAssignment(file, declaration, assignment);
}
- function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers, container) {
+ function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) {
if (ts.isPropertyDeclaration(declaration)) {
updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers);
}
@@ -103229,7 +104535,7 @@ var ts;
updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName);
}
else {
- updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, container);
+ changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer));
}
}
function insertAccessor(changeTracker, file, accessor, declaration, container) {
@@ -103237,11 +104543,592 @@ var ts;
? changeTracker.insertNodeAtClassStart(file, container, accessor)
: changeTracker.insertNodeAfter(file, declaration, accessor);
}
+ function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) {
+ if (!constructor.body)
+ return;
+ var file = context.file, program = context.program, cancellationToken = context.cancellationToken;
+ var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { return ((entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined); });
+ ts.forEach(referenceEntries, function (entry) {
+ var parent = entry.parent;
+ var accessorName = ts.createIdentifier(fieldName.text);
+ var node = ts.isBinaryExpression(parent)
+ ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken)
+ : ts.isPropertyAccessExpression(parent)
+ ? ts.updatePropertyAccess(parent, parent.expression, accessorName)
+ : ts.Debug.fail("Unexpected write access token");
+ changeTracker.replaceNode(file, parent, node);
+ });
+ }
})(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
/* @internal */
var ts;
+(function (ts) {
+ var refactor;
+ (function (refactor) {
+ var refactorName = "Move to a new file";
+ refactor.registerRefactor(refactorName, {
+ getAvailableActions: function (context) {
+ if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined)
+ return undefined;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file);
+ return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }];
+ },
+ getEditsForAction: function (context, actionName) {
+ ts.Debug.assert(actionName === refactorName);
+ var statements = ts.Debug.assertDefined(getStatementsToMove(context));
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host); });
+ return { edits: edits, renameFilename: undefined, renameLocation: undefined };
+ }
+ });
+ function getStatementsToMove(context) {
+ var file = context.file;
+ var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context));
+ var statements = file.statements;
+ var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; });
+ if (startNodeIndex === -1)
+ return undefined;
+ // Can't only partially include the start node or be partially into the next node
+ if (range.pos > statements[startNodeIndex].getStart(file))
+ return undefined;
+ var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex);
+ // Can't be partially into the next node
+ if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end))
+ return undefined;
+ return statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex);
+ }
+ function doChange(oldFile, program, toMove, changes, host) {
+ var checker = program.getTypeChecker();
+ var usage = getUsageInfo(oldFile, toMove, checker);
+ var currentDirectory = ts.getDirectoryPath(oldFile.fileName);
+ var extension = ts.extensionFromPath(oldFile.fileName);
+ var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host);
+ var newFileNameWithExtension = newModuleName + extension;
+ // If previous file was global, this is easy.
+ changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName));
+ addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host));
+ }
+ function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) {
+ var cfg = program.getCompilerOptions().configFile;
+ if (!cfg)
+ return;
+ var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension));
+ var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName);
+ var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression);
+ var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) {
+ return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files";
+ });
+ if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) {
+ changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements);
+ }
+ }
+ function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName) {
+ var checker = program.getTypeChecker();
+ if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) {
+ changes.deleteNodeRange(oldFile, ts.first(toMove), ts.last(toMove));
+ return toMove;
+ }
+ var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator;
+ var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax);
+ if (importsFromNewFile) {
+ changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, /*blankLineBetween*/ true);
+ }
+ deleteUnusedOldImports(oldFile, toMove, changes, usage.unusedImportsFromOldFile, checker);
+ changes.deleteNodeRange(oldFile, ts.first(toMove), ts.last(toMove));
+ updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName);
+ return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax).concat(addExports(oldFile, toMove, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax));
+ }
+ function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) {
+ for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
+ var statement = _a[_i];
+ if (ts.contains(toMove, statement))
+ continue;
+ forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); });
+ }
+ }
+ function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) {
+ var checker = program.getTypeChecker();
+ var _loop_19 = function (sourceFile) {
+ if (sourceFile === oldFile)
+ return "continue";
+ var _loop_20 = function (statement) {
+ forEachImportInStatement(statement, function (importNode) {
+ var shouldMove = function (name) {
+ var symbol = ts.isBindingElement(name.parent)
+ ? ts.getPropertySymbolFromBindingElement(checker, name.parent)
+ : ts.skipAlias(checker.getSymbolAtLocation(name), checker);
+ return !!symbol && movedSymbols.has(symbol);
+ };
+ deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file
+ var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName);
+ var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove);
+ if (newImportDeclaration)
+ changes.insertNodeAfter(sourceFile, statement, newImportDeclaration);
+ });
+ };
+ for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
+ var statement = _a[_i];
+ _loop_20(statement);
+ }
+ };
+ for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
+ var sourceFile = _a[_i];
+ _loop_19(sourceFile);
+ }
+ }
+ function moduleSpecifierFromImport(i) {
+ return (i.kind === 243 /* ImportDeclaration */ ? i.moduleSpecifier
+ : i.kind === 242 /* ImportEqualsDeclaration */ ? i.moduleReference.expression
+ : i.initializer.arguments[0]);
+ }
+ function forEachImportInStatement(statement, cb) {
+ if (ts.isImportDeclaration(statement)) {
+ if (ts.isStringLiteral(statement.moduleSpecifier))
+ cb(statement);
+ }
+ else if (ts.isImportEqualsDeclaration(statement)) {
+ if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) {
+ cb(statement);
+ }
+ }
+ else if (ts.isVariableStatement(statement)) {
+ for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) {
+ cb(decl);
+ }
+ }
+ }
+ }
+ function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports) {
+ var defaultImport;
+ var imports = [];
+ newFileNeedExport.forEach(function (symbol) {
+ if (symbol.escapedName === "default" /* Default */) {
+ defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol));
+ }
+ else {
+ imports.push(symbol.name);
+ }
+ });
+ return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports);
+ }
+ function makeImportOrRequire(defaultImport, imports, path, useEs6Imports) {
+ path = ts.ensurePathIsNonModuleName(path);
+ if (useEs6Imports) {
+ var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); });
+ return ts.makeImportIfNecessary(defaultImport, specifiers, path);
+ }
+ else {
+ ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module.
+ var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); });
+ return bindingElements.length
+ ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path)))
+ : undefined;
+ }
+ }
+ function makeVariableStatement(name, type, initializer, flags) {
+ if (flags === void 0) { flags = 2 /* Const */; }
+ return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags));
+ }
+ function createRequireCall(moduleSpecifier) {
+ return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]);
+ }
+ function addExports(sourceFile, toMove, needExport, useEs6Exports) {
+ return ts.flatMap(toMove, function (statement) {
+ 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;
+ }
+ return statement;
+ });
+ }
+ function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) {
+ switch (importDecl.kind) {
+ case 243 /* ImportDeclaration */:
+ deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused);
+ break;
+ case 242 /* ImportEqualsDeclaration */:
+ if (isUnused(importDecl.name)) {
+ changes.deleteNode(sourceFile, importDecl);
+ }
+ break;
+ case 231 /* VariableDeclaration */:
+ deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused);
+ break;
+ default:
+ ts.Debug.assertNever(importDecl);
+ }
+ }
+ function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) {
+ if (!importDecl.importClause)
+ return;
+ var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings;
+ var defaultUnused = !name || isUnused(name);
+ var namedBindingsUnused = !namedBindings ||
+ (namedBindings.kind === 245 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.every(function (e) { return isUnused(e.name); }));
+ if (defaultUnused && namedBindingsUnused) {
+ changes.deleteNode(sourceFile, importDecl);
+ }
+ else {
+ if (name && defaultUnused) {
+ changes.deleteNode(sourceFile, name);
+ }
+ if (namedBindings) {
+ if (namedBindingsUnused) {
+ changes.deleteNode(sourceFile, namedBindings);
+ }
+ else if (namedBindings.kind === 246 /* NamedImports */) {
+ for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) {
+ var element = _b[_i];
+ if (isUnused(element.name))
+ changes.deleteNodeInList(sourceFile, element);
+ }
+ }
+ }
+ }
+ }
+ function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) {
+ var name = varDecl.name;
+ switch (name.kind) {
+ case 71 /* Identifier */:
+ if (isUnused(name)) {
+ changes.deleteNode(sourceFile, name);
+ }
+ break;
+ case 180 /* ArrayBindingPattern */:
+ break;
+ case 179 /* ObjectBindingPattern */:
+ if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) {
+ changes.deleteNode(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl);
+ }
+ else {
+ for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
+ var element = _a[_i];
+ if (ts.isIdentifier(element.name) && isUnused(element.name)) {
+ changes.deleteNode(sourceFile, element.name);
+ }
+ }
+ }
+ break;
+ }
+ }
+ function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax) {
+ var copiedOldImports = [];
+ for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
+ var oldStatement = _a[_i];
+ forEachImportInStatement(oldStatement, function (i) {
+ ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); }));
+ });
+ }
+ // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file.
+ var oldFileDefault;
+ var oldFileNamedImports = [];
+ var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`.
+ newFileImportsFromOldFile.forEach(function (symbol) {
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (!isTopLevelDeclaration(decl))
+ continue;
+ var name = nameOfTopLevelDeclaration(decl);
+ if (!name)
+ continue;
+ var top = getTopLevelDeclarationStatement(decl);
+ if (markSeenTop(top)) {
+ addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax);
+ }
+ if (ts.hasModifier(decl, 512 /* Default */)) {
+ oldFileDefault = name;
+ }
+ else {
+ oldFileNamedImports.push(name.text);
+ }
+ }
+ });
+ ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax));
+ return copiedOldImports;
+ }
+ function makeUniqueModuleName(moduleName, extension, inDirectory, host) {
+ var newModuleName = moduleName;
+ for (var i = 1;; i++) {
+ var name = ts.combinePaths(inDirectory, newModuleName + extension);
+ if (!host.fileExists(name))
+ return newModuleName;
+ newModuleName = moduleName + "." + i;
+ }
+ }
+ function getNewModuleName(movedSymbols) {
+ return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile";
+ }
+ function getUsageInfo(oldFile, toMove, checker) {
+ var movedSymbols = new SymbolSet();
+ var oldImportsNeededByNewFile = new SymbolSet();
+ var newFileImportsFromOldFile = new SymbolSet();
+ for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) {
+ var statement = toMove_1[_i];
+ forEachTopLevelDeclaration(statement, function (decl) {
+ movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol));
+ });
+ }
+ for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) {
+ var statement = toMove_2[_a];
+ forEachReference(statement, checker, function (symbol) {
+ if (!symbol.declarations)
+ return;
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (isInImport(decl)) {
+ oldImportsNeededByNewFile.add(symbol);
+ }
+ else if (isTopLevelDeclaration(decl) && !movedSymbols.has(symbol)) {
+ newFileImportsFromOldFile.add(symbol);
+ }
+ }
+ });
+ }
+ var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone();
+ var oldFileImportsFromNewFile = new SymbolSet();
+ for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) {
+ var statement = _c[_b];
+ if (ts.contains(toMove, statement))
+ continue;
+ forEachReference(statement, checker, function (symbol) {
+ if (movedSymbols.has(symbol))
+ oldFileImportsFromNewFile.add(symbol);
+ unusedImportsFromOldFile.delete(symbol);
+ });
+ }
+ return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile };
+ }
+ // Below should all be utilities
+ function isInImport(decl) {
+ switch (decl.kind) {
+ case 242 /* ImportEqualsDeclaration */:
+ case 247 /* ImportSpecifier */:
+ case 244 /* ImportClause */:
+ return true;
+ case 231 /* VariableDeclaration */:
+ return isVariableDeclarationInImport(decl);
+ case 181 /* BindingElement */:
+ return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent);
+ default:
+ return false;
+ }
+ }
+ function isVariableDeclarationInImport(decl) {
+ return ts.isSourceFile(decl.parent.parent.parent) &&
+ ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true);
+ }
+ function filterImport(i, moduleSpecifier, keep) {
+ switch (i.kind) {
+ case 243 /* ImportDeclaration */: {
+ var clause = i.importClause;
+ var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined;
+ var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep);
+ return defaultImport || namedBindings
+ ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier)
+ : undefined;
+ }
+ case 242 /* ImportEqualsDeclaration */:
+ return keep(i.name) ? i : undefined;
+ case 231 /* VariableDeclaration */: {
+ var name = filterBindingName(i.name, keep);
+ return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined;
+ }
+ default:
+ return ts.Debug.assertNever(i);
+ }
+ }
+ function filterNamedBindings(namedBindings, keep) {
+ if (namedBindings.kind === 245 /* NamespaceImport */) {
+ return keep(namedBindings.name) ? namedBindings : undefined;
+ }
+ else {
+ var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); });
+ return newElements.length ? ts.createNamedImports(newElements) : undefined;
+ }
+ }
+ function filterBindingName(name, keep) {
+ switch (name.kind) {
+ case 71 /* Identifier */:
+ return keep(name) ? name : undefined;
+ case 180 /* ArrayBindingPattern */:
+ return name;
+ case 179 /* ObjectBindingPattern */: {
+ // We can't handle nested destructurings or property names well here, so just copy them all.
+ var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); });
+ return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined;
+ }
+ }
+ }
+ function forEachReference(node, checker, onReference) {
+ node.forEachChild(function cb(node) {
+ if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) {
+ var sym = checker.getSymbolAtLocation(node);
+ if (sym)
+ onReference(sym);
+ }
+ else {
+ node.forEachChild(cb);
+ }
+ });
+ }
+ var SymbolSet = /** @class */ (function () {
+ function SymbolSet() {
+ this.map = ts.createMap();
+ }
+ SymbolSet.prototype.add = function (symbol) {
+ this.map.set(String(ts.getSymbolId(symbol)), symbol);
+ };
+ SymbolSet.prototype.has = function (symbol) {
+ return this.map.has(String(ts.getSymbolId(symbol)));
+ };
+ SymbolSet.prototype.delete = function (symbol) {
+ this.map.delete(String(ts.getSymbolId(symbol)));
+ };
+ SymbolSet.prototype.forEach = function (cb) {
+ this.map.forEach(cb);
+ };
+ SymbolSet.prototype.forEachEntry = function (cb) {
+ return ts.forEachEntry(this.map, cb);
+ };
+ SymbolSet.prototype.clone = function () {
+ var clone = new SymbolSet();
+ ts.copyEntries(this.map, clone.map);
+ return clone;
+ };
+ return SymbolSet;
+ }());
+ function isTopLevelDeclaration(node) {
+ return isNonVariableTopLevelDeclaration(node) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent);
+ }
+ function isTopLevelDeclarationStatement(node) {
+ ts.Debug.assert(ts.isSourceFile(node.parent));
+ return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node);
+ }
+ function isNonVariableTopLevelDeclaration(node) {
+ switch (node.kind) {
+ case 233 /* FunctionDeclaration */:
+ case 234 /* ClassDeclaration */:
+ case 238 /* ModuleDeclaration */:
+ case 237 /* EnumDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 242 /* ImportEqualsDeclaration */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ function forEachTopLevelDeclaration(statement, cb) {
+ switch (statement.kind) {
+ case 233 /* FunctionDeclaration */:
+ case 234 /* ClassDeclaration */:
+ case 238 /* ModuleDeclaration */:
+ case 237 /* EnumDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 242 /* ImportEqualsDeclaration */:
+ return cb(statement);
+ case 213 /* VariableStatement */:
+ return ts.forEach(statement.declarationList.declarations, cb);
+ case 215 /* ExpressionStatement */: {
+ var expression = statement.expression;
+ return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */
+ ? cb(statement)
+ : undefined;
+ }
+ }
+ }
+ function nameOfTopLevelDeclaration(d) {
+ return d.kind === 215 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier);
+ }
+ function getTopLevelDeclarationStatement(d) {
+ return ts.isVariableDeclaration(d) ? d.parent.parent : d;
+ }
+ function addExportToChanges(sourceFile, decl, changes, useEs6Exports) {
+ if (isExported(sourceFile, decl, useEs6Exports))
+ return;
+ if (useEs6Exports) {
+ if (!ts.isExpressionStatement(decl))
+ changes.insertExportModifier(sourceFile, decl);
+ }
+ else {
+ var names = getNamesToExportInCommonJS(decl);
+ if (names.length !== 0)
+ changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment));
+ }
+ }
+ function isExported(sourceFile, decl, useEs6Exports) {
+ if (useEs6Exports) {
+ return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */);
+ }
+ else {
+ return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); });
+ }
+ }
+ function addExport(decl, useEs6Exports) {
+ return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl);
+ }
+ function addEs6Export(d) {
+ var modifiers = ts.concatenate([ts.createModifier(84 /* ExportKeyword */)], d.modifiers);
+ switch (d.kind) {
+ case 233 /* FunctionDeclaration */:
+ return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body);
+ case 234 /* ClassDeclaration */:
+ return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
+ case 213 /* VariableStatement */:
+ return ts.updateVariableStatement(d, modifiers, d.declarationList);
+ case 238 /* ModuleDeclaration */:
+ return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body);
+ case 237 /* EnumDeclaration */:
+ return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members);
+ case 236 /* TypeAliasDeclaration */:
+ return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type);
+ case 235 /* InterfaceDeclaration */:
+ return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
+ case 242 /* ImportEqualsDeclaration */:
+ return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference);
+ case 215 /* ExpressionStatement */:
+ return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
+ default:
+ return ts.Debug.assertNever(d);
+ }
+ }
+ function addCommonjsExport(decl) {
+ return [decl].concat(getNamesToExportInCommonJS(decl).map(createExportAssignment));
+ }
+ function getNamesToExportInCommonJS(decl) {
+ switch (decl.kind) {
+ case 233 /* FunctionDeclaration */:
+ case 234 /* ClassDeclaration */:
+ return [decl.name.text];
+ case 213 /* VariableStatement */:
+ return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; });
+ case 238 /* ModuleDeclaration */:
+ case 237 /* EnumDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 242 /* ImportEqualsDeclaration */:
+ return undefined;
+ case 215 /* ExpressionStatement */:
+ return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
+ default:
+ ts.Debug.assertNever(decl);
+ }
+ }
+ /** Creates `exports.x = x;` */
+ function createExportAssignment(name) {
+ return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 58 /* EqualsToken */, ts.createIdentifier(name)));
+ }
+ })(refactor = ts.refactor || (ts.refactor = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
(function (ts) {
var sourcemaps;
(function (sourcemaps) {
@@ -103563,7 +105450,7 @@ var ts;
if (!children.length) {
return undefined;
}
- var child = ts.find(children, function (kid) { return kid.kind < 275 /* FirstJSDocNode */ || kid.kind > 293 /* LastJSDocNode */; });
+ var child = ts.find(children, function (kid) { return kid.kind < 277 /* FirstJSDocNode */ || kid.kind > 295 /* LastJSDocNode */; });
return child.kind < 145 /* FirstNode */ ?
child :
child.getFirstToken(sourceFile);
@@ -103633,7 +105520,7 @@ var ts;
}
}
function createSyntaxList(nodes, parent) {
- var list = createNode(294 /* SyntaxList */, nodes.pos, nodes.end, parent);
+ var list = createNode(296 /* SyntaxList */, nodes.pos, nodes.end, parent);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) {
@@ -104156,6 +106043,9 @@ var ts;
HostCache.prototype.compilationSettings = function () {
return this._compilationSettings;
};
+ HostCache.prototype.getProjectReferences = function () {
+ return this.host.getProjectReferences && this.host.getProjectReferences();
+ };
HostCache.prototype.createEntry = function (fileName, path) {
var entry;
var scriptSnapshot = this.host.getScriptSnapshot(fileName);
@@ -104185,9 +106075,18 @@ var ts;
return ts.isString(info) ? undefined : info;
};
HostCache.prototype.getRootFileNames = function () {
- return ts.arrayFrom(this.fileNameToEntry.values(), function (entry) {
- return ts.isString(entry) ? entry : entry.hostFileName;
+ var names = [];
+ this.fileNameToEntry.forEach(function (entry) {
+ if (ts.isString(entry)) {
+ names.push(entry);
+ }
+ else {
+ if (entry.scriptKind !== 6 /* JSON */) {
+ names.push(entry.hostFileName);
+ }
+ }
});
+ return names;
};
HostCache.prototype.getVersion = function (path) {
var file = this.getHostFileInformation(path);
@@ -104363,6 +106262,7 @@ var ts;
}
ts.createSourceFileLikeCache = createSourceFileLikeCache;
function createLanguageService(host, documentRegistry, syntaxOnly) {
+ var _a;
if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); }
if (syntaxOnly === void 0) { syntaxOnly = false; }
var syntaxTreeCache = new SyntaxTreeCache(host);
@@ -104466,7 +106366,14 @@ var ts;
};
}
var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings);
- program = ts.createProgram(rootFileNames, newSettings, compilerHost, program);
+ var options = {
+ rootNames: rootFileNames,
+ options: newSettings,
+ host: compilerHost,
+ oldProgram: program,
+ projectReferences: hostCache.getProjectReferences()
+ };
+ program = ts.createProgram(options);
// hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point.
// It needs to be cleared to allow all collected snapshots to be released
hostCache = undefined;
@@ -104670,6 +106577,11 @@ var ts;
}
return checker.getSymbolAtLocation(node);
}
+ function toLineColumnOffset(fileName, position) {
+ var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
+ var file = program.getSourceFile(path) || sourcemappedFileCache.get(path);
+ return file.getLineAndCharacterOfPosition(position);
+ }
// Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M])
var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)$/gm;
var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/;
@@ -104731,8 +106643,8 @@ var ts;
}
possibleMapLocations.push(fileName + ".map");
for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) {
- var location_4 = possibleMapLocations_1[_i];
- var mapPath = ts.toPath(location_4, ts.getDirectoryPath(fileName), getCanonicalFileName);
+ var location = possibleMapLocations_1[_i];
+ var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName);
if (host.fileExists(mapPath)) {
return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath);
}
@@ -104744,15 +106656,15 @@ var ts;
function getTargetOfMappedPosition(input) {
var info = extract(input);
if (ts.endsWith(info.fileName, ".d.ts" /* Dts */)) {
- var file = program.getSourceFile(info.fileName);
- if (!file) {
+ var file_17 = program.getSourceFile(info.fileName);
+ if (!file_17) {
var path = ts.toPath(info.fileName, currentDirectory, getCanonicalFileName);
- file = sourcemappedFileCache.get(path);
+ file_17 = sourcemappedFileCache.get(path);
}
- if (!file) {
+ if (!file_17) {
return input;
}
- var mapper = getSourceMapper(info.fileName, file);
+ var mapper = getSourceMapper(info.fileName, file_17);
var newLoc = mapper.getOriginalPosition(info);
if (newLoc === info)
return input;
@@ -105317,8 +107229,8 @@ var ts;
getProgram: getProgram,
getApplicableRefactors: getApplicableRefactors,
getEditsForRefactor: getEditsForRefactor,
+ toLineColumnOffset: toLineColumnOffset
};
- var _a;
}
ts.createLanguageService = createLanguageService;
/* @internal */
@@ -105389,20 +107301,20 @@ var ts;
function getPropertySymbolsFromType(type, propName) {
var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName));
if (name && type) {
- var result_6 = [];
+ var result_7 = [];
var symbol = type.getProperty(name);
if (type.flags & 131072 /* Union */) {
ts.forEach(type.types, function (t) {
var symbol = t.getProperty(name);
if (symbol) {
- result_6.push(symbol);
+ result_7.push(symbol);
}
});
- return result_6;
+ return result_7;
}
if (symbol) {
- result_6.push(symbol);
- return result_6;
+ result_7.push(symbol);
+ return result_7;
}
}
return undefined;
@@ -105469,7 +107381,7 @@ var ts;
return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd());
}
function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) {
- return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent));
+ return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile));
}
function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) {
if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) {
@@ -105484,7 +107396,7 @@ var ts;
return spanInNode(ts.findPrecedingToken(node.pos, sourceFile));
}
function spanInNextNode(node) {
- return spanInNode(ts.findNextToken(node, node.parent));
+ return spanInNode(ts.findNextToken(node, node.parent, sourceFile));
}
function spanInNode(node) {
if (node) {
@@ -107042,8 +108954,8 @@ var ts;
var before = log && self.host.getMemoryUsage();
self.host.gc();
if (log) {
- var after = self.host.getMemoryUsage();
- self.logger.perftrc("GC::before " + before + ", after " + after);
+ var after_1 = self.host.getMemoryUsage();
+ self.logger.perftrc("GC::before " + before + ", after " + after_1);
}
};
return GcTimer;
@@ -107905,7 +109817,7 @@ var ts;
this.compilerOptions.allowNonTsExtensions = true;
this.compilerOptions.allowJs = true;
}
- else if (hasExplicitListOfFiles || this.compilerOptions.allowJs) {
+ 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;
}
@@ -107976,6 +109888,9 @@ var ts;
Project.prototype.getProjectVersion = function () {
return this.projectStateVersion.toString();
};
+ Project.prototype.getProjectReferences = function () {
+ return undefined;
+ };
Project.prototype.getScriptFileNames = function () {
var _this = this;
if (!this.rootFiles) {
@@ -108426,15 +110341,16 @@ var ts;
* @returns: true if set of files in the project stays the same and false - otherwise.
*/
Project.prototype.updateGraph = function () {
+ var _a;
this.resolutionCache.startRecordingFilesWithChangedResolutions();
var hasNewProgram = this.updateGraphWorker();
var hasAddedorRemovedFiles = this.hasAddedorRemovedFiles;
this.hasAddedorRemovedFiles = false;
var changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || server.emptyArray;
for (var _i = 0, changedFiles_1 = changedFiles; _i < changedFiles_1.length; _i++) {
- var file = changedFiles_1[_i];
+ var file_18 = changedFiles_1[_i];
// delete cached information for changed files
- this.cachedUnresolvedImportsPerFile.delete(file);
+ this.cachedUnresolvedImportsPerFile.delete(file_18);
}
// update builder only if language service is enabled
// otherwise tell it to drop its internal state
@@ -108448,11 +110364,11 @@ var ts;
if (hasNewProgram || changedFiles.length) {
var result = void 0;
var ambientModules = this.program.getTypeChecker().getAmbientModules().map(function (mod) { return ts.stripQuotes(mod.getName()); });
- for (var _a = 0, _b = this.program.getSourceFiles(); _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _b = 0, _c = this.program.getSourceFiles(); _b < _c.length; _b++) {
+ var sourceFile = _c[_b];
var unResolved = this.extractUnresolvedImportsFromSourceFile(sourceFile, ambientModules);
if (unResolved !== server.emptyArray) {
- (_c = (result || (result = []))).push.apply(_c, unResolved);
+ (_a = (result || (result = []))).push.apply(_a, unResolved);
}
}
this.lastCachedUnresolvedImportsList = result ? server.toDeduplicatedSortedArray(result) : server.emptyArray;
@@ -108466,7 +110382,6 @@ var ts;
this.projectProgramVersion++;
}
return !hasNewProgram;
- var _c;
};
/*@internal*/
Project.prototype.updateTypingFiles = function (typingFiles) {
@@ -108578,9 +110493,9 @@ 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];
- strBuilder += "\t" + file.fileName + "\n";
+ for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) {
+ var file_19 = sourceFiles_8[_i];
+ strBuilder += "\t" + file_19.fileName + "\n";
}
}
return strBuilder;
@@ -108666,7 +110581,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_18 = function (globalPluginName) {
+ var _loop_21 = function (globalPluginName) {
// Skip empty names from odd commandline parses
if (!globalPluginName)
return "continue";
@@ -108681,7 +110596,7 @@ var ts;
// Enable global plugins with synthetic configuration entries
for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) {
var globalPluginName = _a[_i];
- _loop_18(globalPluginName);
+ _loop_21(globalPluginName);
}
}
};
@@ -108691,15 +110606,19 @@ var ts;
var log = function (message) {
_this.projectService.logger.info(message);
};
- for (var _i = 0, searchPaths_1 = searchPaths; _i < searchPaths_1.length; _i++) {
- var searchPath = searchPaths_1[_i];
- var resolvedModule = Project.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log);
- if (resolvedModule) {
- this.enableProxy(resolvedModule, pluginConfigEntry);
- return;
- }
+ var resolvedModule = ts.firstDefined(searchPaths, function (searchPath) {
+ return Project.resolveModule(pluginConfigEntry.name, searchPath, _this.projectService.host, log);
+ });
+ if (resolvedModule) {
+ this.enableProxy(resolvedModule, pluginConfigEntry);
}
- this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name);
+ else {
+ this.projectService.logger.info("Couldn't find " + pluginConfigEntry.name);
+ }
+ };
+ /** 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();
};
Project.prototype.enableProxy = function (pluginModuleFactory, configEntry) {
try {
@@ -108834,9 +110753,10 @@ var ts;
var ConfiguredProject = /** @class */ (function (_super) {
__extends(ConfiguredProject, _super);
/*@internal*/
- function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, cachedDirectoryStructureHost) {
+ function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, cachedDirectoryStructureHost, projectReferences) {
var _this = _super.call(this, configFileName, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, cachedDirectoryStructureHost, ts.getDirectoryPath(configFileName)) || this;
_this.compileOnSaveEnabled = compileOnSaveEnabled;
+ _this.projectReferences = projectReferences;
/** Ref count to the project when opened from external project */
_this.externalProjectRefCount = 0;
_this.canonicalConfigFilePath = server.asNormalizedPath(projectService.toCanonicalFileName(configFileName));
@@ -108867,6 +110787,12 @@ var ts;
ConfiguredProject.prototype.getConfigFilePath = function () {
return server.asNormalizedPath(this.getProjectName());
};
+ ConfiguredProject.prototype.getProjectReferences = function () {
+ return this.projectReferences;
+ };
+ ConfiguredProject.prototype.updateReferences = function (refs) {
+ this.projectReferences = refs;
+ };
ConfiguredProject.prototype.enablePlugins = function () {
var host = this.projectService.host;
var options = this.getCompilationSettings();
@@ -109025,6 +110951,7 @@ var ts;
server.ConfigFileDiagEvent = "configFileDiag";
server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState";
server.ProjectInfoTelemetryEvent = "projectInfo";
+ server.OpenFileInfoTelemetryEvent = "openFileInfo";
function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions) {
var map = ts.createMap();
for (var _i = 0, commandLineOptions_1 = commandLineOptions; _i < commandLineOptions_1.length; _i++) {
@@ -109197,6 +111124,8 @@ var ts;
* Container of all known scripts
*/
this.filenameToScriptInfo = 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
*/
@@ -109388,6 +111317,7 @@ var ts;
ProjectService.prototype.hasPendingProjectUpdate = function (project) {
return this.pendingProjectUpdates.has(project.getProjectName());
};
+ /* @internal */
ProjectService.prototype.sendProjectsUpdatedInBackgroundEvent = function () {
var _this = this;
if (!this.eventHandler) {
@@ -109407,11 +111337,13 @@ var ts;
this.delayEnsureProjectForOpenFiles();
};
ProjectService.prototype.delayUpdateProjectGraphs = function (projects) {
- for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) {
- var project = projects_2[_i];
- this.delayUpdateProjectGraph(project);
+ if (projects.length) {
+ for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) {
+ var project = projects_2[_i];
+ this.delayUpdateProjectGraph(project);
+ }
+ this.delayEnsureProjectForOpenFiles();
}
- this.delayEnsureProjectForOpenFiles();
};
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");
@@ -109510,7 +111442,6 @@ var ts;
this.handleDeletedFile(info);
}
else if (!info.isScriptOpen()) {
- ts.Debug.assert(info.containingProjects.length !== 0);
// 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();
@@ -109632,7 +111563,7 @@ var ts;
}
project.updateGraph();
if (!this.useSingleInferredProject && !project.projectRootPath) {
- var _loop_19 = function (inferredProject) {
+ var _loop_22 = function (inferredProject) {
if (inferredProject === project || inferredProject.isOrphan()) {
return "continue";
}
@@ -109653,7 +111584,7 @@ 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_19(inferredProject);
+ _loop_22(inferredProject);
}
}
return project;
@@ -109927,13 +111858,17 @@ var ts;
* the newly opened file.
*/
ProjectService.prototype.forEachConfigFileLocation = function (info, action) {
+ var _this = this;
if (this.syntaxOnly) {
return undefined;
}
ts.Debug.assert(this.openFiles.has(info.path));
var projectRootPath = this.openFiles.get(info.path);
var searchPath = server.asNormalizedPath(ts.getDirectoryPath(info.fileName));
- while (!projectRootPath || ts.containsPath(projectRootPath, searchPath, this.currentDirectory, !this.host.useCaseSensitiveFileNames)) {
+ var isSearchPathInProjectRoot = function () { return ts.containsPath(projectRootPath, searchPath, _this.currentDirectory, !_this.host.useCaseSensitiveFileNames); };
+ // If projectRootPath doesnt contain info.path, then do normal search for config file
+ var anySearchPathOk = !projectRootPath || !isSearchPathInProjectRoot();
+ do {
var canonicalSearchPath = server.normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName);
var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json"));
var result = action(tsconfigFileName, ts.combinePaths(canonicalSearchPath, "tsconfig.json"));
@@ -109950,7 +111885,7 @@ var ts;
break;
}
searchPath = parentPath;
- }
+ } while (anySearchPathOk || isSearchPathInProjectRoot());
return undefined;
};
/**
@@ -110042,7 +111977,8 @@ var ts;
configHasExcludeProperty: parsedCommandLine.raw.exclude !== undefined,
wildcardDirectories: ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories),
typeAcquisition: parsedCommandLine.typeAcquisition,
- compileOnSave: parsedCommandLine.compileOnSave
+ compileOnSave: parsedCommandLine.compileOnSave,
+ projectReferences: parsedCommandLine.projectReferences
};
return { projectOptions: projectOptions, configFileErrors: errors, configFileSpecs: parsedCommandLine.configFileSpecs };
};
@@ -110145,7 +112081,7 @@ var ts;
var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs;
this.logger.info("Opened configuration file " + configFileName);
var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader);
- var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost);
+ var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, lastFileExceededProgramSize, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave, cachedDirectoryStructureHost, projectOptions.projectReferences);
project.configFileSpecs = configFileSpecs;
// 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 for the program" /* ConfigFilePath */, project);
@@ -110252,6 +112188,7 @@ var ts;
// Update the project
project.configFileSpecs = configFileSpecs;
project.setProjectErrors(configFileErrors);
+ project.updateReferences(projectOptions.projectReferences);
var lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader);
if (lastFileExceededProgramSize) {
project.disableLanguageService(lastFileExceededProgramSize);
@@ -110375,7 +112312,7 @@ var ts;
return projects;
function combineProjects(toAddInfo) {
if (toAddInfo !== info) {
- var _loop_20 = function (project) {
+ var _loop_23 = function (project) {
// Add the projects only if they can use symLink targets and not already in the list
if (project.languageServiceEnabled &&
!project.isOrphan() &&
@@ -110392,7 +112329,7 @@ var ts;
};
for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) {
var project = _a[_i];
- _loop_20(project);
+ _loop_23(project);
}
}
}
@@ -110709,8 +112646,16 @@ var ts;
}
});
this.printProjects();
+ this.telemetryOnOpenFile(info);
return { configFileName: configFileName, configFileErrors: configFileErrors };
};
+ ProjectService.prototype.telemetryOnOpenFile = function (scriptInfo) {
+ if (!this.eventHandler || !scriptInfo.isJavaScript() || !ts.addToSeen(this.allJsFilesForOpenFileTelemetry, scriptInfo.path)) {
+ return;
+ }
+ var info = { checkJs: !!scriptInfo.getDefaultProject().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
@@ -110723,13 +112668,13 @@ var ts;
this.printProjects();
};
ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) {
- var _loop_21 = function (proj) {
+ var _loop_24 = function (proj) {
var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; });
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_21(proj);
+ _loop_24(proj);
}
};
/* @internal */
@@ -110744,25 +112689,25 @@ var ts;
ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) {
if (openFiles) {
for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) {
- var file = openFiles_1[_i];
- var scriptInfo = this.getScriptInfo(file.fileName);
+ var file_20 = openFiles_1[_i];
+ var scriptInfo = this.getScriptInfo(file_20.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);
+ var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file_20.fileName);
+ this.openClientFileWithNormalizedPath(normalizedPath, file_20.content, tryConvertScriptKindName(file_20.scriptKind), file_20.hasMixedContent);
}
}
if (changedFiles) {
for (var _a = 0, changedFiles_2 = changedFiles; _a < changedFiles_2.length; _a++) {
- var file = changedFiles_2[_a];
- var scriptInfo = this.getScriptInfo(file.fileName);
+ var file_21 = changedFiles_2[_a];
+ var scriptInfo = this.getScriptInfo(file_21.fileName);
ts.Debug.assert(!!scriptInfo);
- this.applyChangesToFile(scriptInfo, file.changes);
+ this.applyChangesToFile(scriptInfo, file_21.changes);
}
}
if (closedFiles) {
for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) {
- var file = closedFiles_1[_b];
- this.closeClientFile(file);
+ var file_22 = closedFiles_1[_b];
+ this.closeClientFile(file_22);
}
}
};
@@ -110838,15 +112783,15 @@ var ts;
var excludeRules = [];
var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); });
var excludedFiles = [];
- var _loop_22 = function (name_74) {
- var rule = this_2.safelist[name_74];
+ var _loop_25 = function (name) {
+ var rule_2 = 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_2.logger.info("Excluding files based on rule " + name_74 + " matching file '" + root + "'");
+ if (rule_2.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++) {
+ if (rule_2.types) {
+ for (var _a = 0, _b = rule_2.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'
@@ -110855,9 +112800,9 @@ var ts;
}
}
}
- if (rule.exclude) {
- var _loop_23 = function (exclude) {
- var processedRule = root.replace(rule.match, function () {
+ if (rule_2.exclude) {
+ var _loop_27 = function (exclude) {
+ var processedRule = root.replace(rule_2.match, function () {
var groups = [];
for (var _i = 0; _i < arguments.length; _i++) {
groups[_i] = arguments[_i];
@@ -110868,7 +112813,7 @@ var ts;
if (typeof groupNumberOrString === "number") {
if (!ts.isString(groups[groupNumberOrString])) {
// Specification was wrong - exclude nothing!
- _this.logger.info("Incorrect RegExp specification in safelist rule " + name_74 + " - not enough groups");
+ _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 "\\*";
}
@@ -110881,9 +112826,9 @@ var ts;
excludeRules.push(processedRule);
}
};
- for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) {
+ for (var _c = 0, _d = rule_2.exclude; _c < _d.length; _c++) {
var exclude = _d[_c];
- _loop_23(exclude);
+ _loop_27(exclude);
}
}
else {
@@ -110898,12 +112843,12 @@ var ts;
};
var this_2 = this;
for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) {
- var name_74 = _a[_i];
- _loop_22(name_74);
+ var name = _a[_i];
+ _loop_25(name);
}
var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); });
var filesToKeep = [];
- var _loop_24 = function (i) {
+ var _loop_26 = function (i) {
if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) {
excludedFiles.push(normalizedNames[i]);
}
@@ -110941,7 +112886,7 @@ var ts;
};
var this_3 = this;
for (var i = 0; i < proj.rootFiles.length; i++) {
- _loop_24(i);
+ _loop_26(i);
}
proj.rootFiles = filesToKeep;
return excludedFiles;
@@ -110963,15 +112908,15 @@ var ts;
var tsConfigFiles;
var rootFiles = [];
for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) {
- var file = _a[_i];
- var normalized = server.toNormalizedPath(file.fileName);
+ var file_23 = _a[_i];
+ var normalized = server.toNormalizedPath(file_23.fileName);
if (server.getBaseConfigFileName(normalized)) {
if (!this.syntaxOnly && this.host.fileExists(normalized)) {
(tsConfigFiles || (tsConfigFiles = [])).push(normalized);
}
}
else {
- rootFiles.push(file);
+ rootFiles.push(file_23);
}
}
// sort config files to simplify comparison later
@@ -111055,6 +113000,15 @@ var ts;
this.createExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typeAcquisition, excludedFiles);
}
};
+ ProjectService.prototype.hasDeferredExtension = function () {
+ for (var _i = 0, _a = this.hostConfiguration.extraFileExtensions; _i < _a.length; _i++) {
+ var extension = _a[_i];
+ if (extension.scriptKind === 7 /* Deferred */) {
+ return true;
+ }
+ }
+ return false;
+ };
/** Makes a filename safe to insert in a RegExp */
ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g;
return ProjectService;
@@ -111266,6 +113220,7 @@ var ts;
}
var Session = /** @class */ (function () {
function Session(opts) {
+ var _a;
var _this = this;
this.changeSeq = 0;
this.handlers = ts.createMapFromTemplate((_a = {},
@@ -111600,7 +113555,6 @@ var ts;
};
this.projectService = new server.ProjectService(settings);
this.gcTimer = new server.GcTimer(this.host, /*delay*/ 7000, this.logger);
- var _a;
}
Session.prototype.sendRequestCompletedEvent = function (requestId) {
this.event({ request_seq: requestId }, "requestCompleted");
@@ -111890,11 +113844,13 @@ var ts;
return definitions.map(function (def) { return _this.toFileSpan(def.fileName, def.textSpan, project); });
};
Session.prototype.toFileSpan = function (fileName, textSpan, project) {
- var scriptInfo = project.getScriptInfo(fileName);
+ var ls = project.getLanguageService();
+ var start = ls.toLineColumnOffset(fileName, textSpan.start);
+ var end = ls.toLineColumnOffset(fileName, ts.textSpanEnd(textSpan));
return {
file: fileName,
- start: scriptInfo.positionToLineOffset(textSpan.start),
- end: scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan))
+ start: { line: start.line + 1, offset: start.character + 1 },
+ end: { line: end.line + 1, offset: end.character + 1 }
};
};
Session.prototype.getTypeDefinition = function (args) {
@@ -112238,7 +114194,8 @@ var ts;
textSpan: _this.toLocationTextSpan(s.textSpan, scriptInfo_1),
hintSpan: _this.toLocationTextSpan(s.hintSpan, scriptInfo_1),
bannerText: s.bannerText,
- autoCollapse: s.autoCollapse
+ autoCollapse: s.autoCollapse,
+ kind: s.kind
}); });
}
else {
@@ -112394,10 +114351,10 @@ var ts;
if (simplifiedResult) {
return ts.mapDefined(completions && completions.entries, function (entry) {
if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) {
- var name_75 = entry.name, kind = 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 = 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_75, kind: kind, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended };
+ return { name: name, kind: kind, 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); });
}
@@ -113727,5 +115684,3 @@ var ts;
}());
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
-
-//# sourceMappingURL=tsserverlibrary.js.map
diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts
index d54eff0acbd..4887de7fd2f 100644
--- a/lib/typescript.d.ts
+++ b/lib/typescript.d.ts
@@ -337,32 +337,34 @@ declare namespace ts {
EnumMember = 272,
SourceFile = 273,
Bundle = 274,
- JSDocTypeExpression = 275,
- JSDocAllType = 276,
- JSDocUnknownType = 277,
- JSDocNullableType = 278,
- JSDocNonNullableType = 279,
- JSDocOptionalType = 280,
- JSDocFunctionType = 281,
- JSDocVariadicType = 282,
- JSDocComment = 283,
- JSDocTypeLiteral = 284,
- JSDocTag = 285,
- JSDocAugmentsTag = 286,
- JSDocClassTag = 287,
- JSDocParameterTag = 288,
- JSDocReturnTag = 289,
- JSDocTypeTag = 290,
- JSDocTemplateTag = 291,
- JSDocTypedefTag = 292,
- JSDocPropertyTag = 293,
- SyntaxList = 294,
- NotEmittedStatement = 295,
- PartiallyEmittedExpression = 296,
- CommaListExpression = 297,
- MergeDeclarationMarker = 298,
- EndOfDeclarationMarker = 299,
- Count = 300,
+ UnparsedSource = 275,
+ InputFiles = 276,
+ JSDocTypeExpression = 277,
+ JSDocAllType = 278,
+ JSDocUnknownType = 279,
+ JSDocNullableType = 280,
+ JSDocNonNullableType = 281,
+ JSDocOptionalType = 282,
+ JSDocFunctionType = 283,
+ JSDocVariadicType = 284,
+ JSDocComment = 285,
+ JSDocTypeLiteral = 286,
+ JSDocTag = 287,
+ JSDocAugmentsTag = 288,
+ JSDocClassTag = 289,
+ JSDocParameterTag = 290,
+ JSDocReturnTag = 291,
+ JSDocTypeTag = 292,
+ JSDocTemplateTag = 293,
+ JSDocTypedefTag = 294,
+ JSDocPropertyTag = 295,
+ SyntaxList = 296,
+ NotEmittedStatement = 297,
+ PartiallyEmittedExpression = 298,
+ CommaListExpression = 299,
+ MergeDeclarationMarker = 300,
+ EndOfDeclarationMarker = 301,
+ Count = 302,
FirstAssignment = 58,
LastAssignment = 70,
FirstCompoundAssignment = 59,
@@ -388,10 +390,10 @@ declare namespace ts {
FirstBinaryOperator = 27,
LastBinaryOperator = 70,
FirstNode = 145,
- FirstJSDocNode = 275,
- LastJSDocNode = 293,
- FirstJSDocTagNode = 285,
- LastJSDocTagNode = 293
+ FirstJSDocNode = 277,
+ LastJSDocNode = 295,
+ FirstJSDocTagNode = 287,
+ LastJSDocTagNode = 295
}
enum NodeFlags {
None = 0,
@@ -415,6 +417,7 @@ declare namespace ts {
ThisNodeOrAnySubNodesHasError = 131072,
HasAggregatedChildData = 262144,
JSDoc = 2097152,
+ JsonFile = 16777216,
BlockScoped = 3,
ReachabilityCheckFlags = 384,
ReachabilityAndEmitFlags = 1408,
@@ -1149,7 +1152,7 @@ declare namespace ts {
kind: SyntaxKind.NotEmittedStatement;
}
/**
- * A list of comma-seperated expressions. This node is only created by transformations.
+ * A list of comma-separated expressions. This node is only created by transformations.
*/
interface CommaListExpression extends Expression {
kind: SyntaxKind.CommaListExpression;
@@ -1644,12 +1647,32 @@ declare namespace ts {
}
interface Bundle extends Node {
kind: SyntaxKind.Bundle;
+ prepends: ReadonlyArray;
sourceFiles: ReadonlyArray;
}
+ interface InputFiles extends Node {
+ kind: SyntaxKind.InputFiles;
+ javascriptText: string;
+ declarationText: string;
+ }
+ interface UnparsedSource extends Node {
+ kind: SyntaxKind.UnparsedSource;
+ text: string;
+ }
interface JsonSourceFile extends SourceFile {
- jsonObject?: ObjectLiteralExpression;
+ statements: NodeArray;
+ }
+ interface TsConfigSourceFile extends JsonSourceFile {
extendedSourceFiles?: string[];
}
+ interface JsonMinusNumericLiteral extends PrefixUnaryExpression {
+ kind: SyntaxKind.PrefixUnaryExpression;
+ operator: SyntaxKind.MinusToken;
+ operand: NumericLiteral;
+ }
+ interface JsonObjectExpressionStatement extends ExpressionStatement {
+ expression: ObjectLiteralExpression | ArrayLiteralExpression | JsonMinusNumericLiteral | NumericLiteral | StringLiteral | BooleanLiteral | NullLiteral;
+ }
interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
getSourceFile(fileName: string): SourceFile | undefined;
@@ -1705,12 +1728,19 @@ declare namespace ts {
*/
getTypeChecker(): TypeChecker;
isSourceFileFromExternalLibrary(file: SourceFile): boolean;
+ getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined;
+ }
+ interface ResolvedProjectReference {
+ commandLine: ParsedCommandLine;
+ sourceFile: SourceFile;
}
interface CustomTransformers {
- /** Custom transformers to evaluate before built-in transformations. */
+ /** Custom transformers to evaluate before built-in .js transformations. */
before?: TransformerFactory[];
- /** Custom transformers to evaluate after built-in transformations. */
+ /** Custom transformers to evaluate after built-in .js transformations. */
after?: TransformerFactory[];
+ /** Custom transformers to evaluate after built-in .d.ts transformations. */
+ afterDeclarations?: TransformerFactory[];
}
interface SourceMapSpan {
/** Line number in the .js file. */
@@ -1853,6 +1883,7 @@ declare namespace ts {
None = 0,
NoTruncation = 1,
WriteArrayAsGenericType = 2,
+ GenerateNamesForShadowedTypeParams = 4,
UseStructuralFallback = 8,
WriteTypeArgumentsOfSignature = 32,
UseFullyQualifiedType = 64,
@@ -2274,7 +2305,9 @@ declare namespace ts {
AlwaysStrict = 64,
PriorityImpliesCombination = 28
}
- interface JsFileExtensionInfo {
+ /** @deprecated Use FileExtensionInfo instead. */
+ type JsFileExtensionInfo = FileExtensionInfo;
+ interface FileExtensionInfo {
extension: string;
isMixedContent: boolean;
scriptKind?: ScriptKind;
@@ -2322,7 +2355,17 @@ declare namespace ts {
interface PluginImport {
name: string;
}
- type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | null | undefined;
+ interface ProjectReference {
+ /** A normalized path on disk */
+ path: string;
+ /** The path as the user originally wrote it */
+ originalPath?: string;
+ /** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */
+ prepend?: boolean;
+ /** True if it is intended that this reference form a circularity */
+ circular?: boolean;
+ }
+ type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined;
interface CompilerOptions {
allowJs?: boolean;
allowSyntheticDefaultImports?: boolean;
@@ -2378,6 +2421,7 @@ declare namespace ts {
project?: string;
reactNamespace?: string;
jsxFactory?: string;
+ composite?: boolean;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
@@ -2393,11 +2437,12 @@ declare namespace ts {
suppressImplicitAnyIndexErrors?: boolean;
target?: ScriptTarget;
traceResolution?: boolean;
+ resolveJsonModule?: boolean;
types?: string[];
/** Paths used to compute primary types search locations */
typeRoots?: string[];
esModuleInterop?: boolean;
- [option: string]: CompilerOptionsValue | JsonSourceFile | undefined;
+ [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined;
}
interface TypeAcquisition {
enableAutoDiscovery?: boolean;
@@ -2437,7 +2482,12 @@ declare namespace ts {
TS = 3,
TSX = 4,
External = 5,
- JSON = 6
+ JSON = 6,
+ /**
+ * Used on extensions that doesn't define the ScriptKind but the content defines it.
+ * Deferred extensions are going to be included in all project contexts.
+ */
+ Deferred = 7
}
enum ScriptTarget {
ES3 = 0,
@@ -2447,6 +2497,7 @@ declare namespace ts {
ES2017 = 4,
ES2018 = 5,
ESNext = 6,
+ JSON = 100,
Latest = 6
}
enum LanguageVariant {
@@ -2458,6 +2509,7 @@ declare namespace ts {
options: CompilerOptions;
typeAcquisition?: TypeAcquisition;
fileNames: string[];
+ projectReferences?: ReadonlyArray;
raw?: any;
errors: Diagnostic[];
wildcardDirectories?: MapLike;
@@ -2469,8 +2521,17 @@ declare namespace ts {
}
interface ExpandResult {
fileNames: string[];
+ projectReferences: ReadonlyArray | undefined;
wildcardDirectories: MapLike;
}
+ interface CreateProgramOptions {
+ rootNames: ReadonlyArray;
+ options: CompilerOptions;
+ projectReferences?: ReadonlyArray;
+ host?: CompilerHost;
+ oldProgram?: Program;
+ configFileParsingDiagnostics?: ReadonlyArray;
+ }
interface ModuleResolutionHost {
fileExists(fileName: string): boolean;
readFile(fileName: string): string | undefined;
@@ -2561,6 +2622,7 @@ declare namespace ts {
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
+ readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[];
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[];
/**
* This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files
@@ -3423,6 +3485,8 @@ declare namespace ts {
function createLiteral(value: boolean): BooleanLiteral;
function createLiteral(value: string | number | boolean): PrimaryExpression;
function createNumericLiteral(value: string): NumericLiteral;
+ function createStringLiteral(text: string): StringLiteral;
+ function createRegularExpressionLiteral(text: string): RegularExpressionLiteral;
function createIdentifier(text: string): Identifier;
function updateIdentifier(node: Identifier): Identifier;
/** Create a unique temporary variable. */
@@ -3727,8 +3791,10 @@ declare namespace ts {
function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression;
function createCommaList(elements: ReadonlyArray): CommaListExpression;
function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression;
- function createBundle(sourceFiles: ReadonlyArray): Bundle;
- function updateBundle(node: Bundle, sourceFiles: ReadonlyArray): Bundle;
+ function createBundle(sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle;
+ function createUnparsedSourceFile(text: string): UnparsedSource;
+ function createInputFiles(javascript: string, declaration: string): InputFiles;
+ function updateBundle(node: Bundle, sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray): CallExpression;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray, param: ParameterDeclaration, paramValue: Expression): CallExpression;
function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray): CallExpression;
@@ -3935,6 +4001,7 @@ declare namespace ts {
* @param configFileParsingDiagnostics - error during config file parsing
* @returns A 'Program' object.
*/
+ function createProgram(createProgramOptions: CreateProgramOptions): Program;
function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program;
}
declare namespace ts {
@@ -4074,7 +4141,6 @@ declare namespace ts {
function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram;
}
declare namespace ts {
- type DiagnosticReporter = (diagnostic: Diagnostic) => void;
type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void;
/** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */
type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T;
@@ -4137,15 +4203,6 @@ declare namespace ts {
/** Compiler options */
options: CompilerOptions;
}
- /**
- * Reports config file diagnostics
- */
- interface ConfigFileDiagnosticsReporter {
- /**
- * Reports unrecoverable error when parsing config file
- */
- onUnRecoverableConfigFileDiagnostic: DiagnosticReporter;
- }
/**
* Host to create watch with config file
*/
@@ -4192,6 +4249,26 @@ declare namespace ts {
}
declare namespace ts {
function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine;
+ type DiagnosticReporter = (diagnostic: Diagnostic) => void;
+ /**
+ * Reports config file diagnostics
+ */
+ interface ConfigFileDiagnosticsReporter {
+ /**
+ * Reports unrecoverable error when parsing config file
+ */
+ onUnRecoverableConfigFileDiagnostic: DiagnosticReporter;
+ }
+ /**
+ * Interface extending ParseConfigHost to support ParseConfigFile that reads config file and reports errors
+ */
+ interface ParseConfigFileHost extends ParseConfigHost, ConfigFileDiagnosticsReporter {
+ getCurrentDirectory(): string;
+ }
+ /**
+ * Reads the config file, reports errors if any and exits if the config file cannot be found
+ */
+ function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost): ParsedCommandLine | undefined;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
@@ -4213,7 +4290,7 @@ declare namespace ts {
* Read tsconfig.json file
* @param fileName The path to the config file
*/
- function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): JsonSourceFile;
+ function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile;
/**
* Convert the json syntax tree into the json value
*/
@@ -4225,7 +4302,7 @@ declare namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
- function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine;
+ function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine;
/**
* Parse the contents of a config file (tsconfig.json).
* @param jsonNode The contents of the config file to parse
@@ -4233,7 +4310,7 @@ declare namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
- function parseJsonSourceFileConfigFileContent(sourceFile: JsonSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine;
+ function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine;
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
@@ -4252,7 +4329,7 @@ declare namespace ts {
getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number;
getFullStart(): number;
getEnd(): number;
- getWidth(sourceFile?: SourceFile): number;
+ getWidth(sourceFile?: SourceFileLike): number;
getFullWidth(): number;
getLeadingTriviaWidth(sourceFile?: SourceFile): number;
getFullText(sourceFile?: SourceFile): string;
@@ -4364,6 +4441,7 @@ declare namespace ts {
getScriptKind?(fileName: string): ScriptKind;
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): IScriptSnapshot | undefined;
+ getProjectReferences?(): ReadonlyArray | undefined;
getLocalizedDiagnosticMessages?(): any;
getCancellationToken?(): HostCancellationToken;
getCurrentDirectory(): string;
@@ -4393,6 +4471,7 @@ declare namespace ts {
readonly includeCompletionsForModuleExports?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
+ readonly allowTextChangesInNewFiles?: boolean;
}
interface LanguageService {
cleanupSemanticCache(): void;
@@ -4441,6 +4520,7 @@ declare namespace ts {
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean;
getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan;
+ toLineColumnOffset?(fileName: string, position: number): LineAndCharacter;
getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray;
getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions;
applyCodeActionCommand(action: CodeActionCommand): Promise;
@@ -4465,9 +4545,10 @@ declare namespace ts {
fileName: string;
}
type OrganizeImportsScope = CombinedCodeFixScope;
+ type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<";
interface GetCompletionsAtPositionOptions extends UserPreferences {
/** If the editor is asking for completions because a certain character was typed, and not because the user explicitly requested them, this should be set. */
- triggerCharacter?: string;
+ triggerCharacter?: CompletionsTriggerCharacter;
/** @deprecated Use includeCompletionsForModuleExports */
includeExternalModuleExports?: boolean;
/** @deprecated Use includeCompletionsWithInsertText */
@@ -4865,6 +4946,20 @@ declare namespace ts {
* the 'Collapse to Definitions' command is invoked.
*/
autoCollapse: boolean;
+ /**
+ * Classification of the contents of the span
+ */
+ kind: OutliningSpanKind;
+ }
+ enum OutliningSpanKind {
+ /** Single or multi-line comments */
+ Comment = "comment",
+ /** Sections marked by '// #region' and '// #endregion' comments */
+ Region = "region",
+ /** Declarations and expressions */
+ Code = "code",
+ /** Contiguous blocks of import declarations */
+ Imports = "imports"
}
enum OutputFileType {
JavaScript = 0,
@@ -4988,7 +5083,9 @@ declare namespace ts {
/**
*
*/
- jsxAttribute = "JSX attribute"
+ jsxAttribute = "JSX attribute",
+ /** String literal */
+ string = "string"
}
enum ScriptElementKindModifier {
none = "",
diff --git a/lib/typescript.js b/lib/typescript.js
index 86c2e32ef0e..33caf6392fd 100644
--- a/lib/typescript.js
+++ b/lib/typescript.js
@@ -350,38 +350,40 @@ var ts;
// Top-level nodes
SyntaxKind[SyntaxKind["SourceFile"] = 273] = "SourceFile";
SyntaxKind[SyntaxKind["Bundle"] = 274] = "Bundle";
+ SyntaxKind[SyntaxKind["UnparsedSource"] = 275] = "UnparsedSource";
+ SyntaxKind[SyntaxKind["InputFiles"] = 276] = "InputFiles";
// JSDoc nodes
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 275] = "JSDocTypeExpression";
+ SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 277] = "JSDocTypeExpression";
// The * type
- SyntaxKind[SyntaxKind["JSDocAllType"] = 276] = "JSDocAllType";
+ SyntaxKind[SyntaxKind["JSDocAllType"] = 278] = "JSDocAllType";
// The ? type
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 277] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 278] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 279] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 280] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 281] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 282] = "JSDocVariadicType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 283] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 284] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocTag"] = 285] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 286] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocClassTag"] = 287] = "JSDocClassTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 288] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 289] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 290] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 291] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 292] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 293] = "JSDocPropertyTag";
+ SyntaxKind[SyntaxKind["JSDocUnknownType"] = 279] = "JSDocUnknownType";
+ SyntaxKind[SyntaxKind["JSDocNullableType"] = 280] = "JSDocNullableType";
+ SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 281] = "JSDocNonNullableType";
+ SyntaxKind[SyntaxKind["JSDocOptionalType"] = 282] = "JSDocOptionalType";
+ SyntaxKind[SyntaxKind["JSDocFunctionType"] = 283] = "JSDocFunctionType";
+ SyntaxKind[SyntaxKind["JSDocVariadicType"] = 284] = "JSDocVariadicType";
+ SyntaxKind[SyntaxKind["JSDocComment"] = 285] = "JSDocComment";
+ SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 286] = "JSDocTypeLiteral";
+ SyntaxKind[SyntaxKind["JSDocTag"] = 287] = "JSDocTag";
+ SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 288] = "JSDocAugmentsTag";
+ SyntaxKind[SyntaxKind["JSDocClassTag"] = 289] = "JSDocClassTag";
+ SyntaxKind[SyntaxKind["JSDocParameterTag"] = 290] = "JSDocParameterTag";
+ SyntaxKind[SyntaxKind["JSDocReturnTag"] = 291] = "JSDocReturnTag";
+ SyntaxKind[SyntaxKind["JSDocTypeTag"] = 292] = "JSDocTypeTag";
+ SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 293] = "JSDocTemplateTag";
+ SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 294] = "JSDocTypedefTag";
+ SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 295] = "JSDocPropertyTag";
// Synthesized list
- SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList";
+ SyntaxKind[SyntaxKind["SyntaxList"] = 296] = "SyntaxList";
// Transformation nodes
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker";
+ SyntaxKind[SyntaxKind["NotEmittedStatement"] = 297] = "NotEmittedStatement";
+ SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 298] = "PartiallyEmittedExpression";
+ SyntaxKind[SyntaxKind["CommaListExpression"] = 299] = "CommaListExpression";
+ SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 300] = "MergeDeclarationMarker";
+ SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 301] = "EndOfDeclarationMarker";
// Enum value count
- SyntaxKind[SyntaxKind["Count"] = 300] = "Count";
+ SyntaxKind[SyntaxKind["Count"] = 302] = "Count";
// Markers
SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment";
SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment";
@@ -408,10 +410,10 @@ var ts;
SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator";
SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator";
SyntaxKind[SyntaxKind["FirstNode"] = 145] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 275] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 293] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 285] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 293] = "LastJSDocTagNode";
+ SyntaxKind[SyntaxKind["FirstJSDocNode"] = 277] = "FirstJSDocNode";
+ SyntaxKind[SyntaxKind["LastJSDocNode"] = 295] = "LastJSDocNode";
+ SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 287] = "FirstJSDocTagNode";
+ SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 295] = "LastJSDocTagNode";
/* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword";
/* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 144] = "LastContextualKeyword";
})(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
@@ -451,6 +453,7 @@ var ts;
NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc";
/* @internal */ NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient";
/* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement";
+ NodeFlags[NodeFlags["JsonFile"] = 16777216] = "JsonFile";
NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags";
NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags";
@@ -513,10 +516,9 @@ var ts;
GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
// Flags
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 32] = "Optimistic";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 64] = "FileLevel";
+ GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
+ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
+ GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
})(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
/* @internal */
var TokenFlags;
@@ -591,7 +593,7 @@ var ts;
// Options
NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
- // empty space
+ NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams";
NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
// empty space
NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
@@ -1072,6 +1074,11 @@ var ts;
ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
ScriptKind[ScriptKind["External"] = 5] = "External";
ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
+ /**
+ * Used on extensions that doesn't define the ScriptKind but the content defines it.
+ * Deferred extensions are going to be included in all project contexts.
+ */
+ ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
})(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
var ScriptTarget;
(function (ScriptTarget) {
@@ -1082,6 +1089,7 @@ var ts;
ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext";
+ ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest";
})(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
var LanguageVariant;
@@ -1894,8 +1902,8 @@ var ts;
}
ts.findLast = findLast;
/** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */
- function findIndex(array, predicate) {
- for (var i = 0; i < array.length; i++) {
+ function findIndex(array, predicate, startIndex) {
+ for (var i = startIndex || 0; i < array.length; i++) {
if (predicate(array[i], i)) {
return i;
}
@@ -2498,6 +2506,23 @@ var ts;
return to;
}
ts.addRange = addRange;
+ /**
+ * Appends a range of value to begin of an array, returning the array.
+ *
+ * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array
+ * is created if `value` was appended.
+ * @param from The values to append to the array. If `from` is `undefined`, nothing is
+ * appended. If an element of `from` is `undefined`, that element is not appended.
+ */
+ function prependRange(to, from) {
+ if (from === undefined || from.length === 0)
+ return to;
+ if (to === undefined)
+ return from.slice();
+ to.unshift.apply(to, from);
+ return to;
+ }
+ ts.prependRange = prependRange;
/**
* @return Whether the value was added.
*/
@@ -2747,17 +2772,18 @@ var ts;
}
ts.getOwnValues = getOwnValues;
function arrayFrom(iterator, map) {
+ var _a;
var result = [];
- for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) {
result.push(map ? map(value) : value);
}
return result;
- var _b;
}
ts.arrayFrom = arrayFrom;
function forEachEntry(map, callback) {
+ var _a;
var iterator = map.entries();
- for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) {
var key = pair[0], value = pair[1];
var result = callback(value, key);
if (result) {
@@ -2765,19 +2791,18 @@ var ts;
}
}
return undefined;
- var _b;
}
ts.forEachEntry = forEachEntry;
function forEachKey(map, callback) {
+ var _a;
var iterator = map.keys();
- for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) {
var result = callback(key);
if (result) {
return result;
}
}
return undefined;
- var _b;
}
ts.forEachKey = forEachKey;
function copyEntries(source, target) {
@@ -3334,11 +3359,11 @@ var ts;
comparer(a[key], b[key]);
}
ts.compareProperties = compareProperties;
- function getDiagnosticFileName(diagnostic) {
- return diagnostic.file ? diagnostic.file.fileName : undefined;
+ function getDiagnosticFilePath(diagnostic) {
+ return diagnostic.file ? diagnostic.file.path : undefined;
}
function compareDiagnostics(d1, d2) {
- return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) ||
+ return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
compareValues(d1.start, d2.start) ||
compareValues(d1.length, d2.length) ||
compareValues(d1.code, d2.code) ||
@@ -3370,106 +3395,6 @@ var ts;
// We still have one chain remaining. The shorter chain should come first.
return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */;
}
- function normalizeSlashes(path) {
- return path.replace(/\\/g, "/");
- }
- ts.normalizeSlashes = normalizeSlashes;
- /**
- * Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files")
- */
- function getRootLength(path) {
- if (path.charCodeAt(0) === 47 /* slash */) {
- if (path.charCodeAt(1) !== 47 /* slash */)
- return 1;
- var p1 = path.indexOf("/", 2);
- if (p1 < 0)
- return 2;
- var p2 = path.indexOf("/", p1 + 1);
- if (p2 < 0)
- return p1 + 1;
- return p2 + 1;
- }
- if (path.charCodeAt(1) === 58 /* colon */) {
- if (path.charCodeAt(2) === 47 /* slash */ || path.charCodeAt(2) === 92 /* backslash */)
- return 3;
- }
- // Per RFC 1738 'file' URI schema has the shape file:///
- // if is omitted then it is assumed that host value is 'localhost',
- // however slash after the omitted is not removed.
- // file:///folder1/file1 - this is a correct URI
- // file://folder2/file2 - this is an incorrect URI
- if (path.lastIndexOf("file:///", 0) === 0) {
- return "file:///".length;
- }
- var idx = path.indexOf("://");
- if (idx !== -1) {
- return idx + "://".length;
- }
- return 0;
- }
- ts.getRootLength = getRootLength;
- /**
- * Internally, we represent paths as strings with '/' as the directory separator.
- * When we make system calls (eg: LanguageServiceHost.getDirectory()),
- * we expect the host to correctly handle paths in our specified format.
- */
- ts.directorySeparator = "/";
- var directorySeparatorCharCode = 47 /* slash */;
- function getNormalizedParts(normalizedSlashedPath, rootLength) {
- var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator);
- var normalized = [];
- for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
- var part = parts_1[_i];
- if (part !== ".") {
- if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") {
- normalized.pop();
- }
- else {
- // A part may be an empty string (which is 'falsy') if the path had consecutive slashes,
- // e.g. "path//file.ts". Drop these before re-joining the parts.
- if (part) {
- normalized.push(part);
- }
- }
- }
- }
- return normalized;
- }
- function normalizePath(path) {
- return normalizePathAndParts(path).path;
- }
- ts.normalizePath = normalizePath;
- function normalizePathAndParts(path) {
- path = normalizeSlashes(path);
- var rootLength = getRootLength(path);
- var root = path.substr(0, rootLength);
- var parts = getNormalizedParts(path, rootLength);
- if (parts.length) {
- var joinedParts = root + parts.join(ts.directorySeparator);
- return { path: pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts, parts: parts };
- }
- else {
- return { path: root, parts: parts };
- }
- }
- ts.normalizePathAndParts = normalizePathAndParts;
- /** A path ending with '/' refers to a directory only, never a file. */
- function pathEndsWithDirectorySeparator(path) {
- return path.charCodeAt(path.length - 1) === directorySeparatorCharCode;
- }
- ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator;
- function getDirectoryPath(path) {
- return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator)));
- }
- ts.getDirectoryPath = getDirectoryPath;
- function isUrl(path) {
- return path && !isRootedDiskPath(path) && stringContains(path, "://");
- }
- ts.isUrl = isUrl;
- function pathIsRelative(path) {
- return /^\.\.?($|[\\/])/.test(path);
- }
- ts.pathIsRelative = pathIsRelative;
function getEmitScriptTarget(compilerOptions) {
return compilerOptions.target || 0 /* ES3 */;
}
@@ -3501,6 +3426,10 @@ var ts;
: moduleKind === ts.ModuleKind.System;
}
ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
+ function getEmitDeclarations(compilerOptions) {
+ return !!(compilerOptions.declaration || compilerOptions.composite);
+ }
+ ts.getEmitDeclarations = getEmitDeclarations;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag];
}
@@ -3521,202 +3450,455 @@ var ts;
return true;
}
ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
+ //
+ // Paths
+ //
+ /**
+ * Internally, we represent paths as strings with '/' as the directory separator.
+ * When we make system calls (eg: LanguageServiceHost.getDirectory()),
+ * we expect the host to correctly handle paths in our specified format.
+ */
+ ts.directorySeparator = "/";
+ var altDirectorySeparator = "\\";
+ var urlSchemeSeparator = "://";
+ var backslashRegExp = /\\/g;
+ /**
+ * Normalize path separators.
+ */
+ function normalizeSlashes(path) {
+ return path.replace(backslashRegExp, ts.directorySeparator);
+ }
+ ts.normalizeSlashes = normalizeSlashes;
+ function isVolumeCharacter(charCode) {
+ return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
+ (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
+ }
+ function getFileUrlVolumeSeparatorEnd(url, start) {
+ var ch0 = url.charCodeAt(start);
+ if (ch0 === 58 /* colon */)
+ return start + 1;
+ if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
+ var ch2 = url.charCodeAt(start + 2);
+ if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
+ return start + 3;
+ }
+ return -1;
+ }
+ /**
+ * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
+ * If the root is part of a URL, the twos-complement of the root length is returned.
+ */
+ function getEncodedRootLength(path) {
+ if (!path)
+ return 0;
+ var ch0 = path.charCodeAt(0);
+ // POSIX or UNC
+ if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
+ if (path.charCodeAt(1) !== ch0)
+ return 1; // POSIX: "/" (or non-normalized "\")
+ var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2);
+ if (p1 < 0)
+ return path.length; // UNC: "//server" or "\\server"
+ return p1 + 1; // UNC: "//server/" or "\\server\"
+ }
+ // DOS
+ if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
+ var ch2 = path.charCodeAt(2);
+ if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
+ return 3; // DOS: "c:/" or "c:\"
+ if (path.length === 2)
+ return 2; // DOS: "c:" (but not "c:d")
+ }
+ // URL
+ var schemeEnd = path.indexOf(urlSchemeSeparator);
+ if (schemeEnd !== -1) {
+ var authorityStart = schemeEnd + urlSchemeSeparator.length;
+ var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
+ if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
+ // For local "file" URLs, include the leading DOS volume (if present).
+ // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
+ // special case interpreted as "the machine from which the URL is being interpreted".
+ var scheme = path.slice(0, schemeEnd);
+ var authority = path.slice(authorityStart, authorityEnd);
+ if (scheme === "file" && (authority === "" || authority === "localhost") &&
+ isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
+ var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
+ if (volumeSeparatorEnd !== -1) {
+ if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
+ // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
+ return ~(volumeSeparatorEnd + 1);
+ }
+ if (volumeSeparatorEnd === path.length) {
+ // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
+ // but not "file:///c:d" or "file:///c%3ad"
+ return ~volumeSeparatorEnd;
+ }
+ }
+ }
+ return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
+ }
+ return ~path.length; // URL: "file://server", "http://server"
+ }
+ // relative
+ return 0;
+ }
+ /**
+ * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
+ *
+ * For example:
+ * ```ts
+ * getRootLength("a") === 0 // ""
+ * getRootLength("/") === 1 // "/"
+ * getRootLength("c:") === 2 // "c:"
+ * getRootLength("c:d") === 0 // ""
+ * getRootLength("c:/") === 3 // "c:/"
+ * getRootLength("c:\\") === 3 // "c:\\"
+ * getRootLength("//server") === 7 // "//server"
+ * getRootLength("//server/share") === 8 // "//server/"
+ * getRootLength("\\\\server") === 7 // "\\\\server"
+ * getRootLength("\\\\server\\share") === 8 // "\\\\server\\"
+ * getRootLength("file:///path") === 8 // "file:///"
+ * getRootLength("file:///c:") === 10 // "file:///c:"
+ * getRootLength("file:///c:d") === 8 // "file:///"
+ * getRootLength("file:///c:/path") === 11 // "file:///c:/"
+ * getRootLength("file://server") === 13 // "file://server"
+ * getRootLength("file://server/path") === 14 // "file://server/"
+ * getRootLength("http://server") === 13 // "http://server"
+ * getRootLength("http://server/path") === 14 // "http://server/"
+ * ```
+ */
+ function getRootLength(path) {
+ var rootLength = getEncodedRootLength(path);
+ return rootLength < 0 ? ~rootLength : rootLength;
+ }
+ ts.getRootLength = getRootLength;
+ // TODO(rbuckton): replace references with `resolvePath`
+ function normalizePath(path) {
+ return resolvePath(path);
+ }
+ ts.normalizePath = normalizePath;
+ function normalizePathAndParts(path) {
+ path = normalizeSlashes(path);
+ var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
+ if (parts.length) {
+ var joinedParts = root + parts.join(ts.directorySeparator);
+ return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
+ }
+ else {
+ return { path: root, parts: parts };
+ }
+ }
+ ts.normalizePathAndParts = normalizePathAndParts;
+ function getDirectoryPath(path) {
+ path = normalizeSlashes(path);
+ // If the path provided is itself the root, then return it.
+ var rootLength = getRootLength(path);
+ if (rootLength === path.length)
+ return path;
+ // return the leading portion of the path up to the last (non-terminal) directory separator
+ // but not including any trailing directory separator.
+ path = removeTrailingDirectorySeparator(path);
+ return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
+ }
+ ts.getDirectoryPath = getDirectoryPath;
+ function isUrl(path) {
+ return getEncodedRootLength(path) < 0;
+ }
+ ts.isUrl = isUrl;
+ function pathIsRelative(path) {
+ return /^\.\.?($|[\\/])/.test(path);
+ }
+ ts.pathIsRelative = pathIsRelative;
+ /**
+ * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path
+ * like `c:`, `c:\` or `c:/`).
+ */
function isRootedDiskPath(path) {
- return path && getRootLength(path) !== 0;
+ return getEncodedRootLength(path) > 0;
}
ts.isRootedDiskPath = isRootedDiskPath;
+ /**
+ * Determines whether a path consists only of a path root.
+ */
+ function isDiskPathRoot(path) {
+ var rootLength = getEncodedRootLength(path);
+ return rootLength > 0 && rootLength === path.length;
+ }
+ ts.isDiskPathRoot = isDiskPathRoot;
function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
return !isRootedDiskPath(absoluteOrRelativePath)
? absoluteOrRelativePath
: getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
}
ts.convertToRelativePath = convertToRelativePath;
- function normalizedPathComponents(path, rootLength) {
- var normalizedParts = getNormalizedParts(path, rootLength);
- return [path.substr(0, rootLength)].concat(normalizedParts);
+ function pathComponents(path, rootLength) {
+ var root = path.substring(0, rootLength);
+ var rest = path.substring(rootLength).split(ts.directorySeparator);
+ if (rest.length && !lastOrUndefined(rest))
+ rest.pop();
+ return [root].concat(rest);
}
- function getNormalizedPathComponents(path, currentDirectory) {
- path = normalizeSlashes(path);
+ /**
+ * Parse a path into an array containing a root component (at index 0) and zero or more path
+ * components (at indices > 0). The result is not normalized.
+ * If the path is relative, the root component is `""`.
+ * If the path is absolute, the root component includes the first path separator (`/`).
+ */
+ function getPathComponents(path, currentDirectory) {
+ if (currentDirectory === void 0) { currentDirectory = ""; }
+ path = combinePaths(currentDirectory, path);
var rootLength = getRootLength(path);
- if (rootLength === 0) {
- // If the path is not rooted it is relative to current directory
- path = combinePaths(normalizeSlashes(currentDirectory), path);
- rootLength = getRootLength(path);
+ return pathComponents(path, rootLength);
+ }
+ ts.getPathComponents = getPathComponents;
+ /**
+ * Reduce an array of path components to a more simplified path by navigating any
+ * `"."` or `".."` entries in the path.
+ */
+ function reducePathComponents(components) {
+ if (!some(components))
+ return [];
+ var reduced = [components[0]];
+ for (var i = 1; i < components.length; i++) {
+ var component = components[i];
+ if (!component)
+ continue;
+ if (component === ".")
+ continue;
+ if (component === "..") {
+ if (reduced.length > 1) {
+ if (reduced[reduced.length - 1] !== "..") {
+ reduced.pop();
+ continue;
+ }
+ }
+ else if (reduced[0])
+ continue;
+ }
+ reduced.push(component);
}
- return normalizedPathComponents(path, rootLength);
+ return reduced;
+ }
+ ts.reducePathComponents = reducePathComponents;
+ /**
+ * Parse a path into an array containing a root component (at index 0) and zero or more path
+ * components (at indices > 0). The result is normalized.
+ * If the path is relative, the root component is `""`.
+ * If the path is absolute, the root component includes the first path separator (`/`).
+ */
+ function getNormalizedPathComponents(path, currentDirectory) {
+ return reducePathComponents(getPathComponents(path, currentDirectory));
}
ts.getNormalizedPathComponents = getNormalizedPathComponents;
function getNormalizedAbsolutePath(fileName, currentDirectory) {
- return getNormalizedPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
+ return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
}
ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
- function getNormalizedPathFromPathComponents(pathComponents) {
- if (pathComponents && pathComponents.length) {
- return pathComponents[0] + pathComponents.slice(1).join(ts.directorySeparator);
- }
+ /**
+ * Formats a parsed path consisting of a root component (at index 0) and zero or more path
+ * segments (at indices > 0).
+ */
+ function getPathFromPathComponents(pathComponents) {
+ if (pathComponents.length === 0)
+ return "";
+ var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
+ if (pathComponents.length === 1)
+ return root;
+ return root + pathComponents.slice(1).join(ts.directorySeparator);
}
- ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents;
- function getNormalizedPathComponentsOfUrl(url) {
- // Get root length of http://www.website.com/folder1/folder2/
- // In this example the root is: http://www.website.com/
- // normalized path components should be ["http://www.website.com/", "folder1", "folder2"]
- var urlLength = url.length;
- // Initial root length is http:// part
- var rootLength = url.indexOf("://") + "://".length;
- while (rootLength < urlLength) {
- // Consume all immediate slashes in the protocol
- // eg.initial rootlength is just file:// but it needs to consume another "/" in file:///
- if (url.charCodeAt(rootLength) === 47 /* slash */) {
- rootLength++;
- }
- else {
- // non slash character means we continue proceeding to next component of root search
+ ts.getPathFromPathComponents = getPathFromPathComponents;
+ function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
+ var fromComponents = reducePathComponents(getPathComponents(from));
+ var toComponents = reducePathComponents(getPathComponents(to));
+ var start;
+ for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
+ var fromComponent = getCanonicalFileName(fromComponents[start]);
+ var toComponent = getCanonicalFileName(toComponents[start]);
+ var comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer;
+ if (!comparer(fromComponent, toComponent))
break;
- }
}
- // there are no parts after http:// just return current string as the pathComponent
- if (rootLength === urlLength) {
- return [url];
+ if (start === 0) {
+ return toComponents;
}
- // Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://)
- var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength);
- if (indexOfNextSlash !== -1) {
- // Found the "/" after the website.com so the root is length of http://www.website.com/
- // and get components after the root normally like any other folder components
- rootLength = indexOfNextSlash + 1;
- return normalizedPathComponents(url, rootLength);
- }
- else {
- // Can't find the host assume the rest of the string as component
- // but make sure we append "/" to it as root is not joined using "/"
- // eg. if url passed in was http://website.com we want to use root as [http://website.com/]
- // so that other path manipulations will be correct and it can be merged with relative paths correctly
- return [url + ts.directorySeparator];
+ var components = toComponents.slice(start);
+ var relative = [];
+ for (; start < fromComponents.length; start++) {
+ relative.push("..");
}
+ return [""].concat(relative, components);
}
- function getNormalizedPathOrUrlComponents(pathOrUrl, currentDirectory) {
- if (isUrl(pathOrUrl)) {
- return getNormalizedPathComponentsOfUrl(pathOrUrl);
- }
- else {
- return getNormalizedPathComponents(pathOrUrl, currentDirectory);
- }
+ function getRelativePathFromFile(from, to, getCanonicalFileName) {
+ return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
}
+ ts.getRelativePathFromFile = getRelativePathFromFile;
+ function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
+ Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
+ var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : identity;
+ var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
+ var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive, getCanonicalFileName);
+ return getPathFromPathComponents(pathComponents);
+ }
+ ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
- var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory);
- var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory);
- if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") {
- // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name
- // that is ["test", "cases", ""] needs to be actually ["test", "cases"]
- directoryComponents.pop();
+ var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), equateStringsCaseSensitive, getCanonicalFileName);
+ var firstComponent = pathComponents[0];
+ if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
+ var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
+ pathComponents[0] = prefix + firstComponent;
}
- // Find the component that differs
- var joinStartIndex;
- for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) {
- if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) {
- break;
- }
- }
- // Get the relative path
- if (joinStartIndex) {
- var relativePath = "";
- var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length);
- for (; joinStartIndex < directoryComponents.length; joinStartIndex++) {
- if (directoryComponents[joinStartIndex] !== "") {
- relativePath = relativePath + ".." + ts.directorySeparator;
- }
- }
- return relativePath + relativePathComponents.join(ts.directorySeparator);
- }
- // Cant find the relative path, get the absolute path
- var absolutePath = getNormalizedPathFromPathComponents(pathComponents);
- if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) {
- absolutePath = "file:///" + absolutePath;
- }
- return absolutePath;
+ return getPathFromPathComponents(pathComponents);
}
ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
- function getRelativePath(path, directoryPath, getCanonicalFileName) {
- var relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
- return ensurePathIsRelative(relativePath);
+ /**
+ * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
+ * with `./` or `../`) so as not to be confused with an unprefixed module name.
+ */
+ function ensurePathIsNonModuleName(path) {
+ return getRootLength(path) === 0 && !pathIsRelative(path) ? "./" + path : path;
}
- ts.getRelativePath = getRelativePath;
- function ensurePathIsRelative(path) {
- return !pathIsRelative(path) ? "./" + path : path;
- }
- ts.ensurePathIsRelative = ensurePathIsRelative;
- function getBaseFileName(path) {
- if (path === undefined) {
- return undefined;
- }
- var i = path.lastIndexOf(ts.directorySeparator);
- return i < 0 ? path : path.substring(i + 1);
+ ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
+ function getBaseFileName(path, extensions, ignoreCase) {
+ path = normalizeSlashes(path);
+ // if the path provided is itself the root, then it has not file name.
+ var rootLength = getRootLength(path);
+ if (rootLength === path.length)
+ return "";
+ // return the trailing portion of the path starting after the last (non-terminal) directory
+ // separator but not including any trailing directory separator.
+ path = removeTrailingDirectorySeparator(path);
+ var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
+ var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
+ return extension ? name.slice(0, name.length - extension.length) : name;
}
ts.getBaseFileName = getBaseFileName;
- function combinePaths(path1, path2) {
- if (!(path1 && path1.length))
- return path2;
- if (!(path2 && path2.length))
- return path1;
- if (getRootLength(path2) !== 0)
- return path2;
- if (path1.charAt(path1.length - 1) === ts.directorySeparator)
- return path1 + path2;
- return path1 + ts.directorySeparator + path2;
+ /**
+ * Combines paths. If a path is absolute, it replaces any previous path.
+ */
+ function combinePaths(path) {
+ var paths = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ paths[_i - 1] = arguments[_i];
+ }
+ if (path)
+ path = normalizeSlashes(path);
+ for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
+ var relativePath = paths_1[_a];
+ if (!relativePath)
+ continue;
+ relativePath = normalizeSlashes(relativePath);
+ if (!path || getRootLength(relativePath) !== 0) {
+ path = relativePath;
+ }
+ else {
+ path = ensureTrailingDirectorySeparator(path) + relativePath;
+ }
+ }
+ return path;
}
ts.combinePaths = combinePaths;
+ /**
+ * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
+ * `.` and `..` path components are resolved.
+ */
+ function resolvePath(path) {
+ var paths = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ paths[_i - 1] = arguments[_i];
+ }
+ var combined = some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : normalizeSlashes(path);
+ var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(combined)));
+ return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized;
+ }
+ ts.resolvePath = resolvePath;
+ /**
+ * Determines whether a path has a trailing separator (`/` or `\\`).
+ */
+ function hasTrailingDirectorySeparator(path) {
+ if (path.length === 0)
+ return false;
+ var ch = path.charCodeAt(path.length - 1);
+ return ch === 47 /* slash */ || ch === 92 /* backslash */;
+ }
+ ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
function removeTrailingDirectorySeparator(path) {
- if (path.charAt(path.length - 1) === ts.directorySeparator) {
+ if (hasTrailingDirectorySeparator(path)) {
return path.substr(0, path.length - 1);
}
return path;
}
ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
function ensureTrailingDirectorySeparator(path) {
- if (path.charAt(path.length - 1) !== ts.directorySeparator) {
+ if (!hasTrailingDirectorySeparator(path)) {
return path + ts.directorySeparator;
}
return path;
}
ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
- function comparePaths(a, b, currentDirectory, ignoreCase) {
+ function comparePathsWorker(a, b, componentComparer) {
if (a === b)
return 0 /* EqualTo */;
if (a === undefined)
return -1 /* LessThan */;
if (b === undefined)
return 1 /* GreaterThan */;
- a = removeTrailingDirectorySeparator(a);
- b = removeTrailingDirectorySeparator(b);
- var aComponents = getNormalizedPathComponents(a, currentDirectory);
- var bComponents = getNormalizedPathComponents(b, currentDirectory);
+ var aComponents = reducePathComponents(getPathComponents(a));
+ var bComponents = reducePathComponents(getPathComponents(b));
var sharedLength = Math.min(aComponents.length, bComponents.length);
- var comparer = getStringComparer(ignoreCase);
for (var i = 0; i < sharedLength; i++) {
- var result = comparer(aComponents[i], bComponents[i]);
+ var stringComparer = i === 0 ? compareStringsCaseInsensitive : componentComparer;
+ var result = stringComparer(aComponents[i], bComponents[i]);
if (result !== 0 /* EqualTo */) {
return result;
}
}
return compareValues(aComponents.length, bComponents.length);
}
+ /**
+ * Performs a case-sensitive comparison of two paths.
+ */
+ function comparePathsCaseSensitive(a, b) {
+ return comparePathsWorker(a, b, compareStringsCaseSensitive);
+ }
+ ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
+ /**
+ * Performs a case-insensitive comparison of two paths.
+ */
+ function comparePathsCaseInsensitive(a, b) {
+ return comparePathsWorker(a, b, compareStringsCaseInsensitive);
+ }
+ ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
+ function comparePaths(a, b, currentDirectory, ignoreCase) {
+ if (typeof currentDirectory === "string") {
+ a = combinePaths(currentDirectory, a);
+ b = combinePaths(currentDirectory, b);
+ }
+ else if (typeof currentDirectory === "boolean") {
+ ignoreCase = currentDirectory;
+ }
+ return comparePathsWorker(a, b, getStringComparer(ignoreCase));
+ }
ts.comparePaths = comparePaths;
function containsPath(parent, child, currentDirectory, ignoreCase) {
+ if (typeof currentDirectory === "string") {
+ parent = combinePaths(currentDirectory, parent);
+ child = combinePaths(currentDirectory, child);
+ }
+ else if (typeof currentDirectory === "boolean") {
+ ignoreCase = currentDirectory;
+ }
if (parent === undefined || child === undefined)
return false;
if (parent === child)
return true;
- parent = removeTrailingDirectorySeparator(parent);
- child = removeTrailingDirectorySeparator(child);
- if (parent === child)
- return true;
- var parentComponents = getNormalizedPathComponents(parent, currentDirectory);
- var childComponents = getNormalizedPathComponents(child, currentDirectory);
+ var parentComponents = reducePathComponents(getPathComponents(parent));
+ var childComponents = reducePathComponents(getPathComponents(child));
if (childComponents.length < parentComponents.length) {
return false;
}
- var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive;
+ var componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive;
for (var i = 0; i < parentComponents.length; i++) {
+ var equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer;
if (!equalityComparer(parentComponents[i], childComponents[i])) {
return false;
}
@@ -4050,13 +4232,17 @@ var ts;
ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions);
function getSupportedExtensions(options, extraFileExtensions) {
- var needAllExtensions = options && options.allowJs;
- if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) {
- return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
+ var needJsExtensions = options && options.allowJs;
+ if (!extraFileExtensions || extraFileExtensions.length === 0) {
+ return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
}
- return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive);
+ var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; }));
+ return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive);
}
ts.getSupportedExtensions = getSupportedExtensions;
+ function isJavaScriptLike(scriptKind) {
+ return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
+ }
function hasJavaScriptFileExtension(fileName) {
return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
}
@@ -4128,7 +4314,7 @@ var ts;
}
}
ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
- var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */];
+ var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
function removeFileExtension(path) {
for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
var ext = extensionsToRemove_1[_i];
@@ -4149,9 +4335,14 @@ var ts;
}
ts.removeExtension = removeExtension;
function changeExtension(path, newExtension) {
- return (removeFileExtension(path) + newExtension);
+ return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
}
ts.changeExtension = changeExtension;
+ function changeAnyExtension(path, ext, extensions, ignoreCase) {
+ var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
+ return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path;
+ }
+ ts.changeAnyExtension = changeAnyExtension;
/**
* Takes a string like "jquery-min.4.2.3" and returns "jquery"
*/
@@ -4437,6 +4628,10 @@ var ts;
return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
}
ts.extensionIsTypeScript = extensionIsTypeScript;
+ function resolutionExtensionIsTypeScriptOrJson(ext) {
+ return extensionIsTypeScript(ext) || ext === ".json" /* Json */;
+ }
+ ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson;
/**
* Gets the extension from a path.
* Path must have a valid extension.
@@ -4457,14 +4652,34 @@ var ts;
return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); });
}
ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
- // Retrieves any string from the final "." onwards from a base file name.
- // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
- function getAnyExtensionFromPath(path) {
+ function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
+ if (typeof extensions === "string")
+ extensions = [extensions];
+ for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
+ var extension = extensions_2[_i];
+ if (!startsWith(extension, "."))
+ extension = "." + extension;
+ if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") {
+ var pathExtension = path.slice(path.length - extension.length);
+ if (stringEqualityComparer(pathExtension, extension)) {
+ return pathExtension;
+ }
+ }
+ }
+ return "";
+ }
+ function getAnyExtensionFromPath(path, extensions, ignoreCase) {
+ // Retrieves any string from the final "." onwards from a base file name.
+ // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
+ if (extensions) {
+ return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive);
+ }
var baseFileName = getBaseFileName(path);
var extensionIndex = baseFileName.lastIndexOf(".");
if (extensionIndex >= 0) {
return baseFileName.substring(extensionIndex);
}
+ return "";
}
ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
@@ -4566,12 +4781,12 @@ var ts;
/* @internal */
ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
function createPollingIntervalBasedLevels(levels) {
+ var _a;
return _a = {},
_a[PollingInterval.Low] = levels.Low,
_a[PollingInterval.Medium] = levels.Medium,
_a[PollingInterval.High] = levels.High,
_a;
- var _a;
}
var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
@@ -5685,7 +5900,7 @@ var ts;
Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."),
Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."),
Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."),
- Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."),
+ Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."),
Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."),
Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."),
Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"),
@@ -6162,6 +6377,7 @@ var ts;
Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."),
Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."),
Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."),
+ Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."),
Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."),
Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."),
Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
@@ -6345,6 +6561,17 @@ var ts;
Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."),
Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."),
_0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true),
+ Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
+ All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
+ Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
+ Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
+ Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"),
+ Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."),
+ Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."),
+ Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."),
+ File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."),
+ Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"),
+ Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"),
Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."),
Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."),
Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."),
@@ -6443,6 +6670,7 @@ var ts;
Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
+ Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"),
Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""),
@@ -6506,6 +6734,7 @@ var ts;
Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
+ Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
};
})(ts || (ts = {}));
var ts;
@@ -8666,7 +8895,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 === 294 /* SyntaxList */ && node._children.length > 0) {
+ if (node.kind === 296 /* SyntaxList */ && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -8868,12 +9097,12 @@ var ts;
case 159 /* IndexSignature */:
case 162 /* FunctionType */:
case 163 /* ConstructorType */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
case 234 /* ClassDeclaration */:
case 204 /* ClassExpression */:
case 235 /* InterfaceDeclaration */:
case 236 /* TypeAliasDeclaration */:
- case 291 /* JSDocTemplateTag */:
+ case 293 /* JSDocTemplateTag */:
case 233 /* FunctionDeclaration */:
case 153 /* MethodDeclaration */:
case 154 /* Constructor */:
@@ -8903,6 +9132,12 @@ var ts;
case 243 /* ImportDeclaration */:
case 242 /* ImportEqualsDeclaration */:
case 213 /* VariableStatement */:
+ case 234 /* ClassDeclaration */:
+ case 233 /* FunctionDeclaration */:
+ case 238 /* ModuleDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 237 /* EnumDeclaration */:
return true;
default:
return false;
@@ -9040,6 +9275,8 @@ var ts;
case 155 /* GetAccessor */:
case 156 /* SetAccessor */:
case 236 /* TypeAliasDeclaration */:
+ case 151 /* PropertyDeclaration */:
+ case 150 /* PropertySignature */:
errorNode = node.name;
break;
case 192 /* ArrowFunction */:
@@ -9070,6 +9307,10 @@ var ts;
return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
}
ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
+ function isJsonSourceFile(file) {
+ return file.scriptKind === 6 /* JSON */;
+ }
+ ts.isJsonSourceFile = isJsonSourceFile;
function isConstEnumDeclaration(node) {
return node.kind === 237 /* EnumDeclaration */ && isConst(node);
}
@@ -9409,6 +9650,23 @@ var ts;
});
}
ts.getPropertyAssignment = getPropertyAssignment;
+ function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
+ if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
+ var expression = tsConfigSourceFile.statements[0].expression;
+ return ts.isObjectLiteralExpression(expression) && expression;
+ }
+ }
+ ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
+ function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
+ var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
+ return jsonObjectLiteral &&
+ ts.firstDefined(getPropertyAssignment(jsonObjectLiteral, propKey), function (property) {
+ return ts.isArrayLiteralExpression(property.initializer) ?
+ ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
+ undefined;
+ });
+ }
+ ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
function getContainingFunction(node) {
return ts.findAncestor(node.parent, ts.isFunctionLike);
}
@@ -9786,6 +10044,10 @@ var ts;
return node && !!(node.flags & 65536 /* JavaScriptFile */);
}
ts.isInJavaScriptFile = isInJavaScriptFile;
+ function isInJsonFile(node) {
+ return node && !!(node.flags & 16777216 /* JsonFile */);
+ }
+ ts.isInJsonFile = isInJsonFile;
function isInJSDoc(node) {
return node && !!(node.flags & 2097152 /* JSDoc */);
}
@@ -10073,7 +10335,7 @@ var ts;
}
ts.hasQuestionToken = hasQuestionToken;
function isJSDocConstructSignature(node) {
- return node.kind === 281 /* JSDocFunctionType */ &&
+ return node.kind === 283 /* JSDocFunctionType */ &&
node.parameters.length > 0 &&
node.parameters[0].name &&
node.parameters[0].name.escapedText === "new";
@@ -10187,8 +10449,8 @@ var ts;
}
ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
function getJSDocHost(node) {
- while (node.parent.kind === 284 /* JSDocTypeLiteral */) {
- if (node.parent.parent.kind === 292 /* JSDocTypedefTag */) {
+ while (node.parent.kind === 286 /* JSDocTypeLiteral */) {
+ if (node.parent.parent.kind === 294 /* JSDocTypedefTag */) {
node = node.parent.parent;
}
else {
@@ -10196,7 +10458,7 @@ var ts;
node = node.parent.parent.parent;
}
}
- ts.Debug.assert(node.parent.kind === 283 /* JSDocComment */);
+ ts.Debug.assert(node.parent.kind === 285 /* JSDocComment */);
return node.parent.parent;
}
ts.getJSDocHost = getJSDocHost;
@@ -10212,7 +10474,7 @@ var ts;
}
ts.hasRestParameter = hasRestParameter;
function isRestParameter(node) {
- return node.dotDotDotToken !== undefined || node.type && node.type.kind === 282 /* JSDocVariadicType */;
+ return node.dotDotDotToken !== undefined || node.type && node.type.kind === 284 /* JSDocVariadicType */;
}
ts.isRestParameter = isRestParameter;
var AssignmentKind;
@@ -10354,8 +10616,14 @@ var ts;
if (ts.isDeclaration(name.parent)) {
return name.parent.name === name;
}
- var binExp = name.parent.parent;
- return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name;
+ else if (ts.isQualifiedName(name.parent)) {
+ var tag = name.parent.parent;
+ return ts.isJSDocParameterTag(tag) && tag.name === name.parent;
+ }
+ else {
+ var binExp = name.parent.parent;
+ return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name;
+ }
default:
return false;
}
@@ -10735,7 +11003,7 @@ var ts;
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 297 /* CommaListExpression */:
+ case 299 /* CommaListExpression */:
return 0;
case 203 /* SpreadElement */:
return 1;
@@ -12664,8 +12932,8 @@ var ts;
break;
case 71 /* Identifier */:
return declaration;
- case 293 /* JSDocPropertyTag */:
- case 288 /* JSDocParameterTag */: {
+ case 295 /* JSDocPropertyTag */:
+ case 290 /* JSDocParameterTag */: {
var name = declaration.name;
if (name.kind === 145 /* QualifiedName */) {
return name.right;
@@ -12684,7 +12952,7 @@ var ts;
return undefined;
}
}
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return getNameOfJSDocTypedef(declaration);
case 248 /* ExportAssignment */: {
var expression = declaration.expression;
@@ -12935,6 +13203,11 @@ var ts;
return node.kind === 159 /* IndexSignature */;
}
ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
+ /* @internal */
+ function isGetOrSetAccessorDeclaration(node) {
+ return node.kind === 156 /* SetAccessor */ || node.kind === 155 /* GetAccessor */;
+ }
+ ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
// Type
function isTypePredicateNode(node) {
return node.kind === 160 /* TypePredicate */;
@@ -13063,7 +13336,7 @@ var ts;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 296 /* PartiallyEmittedExpression */) {
+ while (node.kind === 298 /* PartiallyEmittedExpression */) {
node = node.expression;
}
return node;
@@ -13419,79 +13692,79 @@ var ts;
ts.isBundle = isBundle;
// JSDoc
function isJSDocTypeExpression(node) {
- return node.kind === 275 /* JSDocTypeExpression */;
+ return node.kind === 277 /* JSDocTypeExpression */;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 276 /* JSDocAllType */;
+ return node.kind === 278 /* JSDocAllType */;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 277 /* JSDocUnknownType */;
+ return node.kind === 279 /* JSDocUnknownType */;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 278 /* JSDocNullableType */;
+ return node.kind === 280 /* JSDocNullableType */;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 279 /* JSDocNonNullableType */;
+ return node.kind === 281 /* JSDocNonNullableType */;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 280 /* JSDocOptionalType */;
+ return node.kind === 282 /* JSDocOptionalType */;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 281 /* JSDocFunctionType */;
+ return node.kind === 283 /* JSDocFunctionType */;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 282 /* JSDocVariadicType */;
+ return node.kind === 284 /* JSDocVariadicType */;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 283 /* JSDocComment */;
+ return node.kind === 285 /* JSDocComment */;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 286 /* JSDocAugmentsTag */;
+ return node.kind === 288 /* JSDocAugmentsTag */;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 287 /* JSDocClassTag */;
+ return node.kind === 289 /* JSDocClassTag */;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocParameterTag(node) {
- return node.kind === 288 /* JSDocParameterTag */;
+ return node.kind === 290 /* JSDocParameterTag */;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 289 /* JSDocReturnTag */;
+ return node.kind === 291 /* JSDocReturnTag */;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 290 /* JSDocTypeTag */;
+ return node.kind === 292 /* JSDocTypeTag */;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 291 /* JSDocTemplateTag */;
+ return node.kind === 293 /* JSDocTemplateTag */;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 292 /* JSDocTypedefTag */;
+ return node.kind === 294 /* JSDocTypedefTag */;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 293 /* JSDocPropertyTag */;
+ return node.kind === 295 /* JSDocPropertyTag */;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 293 /* JSDocPropertyTag */ || node.kind === 288 /* JSDocParameterTag */;
+ return node.kind === 295 /* JSDocPropertyTag */ || node.kind === 290 /* JSDocParameterTag */;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 284 /* JSDocTypeLiteral */;
+ return node.kind === 286 /* JSDocTypeLiteral */;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
})(ts || (ts = {}));
@@ -13502,7 +13775,7 @@ var ts;
(function (ts) {
/* @internal */
function isSyntaxList(n) {
- return n.kind === 294 /* SyntaxList */;
+ return n.kind === 296 /* SyntaxList */;
}
ts.isSyntaxList = isSyntaxList;
/* @internal */
@@ -13650,7 +13923,7 @@ var ts;
case 158 /* ConstructSignature */:
case 159 /* IndexSignature */:
case 162 /* FunctionType */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
case 163 /* ConstructorType */:
return true;
default:
@@ -13734,13 +14007,13 @@ var ts;
|| kind === 95 /* NullKeyword */
|| kind === 131 /* NeverKeyword */
|| kind === 206 /* ExpressionWithTypeArguments */
- || kind === 276 /* JSDocAllType */
- || kind === 277 /* JSDocUnknownType */
- || kind === 278 /* JSDocNullableType */
- || kind === 279 /* JSDocNonNullableType */
- || kind === 280 /* JSDocOptionalType */
- || kind === 281 /* JSDocFunctionType */
- || kind === 282 /* JSDocVariadicType */;
+ || kind === 278 /* JSDocAllType */
+ || kind === 279 /* JSDocUnknownType */
+ || kind === 280 /* JSDocNullableType */
+ || kind === 281 /* JSDocNonNullableType */
+ || kind === 282 /* JSDocOptionalType */
+ || kind === 283 /* JSDocFunctionType */
+ || kind === 284 /* JSDocVariadicType */;
}
/**
* Node test that determines whether a node is a valid type node.
@@ -13962,8 +14235,8 @@ var ts;
case 203 /* SpreadElement */:
case 207 /* AsExpression */:
case 205 /* OmittedExpression */:
- case 297 /* CommaListExpression */:
- case 296 /* PartiallyEmittedExpression */:
+ case 299 /* CommaListExpression */:
+ case 298 /* PartiallyEmittedExpression */:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -13977,12 +14250,12 @@ var ts;
ts.isAssertionExpression = isAssertionExpression;
/* @internal */
function isPartiallyEmittedExpression(node) {
- return node.kind === 296 /* PartiallyEmittedExpression */;
+ return node.kind === 298 /* PartiallyEmittedExpression */;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
/* @internal */
function isNotEmittedStatement(node) {
- return node.kind === 295 /* NotEmittedStatement */;
+ return node.kind === 297 /* NotEmittedStatement */;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
/* @internal */
@@ -14093,7 +14366,8 @@ var ts;
|| kind === 236 /* TypeAliasDeclaration */
|| kind === 147 /* TypeParameter */
|| kind === 231 /* VariableDeclaration */
- || kind === 292 /* JSDocTypedefTag */;
+ || kind === 294 /* JSDocTypedefTag */
+ || kind === 295 /* JSDocPropertyTag */;
}
function isDeclarationStatementKind(kind) {
return kind === 233 /* FunctionDeclaration */
@@ -14128,14 +14402,14 @@ var ts;
|| kind === 213 /* VariableStatement */
|| kind === 218 /* WhileStatement */
|| kind === 225 /* WithStatement */
- || kind === 295 /* NotEmittedStatement */
- || kind === 299 /* EndOfDeclarationMarker */
- || kind === 298 /* MergeDeclarationMarker */;
+ || kind === 297 /* NotEmittedStatement */
+ || kind === 301 /* EndOfDeclarationMarker */
+ || kind === 300 /* MergeDeclarationMarker */;
}
/* @internal */
function isDeclaration(node) {
if (node.kind === 147 /* TypeParameter */) {
- return node.parent.kind !== 291 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node);
+ return node.parent.kind !== 293 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -14230,18 +14504,18 @@ var ts;
/** True if node is of some JSDoc syntax kind. */
/* @internal */
function isJSDocNode(node) {
- return node.kind >= 275 /* FirstJSDocNode */ && node.kind <= 293 /* LastJSDocNode */;
+ return node.kind >= 277 /* FirstJSDocNode */ && node.kind <= 295 /* LastJSDocNode */;
}
ts.isJSDocNode = isJSDocNode;
/** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node) {
- return node.kind === 283 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node);
+ return node.kind === 285 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node);
}
ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
// TODO: determine what this does before making it public.
/* @internal */
function isJSDocTag(node) {
- return node.kind >= 285 /* FirstJSDocTagNode */ && node.kind <= 293 /* LastJSDocTagNode */;
+ return node.kind >= 287 /* FirstJSDocTagNode */ && node.kind <= 295 /* LastJSDocTagNode */;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -14292,12 +14566,12 @@ var ts;
case 231 /* VariableDeclaration */:
case 233 /* FunctionDeclaration */:
case 236 /* TypeAliasDeclaration */:
- case 275 /* JSDocTypeExpression */:
- case 278 /* JSDocNullableType */:
- case 279 /* JSDocNonNullableType */:
- case 280 /* JSDocOptionalType */:
- case 281 /* JSDocFunctionType */:
- case 282 /* JSDocVariadicType */:
+ case 277 /* JSDocTypeExpression */:
+ case 280 /* JSDocNullableType */:
+ case 281 /* JSDocNonNullableType */:
+ case 282 /* JSDocOptionalType */:
+ case 283 /* JSDocFunctionType */:
+ case 284 /* JSDocVariadicType */:
return true;
}
return false;
@@ -14787,7 +15061,7 @@ var ts;
return visitNode(cbNode, node.expression);
case 252 /* MissingDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 297 /* CommaListExpression */:
+ case 299 /* CommaListExpression */:
return visitNodes(cbNode, cbNodes, node.elements);
case 254 /* JsxElement */:
return visitNode(cbNode, node.openingElement) ||
@@ -14814,23 +15088,23 @@ var ts;
visitNode(cbNode, node.expression);
case 257 /* JsxClosingElement */:
return visitNode(cbNode, node.tagName);
- case 275 /* JSDocTypeExpression */:
+ case 277 /* JSDocTypeExpression */:
return visitNode(cbNode, node.type);
- case 279 /* JSDocNonNullableType */:
+ case 281 /* JSDocNonNullableType */:
return visitNode(cbNode, node.type);
- case 278 /* JSDocNullableType */:
+ case 280 /* JSDocNullableType */:
return visitNode(cbNode, node.type);
- case 280 /* JSDocOptionalType */:
+ case 282 /* JSDocOptionalType */:
return visitNode(cbNode, node.type);
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
return visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 282 /* JSDocVariadicType */:
+ case 284 /* JSDocVariadicType */:
return visitNode(cbNode, node.type);
- case 283 /* JSDocComment */:
+ case 285 /* JSDocComment */:
return visitNodes(cbNode, cbNodes, node.tags);
- case 288 /* JSDocParameterTag */:
- case 293 /* JSDocPropertyTag */:
+ case 290 /* JSDocParameterTag */:
+ case 295 /* JSDocPropertyTag */:
if (node.isNameFirst) {
return visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression);
@@ -14839,17 +15113,17 @@ var ts;
return visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name);
}
- case 289 /* JSDocReturnTag */:
+ case 291 /* JSDocReturnTag */:
return visitNode(cbNode, node.typeExpression);
- case 290 /* JSDocTypeTag */:
+ case 292 /* JSDocTypeTag */:
return visitNode(cbNode, node.typeExpression);
- case 286 /* JSDocAugmentsTag */:
+ case 288 /* JSDocAugmentsTag */:
return visitNode(cbNode, node.class);
- case 291 /* JSDocTemplateTag */:
+ case 293 /* JSDocTemplateTag */:
return visitNodes(cbNode, cbNodes, node.typeParameters);
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
if (node.typeExpression &&
- node.typeExpression.kind === 275 /* JSDocTypeExpression */) {
+ node.typeExpression.kind === 277 /* JSDocTypeExpression */) {
return visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName);
}
@@ -14857,7 +15131,7 @@ var ts;
return visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
}
- case 284 /* JSDocTypeLiteral */:
+ case 286 /* JSDocTypeLiteral */:
if (node.jsDocPropertyTags) {
for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) {
var tag = _a[_i];
@@ -14865,7 +15139,7 @@ var ts;
}
}
return;
- case 296 /* PartiallyEmittedExpression */:
+ case 298 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
}
@@ -14873,7 +15147,13 @@ var ts;
function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
if (setParentNodes === void 0) { setParentNodes = false; }
ts.performance.mark("beforeParse");
- var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
+ var result;
+ if (languageVersion === 100 /* JSON */) {
+ result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes);
+ }
+ else {
+ result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
+ }
ts.performance.mark("afterParse");
ts.performance.measure("Parse", "beforeParse", "afterParse");
return result;
@@ -15033,6 +15313,13 @@ var ts;
var parseErrorBeforeNextFinishedNode = false;
function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
scriptKind = ts.ensureScriptKind(fileName, scriptKind);
+ if (scriptKind === 6 /* JSON */) {
+ var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
+ ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
+ result_1.typeReferenceDirectives = ts.emptyArray;
+ result_1.amdDependencies = ts.emptyArray;
+ return result_1;
+ }
initializeState(sourceText, languageVersion, syntaxCursor, scriptKind);
var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind);
clearState();
@@ -15050,25 +15337,57 @@ var ts;
return isInvalid ? entityName : undefined;
}
Parser.parseIsolatedEntityName = parseIsolatedEntityName;
- function parseJsonText(fileName, sourceText) {
- initializeState(sourceText, 2 /* ES2015 */, /*syntaxCursor*/ undefined, 6 /* JSON */);
+ function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
+ if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; }
+ initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
// Set source file so that errors will be reported with this file name
sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false);
- var result = sourceFile;
// Prime the scanner.
nextToken();
+ var pos = getNodePos();
if (token() === 1 /* EndOfFileToken */) {
+ sourceFile.statements = createNodeArray([], pos, pos);
sourceFile.endOfFileToken = parseTokenNode();
}
- else if (token() === 17 /* OpenBraceToken */ ||
- lookAhead(function () { return token() === 9 /* StringLiteral */; })) {
- result.jsonObject = parseObjectLiteralExpression();
+ else {
+ var statement = createNode(215 /* ExpressionStatement */);
+ switch (token()) {
+ case 21 /* OpenBracketToken */:
+ statement.expression = parseArrayLiteralExpression();
+ break;
+ case 101 /* TrueKeyword */:
+ case 86 /* FalseKeyword */:
+ case 95 /* NullKeyword */:
+ statement.expression = parseTokenNode();
+ break;
+ case 38 /* MinusToken */:
+ if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 56 /* ColonToken */; })) {
+ statement.expression = parsePrefixUnaryExpression();
+ }
+ else {
+ statement.expression = parseObjectLiteralExpression();
+ }
+ break;
+ case 8 /* NumericLiteral */:
+ case 9 /* StringLiteral */:
+ if (lookAhead(function () { return nextToken() !== 56 /* ColonToken */; })) {
+ statement.expression = parseLiteralNode();
+ break;
+ }
+ // falls through
+ default:
+ statement.expression = parseObjectLiteralExpression();
+ break;
+ }
+ finishNode(statement);
+ sourceFile.statements = createNodeArray([statement], pos);
sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
}
- else {
- parseExpected(17 /* OpenBraceToken */);
+ if (setParentNodes) {
+ fixupParentReferences(sourceFile);
}
sourceFile.parseDiagnostics = parseDiagnostics;
+ var result = sourceFile;
clearState();
return result;
}
@@ -15092,9 +15411,11 @@ var ts;
switch (scriptKind) {
case 1 /* JS */:
case 2 /* JSX */:
- case 6 /* JSON */:
contextFlags = 65536 /* JavaScriptFile */;
break;
+ case 6 /* JSON */:
+ contextFlags = 65536 /* JavaScriptFile */ | 16777216 /* JsonFile */;
+ break;
default:
contextFlags = 0 /* None */;
break;
@@ -16340,9 +16661,9 @@ var ts;
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(276 /* JSDocAllType */);
+ var result = createNode(278 /* JSDocAllType */);
if (postFixEquals) {
- return createJSDocPostfixType(280 /* JSDocOptionalType */, result);
+ return createJSDocPostfixType(282 /* JSDocOptionalType */, result);
}
else {
nextToken();
@@ -16350,7 +16671,7 @@ var ts;
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(279 /* JSDocNonNullableType */);
+ var result = createNode(281 /* JSDocNonNullableType */);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -16374,18 +16695,18 @@ var ts;
token() === 29 /* GreaterThanToken */ ||
token() === 58 /* EqualsToken */ ||
token() === 49 /* BarToken */) {
- var result = createNode(277 /* JSDocUnknownType */, pos);
+ var result = createNode(279 /* JSDocUnknownType */, pos);
return finishNode(result);
}
else {
- var result = createNode(278 /* JSDocNullableType */, pos);
+ var result = createNode(280 /* JSDocNullableType */, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(281 /* JSDocFunctionType */);
+ var result = createNodeWithJSDoc(283 /* JSDocFunctionType */);
nextToken();
fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
return finishNode(result);
@@ -16407,12 +16728,12 @@ var ts;
var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */);
var type = parseType();
if (dotdotdot) {
- var variadic = createNode(282 /* JSDocVariadicType */, dotdotdot.pos);
+ var variadic = createNode(284 /* JSDocVariadicType */, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 58 /* EqualsToken */) {
- return createJSDocPostfixType(280 /* JSDocOptionalType */, type);
+ return createJSDocPostfixType(282 /* JSDocOptionalType */, type);
}
return type;
}
@@ -16947,14 +17268,14 @@ var ts;
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 51 /* ExclamationToken */:
- type = createJSDocPostfixType(279 /* JSDocNonNullableType */, type);
+ type = createJSDocPostfixType(281 /* JSDocNonNullableType */, type);
break;
case 55 /* 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 = createJSDocPostfixType(278 /* JSDocNullableType */, type);
+ type = createJSDocPostfixType(280 /* JSDocNullableType */, type);
break;
case 21 /* OpenBracketToken */:
parseExpected(21 /* OpenBracketToken */);
@@ -17518,7 +17839,7 @@ var ts;
// 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
if (token() === 120 /* AsyncKeyword */) {
nextToken();
- // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function
+ // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
// but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) {
return 0 /* False */;
@@ -19905,7 +20226,7 @@ var ts;
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
// Parses out a JSDoc type expression.
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(275 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var result = createNode(277 /* JSDocTypeExpression */, scanner.getTokenPos());
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */);
result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -19925,6 +20246,7 @@ var ts;
}
JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
function parseJSDocComment(parent, start, length) {
+ var _a;
var saveToken = currentToken;
var saveParseDiagnosticsLength = parseDiagnostics.length;
var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
@@ -19942,7 +20264,6 @@ var ts;
parseDiagnostics.length = saveParseDiagnosticsLength;
parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
return comment;
- var _a;
}
JSDocParser.parseJSDocComment = parseJSDocComment;
var JSDocState;
@@ -20076,7 +20397,7 @@ var ts;
}
}
function createJSDocComment() {
- var result = createNode(283 /* JSDocComment */, start);
+ var result = createNode(285 /* JSDocComment */, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
@@ -20201,7 +20522,7 @@ var ts;
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(atToken, tagName) {
- var result = createNode(285 /* JSDocTag */, atToken.pos);
+ var result = createNode(287 /* JSDocTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
return finishNode(result);
@@ -20258,8 +20579,8 @@ var ts;
typeExpression = tryParseTypeExpression();
}
var result = target === 1 /* Parameter */ ?
- createNode(288 /* JSDocParameterTag */, atToken.pos) :
- createNode(293 /* JSDocPropertyTag */, atToken.pos);
+ createNode(290 /* JSDocParameterTag */, atToken.pos) :
+ createNode(295 /* JSDocPropertyTag */, atToken.pos);
var comment;
if (indent !== undefined)
comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos);
@@ -20279,18 +20600,18 @@ var ts;
}
function parseNestedTypeLiteral(typeExpression, name, target) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(275 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(277 /* 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, name); })) {
- if (child.kind === 288 /* JSDocParameterTag */ || child.kind === 293 /* JSDocPropertyTag */) {
+ if (child.kind === 290 /* JSDocParameterTag */ || child.kind === 295 /* JSDocPropertyTag */) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(284 /* JSDocTypeLiteral */, start_2);
+ jsdocTypeLiteral = createNode(286 /* JSDocTypeLiteral */, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 166 /* ArrayType */) {
jsdocTypeLiteral.isArrayType = true;
@@ -20301,27 +20622,27 @@ var ts;
}
}
function parseReturnTag(atToken, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 289 /* JSDocReturnTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 291 /* JSDocReturnTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(289 /* JSDocReturnTag */, atToken.pos);
+ var result = createNode(291 /* JSDocReturnTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(atToken, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 290 /* JSDocTypeTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 292 /* JSDocTypeTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(290 /* JSDocTypeTag */, atToken.pos);
+ var result = createNode(292 /* JSDocTypeTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
return finishNode(result);
}
function parseAugmentsTag(atToken, tagName) {
- var result = createNode(286 /* JSDocAugmentsTag */, atToken.pos);
+ var result = createNode(288 /* JSDocAugmentsTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
@@ -20349,7 +20670,7 @@ var ts;
return node;
}
function parseClassTag(atToken, tagName) {
- var tag = createNode(287 /* JSDocClassTag */, atToken.pos);
+ var tag = createNode(289 /* JSDocClassTag */, atToken.pos);
tag.atToken = atToken;
tag.tagName = tagName;
return finishNode(tag);
@@ -20357,7 +20678,7 @@ var ts;
function parseTypedefTag(atToken, tagName) {
var typeExpression = tryParseTypeExpression();
skipWhitespace();
- var typedefTag = createNode(292 /* JSDocTypedefTag */, atToken.pos);
+ var typedefTag = createNode(294 /* JSDocTypedefTag */, atToken.pos);
typedefTag.atToken = atToken;
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0);
@@ -20382,9 +20703,9 @@ var ts;
var start_3 = scanner.getStartPos();
while (child = tryParse(function () { return parseChildPropertyTag(); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(284 /* JSDocTypeLiteral */, start_3);
+ jsdocTypeLiteral = createNode(286 /* JSDocTypeLiteral */, start_3);
}
- if (child.kind === 290 /* JSDocTypeTag */) {
+ if (child.kind === 292 /* JSDocTypeTag */) {
if (childTypeTag) {
break;
}
@@ -20445,7 +20766,7 @@ var ts;
case 57 /* AtToken */:
if (canParseTag) {
var child = tryParseChildTag(target);
- if (child && child.kind === 288 /* JSDocParameterTag */ &&
+ if (child && child.kind === 290 /* JSDocParameterTag */ &&
(ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
}
@@ -20530,7 +20851,7 @@ var ts;
break;
}
}
- var result = createNode(291 /* JSDocTemplateTag */, atToken.pos);
+ var result = createNode(293 /* JSDocTemplateTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -21523,6 +21844,10 @@ var ts;
return "__index" /* Index */;
case 249 /* ExportDeclaration */:
return "__export" /* ExportStar */;
+ case 273 /* SourceFile */:
+ // json file should behave as
+ // module.exports = ...
+ return "export=" /* ExportEquals */;
case 199 /* BinaryExpression */:
if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) {
// module.exports = ...
@@ -21530,16 +21855,16 @@ var ts;
}
ts.Debug.fail("Unknown binary declaration kind");
break;
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
case 148 /* 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 === 281 /* 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 === 283 /* 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;
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
var name_2 = ts.getNameOfJSDocTypedef(node);
return typeof name_2 !== "undefined" ? name_2.escapedText : undefined;
}
@@ -21679,7 +22004,7 @@ var ts;
// during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
// and this case is specially handled. Module augmentations should only be merged with original module definition
// and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
- if (node.kind === 292 /* JSDocTypedefTag */)
+ if (node.kind === 294 /* JSDocTypedefTag */)
ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypedefTag(node)) {
if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) {
@@ -21928,10 +22253,10 @@ var ts;
case 186 /* CallExpression */:
bindCallExpressionFlow(node);
break;
- case 283 /* JSDocComment */:
+ case 285 /* JSDocComment */:
bindJSDocComment(node);
break;
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
bindJSDocTypedefTag(node);
break;
// In source files and blocks, bind functions first to match hoisting that occurs at runtime
@@ -22550,7 +22875,7 @@ var ts;
}
function bindJSDocComment(node) {
ts.forEachChild(node, function (n) {
- if (n.kind !== 292 /* JSDocTypedefTag */) {
+ if (n.kind !== 294 /* JSDocTypedefTag */) {
bind(n);
}
});
@@ -22596,7 +22921,7 @@ var ts;
case 237 /* EnumDeclaration */:
case 183 /* ObjectLiteralExpression */:
case 165 /* TypeLiteral */:
- case 284 /* JSDocTypeLiteral */:
+ case 286 /* JSDocTypeLiteral */:
case 262 /* JsxAttributes */:
return 1 /* IsContainer */;
case 235 /* InterfaceDeclaration */:
@@ -22618,7 +22943,7 @@ var ts;
case 155 /* GetAccessor */:
case 156 /* SetAccessor */:
case 157 /* CallSignature */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
case 162 /* FunctionType */:
case 158 /* ConstructSignature */:
case 159 /* IndexSignature */:
@@ -22680,7 +23005,7 @@ var ts;
case 237 /* EnumDeclaration */:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
case 165 /* TypeLiteral */:
- case 284 /* JSDocTypeLiteral */:
+ case 286 /* JSDocTypeLiteral */:
case 183 /* ObjectLiteralExpression */:
case 235 /* InterfaceDeclaration */:
case 262 /* JsxAttributes */:
@@ -22703,7 +23028,7 @@ var ts;
case 233 /* FunctionDeclaration */:
case 191 /* FunctionExpression */:
case 192 /* ArrowFunction */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
case 236 /* TypeAliasDeclaration */:
case 176 /* MappedType */:
// All the children of these container types are never visible through another
@@ -23091,7 +23416,7 @@ var ts;
}
for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) {
var tag = _c[_b];
- if (tag.kind === 292 /* JSDocTypedefTag */) {
+ if (tag.kind === 294 /* JSDocTypedefTag */) {
var savedParent = parent;
parent = jsDoc;
bind(tag);
@@ -23130,7 +23455,7 @@ var ts;
// current "blockScopeContainer" needs to be set to its immediate namespace parent.
if (node.isInJSDocNamespace) {
var parentNode = node.parent;
- while (parentNode && parentNode.kind !== 292 /* JSDocTypedefTag */) {
+ while (parentNode && parentNode.kind !== 294 /* JSDocTypedefTag */) {
parentNode = parentNode.parent;
}
bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */);
@@ -23232,11 +23557,11 @@ var ts;
case 156 /* SetAccessor */:
return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */);
case 162 /* FunctionType */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
case 163 /* ConstructorType */:
return bindFunctionOrConstructorType(node);
case 165 /* TypeLiteral */:
- case 284 /* JSDocTypeLiteral */:
+ case 286 /* JSDocTypeLiteral */:
case 176 /* MappedType */:
return bindAnonymousTypeWorker(node);
case 183 /* ObjectLiteralExpression */:
@@ -23292,18 +23617,18 @@ var ts;
// falls through
case 239 /* ModuleBlock */:
return updateStrictModeStatementList(node.statements);
- case 288 /* JSDocParameterTag */:
- if (node.parent.kind !== 284 /* JSDocTypeLiteral */) {
+ case 290 /* JSDocParameterTag */:
+ if (node.parent.kind !== 286 /* JSDocTypeLiteral */) {
break;
}
// falls through
- case 293 /* JSDocPropertyTag */:
+ case 295 /* JSDocPropertyTag */:
var propTag = node;
- var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 280 /* JSDocOptionalType */ ?
+ var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 282 /* JSDocOptionalType */ ?
4 /* Property */ | 16777216 /* Optional */ :
4 /* Property */;
return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
- case 292 /* JSDocTypedefTag */: {
+ case 294 /* JSDocTypedefTag */: {
var fullName = node.fullName;
if (!fullName || fullName.kind === 71 /* Identifier */) {
(delayedTypedefs || (delayedTypedefs = [])).push({ typedef: node, container: container, lastContainer: lastContainer, blockScopeContainer: blockScopeContainer, parent: parent });
@@ -23323,6 +23648,13 @@ var ts;
if (ts.isExternalModule(file)) {
bindSourceFileAsExternalModule();
}
+ else if (ts.isJsonSourceFile(file)) {
+ bindSourceFileAsExternalModule();
+ // Create symbol equivalent for the module.exports = {}
+ var originalSymbol = file.symbol;
+ declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
+ file.symbol = originalSymbol;
+ }
}
function bindSourceFileAsExternalModule() {
bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
@@ -23999,7 +24331,7 @@ var ts;
else {
// A ClassDeclaration is ES6 syntax.
transformFlags = subtreeFlags | 192 /* AssertES2015 */;
- // A class with a parameter property assignment, property initializer, or decorator is
+ // A class with a parameter property assignment, property initializer, computed property name, or decorator is
// TypeScript syntax.
// An exported declaration may be TypeScript syntax, but is handled by the visitor
// for a namespace declaration.
@@ -24136,9 +24468,9 @@ var ts;
function computePropertyDeclaration(node, subtreeFlags) {
// A PropertyDeclaration is TypeScript syntax.
var transformFlags = subtreeFlags | 3 /* AssertTypeScript */;
- // If the PropertyDeclaration has an initializer, we need to inform its ancestor
+ // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor
// so that it handle the transformation.
- if (node.initializer) {
+ if (node.initializer || ts.isComputedPropertyName(node.name)) {
transformFlags |= 8192 /* ContainsPropertyInitializer */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
@@ -24362,7 +24694,7 @@ var ts;
break;
case 189 /* TypeAssertionExpression */:
case 207 /* AsExpression */:
- case 296 /* PartiallyEmittedExpression */:
+ case 298 /* PartiallyEmittedExpression */:
// These nodes are TypeScript syntax.
transformFlags |= 3 /* AssertTypeScript */;
excludeFlags = 536872257 /* OuterExpressionExcludes */;
@@ -24634,7 +24966,7 @@ var ts;
return 940049729 /* BindingPatternExcludes */;
case 189 /* TypeAssertionExpression */:
case 207 /* AsExpression */:
- case 296 /* PartiallyEmittedExpression */:
+ case 298 /* PartiallyEmittedExpression */:
case 190 /* ParenthesizedExpression */:
case 97 /* SuperKeyword */:
return 536872257 /* OuterExpressionExcludes */;
@@ -24850,7 +25182,8 @@ var ts;
(function (Extensions) {
Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
- Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; /** Only '.d.ts' */
+ Extensions[Extensions["Json"] = 2] = "Json";
+ Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; /** Only '.d.ts' */
})(Extensions || (Extensions = {}));
/** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
function resolvedTypeScriptOnly(resolved) {
@@ -24894,7 +25227,13 @@ var ts;
function readJson(path, host) {
try {
var jsonText = host.readFile(path);
- return jsonText ? JSON.parse(jsonText) : {};
+ if (!jsonText)
+ return {};
+ var result = ts.parseConfigFileTextToJson(path, jsonText);
+ if (result.error) {
+ return {};
+ }
+ return result.config;
}
catch (e) {
// gracefully handle if readFile fails or returns not JSON
@@ -25425,7 +25764,11 @@ var ts;
var traceEnabled = isTraceEnabled(compilerOptions, host);
var failedLookupLocations = [];
var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled };
- var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript));
+ var result = jsOnly ?
+ tryResolve(Extensions.JavaScript) :
+ (tryResolve(Extensions.TypeScript) ||
+ tryResolve(Extensions.JavaScript) ||
+ (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined));
if (result && result.value) {
var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport;
return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations);
@@ -25480,7 +25823,7 @@ var ts;
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
}
- if (!ts.pathEndsWithDirectorySeparator(candidate)) {
+ if (!ts.hasTrailingDirectorySeparator(candidate)) {
if (!onlyRecordFailures) {
var parentOfCandidate = ts.getDirectoryPath(candidate);
if (!directoryProbablyExists(parentOfCandidate, state.host)) {
@@ -25565,6 +25908,10 @@ var ts;
* in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
*/
function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) {
+ if (extensions === Extensions.Json) {
+ var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
+ return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state);
+ }
// First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state);
if (resolvedByAddingExtension) {
@@ -25585,9 +25932,9 @@ var ts;
function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) {
if (!onlyRecordFailures) {
// check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
- var directory = ts.getDirectoryPath(candidate);
- if (directory) {
- onlyRecordFailures = !directoryProbablyExists(directory, state.host);
+ var directory_1 = ts.getDirectoryPath(candidate);
+ if (directory_1) {
+ onlyRecordFailures = !directoryProbablyExists(directory_1, state.host);
}
}
switch (extensions) {
@@ -25597,6 +25944,8 @@ var ts;
return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
case Extensions.JavaScript:
return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
+ case Extensions.Json:
+ return tryExtension(".json" /* Json */);
}
function tryExtension(ext) {
var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state);
@@ -25683,7 +26032,7 @@ var ts;
}
}
function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) {
- var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state);
+ var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state);
if (!file) {
return undefined;
}
@@ -25718,6 +26067,8 @@ var ts;
switch (extensions) {
case Extensions.JavaScript:
return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
+ case Extensions.Json:
+ return extension === ".json" /* Json */;
case Extensions.TypeScript:
return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
case Extensions.DtsOnly:
@@ -25788,7 +26139,7 @@ var ts;
if (packageResult) {
return packageResult;
}
- if (extensions !== Extensions.JavaScript) {
+ if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) {
var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
var nodeModulesAtTypesExists = nodeModulesFolderExists;
if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
@@ -26639,17 +26990,17 @@ var ts;
}
function getJsxNamespace(location) {
if (location) {
- var file = ts.getSourceFileOfNode(location);
- if (file) {
- if (file.localJsxNamespace) {
- return file.localJsxNamespace;
+ var file_1 = ts.getSourceFileOfNode(location);
+ if (file_1) {
+ if (file_1.localJsxNamespace) {
+ return file_1.localJsxNamespace;
}
- var jsxPragma = file.pragmas.get("jsx");
+ var jsxPragma = file_1.pragmas.get("jsx");
if (jsxPragma) {
var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
- file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
- if (file.localJsxFactory) {
- return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText;
+ file_1.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
+ if (file_1.localJsxFactory) {
+ return file_1.localJsxNamespace = getFirstIdentifier(file_1.localJsxFactory).escapedText;
}
}
}
@@ -27070,7 +27421,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 & 67901928 /* Type */ && lastLocation.kind !== 283 /* JSDocComment */) {
+ if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 285 /* JSDocComment */) {
useResult = result.flags & 262144 /* TypeParameter */
// type parameters are visible in parameter list, return type and type parameter list
? lastLocation === location.type ||
@@ -27597,8 +27948,8 @@ var ts;
else {
exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias);
}
- var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
- var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias);
+ var file_2 = ts.find(moduleSymbol.declarations, ts.isSourceFile);
+ var hasSyntheticDefault = canHaveSyntheticDefault(file_2, moduleSymbol, dontResolveAlias);
if (!exportDefaultSymbol && !hasSyntheticDefault) {
error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
}
@@ -27859,40 +28210,40 @@ var ts;
else if (name.kind === 145 /* QualifiedName */ || name.kind === 184 /* PropertyAccessExpression */) {
var left = name.kind === 145 /* QualifiedName */ ? name.left : name.expression;
var right = name.kind === 145 /* QualifiedName */ ? name.right : name.name;
- var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
- if (!namespace || ts.nodeIsMissing(right)) {
+ var namespace_1 = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
+ if (!namespace_1 || ts.nodeIsMissing(right)) {
return undefined;
}
- else if (namespace === unknownSymbol) {
- return namespace;
+ else if (namespace_1 === unknownSymbol) {
+ return namespace_1;
}
if (ts.isInJavaScriptFile(name)) {
- var initializer = ts.getDeclaredJavascriptInitializer(namespace.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace.valueDeclaration);
+ var initializer = ts.getDeclaredJavascriptInitializer(namespace_1.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace_1.valueDeclaration);
if (initializer) {
- namespace = getSymbolOfNode(initializer);
+ namespace_1 = getSymbolOfNode(initializer);
}
// Currently, IIFEs may not have a symbol and we don't know about their contents. Give up in this case.
- if (!namespace) {
+ if (!namespace_1) {
return undefined;
}
- if (namespace.valueDeclaration &&
- ts.isVariableDeclaration(namespace.valueDeclaration) &&
- namespace.valueDeclaration.initializer &&
- isCommonJsRequire(namespace.valueDeclaration.initializer)) {
- var moduleName = namespace.valueDeclaration.initializer.arguments[0];
+ if (namespace_1.valueDeclaration &&
+ ts.isVariableDeclaration(namespace_1.valueDeclaration) &&
+ namespace_1.valueDeclaration.initializer &&
+ isCommonJsRequire(namespace_1.valueDeclaration.initializer)) {
+ var moduleName = namespace_1.valueDeclaration.initializer.arguments[0];
var moduleSym = resolveExternalModuleName(moduleName, moduleName);
if (moduleSym) {
var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
if (resolvedModuleSymbol) {
- namespace = resolvedModuleSymbol;
+ namespace_1 = resolvedModuleSymbol;
}
}
}
}
- symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning);
+ symbol = getSymbol(getExportsOfSymbol(namespace_1), right.escapedText, meaning);
if (!symbol) {
if (!ignoreErrors) {
- error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right));
+ error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace_1), ts.declarationNameToString(right));
}
return undefined;
}
@@ -27970,7 +28321,7 @@ var ts;
}
}
// May be an untyped module. If so, ignore resolutionDiagnostic.
- if (resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) {
+ if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) {
if (isForAugmentation) {
var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
@@ -27982,7 +28333,22 @@ var ts;
return undefined;
}
if (moduleNotFoundError) {
- // report errors only if it was requested
+ // For relative paths, see if this was possibly a projectReference redirect
+ if (ts.pathIsRelative(moduleReference)) {
+ var sourceFile_1 = ts.getSourceFileOfNode(location);
+ var redirects = sourceFile_1.redirectedReferences;
+ if (redirects) {
+ var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName));
+ for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) {
+ var ext = _a[_i];
+ var probePath = normalizedTargetPath + ext;
+ if (redirects.indexOf(probePath) >= 0) {
+ error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath);
+ return undefined;
+ }
+ }
+ }
+ }
if (resolutionDiagnostic) {
error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
}
@@ -28429,7 +28795,7 @@ var ts;
* @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible
*/
function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
- if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) {
+ if (symbol && enclosingDeclaration) {
var initialSymbol = symbol;
var meaningToLook = meaning;
while (symbol) {
@@ -28511,6 +28877,11 @@ var ts;
isDeclarationVisible(declaration.parent.parent.parent)) {
return addVisibleAlias(declaration, declaration.parent.parent);
}
+ else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement
+ && !ts.hasModifier(declaration, 1 /* Export */)
+ && isDeclarationVisible(declaration.parent)) {
+ return addVisibleAlias(declaration, declaration);
+ }
// Declaration is not visible
return false;
}
@@ -28770,7 +29141,15 @@ var ts;
}
if (type.flags & 32768 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
if (type.flags & 32768 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) {
- return ts.createInferTypeNode(ts.createTypeParameterDeclaration(getNameOfSymbolAsWritten(type.symbol)));
+ return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined));
+ }
+ if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
+ type.flags & 32768 /* TypeParameter */ &&
+ ts.length(type.symbol.declarations) &&
+ ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
+ typeParameterShadowsNameInScope(type, context) &&
+ !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
+ return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined);
}
var name = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?");
// Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
@@ -28828,7 +29207,16 @@ var ts;
ts.Debug.assert(!!(type.flags & 65536 /* Object */));
var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined;
var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined;
- var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type));
+ var appropriateConstraintTypeNode;
+ if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
+ // We have a { [P in keyof T]: X }
+ // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType`
+ appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context));
+ }
+ else {
+ appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context);
+ }
+ var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context);
var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode);
return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
@@ -29168,17 +29556,29 @@ var ts;
}
return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments);
}
- function typeParameterToDeclaration(type, context, constraint) {
- if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); }
+ function typeParameterShadowsNameInScope(type, context) {
+ return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false);
+ }
+ function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
var savedContextFlags = context.flags;
context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
- var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true);
- var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
+ var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
+ type.symbol.declarations[0] &&
+ ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
+ typeParameterShadowsNameInScope(type, context);
+ var name = shouldUseGeneratedName
+ ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */)
+ : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true);
var defaultParameter = getDefaultFromTypeParameter(type);
var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
context.flags = savedContextFlags;
return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
}
+ function typeParameterToDeclaration(type, context, constraint) {
+ if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); }
+ var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
+ return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
+ }
function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 148 /* Parameter */);
ts.Debug.assert(!!parameterDeclaration || isTransientSymbol(parameterSymbol) && !!parameterSymbol.isRestParameter);
@@ -29281,6 +29681,15 @@ var ts;
}
return typeParameterNodes;
}
+ /**
+ * Given A[B][C][D], finds A[B]
+ */
+ function getTopmostIndexedAccessType(top) {
+ if (ts.isIndexedAccessTypeNode(top.objectType)) {
+ return getTopmostIndexedAccessType(top.objectType);
+ }
+ return top;
+ }
function symbolToTypeNode(symbol, context, meaning) {
var chain = lookupSymbolChain(symbol, context, meaning);
context.flags |= 16777216 /* InInitialEntityName */;
@@ -29289,13 +29698,24 @@ var ts;
var isTypeOf = meaning === 67216319 /* Value */;
if (ambientModuleSymbolRegex.test(rootName)) {
// module is root, must use `ImportTypeNode`
- var nonRootParts = chain.length > 1 ? createEntityNameFromSymbolChain(chain, chain.length - 1, 1) : undefined;
+ var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
var typeParameterNodes = lookupTypeParameterNodes(chain, 0, context);
- return ts.createImportTypeNode(ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1))), nonRootParts, typeParameterNodes, isTypeOf);
+ var lit = ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1)));
+ if (!nonRootParts || ts.isEntityName(nonRootParts)) {
+ return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf);
+ }
+ else {
+ var splitNode = getTopmostIndexedAccessType(nonRootParts);
+ var qualifier = splitNode.objectType.typeName;
+ return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
+ }
+ }
+ var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
+ if (ts.isIndexedAccessTypeNode(entityName)) {
+ return entityName; // Indexed accesses can never be `typeof`
}
- var entityName = createEntityNameFromSymbolChain(chain, chain.length - 1, 0);
return isTypeOf ? ts.createTypeQueryNode(entityName) : ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined);
- function createEntityNameFromSymbolChain(chain, index, stopper) {
+ function createAccessFromSymbolChain(chain, index, stopper) {
var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
var symbol = chain[index];
if (index === 0) {
@@ -29305,9 +29725,27 @@ var ts;
if (index === 0) {
context.flags ^= 16777216 /* InInitialEntityName */;
}
+ var parent = chain[index - 1];
+ if (parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) {
+ // Should use an indexed access
+ var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
+ if (ts.isIndexedAccessTypeNode(LHS)) {
+ return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
+ }
+ else {
+ return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
+ }
+ }
var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
identifier.symbol = symbol;
- return index > stopper ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1, stopper), identifier) : identifier;
+ if (index > stopper) {
+ var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
+ if (!ts.isEntityName(LHS)) {
+ return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
+ }
+ return ts.createQualifiedName(LHS, identifier);
+ }
+ return identifier;
}
}
function symbolToName(symbol, context, meaning, expectsIdentifier) {
@@ -30219,6 +30657,10 @@ var ts;
return links.type = anyType;
}
// Handle export default expressions
+ if (ts.isSourceFile(declaration)) {
+ var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile);
+ return links.type = jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType;
+ }
if (declaration.kind === 248 /* ExportAssignment */) {
return links.type = checkExpression(declaration.expression);
}
@@ -30510,13 +30952,13 @@ var ts;
case 152 /* MethodSignature */:
case 162 /* FunctionType */:
case 163 /* ConstructorType */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
case 233 /* FunctionDeclaration */:
case 153 /* MethodDeclaration */:
case 191 /* FunctionExpression */:
case 192 /* ArrowFunction */:
case 236 /* TypeAliasDeclaration */:
- case 291 /* JSDocTemplateTag */:
+ case 293 /* JSDocTemplateTag */:
case 176 /* MappedType */:
case 170 /* ConditionalType */:
var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
@@ -30828,9 +31270,9 @@ var ts;
return unknownType;
}
var declaration = ts.find(symbol.declarations, function (d) {
- return d.kind === 292 /* JSDocTypedefTag */ || d.kind === 236 /* TypeAliasDeclaration */;
+ return d.kind === 294 /* JSDocTypedefTag */ || d.kind === 236 /* TypeAliasDeclaration */;
});
- var typeNode = declaration.kind === 292 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type;
+ var typeNode = declaration.kind === 294 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type;
// If typeNode is missing, we will error in checkJSDocTypedefTag.
var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType;
if (popTypeResolution()) {
@@ -31084,6 +31526,9 @@ var ts;
var symbol = type.symbol;
var members = getMembersOfSymbol(symbol);
type.declaredProperties = getNamedMembers(members);
+ // Start with signatures at empty array in case of recursive types
+ type.declaredCallSignatures = ts.emptyArray;
+ type.declaredConstructSignatures = ts.emptyArray;
type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
@@ -31644,10 +32089,8 @@ var ts;
var templateType = getTemplateTypeFromMappedType(type.target || type);
var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
var templateModifiers = getMappedTypeModifiers(type);
- var constraintDeclaration = type.declaration.typeParameter.constraint;
var include = keyofStringsOnly ? 32 /* StringLiteral */ : 1120 /* StringOrNumberLiteralOrUnique */;
- if (constraintDeclaration.kind === 174 /* TypeOperator */ &&
- constraintDeclaration.operator === 128 /* KeyOfKeyword */) {
+ if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
// We have a { [P in keyof T]: X }
for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) {
var prop = _a[_i];
@@ -31720,15 +32163,21 @@ var ts;
instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper || identityMapper) :
unknownType);
}
+ function getConstraintDeclarationForMappedType(type) {
+ return type.declaration.typeParameter.constraint;
+ }
+ function isMappedTypeWithKeyofConstraintDeclaration(type) {
+ var constraintDeclaration = getConstraintDeclarationForMappedType(type);
+ return constraintDeclaration.kind === 174 /* TypeOperator */ &&
+ constraintDeclaration.operator === 128 /* KeyOfKeyword */;
+ }
function getModifiersTypeFromMappedType(type) {
if (!type.modifiersType) {
- var constraintDeclaration = type.declaration.typeParameter.constraint;
- if (constraintDeclaration.kind === 174 /* TypeOperator */ &&
- constraintDeclaration.operator === 128 /* KeyOfKeyword */) {
+ if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
// If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
// AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
// 'keyof T' to a literal union type and we can't recover T from that type.
- type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper);
+ type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper);
}
else {
// Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
@@ -31889,9 +32338,9 @@ var ts;
// over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
// removes 'undefined' from T.
if (type.root.isDistributive) {
- var constraint = getConstraintOfType(type.checkType);
+ var constraint = getConstraintOfType(getSimplifiedType(type.checkType));
if (constraint) {
- var mapper = createTypeMapper([type.root.checkType], [constraint]);
+ var mapper = makeUnaryTypeMapper(type.root.checkType, constraint);
var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper));
if (!(instantiated.flags & 16384 /* Never */)) {
return instantiated;
@@ -32295,10 +32744,10 @@ var ts;
function isJSDocOptionalParameter(node) {
return ts.isInJavaScriptFile(node) && (
// node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
- node.type && node.type.kind === 280 /* JSDocOptionalType */
+ node.type && node.type.kind === 282 /* JSDocOptionalType */
|| ts.getJSDocParameterTags(node).some(function (_a) {
var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 280 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 282 /* JSDocOptionalType */;
}));
}
function tryFindAmbientModule(moduleName, withAugmentations) {
@@ -32384,7 +32833,7 @@ var ts;
for (var i = numTypeArguments; i < numTypeParameters; i++) {
var mapper = createTypeMapper(typeParameters, typeArguments);
var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
- if (defaultType && isTypeIdenticalTo(defaultType, emptyObjectType) && isJavaScriptImplicitAny) {
+ if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) {
defaultType = anyType;
}
typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny);
@@ -32859,7 +33308,7 @@ var ts;
var isJs = ts.isInJavaScriptFile(node);
var isJsImplicitAny = !noImplicitAny && isJs;
if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
- var missingAugmentsTag = isJs && node.parent.kind !== 286 /* JSDocAugmentsTag */;
+ var missingAugmentsTag = isJs && node.parent.kind !== 288 /* JSDocAugmentsTag */;
var diag = minTypeArgumentCount === typeParameters.length
? missingAugmentsTag
? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag
@@ -33939,14 +34388,14 @@ var ts;
var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 7897088 /* Instantiable */);
var combinedMapper;
if (root.inferTypeParameters) {
- var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
+ var context_1 = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
if (!isDeferred) {
// We don't want inferences from constraints as they may cause us to eagerly resolve the
// conditional type instead of deferring resolution. Also, we always want strict function
// types rules (i.e. proper contravariance) for inferences.
- inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */);
+ inferTypes(context_1.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */);
}
- combinedMapper = combineTypeMappers(mapper, context);
+ combinedMapper = combineTypeMappers(mapper, context_1);
}
if (!isDeferred) {
// Return union of trueType and falseType for 'any' since it matches anything
@@ -34321,8 +34770,8 @@ var ts;
function getTypeFromTypeNode(node) {
switch (node.kind) {
case 119 /* AnyKeyword */:
- case 276 /* JSDocAllType */:
- case 277 /* JSDocUnknownType */:
+ case 278 /* JSDocAllType */:
+ case 279 /* JSDocUnknownType */:
return anyType;
case 137 /* StringKeyword */:
return stringType;
@@ -34363,21 +34812,21 @@ var ts;
return getTypeFromUnionTypeNode(node);
case 169 /* IntersectionType */:
return getTypeFromIntersectionTypeNode(node);
- case 278 /* JSDocNullableType */:
+ case 280 /* JSDocNullableType */:
return getTypeFromJSDocNullableTypeNode(node);
- case 280 /* JSDocOptionalType */:
+ case 282 /* JSDocOptionalType */:
return addOptionality(getTypeFromTypeNode(node.type));
case 172 /* ParenthesizedType */:
- case 279 /* JSDocNonNullableType */:
- case 275 /* JSDocTypeExpression */:
+ case 281 /* JSDocNonNullableType */:
+ case 277 /* JSDocTypeExpression */:
return getTypeFromTypeNode(node.type);
- case 282 /* JSDocVariadicType */:
+ case 284 /* JSDocVariadicType */:
return getTypeFromJSDocVariadicType(node);
case 162 /* FunctionType */:
case 163 /* ConstructorType */:
case 165 /* TypeLiteral */:
- case 284 /* JSDocTypeLiteral */:
- case 281 /* JSDocFunctionType */:
+ case 286 /* JSDocTypeLiteral */:
+ case 283 /* JSDocFunctionType */:
return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
case 174 /* TypeOperator */:
return getTypeFromTypeOperatorNode(node);
@@ -35802,7 +36251,7 @@ var ts;
}
}
var constraint = getConstraintForRelation(source);
- if (!constraint || constraint.flags & 1 /* Any */) {
+ if (!constraint || (source.flags & 32768 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
// A type variable with no constraint is not related to the non-primitive object type.
if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~134217728 /* NonPrimitive */))) {
errorInfo = saveErrorInfo;
@@ -35939,10 +36388,10 @@ var ts;
var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
if (modifiersRelated) {
- var result_1;
- if (result_1 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) {
+ var result_2;
+ if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) {
var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
- return result_1 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
+ return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
}
}
return 0 /* False */;
@@ -39285,7 +39734,7 @@ var ts;
}
function getTypeForThisExpressionFromJSDoc(node) {
var jsdocType = ts.getJSDocType(node);
- if (jsdocType && jsdocType.kind === 281 /* JSDocFunctionType */) {
+ if (jsdocType && jsdocType.kind === 283 /* JSDocFunctionType */) {
var jsDocFunctionType = jsdocType;
if (jsDocFunctionType.parameters.length > 0 &&
jsDocFunctionType.parameters[0].name &&
@@ -39721,7 +40170,7 @@ var ts;
// except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}`
var type = getContextualType(binaryExpression);
return !type && node === right && !ts.getDeclaredJavascriptInitializer(binaryExpression.parent) && !ts.getAssignedJavascriptInitializer(binaryExpression) ?
- getTypeOfExpression(left, /*cache*/ true) : type;
+ getTypeOfExpression(left) : type;
case 53 /* AmpersandAmpersandToken */:
case 26 /* CommaToken */:
return node === right ? getContextualType(binaryExpression) : undefined;
@@ -40312,7 +40761,7 @@ var ts;
var contextualType = getApparentTypeOfContextualType(node);
var contextualTypeHasPattern = contextualType && contextualType.pattern &&
(contextualType.pattern.kind === 179 /* ObjectBindingPattern */ || contextualType.pattern.kind === 183 /* ObjectLiteralExpression */);
- var isInJSFile = ts.isInJavaScriptFile(node);
+ var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node);
var isJSObjectLiteral = !contextualType && isInJSFile;
var typeFlags = 0;
var patternWithComputedProperties = false;
@@ -43251,8 +43700,8 @@ var ts;
if (allowSyntheticDefaultImports && type && type !== unknownType) {
var synthType = type;
if (!synthType.syntheticType) {
- var file = ts.find(originalSymbol.declarations, ts.isSourceFile);
- var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false);
+ var file_3 = ts.find(originalSymbol.declarations, ts.isSourceFile);
+ var hasSyntheticDefault = canHaveSyntheticDefault(file_3, originalSymbol, /*dontResolveAlias*/ false);
if (hasSyntheticDefault) {
var memberTable = ts.createSymbolTable();
var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
@@ -45036,7 +45485,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
- if (node.kind !== 159 /* IndexSignature */ && node.kind !== 281 /* JSDocFunctionType */) {
+ if (node.kind !== 159 /* IndexSignature */ && node.kind !== 283 /* JSDocFunctionType */) {
registerForUnusedIdentifiersCheck(node);
}
}
@@ -45499,7 +45948,7 @@ var ts;
n.parent.kind !== 234 /* ClassDeclaration */ &&
n.parent.kind !== 204 /* ClassExpression */ &&
n.flags & 4194304 /* Ambient */) {
- if (!(flags & 2 /* Ambient */)) {
+ if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) {
// It is nested in an ambient context, which means it is automatically exported
flags |= 1 /* Export */;
}
@@ -45770,7 +46219,7 @@ var ts;
case 235 /* InterfaceDeclaration */:
case 236 /* TypeAliasDeclaration */:
// A jsdoc typedef is, by definition, a type alias
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return 2 /* ExportType */;
case 238 /* ModuleDeclaration */:
return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
@@ -45792,10 +46241,10 @@ var ts;
case 242 /* ImportEqualsDeclaration */:
case 245 /* NamespaceImport */:
case 244 /* ImportClause */:
- var result_2 = 0 /* None */;
+ var result_3 = 0 /* None */;
var target = resolveAlias(getSymbolOfNode(d));
- ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); });
- return result_2;
+ ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); });
+ return result_3;
case 231 /* VariableDeclaration */:
case 181 /* BindingElement */:
case 233 /* FunctionDeclaration */:
@@ -46373,10 +46822,6 @@ var ts;
for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) {
var node = potentiallyUnusedIdentifiers_1[_i];
switch (node.kind) {
- case 273 /* SourceFile */:
- case 238 /* ModuleDeclaration */:
- checkUnusedModuleMembers(node, addDiagnostic);
- break;
case 234 /* ClassDeclaration */:
case 204 /* ClassExpression */:
checkUnusedClassMembers(node, addDiagnostic);
@@ -46385,6 +46830,8 @@ var ts;
case 235 /* InterfaceDeclaration */:
checkUnusedTypeParameters(node, addDiagnostic);
break;
+ case 273 /* SourceFile */:
+ case 238 /* ModuleDeclaration */:
case 212 /* Block */:
case 240 /* CaseBlock */:
case 219 /* ForStatement */:
@@ -46417,33 +46864,6 @@ var ts;
}
}
}
- function checkUnusedLocalsAndParameters(node, addDiagnostic) {
- if (!(node.flags & 4194304 /* Ambient */)) {
- node.locals.forEach(function (local) {
- // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
- // If it's a type parameter merged with a parameter, check if the parameter-side is used.
- if (local.flags & 262144 /* TypeParameter */ ? (local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : !local.isReferenced) {
- if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 148 /* Parameter */) {
- var parameter = ts.getRootDeclaration(local.valueDeclaration);
- var name = ts.getNameOfDeclaration(local.valueDeclaration);
- if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) {
- addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
- }
- }
- else {
- ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.symbolName(local), addDiagnostic); });
- }
- }
- });
- }
- }
- function isRemovedPropertyFromObjectSpread(node) {
- if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) {
- var lastElement = ts.lastOrUndefined(node.parent.elements);
- return lastElement !== node && !!lastElement.dotDotDotToken;
- }
- return false;
- }
function errorUnusedLocal(declaration, name, addDiagnostic) {
var node = ts.getNameOfDeclaration(declaration) || declaration;
if (isIdentifierThatStartsWithUnderScore(node)) {
@@ -46453,10 +46873,8 @@ var ts;
return;
}
}
- if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) {
- var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
- addDiagnostic(0 /* Local */, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name));
- }
+ var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
+ addDiagnostic(0 /* Local */, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name));
}
function parameterNameStartsWithUnderscore(parameterName) {
return parameterName && isIdentifierThatStartsWithUnderScore(parameterName);
@@ -46513,50 +46931,91 @@ var ts;
}
}
}
- function checkUnusedModuleMembers(node, addDiagnostic) {
- if (!(node.flags & 4194304 /* Ambient */)) {
- // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value.
- var unusedImports_1 = ts.createMap();
- node.locals.forEach(function (local) {
- if (local.isReferenced || local.exportSymbol)
- return;
- for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
- var declaration = _a[_i];
- if (ts.isAmbientModule(declaration))
- continue;
- if (isImportedDeclaration(declaration)) {
- var importClause = importClauseFromImported(declaration);
- var key = String(getNodeId(importClause));
- var group_1 = unusedImports_1.get(key);
- if (group_1) {
- group_1[1].push(declaration);
- }
- else {
- unusedImports_1.set(key, [importClause, [declaration]]);
+ function addToGroup(map, key, value, getKey) {
+ var keyString = String(getKey(key));
+ var group = map.get(keyString);
+ if (group) {
+ group[1].push(value);
+ }
+ else {
+ map.set(keyString, [key, [value]]);
+ }
+ }
+ function tryGetRootParameterDeclaration(node) {
+ return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
+ }
+ function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
+ if (nodeWithLocals.flags & 4194304 /* Ambient */)
+ return;
+ // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value.
+ var unusedImports = ts.createMap();
+ var unusedDestructures = ts.createMap();
+ nodeWithLocals.locals.forEach(function (local) {
+ // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
+ // If it's a type parameter merged with a parameter, check if the parameter-side is used.
+ if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
+ return;
+ }
+ for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
+ var declaration = _a[_i];
+ if (ts.isAmbientModule(declaration))
+ continue;
+ if (isImportedDeclaration(declaration)) {
+ addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
+ }
+ else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) {
+ // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though.
+ var lastElement = ts.last(declaration.parent.elements);
+ if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) {
+ addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
+ }
+ }
+ else {
+ var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
+ if (parameter) {
+ var name = ts.getNameOfDeclaration(local.valueDeclaration);
+ if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) {
+ addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
}
}
else {
errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic);
}
}
- });
- unusedImports_1.forEach(function (_a) {
- var importClause = _a[0], unuseds = _a[1];
- var importDecl = importClause.parent;
- if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) {
- for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
- var unused = unuseds_1[_i];
- errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
- }
+ }
+ });
+ unusedImports.forEach(function (_a) {
+ var importClause = _a[0], unuseds = _a[1];
+ var importDecl = importClause.parent;
+ if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) {
+ for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
+ var unused = unuseds_1[_i];
+ errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
}
- else if (unuseds.length === 1) {
- addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)));
+ }
+ else if (unuseds.length === 1) {
+ addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)));
+ }
+ else {
+ addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused));
+ }
+ });
+ unusedDestructures.forEach(function (_a) {
+ var bindingPattern = _a[0], bindingElements = _a[1];
+ var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
+ if (!bindingPattern.elements.every(function (e) { return ts.contains(bindingElements, e); })) {
+ for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) {
+ var e = bindingElements_1[_i];
+ addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, getBindingElementNameText(e)));
}
- else {
- addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused, ts.showModuleSpecifier(importDecl)));
- }
- });
- }
+ }
+ else if (bindingElements.length === 1) {
+ addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, getBindingElementNameText(ts.first(bindingElements))));
+ }
+ else {
+ addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused));
+ }
+ });
}
function isImportedDeclaration(node) {
return node.kind === 244 /* ImportClause */ || node.kind === 247 /* ImportSpecifier */ || node.kind === 245 /* NamespaceImport */;
@@ -48747,9 +49206,9 @@ var ts;
}
}
// Checks for export * conflicts
- var exports = getExportsOfModule(moduleSymbol);
- if (exports) {
- exports.forEach(function (_a, id) {
+ var exports_1 = getExportsOfModule(moduleSymbol);
+ if (exports_1) {
+ exports_1.forEach(function (_a, id) {
var declarations = _a.declarations, flags = _a.flags;
if (id === "__export") {
return;
@@ -48855,27 +49314,27 @@ var ts;
return checkInferType(node);
case 178 /* ImportType */:
return checkImportType(node);
- case 286 /* JSDocAugmentsTag */:
+ case 288 /* JSDocAugmentsTag */:
return checkJSDocAugmentsTag(node);
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return checkJSDocTypedefTag(node);
- case 288 /* JSDocParameterTag */:
+ case 290 /* JSDocParameterTag */:
return checkJSDocParameterTag(node);
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
checkSignatureDeclaration(node);
// falls through
- case 279 /* JSDocNonNullableType */:
- case 278 /* JSDocNullableType */:
- case 276 /* JSDocAllType */:
- case 277 /* JSDocUnknownType */:
- case 284 /* JSDocTypeLiteral */:
+ case 281 /* JSDocNonNullableType */:
+ case 280 /* JSDocNullableType */:
+ case 278 /* JSDocAllType */:
+ case 279 /* JSDocUnknownType */:
+ case 286 /* JSDocTypeLiteral */:
checkJSDocTypeIsInJsFile(node);
ts.forEachChild(node, checkSourceElement);
return;
- case 282 /* JSDocVariadicType */:
+ case 284 /* JSDocVariadicType */:
checkJSDocVariadicType(node);
return;
- case 275 /* JSDocTypeExpression */:
+ case 277 /* JSDocTypeExpression */:
return checkSourceElement(node.type);
case 175 /* IndexedAccessType */:
return checkIndexedAccessType(node);
@@ -49388,10 +49847,10 @@ var ts;
return entityNameSymbol;
}
}
- if (entityName.parent.kind === 288 /* JSDocParameterTag */) {
+ if (entityName.parent.kind === 290 /* JSDocParameterTag */) {
return ts.getParameterSymbolFromJSDoc(entityName.parent);
}
- if (entityName.parent.kind === 147 /* TypeParameter */ && entityName.parent.parent.kind === 291 /* JSDocTemplateTag */) {
+ if (entityName.parent.kind === 147 /* TypeParameter */ && entityName.parent.parent.kind === 293 /* JSDocTemplateTag */) {
ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true.
var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
return typeParameter && typeParameter.symbol;
@@ -50181,7 +50640,22 @@ var ts;
var symbol = node && getSymbolOfNode(node);
return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */);
},
- getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }
+ getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; },
+ getAllAccessorDeclarations: function (accessor) {
+ accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration);
+ var otherKind = accessor.kind === 156 /* SetAccessor */ ? 155 /* GetAccessor */ : 156 /* SetAccessor */;
+ var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind);
+ var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor;
+ var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor;
+ var setAccessor = accessor.kind === 156 /* SetAccessor */ ? accessor : otherAccessor;
+ var getAccessor = accessor.kind === 155 /* GetAccessor */ ? accessor : otherAccessor;
+ return {
+ firstAccessor: firstAccessor,
+ secondAccessor: secondAccessor,
+ setAccessor: setAccessor,
+ getAccessor: getAccessor
+ };
+ }
};
function isInHeritageClause(node) {
return node.parent && node.parent.kind === 206 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 267 /* HeritageClause */;
@@ -50217,8 +50691,8 @@ var ts;
var decl = _a[_i];
// check meaning of the local symbol to see if declaration needs to be analyzed further
if (decl.symbol && decl.symbol.flags & meaning) {
- var file = ts.getSourceFileOfNode(decl);
- var typeReferenceDirective = fileToDirective.get(file.path);
+ var file_4 = ts.getSourceFileOfNode(decl);
+ var typeReferenceDirective = fileToDirective.get(file_4.path);
if (typeReferenceDirective) {
(typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective);
}
@@ -50253,8 +50727,8 @@ var ts;
// check that at least one declaration of top level symbol originates from type declaration file
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
- var file = ts.getSourceFileOfNode(decl);
- if (fileToDirective.has(file.path)) {
+ var file_5 = ts.getSourceFileOfNode(decl);
+ if (fileToDirective.has(file_5.path)) {
return true;
}
}
@@ -50272,25 +50746,25 @@ var ts;
function initializeTypeChecker() {
// Bind all source files and propagate errors
for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
- var file = _a[_i];
- ts.bindSourceFile(file, compilerOptions);
+ var file_6 = _a[_i];
+ ts.bindSourceFile(file_6, compilerOptions);
}
// Initialize global symbol table
var augmentations;
for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
- var file = _c[_b];
- if (!ts.isExternalOrCommonJsModule(file)) {
- mergeSymbolTable(globals, file.locals);
+ var file_7 = _c[_b];
+ if (!ts.isExternalOrCommonJsModule(file_7)) {
+ mergeSymbolTable(globals, file_7.locals);
}
- if (file.patternAmbientModules && file.patternAmbientModules.length) {
- patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules);
+ if (file_7.patternAmbientModules && file_7.patternAmbientModules.length) {
+ patternAmbientModules = ts.concatenate(patternAmbientModules, file_7.patternAmbientModules);
}
- if (file.moduleAugmentations.length) {
- (augmentations || (augmentations = [])).push(file.moduleAugmentations);
+ if (file_7.moduleAugmentations.length) {
+ (augmentations || (augmentations = [])).push(file_7.moduleAugmentations);
}
- if (file.symbol && file.symbol.globalExports) {
+ if (file_7.symbol && file_7.symbol.globalExports) {
// Merge in UMD exports with first-in-wins semantics (see #9771)
- var source = file.symbol.globalExports;
+ var source = file_7.symbol.globalExports;
source.forEach(function (sourceSymbol, id) {
if (!globals.has(id)) {
globals.set(id, sourceSymbol);
@@ -51578,7 +52052,7 @@ var ts;
}
function checkGrammarImportCallExpression(node) {
if (moduleKind === ts.ModuleKind.ES2015) {
- return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules);
+ return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext);
}
if (node.typeArguments) {
return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments);
@@ -51657,10 +52131,8 @@ var ts;
if (!elements || elements === ts.emptyArray) {
elements = [];
}
- else {
- if (ts.isNodeArray(elements)) {
- return elements;
- }
+ else if (ts.isNodeArray(elements)) {
+ return elements;
}
var array = elements;
array.pos = -1;
@@ -51720,6 +52192,13 @@ var ts;
node.text = text;
return node;
}
+ ts.createStringLiteral = createStringLiteral;
+ function createRegularExpressionLiteral(text) {
+ var node = createSynthesizedNode(12 /* RegularExpressionLiteral */);
+ node.text = text;
+ return node;
+ }
+ ts.createRegularExpressionLiteral = createRegularExpressionLiteral;
function createLiteralFromNode(sourceNode) {
var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode));
node.textSourceNode = sourceNode;
@@ -51753,7 +52232,7 @@ var ts;
recordTempVariable(name);
}
if (reservedInNestedScopes) {
- name.autoGenerateFlags |= 16 /* ReservedInNestedScopes */;
+ name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
}
return name;
}
@@ -51779,7 +52258,7 @@ var ts;
/** Create a unique name based on the supplied text. */
function createOptimisticUniqueName(text) {
var name = createIdentifier(text);
- name.autoGenerateFlags = 3 /* Unique */ | 32 /* Optimistic */;
+ name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */;
name.autoGenerateId = nextAutoGenerateId;
nextAutoGenerateId++;
return name;
@@ -51788,18 +52267,15 @@ var ts;
/** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */
function createFileLevelUniqueName(text) {
var name = createOptimisticUniqueName(text);
- name.autoGenerateFlags |= 64 /* FileLevel */;
+ name.autoGenerateFlags |= 32 /* FileLevel */;
return name;
}
ts.createFileLevelUniqueName = createFileLevelUniqueName;
- function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) {
- var name = createIdentifier("");
- name.autoGenerateFlags = 4 /* Node */;
+ function getGeneratedNameForNode(node, flags) {
+ var name = createIdentifier(ts.isIdentifier(node) ? ts.idText(node) : "");
+ name.autoGenerateFlags = 4 /* Node */ | flags;
name.autoGenerateId = nextAutoGenerateId;
name.original = node;
- if (shouldSkipNameGenerationScope) {
- name.autoGenerateFlags |= 8 /* SkipNameGenerationScope */;
- }
nextAutoGenerateId++;
return name;
}
@@ -51890,7 +52366,7 @@ var ts;
ts.updateQualifiedName = updateQualifiedName;
function parenthesizeForComputedName(expression) {
return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */) ||
- expression.kind === 297 /* CommaListExpression */ ?
+ expression.kind === 299 /* CommaListExpression */ ?
createParen(expression) :
expression;
}
@@ -52940,6 +53416,13 @@ var ts;
return block;
}
ts.createBlock = createBlock;
+ /* @internal */
+ function createExpressionStatement(expression) {
+ var node = createSynthesizedNode(215 /* ExpressionStatement */);
+ node.expression = expression;
+ return node;
+ }
+ ts.createExpressionStatement = createExpressionStatement;
function updateBlock(node, statements) {
return node.statements !== statements
? updateNode(createBlock(statements, node.multiLine), node)
@@ -52966,9 +53449,7 @@ var ts;
}
ts.createEmptyStatement = createEmptyStatement;
function createStatement(expression) {
- var node = createSynthesizedNode(215 /* ExpressionStatement */);
- node.expression = ts.parenthesizeExpressionForExpressionStatement(expression);
- return node;
+ return createExpressionStatement(ts.parenthesizeExpressionForExpressionStatement(expression));
}
ts.createStatement = createStatement;
function updateStatement(node, expression) {
@@ -53864,7 +54345,7 @@ var ts;
* @param original The original statement.
*/
function createNotEmittedStatement(original) {
- var node = createSynthesizedNode(295 /* NotEmittedStatement */);
+ var node = createSynthesizedNode(297 /* NotEmittedStatement */);
node.original = original;
setTextRange(node, original);
return node;
@@ -53876,7 +54357,7 @@ var ts;
*/
/* @internal */
function createEndOfDeclarationMarker(original) {
- var node = createSynthesizedNode(299 /* EndOfDeclarationMarker */);
+ var node = createSynthesizedNode(301 /* EndOfDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -53888,7 +54369,7 @@ var ts;
*/
/* @internal */
function createMergeDeclarationMarker(original) {
- var node = createSynthesizedNode(298 /* MergeDeclarationMarker */);
+ var node = createSynthesizedNode(300 /* MergeDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -53903,7 +54384,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(296 /* PartiallyEmittedExpression */);
+ var node = createSynthesizedNode(298 /* PartiallyEmittedExpression */);
node.expression = expression;
node.original = original;
setTextRange(node, original);
@@ -53919,7 +54400,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 === 297 /* CommaListExpression */) {
+ if (node.kind === 299 /* CommaListExpression */) {
return node.elements;
}
if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) {
@@ -53929,7 +54410,7 @@ var ts;
return node;
}
function createCommaList(elements) {
- var node = createSynthesizedNode(297 /* CommaListExpression */);
+ var node = createSynthesizedNode(299 /* CommaListExpression */);
node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
return node;
}
@@ -53940,15 +54421,31 @@ var ts;
: node;
}
ts.updateCommaList = updateCommaList;
- function createBundle(sourceFiles) {
+ function createBundle(sourceFiles, prepends) {
+ if (prepends === void 0) { prepends = ts.emptyArray; }
var node = ts.createNode(274 /* Bundle */);
+ node.prepends = prepends;
node.sourceFiles = sourceFiles;
return node;
}
ts.createBundle = createBundle;
- function updateBundle(node, sourceFiles) {
- if (node.sourceFiles !== sourceFiles) {
- return createBundle(sourceFiles);
+ function createUnparsedSourceFile(text) {
+ var node = ts.createNode(275 /* UnparsedSource */);
+ node.text = text;
+ return node;
+ }
+ ts.createUnparsedSourceFile = createUnparsedSourceFile;
+ function createInputFiles(javascript, declaration) {
+ var node = ts.createNode(276 /* InputFiles */);
+ node.javascriptText = javascript;
+ node.declarationText = declaration;
+ return node;
+ }
+ ts.createInputFiles = createInputFiles;
+ function updateBundle(node, sourceFiles, prepends) {
+ if (prepends === void 0) { prepends = ts.emptyArray; }
+ if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) {
+ return createBundle(sourceFiles, prepends);
}
return node;
}
@@ -55192,7 +55689,7 @@ var ts;
// if should be wrapped in parens since comma operator has the lowest precedence
var emittedExpression = ts.skipPartiallyEmittedExpressions(e);
return emittedExpression.kind === 199 /* BinaryExpression */ && emittedExpression.operatorToken.kind === 26 /* CommaToken */ ||
- emittedExpression.kind === 297 /* CommaListExpression */
+ emittedExpression.kind === 299 /* CommaListExpression */
? ts.createParen(e)
: e;
}
@@ -55212,7 +55709,7 @@ var ts;
var check = ts.skipPartiallyEmittedExpressions(e);
return (check.kind === 204 /* ClassExpression */ ||
check.kind === 191 /* FunctionExpression */ ||
- check.kind === 297 /* CommaListExpression */ ||
+ check.kind === 299 /* CommaListExpression */ ||
ts.isBinaryExpression(check) && check.operatorToken.kind === 26 /* CommaToken */)
? ts.createParen(e)
: e;
@@ -55333,6 +55830,7 @@ var ts;
switch (member.kind) {
case 164 /* TypeQuery */:
case 174 /* TypeOperator */:
+ case 171 /* InferType */:
return ts.createParenthesizedType(member);
}
return parenthesizeElementTypeMember(member);
@@ -55376,7 +55874,7 @@ var ts;
case 184 /* PropertyAccessExpression */:
node = node.expression;
continue;
- case 296 /* PartiallyEmittedExpression */:
+ case 298 /* PartiallyEmittedExpression */:
node = node.expression;
continue;
}
@@ -55406,7 +55904,7 @@ var ts;
case 207 /* AsExpression */:
case 208 /* NonNullExpression */:
return (kinds & 2 /* Assertions */) !== 0;
- case 296 /* PartiallyEmittedExpression */:
+ case 298 /* PartiallyEmittedExpression */:
return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0;
}
return false;
@@ -55443,7 +55941,7 @@ var ts;
case 189 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
case 207 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
case 208 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
- case 296 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
+ case 298 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
}
}
/**
@@ -55931,7 +56429,7 @@ var ts;
statements = ts.setTextRange(ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements)), statements);
}
var declarations = context.endLexicalEnvironment();
- return ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements);
+ return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements);
}
ts.visitLexicalEnvironment = visitLexicalEnvironment;
/**
@@ -56228,9 +56726,9 @@ var ts;
case 273 /* SourceFile */:
return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
// Transformation nodes
- case 296 /* PartiallyEmittedExpression */:
+ case 298 /* PartiallyEmittedExpression */:
return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- case 297 /* CommaListExpression */:
+ case 299 /* CommaListExpression */:
return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
default:
// No need to visit nodes with no children.
@@ -56286,7 +56784,7 @@ var ts;
case 214 /* EmptyStatement */:
case 205 /* OmittedExpression */:
case 230 /* DebuggerStatement */:
- case 295 /* NotEmittedStatement */:
+ case 297 /* NotEmittedStatement */:
// No need to visit nodes with no children.
break;
// Names
@@ -56665,10 +57163,10 @@ var ts;
result = reduceNodes(node.statements, cbNodes, result);
break;
// Transformation nodes
- case 296 /* PartiallyEmittedExpression */:
+ case 298 /* PartiallyEmittedExpression */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 297 /* CommaListExpression */:
+ case 299 /* CommaListExpression */:
result = reduceNodes(node.elements, cbNodes, result);
break;
default:
@@ -56682,8 +57180,8 @@ var ts;
return statements;
}
return ts.isNodeArray(statements)
- ? ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements)
- : ts.addRange(statements, declarations);
+ ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements)
+ : ts.prependRange(statements, declarations);
}
ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
/**
@@ -56833,16 +57331,6 @@ var ts;
return node ? ts.getNodeId(node) : 0;
}
ts.getOriginalNodeId = getOriginalNodeId;
- function getNamedImportCount(node) {
- if (!(node.importClause && node.importClause.namedBindings))
- return 0;
- var names = node.importClause.namedBindings;
- if (!names)
- return 0;
- if (!ts.isNamedImports(names))
- return 0;
- return names.elements.length;
- }
function containsDefaultReference(node) {
if (!node)
return false;
@@ -56853,12 +57341,40 @@ var ts;
function isNamedDefaultReference(e) {
return e.propertyName && e.propertyName.escapedText === "default" /* Default */;
}
+ function chainBundle(transformSourceFile) {
+ return transformSourceFileOrBundle;
+ function transformSourceFileOrBundle(node) {
+ return node.kind === 273 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
+ }
+ function transformBundle(node) {
+ return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
+ }
+ }
+ ts.chainBundle = chainBundle;
function getImportNeedsImportStarHelper(node) {
- return !!ts.getNamespaceDeclarationNode(node) || (getNamedImportCount(node) > 1 && containsDefaultReference(node.importClause.namedBindings));
+ if (!!ts.getNamespaceDeclarationNode(node)) {
+ return true;
+ }
+ var bindings = node.importClause && node.importClause.namedBindings;
+ if (!bindings) {
+ return false;
+ }
+ if (!ts.isNamedImports(bindings))
+ return false;
+ var defaultRefCount = 0;
+ for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) {
+ var binding = _a[_i];
+ if (isNamedDefaultReference(binding)) {
+ defaultRefCount++;
+ }
+ }
+ // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import
+ return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node));
}
ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper;
function getImportNeedsImportDefaultHelper(node) {
- return ts.isDefaultImport(node) || (getNamedImportCount(node) === 1 && containsDefaultReference(node.importClause.namedBindings));
+ // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested)
+ return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings)));
}
ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper;
function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) {
@@ -57595,7 +58111,21 @@ var ts;
* at the next execution site, in document order
*/
var pendingExpressions;
- return transformSourceFile;
+ return transformSourceFileOrBundle;
+ function transformSourceFileOrBundle(node) {
+ if (node.kind === 274 /* 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 === 276 /* InputFiles */) {
+ return ts.createUnparsedSourceFile(prepend.javascriptText);
+ }
+ return prepend;
+ }));
+ }
/**
* Transform TypeScript-specific syntax in a SourceFile.
*
@@ -58085,7 +58615,7 @@ var ts;
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addRange(statements, context.endLexicalEnvironment());
+ ts.prependRange(statements, context.endLexicalEnvironment());
var iife = ts.createImmediatelyInvokedArrowFunction(statements);
ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
var varStatement = ts.createVariableStatement(
@@ -58290,7 +58820,7 @@ var ts;
// record an alias as the class name is not in scope for statics.
enableSubstitutionForClassAliases();
var alias = ts.getSynthesizedClone(temp);
- alias.autoGenerateFlags &= ~16 /* ReservedInNestedScopes */;
+ alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */;
classAliases[ts.getOriginalNodeId(node)] = alias;
}
// To preserve the behavior of the old emitter, we explicitly indent
@@ -58567,7 +59097,7 @@ var ts;
function transformInitializedProperty(property, receiver) {
// We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression)
- ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name, !ts.hasModifier(property, 32 /* Static */)))
+ ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name))
: property.name;
var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression);
var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName);
@@ -59702,8 +60232,9 @@ var ts;
currentNamespaceContainerName = localName;
var statements = [];
startLexicalEnvironment();
- ts.addRange(statements, ts.map(node.members, transformEnumMember));
- ts.addRange(statements, endLexicalEnvironment());
+ var members = ts.map(node.members, transformEnumMember);
+ ts.prependRange(statements, endLexicalEnvironment());
+ ts.addRange(statements, members);
currentNamespaceContainerName = savedCurrentNamespaceLocalName;
return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members),
/*multiLine*/ true);
@@ -59943,7 +60474,7 @@ var ts;
var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
}
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
currentNamespaceContainerName = savedCurrentNamespaceContainerName;
currentNamespace = savedCurrentNamespace;
currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
@@ -60480,7 +61011,7 @@ var ts;
// Set new transformation hooks.
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -60752,7 +61283,7 @@ var ts;
var statements = [];
var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var block = ts.createBlock(statements, /*multiLine*/ true);
ts.setTextRange(block, node.body);
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
@@ -60774,7 +61305,7 @@ var ts;
var declarations = endLexicalEnvironment();
if (ts.some(declarations)) {
var block = ts.convertToFunctionBody(expression);
- result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements));
+ result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements));
}
else {
result = expression;
@@ -60964,7 +61495,7 @@ var ts;
var enabledSubstitutions;
var enclosingFunctionFlags;
var enclosingSuperContainerFlags = 0;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -61042,9 +61573,14 @@ var ts;
return ts.visitEachChild(node, visitor, context);
}
function visitYieldExpression(node) {
- if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ && node.asteriskToken) {
- var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
- return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node);
+ if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
+ if (node.asteriskToken) {
+ var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
+ return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node);
+ }
+ return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression
+ ? ts.visitNode(node.expression, visitor, ts.isExpression)
+ : ts.createVoidZero())), node), node);
}
return ts.visitEachChild(node, visitor, context);
}
@@ -61346,7 +61882,7 @@ var ts;
/*typeParameters*/ undefined,
/*parameters*/ [],
/*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))));
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var block = ts.updateBlock(node.body, statements);
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
// This step isn't needed if we eventually transform this to ES5.
@@ -61371,11 +61907,11 @@ var ts;
statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
}
ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
- var trailingStatements = endLexicalEnvironment();
- if (statementOffset > 0 || ts.some(statements) || ts.some(trailingStatements)) {
+ var leadingStatements = endLexicalEnvironment();
+ if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
+ ts.prependRange(statements, leadingStatements);
ts.addRange(statements, block.statements.slice(statementOffset));
- ts.addRange(statements, trailingStatements);
return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
}
return body;
@@ -61575,7 +62111,7 @@ var ts;
function transformJsx(context) {
var compilerOptions = context.getCompilerOptions();
var currentSourceFile;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
/**
* Transform JSX-specific syntax in a SourceFile.
*
@@ -62083,7 +62619,7 @@ var ts;
(function (ts) {
function transformES2016(context) {
var hoistVariableDeclaration = context.hoistVariableDeclaration;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -62291,7 +62827,7 @@ var ts;
* be reset.
*/
var enabledSubstitutions;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -62467,7 +63003,7 @@ var ts;
if (taggedTemplateStringDeclarations) {
statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
}
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
}
@@ -62721,7 +63257,7 @@ var ts;
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
ts.setEmitFlags(block, 1536 /* NoComments */);
return block;
@@ -62834,7 +63370,7 @@ var ts;
&& !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) {
statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
}
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
if (constructor) {
prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false);
}
@@ -63476,7 +64012,7 @@ var ts;
closeBraceLocation = body;
}
var lexicalEnvironment = context.endLexicalEnvironment();
- ts.addRange(statements, lexicalEnvironment);
+ ts.prependRange(statements, lexicalEnvironment);
prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false);
// If we added any final generated statements, this must be a multi-line block
if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) {
@@ -64057,7 +64593,7 @@ var ts;
if (loopOutParameters.length) {
copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4);
}
- ts.addRange(statements_4, lexicalEnvironment);
+ ts.prependRange(statements_4, lexicalEnvironment);
loopBody = ts.createBlock(statements_4, /*multiline*/ true);
}
if (ts.isBlock(loopBody)) {
@@ -64510,10 +65046,12 @@ var ts;
// We skip any outer expressions in a number of places to get to the innermost
// expression, but we will restore them later to preserve comments and source maps.
var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock);
- // The class statements are the statements generated by visiting the first statement of the
+ // The class statements are the statements generated by visiting the first statement with initializer of the
// body (1), while all other statements are added to remainingStatements (2)
- var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1);
- var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1);
+ var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.firstOrUndefined(stmt.declarationList.declarations).initializer; };
+ var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement);
+ var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer);
+ var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); });
var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement);
// We know there is only one variable declaration here as we verified this in an
// earlier call to isTypeScriptClassWrapper
@@ -64523,6 +65061,7 @@ var ts;
// we see as an assignment, for example:
//
// (function () {
+ // var C_1;
// var C = C_1 = (function () {
// function C() {
// }
@@ -64531,7 +65070,6 @@ var ts;
// }());
// C = C_1 = __decorate([dec], C);
// return C;
- // var C_1;
// }())
//
var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression);
@@ -65161,7 +65699,7 @@ var ts;
context.onSubstituteNode = onSubstituteNode;
context.enableSubstitution(184 /* PropertyAccessExpression */);
context.enableSubstitution(269 /* PropertyAssignment */);
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
/**
* Transforms an ES5 source file to ES3.
*
@@ -65473,7 +66011,7 @@ var ts;
var exceptionBlockStack; // A stack of containing exception blocks.
var currentExceptionBlock; // The current exception block.
var withBlockStack; // A stack containing `with` blocks.
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
return node;
@@ -65730,7 +66268,7 @@ var ts;
var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
transformAndEmitStatements(body.statements, statementOffset);
var buildResult = build();
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
statements.push(ts.createReturn(buildResult));
// Restore previous generator state
inGeneratorFunctionBody = savedInGeneratorFunctionBody;
@@ -67923,7 +68461,7 @@ var ts;
var currentModuleInfo; // The ExternalModuleInfo for the current file.
var noSubstitution; // Set of nodes for which substitution rules should be ignored.
var needUMDDynamicImportHelper;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
/**
* Transforms the module aspects of a SourceFile.
*
@@ -67966,7 +68504,7 @@ var ts;
ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
// If we have any `export * from ...` declarations
@@ -68189,7 +68727,7 @@ var ts;
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
// End the lexical environment for the module body
// and merge any new lexical declarations.
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var body = ts.createBlock(statements, /*multiLine*/ true);
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
// If we have any `export * from ...` declarations
@@ -68211,7 +68749,7 @@ var ts;
*/
function addExportEqualsIfNeeded(statements, emitAsReturn) {
if (currentModuleInfo.exportEquals) {
- var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, importCallExpressionVisitor);
+ var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor);
if (expressionResult) {
if (emitAsReturn) {
var statement = ts.createReturn(expressionResult);
@@ -68252,29 +68790,84 @@ var ts;
return visitFunctionDeclaration(node);
case 234 /* ClassDeclaration */:
return visitClassDeclaration(node);
- case 298 /* MergeDeclarationMarker */:
+ case 300 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 299 /* EndOfDeclarationMarker */:
+ case 301 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
- return ts.visitEachChild(node, importCallExpressionVisitor, context);
+ return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
}
}
- function importCallExpressionVisitor(node) {
- // This visitor does not need to descend into the tree if there is no dynamic import,
+ function moduleExpressionElementVisitor(node) {
+ // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
// as export/import statements are only transformed at the top level of a file.
- if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */)) {
+ if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) {
return node;
}
if (ts.isImportCall(node)) {
return visitImportCallExpression(node);
}
+ else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) {
+ return visitDestructuringAssignment(node);
+ }
else {
- return ts.visitEachChild(node, importCallExpressionVisitor, context);
+ return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
}
}
+ function destructuringNeedsFlattening(node) {
+ if (ts.isObjectLiteralExpression(node)) {
+ for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
+ var elem = _a[_i];
+ switch (elem.kind) {
+ case 269 /* PropertyAssignment */:
+ if (destructuringNeedsFlattening(elem.initializer)) {
+ return true;
+ }
+ break;
+ case 270 /* ShorthandPropertyAssignment */:
+ if (destructuringNeedsFlattening(elem.name)) {
+ return true;
+ }
+ break;
+ case 271 /* SpreadAssignment */:
+ if (destructuringNeedsFlattening(elem.expression)) {
+ return true;
+ }
+ break;
+ case 153 /* MethodDeclaration */:
+ case 155 /* GetAccessor */:
+ case 156 /* SetAccessor */:
+ return false;
+ default: ts.Debug.assertNever(elem, "Unhandled object member kind");
+ }
+ }
+ }
+ else if (ts.isArrayLiteralExpression(node)) {
+ for (var _b = 0, _c = node.elements; _b < _c.length; _b++) {
+ var elem = _c[_b];
+ if (ts.isSpreadElement(elem)) {
+ if (destructuringNeedsFlattening(elem.expression)) {
+ return true;
+ }
+ }
+ else if (destructuringNeedsFlattening(elem)) {
+ return true;
+ }
+ }
+ }
+ else if (ts.isIdentifier(node)) {
+ return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0);
+ }
+ return false;
+ }
+ function visitDestructuringAssignment(node) {
+ if (destructuringNeedsFlattening(node.left)) {
+ return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions);
+ }
+ return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
+ }
function visitImportCallExpression(node) {
- var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor);
+ var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */);
switch (compilerOptions.module) {
case ts.ModuleKind.AMD:
@@ -68568,10 +69161,10 @@ var ts;
if (original && hasAssociatedEndOfDeclarationMarker(original)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
var id = ts.getOriginalNodeId(node);
- deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true);
+ deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
}
else {
- statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true);
+ statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
}
return ts.singleOrMany(statements);
}
@@ -68585,13 +69178,13 @@ var ts;
if (ts.hasModifier(node, 1 /* Export */)) {
statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
/*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
- /*typeParameters*/ undefined, ts.visitNodes(node.parameters, importCallExpressionVisitor),
- /*type*/ undefined, ts.visitEachChild(node.body, importCallExpressionVisitor, context)),
+ /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor),
+ /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)),
/*location*/ node),
/*original*/ node));
}
else {
- statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context));
+ statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
@@ -68613,10 +69206,10 @@ var ts;
if (ts.hasModifier(node, 1 /* Export */)) {
statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(
/*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
- /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, importCallExpressionVisitor), ts.visitNodes(node.members, importCallExpressionVisitor)), node), node));
+ /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node));
}
else {
- statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context));
+ statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
@@ -68661,7 +69254,7 @@ var ts;
}
}
else {
- statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context));
+ statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
@@ -68673,6 +69266,21 @@ var ts;
}
return ts.singleOrMany(statements);
}
+ function createAllExportExpressions(name, value, location) {
+ var exportedNames = getExports(name);
+ if (exportedNames) {
+ // For each additional export of the declaration, apply an export assignment.
+ var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value);
+ for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
+ var exportName = exportedNames_1[_i];
+ // Mark the node to prevent triggering substitution.
+ ts.setEmitFlags(expression, 4 /* NoSubstitution */);
+ expression = createExportExpression(exportName, expression, /*location*/ location);
+ }
+ return expression;
+ }
+ return ts.createAssignment(name, value);
+ }
/**
* Transforms an exported variable with an initializer into an expression.
*
@@ -68680,13 +69288,13 @@ var ts;
*/
function transformInitializedVariable(node) {
if (ts.isBindingPattern(node.name)) {
- return ts.flattenDestructuringAssignment(ts.visitNode(node, importCallExpressionVisitor),
+ return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor),
/*visitor*/ undefined, context, 0 /* All */,
- /*needsValue*/ false, createExportExpression);
+ /*needsValue*/ false, createAllExportExpressions);
}
else {
return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name),
- /*location*/ node.name), ts.visitNode(node.initializer, importCallExpressionVisitor));
+ /*location*/ node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor));
}
}
/**
@@ -69090,8 +69698,8 @@ var ts;
if (exportedNames) {
// For each additional export of the declaration, apply an export assignment.
var expression = node;
- for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
- var exportName = exportedNames_1[_i];
+ for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
+ var exportName = exportedNames_2[_i];
// Mark the node to prevent triggering this rule again.
noSubstitution[ts.getNodeId(expression)] = true;
expression = createExportExpression(exportName, expression, /*location*/ node);
@@ -69127,8 +69735,8 @@ var ts;
? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)),
/*location*/ node)
: node;
- for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
- var exportName = exportedNames_2[_i];
+ for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
+ var exportName = exportedNames_3[_i];
// Mark the node to prevent triggering this rule again.
noSubstitution[ts.getNodeId(expression)] = true;
expression = createExportExpression(exportName, expression);
@@ -69215,7 +69823,7 @@ var ts;
var hoistedStatements;
var enclosingBlockScopedContainer;
var noSubstitution; // Set of nodes for which substitution rules should be ignored.
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
/**
* Transforms the module aspects of a SourceFile.
*
@@ -69388,7 +69996,7 @@ var ts;
// We emit hoisted variables early to align roughly with our previous emit output.
// Two key differences in this approach are:
// - Temporary variables will appear at the top rather than at the bottom of the file
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var exportStarFunction = addExportStarIfNeeded(statements);
var moduleObject = ts.createObjectLiteral([
ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
@@ -69518,12 +70126,12 @@ var ts;
function createSettersArray(exportStarFunction, dependencyGroups) {
var setters = [];
for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
- var group_2 = dependencyGroups_1[_i];
+ var group_1 = dependencyGroups_1[_i];
// derive a unique name for parameter from the first named entry in the group
- var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); });
+ var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); });
var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName("");
var statements = [];
- for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) {
+ for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) {
var entry = _b[_a];
var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile);
switch (entry.kind) {
@@ -70116,9 +70724,9 @@ var ts;
return visitCatchClause(node);
case 212 /* Block */:
return visitBlock(node);
- case 298 /* MergeDeclarationMarker */:
+ case 300 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 299 /* EndOfDeclarationMarker */:
+ case 301 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return destructuringAndImportCallVisitor(node);
@@ -70551,8 +71159,8 @@ var ts;
if (exportedNames) {
// For each additional export of the declaration, apply an export assignment.
var expression = node;
- for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
- var exportName = exportedNames_3[_i];
+ for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
+ var exportName = exportedNames_4[_i];
expression = createExportExpression(exportName, preventSubstitution(expression));
}
return expression;
@@ -70585,8 +71193,8 @@ var ts;
var expression = node.kind === 198 /* PostfixUnaryExpression */
? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node)
: node;
- for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
- var exportName = exportedNames_4[_i];
+ for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) {
+ var exportName = exportedNames_5[_i];
expression = createExportExpression(exportName, preventSubstitution(expression));
}
if (node.kind === 198 /* PostfixUnaryExpression */) {
@@ -70653,7 +71261,7 @@ var ts;
context.enableEmitNotification(273 /* SourceFile */);
context.enableSubstitution(71 /* Identifier */);
var currentSourceFile;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -71160,7 +71768,12 @@ var ts;
return result.diagnostics;
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
- var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */;
+ var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
+ 2048 /* WriteClassExpressionAsTypeLiteral */ |
+ 4096 /* UseTypeOfFunction */ |
+ 8 /* UseStructuralFallback */ |
+ 524288 /* AllowEmptyTuple */ |
+ 4 /* GenerateNamesForShadowedTypeParams */;
/**
* Transforms a ts file into a .d.ts file
* This process requires type information, which is retrieved through the emit resolver. Because of this,
@@ -71234,6 +71847,8 @@ var ts;
}
}
function trackSymbol(symbol, enclosingDeclaration, meaning) {
+ if (symbol.flags & 262144 /* TypeParameter */)
+ return;
handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
}
@@ -71277,12 +71892,16 @@ var ts;
resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
needsDeclare = false;
var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
- var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false);
+ var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false);
return newFile;
}
needsDeclare = true;
var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
- return ts.updateSourceFileNode(sourceFile, filterCandidateImports(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false);
+ return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false);
+ }), ts.mapDefined(node.prepends, function (prepend) {
+ if (prepend.kind === 276 /* InputFiles */) {
+ return ts.createUnparsedSourceFile(prepend.declarationText);
+ }
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
@@ -71311,7 +71930,7 @@ var ts;
var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
refs.forEach(referenceVisitor);
var statements = ts.visitNodes(node.statements, visitDeclarationStatements);
- var combinedStatements = ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements)), node.statements);
+ var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements);
@@ -71366,7 +71985,7 @@ var ts;
ts.forEach(sourceFile.referencedFiles, function (f) {
var elem = ts.tryResolveScriptReference(host, sourceFile, f);
if (elem) {
- ret.set("" + ts.getNodeId(elem), elem);
+ ret.set("" + ts.getOriginalNodeId(elem), elem);
}
});
return ret;
@@ -71583,7 +72202,7 @@ var ts;
}
// Nothing visible
}
- function filterCandidateImports(statements) {
+ function transformAndReplaceLatePaintedStatements(statements) {
// This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during
// error handling which must now be included in the output and themselves checked for errors.
// For example:
@@ -71598,62 +72217,45 @@ var ts;
// In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must
// be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of
// dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
- var unconsideredStatements = [];
while (ts.length(lateMarkedStatements)) {
var i = lateMarkedStatements.shift();
- if ((ts.isSourceFile(i.parent) ? i.parent : i.parent.parent) !== enclosingDeclaration) { // Filter to only declarations in the current scope
- unconsideredStatements.push(i);
- continue;
- }
if (!ts.isLateVisibilityPaintedStatement(i)) {
- return ts.Debug.fail("Late replaced statement was foudn which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind));
- }
- switch (i.kind) {
- case 242 /* ImportEqualsDeclaration */: {
- var result = transformImportEqualsDeclaration(i);
- lateStatementReplacementMap.set("" + ts.getNodeId(i), result);
- break;
- }
- case 243 /* ImportDeclaration */: {
- var result = transformImportDeclaration(i);
- lateStatementReplacementMap.set("" + ts.getNodeId(i), result);
- break;
- }
- case 213 /* VariableStatement */: {
- var result = transformVariableStatement(i, /*privateDeclaration*/ true); // Transform the statement (potentially again, possibly revealing more sub-nodes)
- lateStatementReplacementMap.set("" + ts.getNodeId(i), result);
- break;
- }
- default: ts.Debug.assertNever(i, "Unhandled late painted statement!");
+ return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind));
}
+ var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true);
+ lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result);
}
- // Filtering available imports is the last thing done within a scope, so the possible set becomes those which could not
- // be considered in the child scope
- lateMarkedStatements = unconsideredStatements;
// And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list
// (and remove them from the set to examine for outter declarations)
return ts.visitNodes(statements, visitLateVisibilityMarkedStatements);
- }
- function visitLateVisibilityMarkedStatements(statement) {
- if (ts.isLateVisibilityPaintedStatement(statement)) {
- var key = "" + ts.getNodeId(statement);
- if (lateStatementReplacementMap.has(key)) {
- var result = lateStatementReplacementMap.get(key);
- lateStatementReplacementMap.delete(key);
- if (result && ts.isSourceFile(statement.parent) && !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */)) {
- // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
- needsScopeFixMarker = true;
+ function visitLateVisibilityMarkedStatements(statement) {
+ if (ts.isLateVisibilityPaintedStatement(statement)) {
+ var key = "" + ts.getOriginalNodeId(statement);
+ if (lateStatementReplacementMap.has(key)) {
+ var result = lateStatementReplacementMap.get(key);
+ lateStatementReplacementMap.delete(key);
+ if (result && ts.isSourceFile(statement.parent)) {
+ if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) {
+ // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
+ needsScopeFixMarker = true;
+ }
+ if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) {
+ resultHasExternalModuleIndicator = true;
+ }
+ }
+ return result;
}
- return result;
}
- else {
- return ts.getParseTreeNode(statement) ? undefined : statement;
- }
- }
- else {
return statement;
}
}
+ function isExternalModuleIndicator(result) {
+ // Exported top-level member indicates moduleness
+ return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */);
+ }
+ function needsScopeMarker(result) {
+ return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
+ }
function visitDeclarationSubtree(input) {
if (shouldStripInternal(input))
return;
@@ -71851,13 +72453,21 @@ var ts;
return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
}
}
- case 242 /* ImportEqualsDeclaration */:
+ }
+ var result = transformTopLevelDeclaration(input);
+ // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass
+ lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result);
+ return input;
+ }
+ function transformTopLevelDeclaration(input, isPrivate) {
+ if (shouldStripInternal(input))
+ return;
+ switch (input.kind) {
+ case 242 /* ImportEqualsDeclaration */: {
+ return transformImportEqualsDeclaration(input);
+ }
case 243 /* ImportDeclaration */: {
- // Different parts of the import may be marked visible at different times (via visibility checking), so we defer our first look until later
- // to reduce the likelihood we need to rewrite it
- lateMarkedStatements = lateMarkedStatements || [];
- ts.pushIfUnique(lateMarkedStatements, input);
- return input;
+ return transformImportDeclaration(input);
}
}
if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input))
@@ -71870,52 +72480,53 @@ var ts;
previousEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = input;
}
- var previousNeedsDeclare;
var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
var oldDiag = getSymbolAccessibilityDiagnostic;
if (canProdiceDiagnostic) {
getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
}
- var oldPossibleImports;
+ var previousNeedsDeclare = needsDeclare;
switch (input.kind) {
case 236 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all
return cleanup(ts.updateTypeAliasDeclaration(input,
- /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
+ /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
case 235 /* InterfaceDeclaration */: {
return cleanup(ts.updateInterfaceDeclaration(input,
- /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
+ /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
}
case 233 /* FunctionDeclaration */: {
// Generators lose their generator-ness, excepting their return type
return cleanup(ts.updateFunctionDeclaration(input,
- /*decorators*/ undefined, ensureModifiers(input),
+ /*decorators*/ undefined, ensureModifiers(input, isPrivate),
/*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type),
/*body*/ undefined));
}
case 238 /* ModuleDeclaration */: {
- previousNeedsDeclare = needsDeclare;
needsDeclare = false;
- oldPossibleImports = lateMarkedStatements;
- lateMarkedStatements = undefined;
var inner = input.body;
if (inner && inner.kind === 239 /* ModuleBlock */) {
var statements = ts.visitNodes(inner.statements, visitDeclarationStatements);
- var body = ts.updateModuleBlock(inner, filterCandidateImports(statements));
+ var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements));
needsDeclare = previousNeedsDeclare;
- var mods = ensureModifiers(input);
+ var mods = ensureModifiers(input, isPrivate);
return cleanup(ts.updateModuleDeclaration(input,
/*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body));
}
else {
needsDeclare = previousNeedsDeclare;
- var mods = ensureModifiers(input);
+ var mods = ensureModifiers(input, isPrivate);
needsDeclare = false;
+ ts.visitNode(inner, visitDeclarationStatements);
+ // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
+ var id = "" + ts.getOriginalNodeId(inner);
+ var body = lateStatementReplacementMap.get(id);
+ lateStatementReplacementMap.delete(id);
return cleanup(ts.updateModuleDeclaration(input,
- /*decorators*/ undefined, mods, input.name, ts.visitNode(inner, visitDeclarationStatements)));
+ /*decorators*/ undefined, mods, input.name, body));
}
}
case 234 /* ClassDeclaration */: {
- var modifiers = ts.createNodeArray(ensureModifiers(input));
+ var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate));
var typeParameters = ensureTypeParams(input, input.typeParameters);
var ctor = ts.getFirstConstructorWithBody(input);
var parameterProperties = void 0;
@@ -71985,12 +72596,10 @@ var ts;
}
}
case 213 /* VariableStatement */: {
- var result = transformVariableStatement(input);
- lateStatementReplacementMap.set("" + ts.getNodeId(input), result); // Don't actually elide yet; just leave as original node - will be elided/swapped by late pass
- return cleanup(input);
+ return cleanup(transformVariableStatement(input, isPrivate));
}
case 237 /* EnumDeclaration */: {
- return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) {
+ return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) {
if (shouldStripInternal(m))
return;
// Rewrite enum values to their constants, if available
@@ -72001,27 +72610,20 @@ var ts;
}
// Anything left unhandled is an error, so this should be unreachable
return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]);
- function cleanup(returnValue) {
+ function cleanup(node) {
if (isEnclosingDeclaration(input)) {
enclosingDeclaration = previousEnclosingDeclaration;
}
- if (input.kind === 238 /* ModuleDeclaration */) {
- needsDeclare = previousNeedsDeclare;
- lateMarkedStatements = ts.concatenate(oldPossibleImports, lateMarkedStatements);
- }
if (canProdiceDiagnostic) {
getSymbolAccessibilityDiagnostic = oldDiag;
}
- if (returnValue && (!ts.isLateVisibilityPaintedStatement(input) || lateStatementReplacementMap.get("" + ts.getNodeId(input)))) {
- if (!resultHasExternalModuleIndicator && ts.hasModifier(input, 1 /* Export */) && ts.isSourceFile(input.parent)) {
- // Exported top-level member indicates moduleness
- resultHasExternalModuleIndicator = true;
- }
+ if (input.kind === 238 /* ModuleDeclaration */) {
+ needsDeclare = previousNeedsDeclare;
}
- if (returnValue === input) {
- return returnValue;
+ if (node === input) {
+ return node;
}
- return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input);
+ return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
}
}
function transformVariableStatement(input, privateDeclaration) {
@@ -72098,7 +72700,7 @@ var ts;
return maskModifierFlags(node, mask, additions);
}
function ensureAccessor(node) {
- var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
+ var accessors = resolver.getAllAccessorDeclarations(node);
if (node.kind !== accessors.firstAccessor.kind) {
return;
}
@@ -72287,7 +72889,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(300 /* Count */);
+ var enabledSyntaxKindFeatures = new Array(302 /* Count */);
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
@@ -72782,7 +73384,7 @@ var ts;
source = undefined;
if (source)
setSourceFile(source);
- if (node.kind !== 295 /* NotEmittedStatement */
+ if (node.kind !== 297 /* NotEmittedStatement */
&& (emitFlags & 16 /* NoLeadingSourceMap */) === 0
&& pos >= 0) {
emitPos(skipSourceTrivia(pos));
@@ -72799,7 +73401,7 @@ var ts;
}
if (source)
setSourceFile(source);
- if (node.kind !== 295 /* NotEmittedStatement */
+ if (node.kind !== 297 /* NotEmittedStatement */
&& (emitFlags & 32 /* NoTrailingSourceMap */) === 0
&& end >= 0) {
emitPos(end);
@@ -72975,7 +73577,7 @@ var ts;
if (extendedDiagnostics) {
ts.performance.mark("preEmitNodeWithComment");
}
- var isEmittedNode = node.kind !== 295 /* NotEmittedStatement */;
+ var isEmittedNode = node.kind !== 297 /* 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 === 10 /* JsxText */;
@@ -73299,6 +73901,7 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
+ var infoExtension = ".tsbundleinfo";
var brackets = createBracketsMap();
/*@internal*/
/**
@@ -73315,7 +73918,7 @@ var ts;
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
if (sourceFiles.length) {
- var bundle = ts.createBundle(sourceFiles);
+ var bundle = ts.createBundle(sourceFiles, host.getPrependNodes());
var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
if (result) {
return result;
@@ -73341,7 +73944,8 @@ var ts;
var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined;
var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath };
+ var bundleInfoPath = options.references && jsFilePath && (ts.removeFileExtension(jsFilePath) + infoExtension);
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath };
}
else {
var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options));
@@ -73350,17 +73954,27 @@ var ts;
var isJs = ts.isSourceFileJavaScript(sourceFile);
var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath };
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: 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
+ /* @internal */
function getOutputExtension(sourceFile, options) {
+ if (ts.isJsonSourceFile(sourceFile)) {
+ return ".json" /* Json */;
+ }
if (options.jsx === 1 /* Preserve */) {
if (ts.isSourceFileJavaScript(sourceFile)) {
if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) {
@@ -73374,9 +73988,10 @@ var ts;
}
return ".js" /* Js */;
}
+ 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) {
+ function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) {
var compilerOptions = host.getCompilerOptions();
var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
@@ -73390,6 +74005,7 @@ var ts;
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
});
+ var bundleInfo = createDefaultBundleInfo();
var emitSkipped = false;
// Emit each output file
ts.performance.mark("beforePrint");
@@ -73402,8 +74018,8 @@ var ts;
sourceMaps: sourceMapDataList
};
function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
- var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
- emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
+ var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath;
+ emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
@@ -73415,10 +74031,12 @@ var ts;
if (declarationFilePath) {
emittedFilesList.push(declarationFilePath);
}
+ if (bundleInfoPath) {
+ emittedFilesList.push(bundleInfoPath);
+ }
}
}
- function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) {
- var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
+ function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) {
// Make sure not to write js file and source map file if any of them cannot be written
if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) {
emitSkipped = true;
@@ -73428,7 +74046,7 @@ var ts;
return;
}
// Transform the source files
- var transform = ts.transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, /*allowDtsFiles*/ false);
+ var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false);
// Create a printer to print the nodes
var printer = createPrinter(__assign({}, compilerOptions, { noEmitHelpers: compilerOptions.noEmitHelpers }), {
// resolver hooks
@@ -73443,7 +74061,8 @@ var ts;
// emitter hooks
onSetSourceFile: setSourceFile,
});
- printSourceFileOrBundle(jsFilePath, sourceMapFilePath, ts.isSourceFile(sourceFileOrBundle) ? transform.transformed[0] : ts.createBundle(transform.transformed), printer, sourceMap);
+ ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap);
// Clean up emit nodes on parse tree
transform.dispose();
}
@@ -73454,8 +74073,8 @@ var ts;
var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
// Setup and perform the transformation to retrieve declarations from the input files
var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript);
- var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles)] : nonJsFiles;
- var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, [ts.transformDeclarations], /*allowDtsFiles*/ false);
+ var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles;
+ var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), /*allowDtsFiles*/ false);
if (ts.length(declarationTransform.diagnostics)) {
for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) {
var diagnostic = _b[_a];
@@ -73477,17 +74096,18 @@ var ts;
var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
emitSkipped = emitSkipped || declBlocked;
if (!declBlocked || emitOnlyDtsFiles) {
- printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, declarationSourceMap);
+ 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, declarationSourceMap);
}
declarationTransform.dispose();
}
- function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapRecorder) {
+ function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) {
var bundle = sourceFileOrBundle.kind === 274 /* Bundle */ ? sourceFileOrBundle : undefined;
var sourceFile = sourceFileOrBundle.kind === 273 /* SourceFile */ ? sourceFileOrBundle : undefined;
var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList);
if (bundle) {
- printer.writeBundle(bundle, writer);
+ printer.writeBundle(bundle, writer, bundleInfo);
}
else {
printer.writeFile(sourceFile, writer);
@@ -73503,9 +74123,15 @@ 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
mapRecorder.reset();
writer.clear();
+ bundleInfo = createDefaultBundleInfo();
}
function setSourceFile(node) {
sourceMap.setSourceFile(node);
@@ -73515,6 +74141,13 @@ var ts;
}
}
ts.emitFiles = emitFiles;
+ var PipelinePhase;
+ (function (PipelinePhase) {
+ PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
+ PipelinePhase[PipelinePhase["Comments"] = 1] = "Comments";
+ PipelinePhase[PipelinePhase["SourceMaps"] = 2] = "SourceMaps";
+ PipelinePhase[PipelinePhase["Emit"] = 3] = "Emit";
+ })(PipelinePhase || (PipelinePhase = {}));
function createPrinter(printerOptions, handlers) {
if (printerOptions === void 0) { printerOptions = {}; }
if (handlers === void 0) { handlers = {}; }
@@ -73572,6 +74205,7 @@ var ts;
switch (node.kind) {
case 273 /* SourceFile */: return printFile(node);
case 274 /* Bundle */: return printBundle(node);
+ case 275 /* UnparsedSource */: return printUnparsedSource(node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
@@ -73588,6 +74222,10 @@ var ts;
writeFile(sourceFile, beginPrint());
return endPrint();
}
+ function printUnparsedSource(unparsed) {
+ writeUnparsedSource(unparsed, beginPrint());
+ return endPrint();
+ }
function writeNode(hint, node, sourceFile, output) {
var previousWriter = writer;
setWriter(output);
@@ -73605,7 +74243,7 @@ var ts;
reset();
writer = previousWriter;
}
- function writeBundle(bundle, output) {
+ function writeBundle(bundle, output, bundleInfo) {
isOwnFileEmit = false;
var previousWriter = writer;
setWriter(output);
@@ -73613,13 +74251,28 @@ var ts;
emitPrologueDirectivesIfNeeded(bundle);
emitHelpers(bundle);
emitSyntheticTripleSlashReferencesIfNeeded(bundle);
- for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
+ writeLine();
+ }
+ if (bundleInfo) {
+ bundleInfo.originalOffset = writer.getTextPos();
+ }
+ for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
print(0 /* SourceFile */, sourceFile, sourceFile);
}
reset();
writer = previousWriter;
}
+ function writeUnparsedSource(unparsed, output) {
+ var previousWriter = writer;
+ setWriter(output);
+ print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined);
+ reset();
+ writer = previousWriter;
+ }
function writeFile(sourceFile, output) {
isOwnFileEmit = true;
var previousWriter = writer;
@@ -73642,7 +74295,8 @@ var ts;
if (sourceFile) {
setSourceFile(sourceFile);
}
- pipelineEmitWithNotification(hint, node);
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, hint);
+ pipelinePhase(hint, node);
}
function setSourceFile(sourceFile) {
currentSourceFile = sourceFile;
@@ -73665,417 +74319,422 @@ var ts;
comments.reset();
setWriter(/*output*/ undefined);
}
- // TODO: Should this just be `emit`?
- // See https://github.com/Microsoft/TypeScript/pull/18284#discussion_r137611034
- function emitIfPresent(node) {
- if (node) {
- emit(node);
- }
- }
function emit(node) {
- pipelineEmitWithNotification(4 /* Unspecified */, node);
+ if (!node)
+ return;
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, 4 /* Unspecified */);
+ pipelinePhase(4 /* Unspecified */, node);
}
function emitIdentifierName(node) {
- pipelineEmitWithNotification(2 /* IdentifierName */, node);
+ if (!node)
+ return;
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, 2 /* IdentifierName */);
+ pipelinePhase(2 /* IdentifierName */, node);
}
function emitExpression(node) {
- pipelineEmitWithNotification(1 /* Expression */, node);
+ if (!node)
+ return;
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */);
+ pipelinePhase(1 /* Expression */, node);
+ }
+ function getPipelinePhase(phase, hint) {
+ switch (phase) {
+ case 0 /* Notification */:
+ if (onEmitNode) {
+ return pipelineEmitWithNotification;
+ }
+ // falls through
+ case 1 /* Comments */:
+ if (emitNodeWithComments && hint !== 0 /* SourceFile */) {
+ return pipelineEmitWithComments;
+ }
+ return pipelineEmitWithoutComments;
+ case 2 /* SourceMaps */:
+ if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) {
+ return pipelineEmitWithSourceMap;
+ }
+ // falls through
+ case 3 /* Emit */:
+ return pipelineEmitWithHint;
+ default:
+ return ts.Debug.assertNever(phase, "Unexpected value for PipelinePhase: " + phase);
+ }
+ }
+ function getNextPipelinePhase(currentPhase, hint) {
+ return getPipelinePhase(currentPhase + 1, hint);
}
function pipelineEmitWithNotification(hint, node) {
- if (onEmitNode) {
- onEmitNode(hint, node, pipelineEmitWithComments);
- }
- else {
- pipelineEmitWithComments(hint, node);
- }
+ ts.Debug.assertDefined(onEmitNode);
+ onEmitNode(hint, node, getNextPipelinePhase(0 /* Notification */, hint));
}
function pipelineEmitWithComments(hint, node) {
- node = trySubstituteNode(hint, node);
- if (emitNodeWithComments && hint !== 0 /* SourceFile */) {
- emitNodeWithComments(hint, node, pipelineEmitWithSourceMap);
- }
- else {
- pipelineEmitWithSourceMap(hint, node);
- }
+ ts.Debug.assertDefined(emitNodeWithComments);
+ ts.Debug.assert(hint !== 0 /* SourceFile */);
+ emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(1 /* Comments */, hint));
+ }
+ function pipelineEmitWithoutComments(hint, node) {
+ var pipelinePhase = getNextPipelinePhase(1 /* Comments */, hint);
+ pipelinePhase(hint, trySubstituteNode(hint, node));
}
function pipelineEmitWithSourceMap(hint, node) {
- if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) {
- onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint);
- }
- else {
- pipelineEmitWithHint(hint, node);
- }
+ ts.Debug.assertDefined(onEmitSourceMapOfNode);
+ ts.Debug.assert(hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */);
+ onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint);
}
function pipelineEmitWithHint(hint, node) {
- switch (hint) {
- case 0 /* SourceFile */: return pipelineEmitSourceFile(node);
- case 2 /* IdentifierName */: return pipelineEmitIdentifierName(node);
- case 1 /* Expression */: return pipelineEmitExpression(node);
- case 3 /* MappedTypeParameter */: return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
- case 4 /* Unspecified */: return pipelineEmitUnspecified(node);
+ if (hint === 0 /* SourceFile */)
+ return emitSourceFile(ts.cast(node, ts.isSourceFile));
+ if (hint === 2 /* IdentifierName */)
+ return emitIdentifier(ts.cast(node, ts.isIdentifier));
+ if (hint === 3 /* MappedTypeParameter */)
+ return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
+ if (hint === 4 /* Unspecified */) {
+ if (ts.isKeyword(node.kind))
+ return writeTokenNode(node, writeKeyword);
+ switch (node.kind) {
+ // Pseudo-literals
+ case 14 /* TemplateHead */:
+ case 15 /* TemplateMiddle */:
+ case 16 /* TemplateTail */:
+ return emitLiteral(node);
+ case 275 /* UnparsedSource */:
+ return emitUnparsedSource(node);
+ // Identifiers
+ case 71 /* Identifier */:
+ return emitIdentifier(node);
+ // Parse tree nodes
+ // Names
+ case 145 /* QualifiedName */:
+ return emitQualifiedName(node);
+ case 146 /* ComputedPropertyName */:
+ return emitComputedPropertyName(node);
+ // Signature elements
+ case 147 /* TypeParameter */:
+ return emitTypeParameter(node);
+ case 148 /* Parameter */:
+ return emitParameter(node);
+ case 149 /* Decorator */:
+ return emitDecorator(node);
+ // Type members
+ case 150 /* PropertySignature */:
+ return emitPropertySignature(node);
+ case 151 /* PropertyDeclaration */:
+ return emitPropertyDeclaration(node);
+ case 152 /* MethodSignature */:
+ return emitMethodSignature(node);
+ case 153 /* MethodDeclaration */:
+ return emitMethodDeclaration(node);
+ case 154 /* Constructor */:
+ return emitConstructor(node);
+ case 155 /* GetAccessor */:
+ case 156 /* SetAccessor */:
+ return emitAccessorDeclaration(node);
+ case 157 /* CallSignature */:
+ return emitCallSignature(node);
+ case 158 /* ConstructSignature */:
+ return emitConstructSignature(node);
+ case 159 /* IndexSignature */:
+ return emitIndexSignature(node);
+ // Types
+ case 160 /* TypePredicate */:
+ return emitTypePredicate(node);
+ case 161 /* TypeReference */:
+ return emitTypeReference(node);
+ case 162 /* FunctionType */:
+ return emitFunctionType(node);
+ case 283 /* JSDocFunctionType */:
+ return emitJSDocFunctionType(node);
+ case 163 /* ConstructorType */:
+ return emitConstructorType(node);
+ case 164 /* TypeQuery */:
+ return emitTypeQuery(node);
+ case 165 /* TypeLiteral */:
+ return emitTypeLiteral(node);
+ case 166 /* ArrayType */:
+ return emitArrayType(node);
+ case 167 /* TupleType */:
+ return emitTupleType(node);
+ case 168 /* UnionType */:
+ return emitUnionType(node);
+ case 169 /* IntersectionType */:
+ return emitIntersectionType(node);
+ case 170 /* ConditionalType */:
+ return emitConditionalType(node);
+ case 171 /* InferType */:
+ return emitInferType(node);
+ case 172 /* ParenthesizedType */:
+ return emitParenthesizedType(node);
+ case 206 /* ExpressionWithTypeArguments */:
+ return emitExpressionWithTypeArguments(node);
+ case 173 /* ThisType */:
+ return emitThisType();
+ case 174 /* TypeOperator */:
+ return emitTypeOperator(node);
+ case 175 /* IndexedAccessType */:
+ return emitIndexedAccessType(node);
+ case 176 /* MappedType */:
+ return emitMappedType(node);
+ case 177 /* LiteralType */:
+ return emitLiteralType(node);
+ case 178 /* ImportType */:
+ return emitImportTypeNode(node);
+ case 278 /* JSDocAllType */:
+ write("*");
+ return;
+ case 279 /* JSDocUnknownType */:
+ write("?");
+ return;
+ case 280 /* JSDocNullableType */:
+ return emitJSDocNullableType(node);
+ case 281 /* JSDocNonNullableType */:
+ return emitJSDocNonNullableType(node);
+ case 282 /* JSDocOptionalType */:
+ return emitJSDocOptionalType(node);
+ case 284 /* JSDocVariadicType */:
+ return emitJSDocVariadicType(node);
+ // Binding patterns
+ case 179 /* ObjectBindingPattern */:
+ return emitObjectBindingPattern(node);
+ case 180 /* ArrayBindingPattern */:
+ return emitArrayBindingPattern(node);
+ case 181 /* BindingElement */:
+ return emitBindingElement(node);
+ // Misc
+ case 210 /* TemplateSpan */:
+ return emitTemplateSpan(node);
+ case 211 /* SemicolonClassElement */:
+ return emitSemicolonClassElement();
+ // Statements
+ case 212 /* Block */:
+ return emitBlock(node);
+ case 213 /* VariableStatement */:
+ return emitVariableStatement(node);
+ case 214 /* EmptyStatement */:
+ return emitEmptyStatement();
+ case 215 /* ExpressionStatement */:
+ return emitExpressionStatement(node);
+ case 216 /* IfStatement */:
+ return emitIfStatement(node);
+ case 217 /* DoStatement */:
+ return emitDoStatement(node);
+ case 218 /* WhileStatement */:
+ return emitWhileStatement(node);
+ case 219 /* ForStatement */:
+ return emitForStatement(node);
+ case 220 /* ForInStatement */:
+ return emitForInStatement(node);
+ case 221 /* ForOfStatement */:
+ return emitForOfStatement(node);
+ case 222 /* ContinueStatement */:
+ return emitContinueStatement(node);
+ case 223 /* BreakStatement */:
+ return emitBreakStatement(node);
+ case 224 /* ReturnStatement */:
+ return emitReturnStatement(node);
+ case 225 /* WithStatement */:
+ return emitWithStatement(node);
+ case 226 /* SwitchStatement */:
+ return emitSwitchStatement(node);
+ case 227 /* LabeledStatement */:
+ return emitLabeledStatement(node);
+ case 228 /* ThrowStatement */:
+ return emitThrowStatement(node);
+ case 229 /* TryStatement */:
+ return emitTryStatement(node);
+ case 230 /* DebuggerStatement */:
+ return emitDebuggerStatement(node);
+ // Declarations
+ case 231 /* VariableDeclaration */:
+ return emitVariableDeclaration(node);
+ case 232 /* VariableDeclarationList */:
+ return emitVariableDeclarationList(node);
+ case 233 /* FunctionDeclaration */:
+ return emitFunctionDeclaration(node);
+ case 234 /* ClassDeclaration */:
+ return emitClassDeclaration(node);
+ case 235 /* InterfaceDeclaration */:
+ return emitInterfaceDeclaration(node);
+ case 236 /* TypeAliasDeclaration */:
+ return emitTypeAliasDeclaration(node);
+ case 237 /* EnumDeclaration */:
+ return emitEnumDeclaration(node);
+ case 238 /* ModuleDeclaration */:
+ return emitModuleDeclaration(node);
+ case 239 /* ModuleBlock */:
+ return emitModuleBlock(node);
+ case 240 /* CaseBlock */:
+ return emitCaseBlock(node);
+ case 241 /* NamespaceExportDeclaration */:
+ return emitNamespaceExportDeclaration(node);
+ case 242 /* ImportEqualsDeclaration */:
+ return emitImportEqualsDeclaration(node);
+ case 243 /* ImportDeclaration */:
+ return emitImportDeclaration(node);
+ case 244 /* ImportClause */:
+ return emitImportClause(node);
+ case 245 /* NamespaceImport */:
+ return emitNamespaceImport(node);
+ case 246 /* NamedImports */:
+ return emitNamedImports(node);
+ case 247 /* ImportSpecifier */:
+ return emitImportSpecifier(node);
+ case 248 /* ExportAssignment */:
+ return emitExportAssignment(node);
+ case 249 /* ExportDeclaration */:
+ return emitExportDeclaration(node);
+ case 250 /* NamedExports */:
+ return emitNamedExports(node);
+ case 251 /* ExportSpecifier */:
+ return emitExportSpecifier(node);
+ case 252 /* MissingDeclaration */:
+ return;
+ // Module references
+ case 253 /* ExternalModuleReference */:
+ return emitExternalModuleReference(node);
+ // JSX (non-expression)
+ case 10 /* JsxText */:
+ return emitJsxText(node);
+ case 256 /* JsxOpeningElement */:
+ case 259 /* JsxOpeningFragment */:
+ return emitJsxOpeningElementOrFragment(node);
+ case 257 /* JsxClosingElement */:
+ case 260 /* JsxClosingFragment */:
+ return emitJsxClosingElementOrFragment(node);
+ case 261 /* JsxAttribute */:
+ return emitJsxAttribute(node);
+ case 262 /* JsxAttributes */:
+ return emitJsxAttributes(node);
+ case 263 /* JsxSpreadAttribute */:
+ return emitJsxSpreadAttribute(node);
+ case 264 /* JsxExpression */:
+ return emitJsxExpression(node);
+ // Clauses
+ case 265 /* CaseClause */:
+ return emitCaseClause(node);
+ case 266 /* DefaultClause */:
+ return emitDefaultClause(node);
+ case 267 /* HeritageClause */:
+ return emitHeritageClause(node);
+ case 268 /* CatchClause */:
+ return emitCatchClause(node);
+ // Property assignments
+ case 269 /* PropertyAssignment */:
+ return emitPropertyAssignment(node);
+ case 270 /* ShorthandPropertyAssignment */:
+ return emitShorthandPropertyAssignment(node);
+ case 271 /* SpreadAssignment */:
+ return emitSpreadAssignment(node);
+ // Enum
+ case 272 /* EnumMember */:
+ return emitEnumMember(node);
+ // JSDoc nodes (ignored)
+ // Transformation nodes (ignored)
+ }
+ if (ts.isExpression(node)) {
+ hint = 1 /* Expression */;
+ node = trySubstituteNode(1 /* Expression */, node);
+ }
+ else if (ts.isToken(node)) {
+ return writeTokenNode(node, writePunctuation);
+ }
+ }
+ if (hint === 1 /* Expression */) {
+ switch (node.kind) {
+ // Literals
+ case 8 /* NumericLiteral */:
+ return emitNumericLiteral(node);
+ case 9 /* StringLiteral */:
+ case 12 /* RegularExpressionLiteral */:
+ case 13 /* NoSubstitutionTemplateLiteral */:
+ return emitLiteral(node);
+ // Identifiers
+ case 71 /* Identifier */:
+ return emitIdentifier(node);
+ // Reserved words
+ case 86 /* FalseKeyword */:
+ case 95 /* NullKeyword */:
+ case 97 /* SuperKeyword */:
+ case 101 /* TrueKeyword */:
+ case 99 /* ThisKeyword */:
+ case 91 /* ImportKeyword */:
+ writeTokenNode(node, writeKeyword);
+ return;
+ // Expressions
+ case 182 /* ArrayLiteralExpression */:
+ return emitArrayLiteralExpression(node);
+ case 183 /* ObjectLiteralExpression */:
+ return emitObjectLiteralExpression(node);
+ case 184 /* PropertyAccessExpression */:
+ return emitPropertyAccessExpression(node);
+ case 185 /* ElementAccessExpression */:
+ return emitElementAccessExpression(node);
+ case 186 /* CallExpression */:
+ return emitCallExpression(node);
+ case 187 /* NewExpression */:
+ return emitNewExpression(node);
+ case 188 /* TaggedTemplateExpression */:
+ return emitTaggedTemplateExpression(node);
+ case 189 /* TypeAssertionExpression */:
+ return emitTypeAssertionExpression(node);
+ case 190 /* ParenthesizedExpression */:
+ return emitParenthesizedExpression(node);
+ case 191 /* FunctionExpression */:
+ return emitFunctionExpression(node);
+ case 192 /* ArrowFunction */:
+ return emitArrowFunction(node);
+ case 193 /* DeleteExpression */:
+ return emitDeleteExpression(node);
+ case 194 /* TypeOfExpression */:
+ return emitTypeOfExpression(node);
+ case 195 /* VoidExpression */:
+ return emitVoidExpression(node);
+ case 196 /* AwaitExpression */:
+ return emitAwaitExpression(node);
+ case 197 /* PrefixUnaryExpression */:
+ return emitPrefixUnaryExpression(node);
+ case 198 /* PostfixUnaryExpression */:
+ return emitPostfixUnaryExpression(node);
+ case 199 /* BinaryExpression */:
+ return emitBinaryExpression(node);
+ case 200 /* ConditionalExpression */:
+ return emitConditionalExpression(node);
+ case 201 /* TemplateExpression */:
+ return emitTemplateExpression(node);
+ case 202 /* YieldExpression */:
+ return emitYieldExpression(node);
+ case 203 /* SpreadElement */:
+ return emitSpreadExpression(node);
+ case 204 /* ClassExpression */:
+ return emitClassExpression(node);
+ case 205 /* OmittedExpression */:
+ return;
+ case 207 /* AsExpression */:
+ return emitAsExpression(node);
+ case 208 /* NonNullExpression */:
+ return emitNonNullExpression(node);
+ case 209 /* MetaProperty */:
+ return emitMetaProperty(node);
+ // JSX
+ case 254 /* JsxElement */:
+ return emitJsxElement(node);
+ case 255 /* JsxSelfClosingElement */:
+ return emitJsxSelfClosingElement(node);
+ case 258 /* JsxFragment */:
+ return emitJsxFragment(node);
+ // Transformation nodes
+ case 298 /* PartiallyEmittedExpression */:
+ return emitPartiallyEmittedExpression(node);
+ case 299 /* CommaListExpression */:
+ return emitCommaList(node);
+ }
}
- }
- function pipelineEmitSourceFile(node) {
- ts.Debug.assertNode(node, ts.isSourceFile);
- emitSourceFile(node);
- }
- function pipelineEmitIdentifierName(node) {
- ts.Debug.assertNode(node, ts.isIdentifier);
- emitIdentifier(node);
}
function emitMappedTypeParameter(node) {
emit(node.name);
writeSpace();
writeKeyword("in");
writeSpace();
- emitIfPresent(node.constraint);
- }
- function pipelineEmitUnspecified(node) {
- var kind = node.kind;
- // Reserved words
- // Strict mode reserved words
- // Contextual keywords
- if (ts.isKeyword(kind)) {
- writeTokenNode(node, writeKeyword);
- return;
- }
- switch (kind) {
- // Pseudo-literals
- case 14 /* TemplateHead */:
- case 15 /* TemplateMiddle */:
- case 16 /* TemplateTail */:
- return emitLiteral(node);
- // Identifiers
- case 71 /* Identifier */:
- return emitIdentifier(node);
- // Parse tree nodes
- // Names
- case 145 /* QualifiedName */:
- return emitQualifiedName(node);
- case 146 /* ComputedPropertyName */:
- return emitComputedPropertyName(node);
- // Signature elements
- case 147 /* TypeParameter */:
- return emitTypeParameter(node);
- case 148 /* Parameter */:
- return emitParameter(node);
- case 149 /* Decorator */:
- return emitDecorator(node);
- // Type members
- case 150 /* PropertySignature */:
- return emitPropertySignature(node);
- case 151 /* PropertyDeclaration */:
- return emitPropertyDeclaration(node);
- case 152 /* MethodSignature */:
- return emitMethodSignature(node);
- case 153 /* MethodDeclaration */:
- return emitMethodDeclaration(node);
- case 154 /* Constructor */:
- return emitConstructor(node);
- case 155 /* GetAccessor */:
- case 156 /* SetAccessor */:
- return emitAccessorDeclaration(node);
- case 157 /* CallSignature */:
- return emitCallSignature(node);
- case 158 /* ConstructSignature */:
- return emitConstructSignature(node);
- case 159 /* IndexSignature */:
- return emitIndexSignature(node);
- // Types
- case 160 /* TypePredicate */:
- return emitTypePredicate(node);
- case 161 /* TypeReference */:
- return emitTypeReference(node);
- case 162 /* FunctionType */:
- return emitFunctionType(node);
- case 281 /* JSDocFunctionType */:
- return emitJSDocFunctionType(node);
- case 163 /* ConstructorType */:
- return emitConstructorType(node);
- case 164 /* TypeQuery */:
- return emitTypeQuery(node);
- case 165 /* TypeLiteral */:
- return emitTypeLiteral(node);
- case 166 /* ArrayType */:
- return emitArrayType(node);
- case 167 /* TupleType */:
- return emitTupleType(node);
- case 168 /* UnionType */:
- return emitUnionType(node);
- case 169 /* IntersectionType */:
- return emitIntersectionType(node);
- case 170 /* ConditionalType */:
- return emitConditionalType(node);
- case 171 /* InferType */:
- return emitInferType(node);
- case 172 /* ParenthesizedType */:
- return emitParenthesizedType(node);
- case 206 /* ExpressionWithTypeArguments */:
- return emitExpressionWithTypeArguments(node);
- case 173 /* ThisType */:
- return emitThisType();
- case 174 /* TypeOperator */:
- return emitTypeOperator(node);
- case 175 /* IndexedAccessType */:
- return emitIndexedAccessType(node);
- case 176 /* MappedType */:
- return emitMappedType(node);
- case 177 /* LiteralType */:
- return emitLiteralType(node);
- case 178 /* ImportType */:
- return emitImportTypeNode(node);
- case 276 /* JSDocAllType */:
- write("*");
- return;
- case 277 /* JSDocUnknownType */:
- write("?");
- return;
- case 278 /* JSDocNullableType */:
- return emitJSDocNullableType(node);
- case 279 /* JSDocNonNullableType */:
- return emitJSDocNonNullableType(node);
- case 280 /* JSDocOptionalType */:
- return emitJSDocOptionalType(node);
- case 282 /* JSDocVariadicType */:
- return emitJSDocVariadicType(node);
- // Binding patterns
- case 179 /* ObjectBindingPattern */:
- return emitObjectBindingPattern(node);
- case 180 /* ArrayBindingPattern */:
- return emitArrayBindingPattern(node);
- case 181 /* BindingElement */:
- return emitBindingElement(node);
- // Misc
- case 210 /* TemplateSpan */:
- return emitTemplateSpan(node);
- case 211 /* SemicolonClassElement */:
- return emitSemicolonClassElement();
- // Statements
- case 212 /* Block */:
- return emitBlock(node);
- case 213 /* VariableStatement */:
- return emitVariableStatement(node);
- case 214 /* EmptyStatement */:
- return emitEmptyStatement();
- case 215 /* ExpressionStatement */:
- return emitExpressionStatement(node);
- case 216 /* IfStatement */:
- return emitIfStatement(node);
- case 217 /* DoStatement */:
- return emitDoStatement(node);
- case 218 /* WhileStatement */:
- return emitWhileStatement(node);
- case 219 /* ForStatement */:
- return emitForStatement(node);
- case 220 /* ForInStatement */:
- return emitForInStatement(node);
- case 221 /* ForOfStatement */:
- return emitForOfStatement(node);
- case 222 /* ContinueStatement */:
- return emitContinueStatement(node);
- case 223 /* BreakStatement */:
- return emitBreakStatement(node);
- case 224 /* ReturnStatement */:
- return emitReturnStatement(node);
- case 225 /* WithStatement */:
- return emitWithStatement(node);
- case 226 /* SwitchStatement */:
- return emitSwitchStatement(node);
- case 227 /* LabeledStatement */:
- return emitLabeledStatement(node);
- case 228 /* ThrowStatement */:
- return emitThrowStatement(node);
- case 229 /* TryStatement */:
- return emitTryStatement(node);
- case 230 /* DebuggerStatement */:
- return emitDebuggerStatement(node);
- // Declarations
- case 231 /* VariableDeclaration */:
- return emitVariableDeclaration(node);
- case 232 /* VariableDeclarationList */:
- return emitVariableDeclarationList(node);
- case 233 /* FunctionDeclaration */:
- return emitFunctionDeclaration(node);
- case 234 /* ClassDeclaration */:
- return emitClassDeclaration(node);
- case 235 /* InterfaceDeclaration */:
- return emitInterfaceDeclaration(node);
- case 236 /* TypeAliasDeclaration */:
- return emitTypeAliasDeclaration(node);
- case 237 /* EnumDeclaration */:
- return emitEnumDeclaration(node);
- case 238 /* ModuleDeclaration */:
- return emitModuleDeclaration(node);
- case 239 /* ModuleBlock */:
- return emitModuleBlock(node);
- case 240 /* CaseBlock */:
- return emitCaseBlock(node);
- case 241 /* NamespaceExportDeclaration */:
- return emitNamespaceExportDeclaration(node);
- case 242 /* ImportEqualsDeclaration */:
- return emitImportEqualsDeclaration(node);
- case 243 /* ImportDeclaration */:
- return emitImportDeclaration(node);
- case 244 /* ImportClause */:
- return emitImportClause(node);
- case 245 /* NamespaceImport */:
- return emitNamespaceImport(node);
- case 246 /* NamedImports */:
- return emitNamedImports(node);
- case 247 /* ImportSpecifier */:
- return emitImportSpecifier(node);
- case 248 /* ExportAssignment */:
- return emitExportAssignment(node);
- case 249 /* ExportDeclaration */:
- return emitExportDeclaration(node);
- case 250 /* NamedExports */:
- return emitNamedExports(node);
- case 251 /* ExportSpecifier */:
- return emitExportSpecifier(node);
- case 252 /* MissingDeclaration */:
- return;
- // Module references
- case 253 /* ExternalModuleReference */:
- return emitExternalModuleReference(node);
- // JSX (non-expression)
- case 10 /* JsxText */:
- return emitJsxText(node);
- case 256 /* JsxOpeningElement */:
- case 259 /* JsxOpeningFragment */:
- return emitJsxOpeningElementOrFragment(node);
- case 257 /* JsxClosingElement */:
- case 260 /* JsxClosingFragment */:
- return emitJsxClosingElementOrFragment(node);
- case 261 /* JsxAttribute */:
- return emitJsxAttribute(node);
- case 262 /* JsxAttributes */:
- return emitJsxAttributes(node);
- case 263 /* JsxSpreadAttribute */:
- return emitJsxSpreadAttribute(node);
- case 264 /* JsxExpression */:
- return emitJsxExpression(node);
- // Clauses
- case 265 /* CaseClause */:
- return emitCaseClause(node);
- case 266 /* DefaultClause */:
- return emitDefaultClause(node);
- case 267 /* HeritageClause */:
- return emitHeritageClause(node);
- case 268 /* CatchClause */:
- return emitCatchClause(node);
- // Property assignments
- case 269 /* PropertyAssignment */:
- return emitPropertyAssignment(node);
- case 270 /* ShorthandPropertyAssignment */:
- return emitShorthandPropertyAssignment(node);
- case 271 /* SpreadAssignment */:
- return emitSpreadAssignment(node);
- // Enum
- case 272 /* EnumMember */:
- return emitEnumMember(node);
- // JSDoc nodes (ignored)
- // Transformation nodes (ignored)
- }
- // If the node is an expression, try to emit it as an expression with
- // substitution.
- if (ts.isExpression(node)) {
- return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node));
- }
- if (ts.isToken(node)) {
- writeTokenNode(node, writePunctuation);
- return;
- }
- }
- function pipelineEmitExpression(node) {
- var kind = node.kind;
- switch (kind) {
- // Literals
- case 8 /* NumericLiteral */:
- return emitNumericLiteral(node);
- case 9 /* StringLiteral */:
- case 12 /* RegularExpressionLiteral */:
- case 13 /* NoSubstitutionTemplateLiteral */:
- return emitLiteral(node);
- // Identifiers
- case 71 /* Identifier */:
- return emitIdentifier(node);
- // Reserved words
- case 86 /* FalseKeyword */:
- case 95 /* NullKeyword */:
- case 97 /* SuperKeyword */:
- case 101 /* TrueKeyword */:
- case 99 /* ThisKeyword */:
- case 91 /* ImportKeyword */:
- writeTokenNode(node, writeKeyword);
- return;
- // Expressions
- case 182 /* ArrayLiteralExpression */:
- return emitArrayLiteralExpression(node);
- case 183 /* ObjectLiteralExpression */:
- return emitObjectLiteralExpression(node);
- case 184 /* PropertyAccessExpression */:
- return emitPropertyAccessExpression(node);
- case 185 /* ElementAccessExpression */:
- return emitElementAccessExpression(node);
- case 186 /* CallExpression */:
- return emitCallExpression(node);
- case 187 /* NewExpression */:
- return emitNewExpression(node);
- case 188 /* TaggedTemplateExpression */:
- return emitTaggedTemplateExpression(node);
- case 189 /* TypeAssertionExpression */:
- return emitTypeAssertionExpression(node);
- case 190 /* ParenthesizedExpression */:
- return emitParenthesizedExpression(node);
- case 191 /* FunctionExpression */:
- return emitFunctionExpression(node);
- case 192 /* ArrowFunction */:
- return emitArrowFunction(node);
- case 193 /* DeleteExpression */:
- return emitDeleteExpression(node);
- case 194 /* TypeOfExpression */:
- return emitTypeOfExpression(node);
- case 195 /* VoidExpression */:
- return emitVoidExpression(node);
- case 196 /* AwaitExpression */:
- return emitAwaitExpression(node);
- case 197 /* PrefixUnaryExpression */:
- return emitPrefixUnaryExpression(node);
- case 198 /* PostfixUnaryExpression */:
- return emitPostfixUnaryExpression(node);
- case 199 /* BinaryExpression */:
- return emitBinaryExpression(node);
- case 200 /* ConditionalExpression */:
- return emitConditionalExpression(node);
- case 201 /* TemplateExpression */:
- return emitTemplateExpression(node);
- case 202 /* YieldExpression */:
- return emitYieldExpression(node);
- case 203 /* SpreadElement */:
- return emitSpreadExpression(node);
- case 204 /* ClassExpression */:
- return emitClassExpression(node);
- case 205 /* OmittedExpression */:
- return;
- case 207 /* AsExpression */:
- return emitAsExpression(node);
- case 208 /* NonNullExpression */:
- return emitNonNullExpression(node);
- case 209 /* MetaProperty */:
- return emitMetaProperty(node);
- // JSX
- case 254 /* JsxElement */:
- return emitJsxElement(node);
- case 255 /* JsxSelfClosingElement */:
- return emitJsxSelfClosingElement(node);
- case 258 /* JsxFragment */:
- return emitJsxFragment(node);
- // Transformation nodes
- case 296 /* PartiallyEmittedExpression */:
- return emitPartiallyEmittedExpression(node);
- case 297 /* CommaListExpression */:
- return emitCommaList(node);
- }
+ emit(node.constraint);
}
function trySubstituteNode(hint, node) {
return node && substituteNode && substituteNode(hint, node) || node;
@@ -74151,6 +74810,10 @@ var ts;
writeStringLiteral(text);
}
}
+ // SyntaxKind.UnparsedSource
+ function emitUnparsedSource(unparsed) {
+ write(unparsed.text);
+ }
//
// Identifiers
//
@@ -74201,13 +74864,11 @@ var ts;
function emitParameter(node) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
- emitIfPresent(node.dotDotDotToken);
- if (node.name) {
- emitNodeWithWriter(node.name, writeParameter);
- }
- emitIfPresent(node.questionToken);
- if (node.parent && node.parent.kind === 281 /* JSDocFunctionType */ && !node.name) {
- emitIfPresent(node.type);
+ emit(node.dotDotDotToken);
+ emitNodeWithWriter(node.name, writeParameter);
+ emit(node.questionToken);
+ if (node.parent && node.parent.kind === 283 /* JSDocFunctionType */ && !node.name) {
+ emit(node.type);
}
else {
emitTypeAnnotation(node.type);
@@ -74226,7 +74887,7 @@ var ts;
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emitNodeWithWriter(node.name, writeProperty);
- emitIfPresent(node.questionToken);
+ emit(node.questionToken);
emitTypeAnnotation(node.type);
writeSemicolon();
}
@@ -74234,28 +74895,30 @@ var ts;
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emit(node.name);
- emitIfPresent(node.questionToken);
- emitIfPresent(node.exclamationToken);
+ emit(node.questionToken);
+ emit(node.exclamationToken);
emitTypeAnnotation(node.type);
emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
writeSemicolon();
}
function emitMethodSignature(node) {
+ pushNameGenerationScope(node);
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emit(node.name);
- emitIfPresent(node.questionToken);
+ emit(node.questionToken);
emitTypeParameters(node, node.typeParameters);
emitParameters(node, node.parameters);
emitTypeAnnotation(node.type);
writeSemicolon();
+ popNameGenerationScope(node);
}
function emitMethodDeclaration(node) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
- emitIfPresent(node.asteriskToken);
+ emit(node.asteriskToken);
emit(node.name);
- emitIfPresent(node.questionToken);
+ emit(node.questionToken);
emitSignatureAndBody(node, emitSignatureHead);
}
function emitConstructor(node) {
@@ -74272,14 +74935,17 @@ var ts;
emitSignatureAndBody(node, emitSignatureHead);
}
function emitCallSignature(node) {
+ pushNameGenerationScope(node);
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emitTypeParameters(node, node.typeParameters);
emitParameters(node, node.parameters);
emitTypeAnnotation(node.type);
writeSemicolon();
+ popNameGenerationScope(node);
}
function emitConstructSignature(node) {
+ pushNameGenerationScope(node);
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
writeKeyword("new");
@@ -74288,6 +74954,7 @@ var ts;
emitParameters(node, node.parameters);
emitTypeAnnotation(node.type);
writeSemicolon();
+ popNameGenerationScope(node);
}
function emitIndexSignature(node) {
emitDecorators(node, node.decorators);
@@ -74314,18 +74981,20 @@ var ts;
emitTypeArguments(node, node.typeArguments);
}
function emitFunctionType(node) {
+ pushNameGenerationScope(node);
emitTypeParameters(node, node.typeParameters);
emitParametersForArrow(node, node.parameters);
writeSpace();
writePunctuation("=>");
writeSpace();
- emitIfPresent(node.type);
+ emit(node.type);
+ popNameGenerationScope(node);
}
function emitJSDocFunctionType(node) {
write("function");
emitParameters(node, node.parameters);
write(":");
- emitIfPresent(node.type);
+ emit(node.type);
}
function emitJSDocNullableType(node) {
write("?");
@@ -74340,6 +75009,7 @@ var ts;
write("=");
}
function emitConstructorType(node) {
+ pushNameGenerationScope(node);
writeKeyword("new");
writeSpace();
emitTypeParameters(node, node.typeParameters);
@@ -74347,7 +75017,8 @@ var ts;
writeSpace();
writePunctuation("=>");
writeSpace();
- emitIfPresent(node.type);
+ emit(node.type);
+ popNameGenerationScope(node);
}
function emitTypeQuery(node) {
writeKeyword("typeof");
@@ -74437,7 +75108,8 @@ var ts;
writeSpace();
}
writePunctuation("[");
- pipelineEmitWithNotification(3 /* MappedTypeParameter */, node.typeParameter);
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, 3 /* MappedTypeParameter */);
+ pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter);
writePunctuation("]");
if (node.questionToken) {
emit(node.questionToken);
@@ -74447,7 +75119,7 @@ var ts;
}
writePunctuation(":");
writeSpace();
- emitIfPresent(node.type);
+ emit(node.type);
writeSemicolon();
if (emitFlags & 1 /* SingleLine */) {
writeSpace();
@@ -74490,7 +75162,7 @@ var ts;
writePunctuation("]");
}
function emitBindingElement(node) {
- emitIfPresent(node.dotDotDotToken);
+ emit(node.dotDotDotToken);
if (node.propertyName) {
emit(node.propertyName);
writePunctuation(":");
@@ -74508,6 +75180,7 @@ var ts;
emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine);
}
function emitObjectLiteralExpression(node) {
+ ts.forEach(node.properties, generateMemberNames);
var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
if (indentedFlag) {
increaseIndent();
@@ -74597,6 +75270,7 @@ var ts;
emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
}
function emitFunctionExpression(node) {
+ generateNameIfNeeded(node.name);
emitFunctionDeclarationOrExpression(node);
}
function emitArrowFunction(node) {
@@ -74696,7 +75370,7 @@ var ts;
}
function emitYieldExpression(node) {
emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node);
- emitIfPresent(node.asteriskToken);
+ emit(node.asteriskToken);
emitExpressionWithLeadingSpace(node.expression);
}
function emitSpreadExpression(node) {
@@ -74704,6 +75378,7 @@ var ts;
emitExpression(node.expression);
}
function emitClassExpression(node) {
+ generateNameIfNeeded(node.name);
emitClassDeclarationOrExpression(node);
}
function emitExpressionWithTypeArguments(node) {
@@ -74757,7 +75432,9 @@ var ts;
}
function emitExpressionStatement(node) {
emitExpression(node.expression);
- writeSemicolon();
+ if (!ts.isJsonSourceFile(currentSourceFile)) {
+ writeSemicolon();
+ }
}
function emitIfStatement(node) {
var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node);
@@ -74953,7 +75630,7 @@ var ts;
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
writeKeyword("function");
- emitIfPresent(node.asteriskToken);
+ emit(node.asteriskToken);
writeSpace();
emitIdentifierName(node.name);
emitSignatureAndBody(node, emitSignatureHead);
@@ -74970,6 +75647,8 @@ var ts;
increaseIndent();
}
pushNameGenerationScope(node);
+ ts.forEach(node.parameters, generateNames);
+ generateNames(node.body);
emitSignatureHead(node);
if (onEmitNode) {
onEmitNode(4 /* Unspecified */, body, emitBlockCallback);
@@ -75065,6 +75744,7 @@ var ts;
emitClassDeclarationOrExpression(node);
}
function emitClassDeclarationOrExpression(node) {
+ ts.forEach(node.members, generateMemberNames);
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
writeKeyword("class");
@@ -75142,6 +75822,7 @@ var ts;
}
function emitModuleBlock(node) {
pushNameGenerationScope(node);
+ ts.forEach(node.statements, generateNames);
emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
popNameGenerationScope(node);
}
@@ -75183,12 +75864,12 @@ var ts;
writeSemicolon();
}
function emitImportClause(node) {
- emitIfPresent(node.name);
+ emit(node.name);
if (node.name && node.namedBindings) {
emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node);
writeSpace();
}
- emitIfPresent(node.namedBindings);
+ emit(node.namedBindings);
}
function emitNamespaceImport(node) {
var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node);
@@ -75330,7 +76011,7 @@ var ts;
function emitJsxExpression(node) {
if (node.expression) {
writePunctuation("{");
- emitIfPresent(node.dotDotDotToken);
+ emit(node.dotDotDotToken);
emitExpression(node.expression);
writePunctuation("}");
}
@@ -75495,6 +76176,7 @@ var ts;
function emitSourceFileWorker(node) {
var statements = node.statements;
pushNameGenerationScope(node);
+ ts.forEach(node.statements, generateNames);
emitHelpers(node);
var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
emitTripleSlashDirectivesIfNeeded(node);
@@ -75571,6 +76253,8 @@ var ts;
// Helpers
//
function emitNodeWithWriter(node, writer) {
+ if (!node)
+ return;
var savedWrite = write;
write = writer;
emit(node);
@@ -76060,7 +76744,7 @@ var ts;
if (ts.isGeneratedIdentifier(node)) {
return generateName(node);
}
- else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
+ else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) {
return ts.idText(node);
}
else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) {
@@ -76112,6 +76796,113 @@ var ts;
}
reservedNames.set(name, true);
}
+ function generateNames(node) {
+ if (!node)
+ return;
+ switch (node.kind) {
+ case 212 /* Block */:
+ ts.forEach(node.statements, generateNames);
+ break;
+ case 227 /* LabeledStatement */:
+ case 225 /* WithStatement */:
+ case 217 /* DoStatement */:
+ case 218 /* WhileStatement */:
+ generateNames(node.statement);
+ break;
+ case 216 /* IfStatement */:
+ generateNames(node.thenStatement);
+ generateNames(node.elseStatement);
+ break;
+ case 219 /* ForStatement */:
+ case 221 /* ForOfStatement */:
+ case 220 /* ForInStatement */:
+ generateNames(node.initializer);
+ generateNames(node.statement);
+ break;
+ case 226 /* SwitchStatement */:
+ generateNames(node.caseBlock);
+ break;
+ case 240 /* CaseBlock */:
+ ts.forEach(node.clauses, generateNames);
+ break;
+ case 265 /* CaseClause */:
+ case 266 /* DefaultClause */:
+ ts.forEach(node.statements, generateNames);
+ break;
+ case 229 /* TryStatement */:
+ generateNames(node.tryBlock);
+ generateNames(node.catchClause);
+ generateNames(node.finallyBlock);
+ break;
+ case 268 /* CatchClause */:
+ generateNames(node.variableDeclaration);
+ generateNames(node.block);
+ break;
+ case 213 /* VariableStatement */:
+ generateNames(node.declarationList);
+ break;
+ case 232 /* VariableDeclarationList */:
+ ts.forEach(node.declarations, generateNames);
+ break;
+ case 231 /* VariableDeclaration */:
+ case 148 /* Parameter */:
+ case 181 /* BindingElement */:
+ case 234 /* ClassDeclaration */:
+ generateNameIfNeeded(node.name);
+ break;
+ case 233 /* FunctionDeclaration */:
+ generateNameIfNeeded(node.name);
+ if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
+ ts.forEach(node.parameters, generateNames);
+ generateNames(node.body);
+ }
+ break;
+ case 179 /* ObjectBindingPattern */:
+ case 180 /* ArrayBindingPattern */:
+ ts.forEach(node.elements, generateNames);
+ break;
+ case 243 /* ImportDeclaration */:
+ generateNames(node.importClause);
+ break;
+ case 244 /* ImportClause */:
+ generateNameIfNeeded(node.name);
+ generateNames(node.namedBindings);
+ break;
+ case 245 /* NamespaceImport */:
+ generateNameIfNeeded(node.name);
+ break;
+ case 246 /* NamedImports */:
+ ts.forEach(node.elements, generateNames);
+ break;
+ case 247 /* ImportSpecifier */:
+ generateNameIfNeeded(node.propertyName || node.name);
+ break;
+ }
+ }
+ function generateMemberNames(node) {
+ if (!node)
+ return;
+ switch (node.kind) {
+ case 269 /* PropertyAssignment */:
+ case 270 /* ShorthandPropertyAssignment */:
+ case 151 /* PropertyDeclaration */:
+ case 153 /* MethodDeclaration */:
+ case 155 /* GetAccessor */:
+ case 156 /* SetAccessor */:
+ generateNameIfNeeded(node.name);
+ break;
+ }
+ }
+ function generateNameIfNeeded(name) {
+ if (name) {
+ if (ts.isGeneratedIdentifier(name)) {
+ generateName(name);
+ }
+ else if (ts.isBindingPattern(name)) {
+ generateNames(name);
+ }
+ }
+ }
/**
* Generate the text for a generated identifier.
*/
@@ -76119,17 +76910,7 @@ var ts;
if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) {
// Node names generate unique names based on their original node
// and are cached based on that node's id.
- if (name.autoGenerateFlags & 8 /* SkipNameGenerationScope */) {
- var savedTempFlags = tempFlags;
- popNameGenerationScope(/*node*/ undefined);
- var result = generateNameCached(getNodeForGeneratedName(name));
- pushNameGenerationScope(/*node*/ undefined);
- tempFlags = savedTempFlags;
- return result;
- }
- else {
- return generateNameCached(getNodeForGeneratedName(name));
- }
+ return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags);
}
else {
// Auto, Loop, and Unique names are cached based on their unique
@@ -76138,9 +76919,9 @@ var ts;
return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
}
}
- function generateNameCached(node) {
+ function generateNameCached(node, flags) {
var nodeId = ts.getNodeId(node);
- return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node));
+ return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags));
}
/**
* Returns a value indicating whether a name is unique globally, within the current file,
@@ -76155,7 +76936,7 @@ var ts;
* Returns a value indicating whether a name is unique globally or within the current file.
*/
function isFileLevelUniqueName(name) {
- return ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName);
+ return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
}
/**
* Returns a value indicating whether a name is unique within a container.
@@ -76212,11 +76993,16 @@ var ts;
* makeUniqueName are guaranteed to never conflict.
* If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1'
*/
- function makeUniqueName(baseName, checkFn, optimistic) {
+ function makeUniqueName(baseName, checkFn, optimistic, scoped) {
if (checkFn === void 0) { checkFn = isUniqueName; }
if (optimistic) {
if (checkFn(baseName)) {
- generatedNames.set(baseName, true);
+ if (scoped) {
+ reserveNameInNestedScopes(baseName);
+ }
+ else {
+ generatedNames.set(baseName, true);
+ }
return baseName;
}
}
@@ -76228,7 +77014,12 @@ var ts;
while (true) {
var generatedName = baseName + i;
if (checkFn(generatedName)) {
- generatedNames.set(generatedName, true);
+ if (scoped) {
+ reserveNameInNestedScopes(generatedName);
+ }
+ else {
+ generatedNames.set(generatedName, true);
+ }
return generatedName;
}
i++;
@@ -76275,10 +77066,10 @@ var ts;
/**
* Generates a unique name from a node.
*/
- function generateNameForNode(node) {
+ function generateNameForNode(node, flags) {
switch (node.kind) {
case 71 /* Identifier */:
- return makeUniqueName(getTextOfNode(node));
+ return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */));
case 238 /* ModuleDeclaration */:
case 237 /* EnumDeclaration */:
return generateNameForModuleOrEnum(node);
@@ -76305,11 +77096,11 @@ var ts;
function makeName(name) {
switch (name.autoGenerateFlags & 7 /* KindMask */) {
case 1 /* Auto */:
- return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */));
+ return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
case 2 /* Loop */:
- return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */));
+ return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
case 3 /* Unique */:
- return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 64 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 32 /* Optimistic */));
+ return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
}
ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
}
@@ -76325,7 +77116,7 @@ var ts;
// if "node" is a different generated name (having a different
// "autoGenerateId"), use it and stop traversing.
if (ts.isIdentifier(node)
- && node.autoGenerateFlags === 4 /* Node */
+ && !!(node.autoGenerateFlags & 4 /* Node */)
&& node.autoGenerateId !== autoGenerateId) {
break;
}
@@ -76384,7 +77175,7 @@ var ts;
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
}
function getCachedFileSystemEntries(rootDirPath) {
- return cachedReadDirectoryResult.get(rootDirPath);
+ return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath));
}
function getCachedFileSystemEntriesForBaseDir(path) {
return getCachedFileSystemEntries(ts.getDirectoryPath(path));
@@ -76397,7 +77188,7 @@ var ts;
files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [],
directories: host.getDirectories(rootDir) || []
};
- cachedReadDirectoryResult.set(rootDirPath, resultFromHost);
+ cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
return resultFromHost;
}
/**
@@ -76406,6 +77197,7 @@ var ts;
* The host request is done under try catch block to avoid caching incorrect result
*/
function tryReadDirectory(rootDir, rootDirPath) {
+ rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath);
var cachedResult = getCachedFileSystemEntries(rootDirPath);
if (cachedResult) {
return cachedResult;
@@ -76415,7 +77207,7 @@ var ts;
}
catch (_e) {
// If there is exception to read directories, dont cache the result and direct the calls to host
- ts.Debug.assert(!cachedReadDirectoryResult.has(rootDirPath));
+ ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath)));
return undefined;
}
}
@@ -76451,7 +77243,7 @@ var ts;
}
function directoryExists(dirPath) {
var path = toPath(dirPath);
- return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath);
+ return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
}
function createDirectory(dirPath) {
var path = toPath(dirPath);
@@ -76725,7 +77517,7 @@ var ts;
if (!commonPathComponents) { // Can happen when all input files are .d.ts files
return currentDirectory;
}
- return ts.getNormalizedPathFromPathComponents(commonPathComponents);
+ return ts.getPathFromPathComponents(commonPathComponents);
}
ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
function createCompilerHost(options, setParentNodes) {
@@ -76832,7 +77624,8 @@ var ts;
directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); },
getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; },
getDirectories: function (path) { return ts.sys.getDirectories(path); },
- realpath: realpath
+ realpath: realpath,
+ readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }
};
}
ts.createCompilerHost = createCompilerHost;
@@ -76900,52 +77693,52 @@ var ts;
var output = "";
for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
var diagnostic = diagnostics_2[_i];
- var context = "";
+ var context_2 = "";
if (diagnostic.file) {
- var start = diagnostic.start, length_4 = diagnostic.length, file = diagnostic.file;
- var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
- var _b = ts.getLineAndCharacterOfPosition(file, start + length_4), lastLine = _b.line, lastLineChar = _b.character;
- var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
- var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
+ var start = diagnostic.start, length_4 = diagnostic.length, file_8 = diagnostic.file;
+ var _a = ts.getLineAndCharacterOfPosition(file_8, start), firstLine = _a.line, firstLineChar = _a.character;
+ var _b = ts.getLineAndCharacterOfPosition(file_8, start + length_4), lastLine = _b.line, lastLineChar = _b.character;
+ var lastLineInFile = ts.getLineAndCharacterOfPosition(file_8, file_8.text.length).line;
+ var relativeFileName = host ? ts.convertToRelativePath(file_8.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file_8.fileName;
var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
var gutterWidth = (lastLine + 1 + "").length;
if (hasMoreThanFiveLines) {
gutterWidth = Math.max(ellipsis.length, gutterWidth);
}
for (var i = firstLine; i <= lastLine; i++) {
- context += host.getNewLine();
+ context_2 += host.getNewLine();
// If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
// so we'll skip ahead to the second-to-last line.
if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
- context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
+ context_2 += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
i = lastLine - 1;
}
- var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0);
- var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
- var lineContent = file.text.slice(lineStart, lineEnd);
+ var lineStart = ts.getPositionOfLineAndCharacter(file_8, i, 0);
+ var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file_8, i + 1, 0) : file_8.text.length;
+ var lineContent = file_8.text.slice(lineStart, lineEnd);
lineContent = lineContent.replace(/\s+$/g, ""); // trim from end
lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces
// Output the gutter and the actual contents of the line.
- context += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
- context += lineContent + host.getNewLine();
+ context_2 += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
+ context_2 += lineContent + host.getNewLine();
// Output the gutter and the error span for the line using tildes.
- context += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
- context += ForegroundColorEscapeSequences.Red;
+ context_2 += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
+ context_2 += ForegroundColorEscapeSequences.Red;
if (i === firstLine) {
// If we're on the last line, then limit it to the last character of the last line.
// Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
var lastCharForLine = i === lastLine ? lastLineChar : undefined;
- context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
- context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
+ context_2 += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
+ context_2 += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
}
else if (i === lastLine) {
- context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
+ context_2 += lineContent.slice(0, lastLineChar).replace(/./g, "~");
}
else {
// Squiggle the entire line.
- context += lineContent.replace(/./g, "~");
+ context_2 += lineContent.replace(/./g, "~");
}
- context += resetEscapeSequence;
+ context_2 += resetEscapeSequence;
}
output += formatColorAndReset(relativeFileName, ForegroundColorEscapeSequences.Cyan);
output += ":";
@@ -76959,7 +77752,7 @@ var ts;
output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
if (diagnostic.file) {
output += host.getNewLine();
- output += context;
+ output += context_2;
}
output += host.getNewLine();
}
@@ -77069,21 +77862,19 @@ var ts;
oldOptions.baseUrl !== newOptions.baseUrl ||
!ts.equalOwnProperties(oldOptions.paths, newOptions.paths));
}
- /**
- * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions'
- * that represent a compilation unit.
- *
- * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and
- * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in.
- *
- * @param rootNames - A set of root files.
- * @param options - The compiler options which should be used.
- * @param host - The host interacts with the underlying file system.
- * @param oldProgram - Reuses an old program structure.
- * @param configFileParsingDiagnostics - error during config file parsing
- * @returns A 'Program' object.
- */
- function createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
+ function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
+ return {
+ rootNames: rootNames,
+ options: options,
+ host: host,
+ oldProgram: oldProgram,
+ configFileParsingDiagnostics: configFileParsingDiagnostics
+ };
+ }
+ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
+ var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions;
+ var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
+ var host = createProgramOptions.host, oldProgram = createProgramOptions.oldProgram;
var program;
var files = [];
var commonSourceDirectory;
@@ -77111,6 +77902,7 @@ var ts;
var sourceFilesFoundSearchingNodeModules = ts.createMap();
ts.performance.mark("beforeProgram");
host = host || createCompilerHost(options);
+ var configParsingHost = parseConfigHostFromCompilerHost(host);
var skipDefaultLib = options.noLib;
var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); });
var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName());
@@ -77120,6 +77912,7 @@ var ts;
// Map storing if there is emit blocking diagnostics for given input
var hasEmitBlockingDiagnostics = ts.createMap();
var _compilerOptionsObjectLiteralSyntax;
+ var _referencesArrayLiteralSyntax;
var moduleResolutionCache;
var resolveModuleNamesWorker;
var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
@@ -77159,6 +77952,23 @@ var ts;
// stores 'filename -> file association' ignoring case
// used to track cases when two file names differ only in casing
var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined;
+ // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
+ var resolvedProjectReferences = projectReferences ? [] : undefined;
+ var projectReferenceRedirects = ts.createMap();
+ if (projectReferences) {
+ for (var _i = 0, projectReferences_1 = projectReferences; _i < projectReferences_1.length; _i++) {
+ var ref = projectReferences_1[_i];
+ var parsedRef = parseProjectReferenceConfigFile(ref);
+ resolvedProjectReferences.push(parsedRef);
+ if (parsedRef) {
+ if (parsedRef.commandLine.options.outFile) {
+ var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts");
+ processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*packageId*/ undefined);
+ }
+ addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects);
+ }
+ }
+ }
var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
var structuralIsReused = tryReuseStructureFromOldProgram();
if (structuralIsReused !== 2 /* Completely */) {
@@ -77198,8 +78008,8 @@ var ts;
// not part of the new program.
if (oldProgram && host.onReleaseOldSourceFile) {
var oldSourceFiles = oldProgram.getSourceFiles();
- for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) {
- var oldSourceFile = oldSourceFiles_1[_i];
+ for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) {
+ var oldSourceFile = oldSourceFiles_1[_a];
if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) {
host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions());
}
@@ -77240,6 +78050,7 @@ var ts;
isEmittedFile: isEmittedFile,
getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics,
getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
+ getProjectReferences: getProjectReferences
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -77255,9 +78066,14 @@ var ts;
if (commonSourceDirectory === undefined) {
var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); });
if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
- // If a rootDir is specified and is valid use it as the commonSourceDirectory
+ // If a rootDir is specified use it as the commonSourceDirectory
commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
}
+ else if (options.composite) {
+ // Project compilations never infer their root from the input source paths
+ commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
+ checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory);
+ }
else {
commonSourceDirectory = computeCommonSourceDirectory(emittedFiles);
}
@@ -77295,16 +78111,16 @@ var ts;
// We only set `file.resolvedModules` via work from the current function,
// so it is defined iff we already called the current function on `file`.
// That call happened no later than the creation of the `file` object,
- // which per above occured during the current program creation.
+ // which per above occurred during the current program creation.
// Since we assume the filesystem does not change during program creation,
// it is safe to reuse resolutions from the earlier call.
- var result_3 = [];
+ var result_4 = [];
for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
var moduleName = moduleNames_1[_i];
var resolvedModule = file.resolvedModules.get(moduleName);
- result_3.push(resolvedModule);
+ result_4.push(resolvedModule);
}
- return result_3;
+ return result_4;
}
// At this point, we know at least one of the following hold:
// - file has local declarations for ambient modules
@@ -77435,6 +78251,34 @@ var ts;
if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) {
return oldProgram.structureIsReused = 0 /* Not */;
}
+ // Check if any referenced project tsconfig files are different
+ var oldRefs = oldProgram.getProjectReferences();
+ if (projectReferences) {
+ if (!oldRefs) {
+ return oldProgram.structureIsReused = 0 /* Not */;
+ }
+ for (var i = 0; i < projectReferences.length; i++) {
+ var oldRef = oldRefs[i];
+ if (oldRef) {
+ var newRef = parseProjectReferenceConfigFile(projectReferences[i]);
+ if (!newRef || newRef.sourceFile !== oldRef.sourceFile) {
+ // Resolved project reference has gone missing or changed
+ return oldProgram.structureIsReused = 0 /* Not */;
+ }
+ }
+ else {
+ // A previously-unresolved reference may be resolved now
+ if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) {
+ return oldProgram.structureIsReused = 0 /* Not */;
+ }
+ }
+ }
+ }
+ else {
+ if (oldRefs) {
+ return oldProgram.structureIsReused = 0 /* Not */;
+ }
+ }
// check if program source files has changed in the way that can affect structure of the program
var newSourceFiles = [];
var filePaths = [];
@@ -77602,6 +78446,7 @@ var ts;
}
function getEmitHost(writeFileCallback) {
return {
+ getPrependNodes: getPrependNodes,
getCanonicalFileName: getCanonicalFileName,
getCommonSourceDirectory: program.getCommonSourceDirectory,
getCompilerOptions: program.getCompilerOptions,
@@ -77615,6 +78460,32 @@ var ts;
isEmitBlocked: isEmitBlocked,
};
}
+ function getProjectReferences() {
+ if (!resolvedProjectReferences)
+ return;
+ return resolvedProjectReferences;
+ }
+ 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) {
+ // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
+ if (!resolvedRefOpts.options.outFile)
+ continue;
+ var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts");
+ var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n";
+ var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n";
+ var node = ts.createInputFiles(js, dts);
+ nodes.push(node);
+ }
+ }
+ return nodes;
+ }
function isSourceFileFromExternalLibrary(file) {
return sourceFilesFoundSearchingNodeModules.get(file.path);
}
@@ -77685,7 +78556,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, emitOnlyDtsFiles, transformers);
+ 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;
@@ -77769,9 +78640,9 @@ var ts;
var typeChecker = getDiagnosticsProducingTypeChecker();
ts.Debug.assert(!!sourceFile.bindDiagnostics);
var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options);
- // By default, only type-check .ts, .tsx, and 'External' files (external files are added by plugins)
+ // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ ||
- sourceFile.scriptKind === 5 /* External */ || isCheckJs;
+ sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */;
var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray;
var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray;
var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
@@ -78147,7 +79018,13 @@ var ts;
var sourceFile = getSourceFile(fileName);
if (fail) {
if (!sourceFile) {
- fail(ts.Diagnostics.File_0_not_found, fileName);
+ var redirect = getProjectReferenceRedirect(fileName);
+ if (redirect) {
+ fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
+ }
+ else {
+ fail(ts.Diagnostics.File_0_not_found, fileName);
+ }
}
else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) {
fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
@@ -78208,31 +79085,45 @@ var ts;
// Get source file from normalized fileName
function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd, packageId) {
if (filesByName.has(path)) {
- var file_1 = filesByName.get(path);
+ var file_9 = filesByName.get(path);
// try to check if we've already seen this file but with a different casing in path
// NOTE: this only makes sense for case-insensitive file systems
- if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
- reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
+ if (file_9 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_9.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
+ reportFileNamesDifferOnlyInCasingError(fileName, file_9.fileName, refFile, refPos, refEnd);
}
// If the file was previously found via a node_modules search, but is now being processed as a root file,
// then everything it sucks in may also be marked incorrectly, and needs to be checked again.
- if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) {
- sourceFilesFoundSearchingNodeModules.set(file_1.path, false);
+ if (file_9 && sourceFilesFoundSearchingNodeModules.get(file_9.path) && currentNodeModulesDepth === 0) {
+ sourceFilesFoundSearchingNodeModules.set(file_9.path, false);
if (!options.noResolve) {
- processReferencedFiles(file_1, isDefaultLib);
- processTypeReferenceDirectives(file_1);
+ processReferencedFiles(file_9, isDefaultLib);
+ processTypeReferenceDirectives(file_9);
}
- modulesWithElidedImports.set(file_1.path, false);
- processImportedModules(file_1);
+ modulesWithElidedImports.set(file_9.path, false);
+ processImportedModules(file_9);
}
// See if we need to reprocess the imports due to prior skipped imports
- else if (file_1 && modulesWithElidedImports.get(file_1.path)) {
+ else if (file_9 && modulesWithElidedImports.get(file_9.path)) {
if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
- modulesWithElidedImports.set(file_1.path, false);
- processImportedModules(file_1);
+ modulesWithElidedImports.set(file_9.path, false);
+ processImportedModules(file_9);
}
}
- return file_1;
+ return file_9;
+ }
+ var redirectedPath;
+ if (refFile) {
+ var redirect = getProjectReferenceRedirect(fileName);
+ if (redirect) {
+ (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName);
+ fileName = redirect;
+ // Once we start redirecting to a file, we can potentially come back to it
+ // via a back-reference from another file in the .d.ts folder. If that happens we'll
+ // end up trying to add it to the program *again* because we were tracking it via its
+ // original (un-redirected) name. So we have to map both the original path and the redirected path
+ // to the source file we're about to find/create
+ redirectedPath = toPath(redirect);
+ }
}
// We haven't looked for this file, do so now and cache result
var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) {
@@ -78263,6 +79154,9 @@ var ts;
}
}
filesByName.set(path, file);
+ if (redirectedPath) {
+ filesByName.set(redirectedPath, file);
+ }
if (file) {
sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
file.path = path;
@@ -78293,6 +79187,22 @@ var ts;
}
return file;
}
+ function getProjectReferenceRedirect(fileName) {
+ var path = toPath(fileName);
+ // If this file is produced by a referenced project, we need to rewrite it to
+ // look in the output folder of the referenced project rather than the input
+ var normalized = ts.getNormalizedAbsolutePath(fileName, path);
+ var result;
+ projectReferenceRedirects.forEach(function (v, k) {
+ if (result !== undefined) {
+ return undefined;
+ }
+ if (normalized.indexOf(k) === 0) {
+ result = ts.changeExtension(fileName.replace(k, v), ".d.ts");
+ }
+ });
+ return result;
+ }
function processReferencedFiles(file, isDefaultLib) {
ts.forEach(file.referencedFiles, function (ref) {
var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName);
@@ -78302,6 +79212,9 @@ var ts;
function processTypeReferenceDirectives(file) {
// We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); });
+ if (!typeDirectives) {
+ return;
+ }
var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName);
for (var i = 0; i < typeDirectives.length; i++) {
var ref = file.typeReferenceDirectives[i];
@@ -78381,7 +79294,7 @@ var ts;
continue;
}
var isFromNodeModulesSearch = resolution.isExternalLibraryImport;
- var isJsFile = !ts.extensionIsTypeScript(resolution.extension);
+ var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension);
var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
var resolvedFileName = resolution.resolvedFileName;
if (isFromNodeModulesSearch) {
@@ -78423,9 +79336,9 @@ var ts;
function computeCommonSourceDirectory(sourceFiles) {
var fileNames = [];
for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
- var file = sourceFiles_2[_i];
- if (!file.isDeclarationFile) {
- fileNames.push(file.fileName);
+ var file_10 = sourceFiles_2[_i];
+ if (!file_10.isDeclarationFile) {
+ fileNames.push(file_10.fileName);
}
}
return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
@@ -78447,6 +79360,27 @@ var ts;
}
return allFilesBelongToPath;
}
+ function parseProjectReferenceConfigFile(ref) {
+ // The actual filename (i.e. add "/tsconfig.json" if necessary)
+ var refPath = resolveProjectReferencePath(host, ref);
+ // An absolute path pointing to the containing directory of the config file
+ var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
+ var sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
+ if (sourceFile === undefined) {
+ return undefined;
+ }
+ var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath);
+ return { commandLine: commandLine, sourceFile: sourceFile };
+ }
+ function addProjectReferenceRedirects(referencedProject, target) {
+ var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath));
+ target.set(rootDir, getDeclarationOutputDirectory(referencedProject));
+ }
+ function getDeclarationOutputDirectory(proj) {
+ return proj.options.declarationDir ||
+ proj.options.outDir ||
+ ts.getDirectoryPath(proj.options.configFilePath);
+ }
function verifyCompilerOptions() {
if (options.strictPropertyInitialization && !options.strictNullChecks) {
createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
@@ -78476,6 +79410,48 @@ var ts;
if (options.paths && options.baseUrl === undefined) {
createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths");
}
+ if (options.composite) {
+ if (options.declaration === false) {
+ createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
+ }
+ }
+ if (projectReferences) {
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options;
+ if (resolvedRefOpts === undefined) {
+ createDiagnosticForReference(i, ts.Diagnostics.File_0_does_not_exist, ref.path);
+ continue;
+ }
+ if (!resolvedRefOpts.composite) {
+ createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
+ }
+ if (ref.prepend) {
+ if (resolvedRefOpts.outFile) {
+ if (!host.fileExists(resolvedRefOpts.outFile)) {
+ createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path);
+ }
+ }
+ else {
+ createDiagnosticForReference(i, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
+ }
+ }
+ }
+ }
+ // List of collected files is complete; validate exhautiveness if this is a project with a file list
+ if (options.composite && rootNames.length < files.length) {
+ var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); });
+ var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); });
+ var _loop_9 = function (file_11) {
+ if (normalizedRootNames.every(function (r) { return r !== file_11; })) {
+ programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file_11));
+ }
+ };
+ for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
+ var file_11 = sourceFiles_4[_i];
+ _loop_9(file_11);
+ }
+ }
if (options.paths) {
for (var key in options.paths) {
if (!ts.hasProperty(options.paths, key)) {
@@ -78567,6 +79543,11 @@ var ts;
programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile"));
}
}
+ if (options.resolveJsonModule) {
+ if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
+ }
+ }
// there has to be common source directory if user specified --outdir || --sourceRoot
// if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
if (options.outDir || // there is --outDir specified
@@ -78679,12 +79660,15 @@ var ts;
programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0));
}
}
- function getOptionPathsSyntax() {
+ function getOptionsSyntaxByName(name) {
var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
if (compilerOptionsObjectLiteralSyntax) {
- return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths");
+ return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
}
- return ts.emptyArray;
+ return undefined;
+ }
+ function getOptionPathsSyntax() {
+ return getOptionsSyntaxByName("paths") || ts.emptyArray;
}
function createDiagnosticForOptionName(message, option1, option2, option3) {
createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
@@ -78692,6 +79676,15 @@ var ts;
function createOptionValueDiagnostic(option1, message, arg0) {
createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0);
}
+ function createDiagnosticForReference(index, message, arg0, arg1) {
+ var referencesSyntax = getProjectReferencesSyntax();
+ if (referencesSyntax) {
+ if (createOptionDiagnosticInArrayLiteralSyntax(referencesSyntax, index, message, arg0, arg1)) {
+ return;
+ }
+ }
+ programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1));
+ }
function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) {
var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
@@ -78700,11 +79693,28 @@ var ts;
programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
}
}
+ function getProjectReferencesSyntax() {
+ if (_referencesArrayLiteralSyntax === undefined) {
+ _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword
+ if (options.configFile) {
+ var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
+ for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) {
+ var prop = _a[_i];
+ if (ts.isArrayLiteralExpression(prop.initializer)) {
+ _referencesArrayLiteralSyntax = prop.initializer;
+ break;
+ }
+ }
+ }
+ }
+ return _referencesArrayLiteralSyntax;
+ }
function getCompilerOptionsObjectLiteralSyntax() {
if (_compilerOptionsObjectLiteralSyntax === undefined) {
_compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword
- if (options.configFile && options.configFile.jsonObject) {
- for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) {
+ var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
+ if (jsonObjectLiteral) {
+ for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
var prop = _a[_i];
if (ts.isObjectLiteralExpression(prop.initializer)) {
_compilerOptionsObjectLiteralSyntax = prop.initializer;
@@ -78723,6 +79733,13 @@ var ts;
}
return !!props.length;
}
+ function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral, index, message, arg0, arg1, arg2) {
+ if (arrayLiteral.elements.length <= index) {
+ // Out-of-bounds
+ return false;
+ }
+ programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2));
+ }
function blockEmittingOfFile(emitFileName, diag) {
hasEmitBlockingDiagnostics.set(toPath(emitFileName), true);
programDiagnostics.add(diag);
@@ -78759,6 +79776,27 @@ var ts;
}
ts.createProgram = createProgram;
/* @internal */
+ function parseConfigHostFromCompilerHost(host) {
+ return {
+ fileExists: function (f) { return host.fileExists(f); },
+ readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; },
+ readFile: function (f) { return host.readFile(f); },
+ useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
+ getCurrentDirectory: function () { return host.getCurrentDirectory(); },
+ onUnRecoverableConfigFileDiagnostic: function () { return undefined; }
+ };
+ }
+ ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost;
+ /**
+ * Returns the target config filename of a project reference
+ */
+ function resolveProjectReferencePath(host, ref) {
+ if (!host.fileExists(ref.path)) {
+ return ts.combinePaths(ref.path, "tsconfig.json");
+ }
+ return ref.path;
+ }
+ /* @internal */
/**
* Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
* The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
@@ -78769,6 +79807,7 @@ var ts;
switch (extension) {
case ".ts" /* Ts */:
case ".d.ts" /* Dts */:
+ case ".json" /* Json */: // Since module is resolved to json file only when --resolveJsonModule, we dont need further check
// These are always allowed.
return undefined;
case ".tsx" /* Tsx */:
@@ -78969,6 +80008,7 @@ var ts;
* Get all the dependencies of the sourceFile
*/
function getAllDependencies(state, programOfThisState, sourceFile) {
+ var _a;
var compilerOptions = programOfThisState.getCompilerOptions();
// With --out or --outFile all outputs go into single file, all files depend on each other
if (compilerOptions.outFile || compilerOptions.out) {
@@ -78988,7 +80028,7 @@ var ts;
var references = state.referencedMap.get(path);
if (references) {
var iterator = references.keys();
- for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) {
queue.push(value);
}
}
@@ -78998,7 +80038,6 @@ var ts;
var file = programOfThisState.getSourceFileByPath(path);
return file ? file.fileName : path;
}));
- var _b;
}
BuilderState.getAllDependencies = getAllDependencies;
/**
@@ -79443,8 +80482,8 @@ var ts;
}
var diagnostics;
for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) {
- var sourceFile_1 = _a[_i];
- diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
+ var sourceFile_2 = _a[_i];
+ diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken));
}
return diagnostics || ts.emptyArray;
}
@@ -79741,17 +80780,19 @@ var ts;
return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath));
}
// Use some ancestor of the root directory
+ var subDirectory;
if (rootPath !== undefined) {
while (!isInDirectoryPath(dirPath, rootPath)) {
var parentPath = ts.getDirectoryPath(dirPath);
if (parentPath === dirPath) {
break;
}
+ subDirectory = dirPath.slice(parentPath.length + ts.directorySeparator.length);
dirPath = parentPath;
dir = ts.getDirectoryPath(dir);
}
}
- return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath);
+ return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath, subDirectory: subDirectory }, dirPath);
}
function isPathWithDefaultFailedLookupExtension(path) {
return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
@@ -79771,7 +80812,7 @@ var ts;
for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
var failedLookupLocation = failedLookupLocations_1[_i];
var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
- var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore;
+ var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore, subDirectory = _a.subDirectory;
if (!ignore) {
// If the failed lookup location path is not one of the supported extensions,
// store it in the custom path
@@ -79783,7 +80824,7 @@ var ts;
setAtRoot = true;
}
else {
- setDirectoryWatcher(dir, dirPath);
+ setDirectoryWatcher(dir, dirPath, subDirectory);
}
}
}
@@ -79791,13 +80832,19 @@ var ts;
setDirectoryWatcher(rootDir, rootPath);
}
}
- function setDirectoryWatcher(dir, dirPath) {
+ function setDirectoryWatcher(dir, dirPath, subDirectory) {
var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
if (dirWatcher) {
dirWatcher.refCount++;
}
else {
- directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 });
+ dirWatcher = { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 };
+ directoryWatchesOfFailedLookups.set(dirPath, dirWatcher);
+ }
+ if (subDirectory) {
+ var subDirectoryMap = dirWatcher.subDirectoryMap || (dirWatcher.subDirectoryMap = ts.createMap());
+ var existing = subDirectoryMap.get(subDirectory) || 0;
+ subDirectoryMap.set(subDirectory, existing + 1);
}
}
function stopWatchFailedLookupLocationOfResolution(resolution) {
@@ -79813,7 +80860,7 @@ var ts;
for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
var failedLookupLocation = failedLookupLocations_2[_i];
var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
- var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore;
+ var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore, subDirectory = _a.subDirectory;
if (!ignore) {
var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
if (refCount) {
@@ -79829,7 +80876,7 @@ var ts;
removeAtRoot = true;
}
else {
- removeDirectoryWatcher(dirPath);
+ removeDirectoryWatcher(dirPath, subDirectory);
}
}
}
@@ -79837,22 +80884,40 @@ var ts;
removeDirectoryWatcher(rootPath);
}
}
- function removeDirectoryWatcher(dirPath) {
+ function removeDirectoryWatcher(dirPath, subDirectory) {
var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
+ if (subDirectory) {
+ var existing = dirWatcher.subDirectoryMap.get(subDirectory);
+ if (existing === 1) {
+ dirWatcher.subDirectoryMap.delete(subDirectory);
+ }
+ else {
+ dirWatcher.subDirectoryMap.set(subDirectory, existing - 1);
+ }
+ }
// Do not close the watcher yet since it might be needed by other failed lookup locations.
dirWatcher.refCount--;
}
+ function inWatchedSubdirectory(dirPath, fileOrDirectoryPath) {
+ var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
+ if (!dirWatcher || !dirWatcher.subDirectoryMap)
+ return false;
+ return ts.forEachKey(dirWatcher.subDirectoryMap, function (subDirectory) {
+ var fullSubDirectory = dirPath + "/" + subDirectory;
+ return fullSubDirectory === fileOrDirectoryPath || isInDirectoryPath(fullSubDirectory, fileOrDirectoryPath);
+ });
+ }
function createDirectoryWatcher(directory, dirPath) {
return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
if (cachedDirectoryStructureHost) {
- // Since the file existance changed, update the sourceFiles cache
+ // Since the file existence changed, update the sourceFiles cache
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
// If the files are added to project root or node_modules directory, always run through the invalidation process
// Otherwise run through invalidation only if adding to the immediate directory
if (!allFilesHaveInvalidatedResolution &&
- dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) {
+ (dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath || inWatchedSubdirectory(dirPath, fileOrDirectoryPath))) {
if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
resolutionHost.onInvalidatedResolution();
}
@@ -79976,7 +81041,7 @@ var ts;
return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) {
var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
if (cachedDirectoryStructureHost) {
- // Since the file existance changed, update the sourceFiles cache
+ // Since the file existence changed, update the sourceFiles cache
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
// For now just recompile
@@ -80112,34 +81177,11 @@ var ts;
function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) {
var host = system;
host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); };
- var result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host);
+ var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host);
host.onUnRecoverableConfigFileDiagnostic = undefined;
return result;
}
ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
- /**
- * Reads the config file, reports errors if any and exits if the config file cannot be found
- */
- function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) {
- var configFileText;
- try {
- configFileText = host.readFile(configFileName);
- }
- catch (e) {
- var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message);
- host.onUnRecoverableConfigFileDiagnostic(error);
- return undefined;
- }
- if (!configFileText) {
- var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
- host.onUnRecoverableConfigFileDiagnostic(error);
- return undefined;
- }
- var result = ts.parseJsonText(configFileName, configFileText);
- var cwd = host.getCurrentDirectory();
- return ts.parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd));
- }
- ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
/**
* Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
*/
@@ -80221,12 +81263,12 @@ var ts;
watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; },
watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; },
setTimeout: system.setTimeout ? (function (callback, ms) {
+ var _a;
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args));
- var _a;
}) : ts.noop,
clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop,
trace: function (s) { return system.write(s); },
@@ -80986,6 +82028,13 @@ var ts;
category: ts.Diagnostics.Basic_Options,
description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
},
+ {
+ name: "composite",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_project_compilation,
+ },
{
name: "removeComments",
type: "boolean",
@@ -81246,6 +82295,12 @@ var ts;
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
},
+ {
+ name: "resolveJsonModule",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Include_modules_imported_with_json_extension
+ },
{
name: "listFiles",
type: "boolean",
@@ -81539,11 +82594,13 @@ var ts;
function parseCommandLine(commandLine, readFile) {
var options = {};
var fileNames = [];
+ var projectReferences = undefined;
var errors = [];
parseStrings(commandLine);
return {
options: options,
fileNames: fileNames,
+ projectReferences: projectReferences,
errors: errors
};
function parseStrings(args) {
@@ -81656,6 +82713,29 @@ var ts;
}
return optionNameMap.get(optionName);
}
+ /**
+ * Reads the config file, reports errors if any and exits if the config file cannot be found
+ */
+ function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) {
+ var configFileText;
+ try {
+ configFileText = host.readFile(configFileName);
+ }
+ catch (e) {
+ var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message);
+ host.onUnRecoverableConfigFileDiagnostic(error);
+ return undefined;
+ }
+ if (!configFileText) {
+ var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
+ host.onUnRecoverableConfigFileDiagnostic(error);
+ return undefined;
+ }
+ var result = ts.parseJsonText(configFileName, configFileText);
+ var cwd = host.getCurrentDirectory();
+ return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd));
+ }
+ ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
@@ -81703,55 +82783,67 @@ var ts;
var _tsconfigRootOptions;
function getTsconfigRootOptionsMap() {
if (_tsconfigRootOptions === undefined) {
- _tsconfigRootOptions = commandLineOptionsToMap([
- {
- name: "compilerOptions",
- type: "object",
- elementOptions: commandLineOptionsToMap(ts.optionDeclarations),
- extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0
- },
- {
- name: "typingOptions",
- type: "object",
- elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
- extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
- },
- {
- name: "typeAcquisition",
- type: "object",
- elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
- extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
- },
- {
- name: "extends",
- type: "string"
- },
- {
- name: "files",
- type: "list",
- element: {
+ _tsconfigRootOptions = {
+ name: undefined,
+ type: "object",
+ elementOptions: commandLineOptionsToMap([
+ {
+ name: "compilerOptions",
+ type: "object",
+ elementOptions: commandLineOptionsToMap(ts.optionDeclarations),
+ extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0
+ },
+ {
+ name: "typingOptions",
+ type: "object",
+ elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
+ extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
+ },
+ {
+ name: "typeAcquisition",
+ type: "object",
+ elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
+ extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
+ },
+ {
+ name: "extends",
+ type: "string"
+ },
+ {
+ name: "references",
+ type: "list",
+ element: {
+ name: "references",
+ type: "object"
+ }
+ },
+ {
name: "files",
- type: "string"
- }
- },
- {
- name: "include",
- type: "list",
- element: {
+ type: "list",
+ element: {
+ name: "files",
+ type: "string"
+ }
+ },
+ {
name: "include",
- type: "string"
- }
- },
- {
- name: "exclude",
- type: "list",
- element: {
+ type: "list",
+ element: {
+ name: "include",
+ type: "string"
+ }
+ },
+ {
name: "exclude",
- type: "string"
- }
- },
- ts.compileOnSaveCommandLineOption
- ]);
+ type: "list",
+ element: {
+ name: "exclude",
+ type: "string"
+ }
+ },
+ ts.compileOnSaveCommandLineOption
+ ])
+ };
}
return _tsconfigRootOptions;
}
@@ -81759,20 +82851,25 @@ var ts;
* Convert the json syntax tree into the json value
*/
function convertToObject(sourceFile, errors) {
- return convertToObjectWorker(sourceFile, errors, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
+ return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
}
ts.convertToObject = convertToObject;
/**
- * Convert the json syntax tree into the json value
+ * Convert the json syntax tree into the json value and report errors
+ * This returns the json value (apart from checking errors) only if returnValue provided is true.
+ * Otherwise it just checks the errors and returns undefined
*/
- function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) {
- if (!sourceFile.jsonObject) {
- return {};
+ /*@internal*/
+ function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
+ if (!sourceFile.statements.length) {
+ return returnValue ? {} : undefined;
+ }
+ return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
+ function isRootOptionMap(knownOptions) {
+ return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
}
- return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions,
- /*extraKeyDiagnosticMessage*/ undefined, /*parentOption*/ undefined);
function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) {
- var result = {};
+ var result = returnValue ? {} : undefined;
for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
var element = _a[_i];
if (element.kind !== 269 /* PropertyAssignment */) {
@@ -81792,11 +82889,13 @@ var ts;
}
var value = convertPropertyValueToJson(element.initializer, option);
if (typeof keyText !== "undefined") {
- result[keyText] = value;
+ if (returnValue) {
+ result[keyText] = value;
+ }
// Notify key value set, if user asked for it
if (jsonConversionNotifier &&
// Current callbacks are only on known parent option or if we are setting values in the root
- (parentOption || knownOptions === knownRootOptions)) {
+ (parentOption || isRootOptionMap(knownOptions))) {
var isValidOptionValue = isCompilerOptionsValue(option, value);
if (parentOption) {
if (isValidOptionValue) {
@@ -81804,7 +82903,7 @@ var ts;
jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
}
}
- else if (knownOptions === knownRootOptions) {
+ else if (isRootOptionMap(knownOptions)) {
if (isValidOptionValue) {
// Notify about the valid root key value being set
jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
@@ -81820,7 +82919,7 @@ var ts;
return result;
}
function convertArrayLiteralExpressionToJson(elements, elementOption) {
- return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); });
+ return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); });
}
function convertPropertyValueToJson(valueExpression, option) {
switch (valueExpression.kind) {
@@ -81895,6 +82994,7 @@ var ts;
return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
}
}
+ ts.convertToObjectWorker = convertToObjectWorker;
function getCompilerOptionValueTypeString(option) {
return option.type === "list" ?
"Array" :
@@ -81944,7 +83044,7 @@ var ts;
function serializeCompilerOptions(options) {
var result = ts.createMap();
var optionsNameMap = getOptionNameMap().optionNameMap;
- var _loop_9 = function (name) {
+ var _loop_10 = function (name) {
if (ts.hasProperty(options, name)) {
// tsconfig only options cannot be specified via command line,
// so we can assume that only types that can appear here string | number | boolean
@@ -81973,7 +83073,7 @@ var ts;
}
};
for (var name in options) {
- _loop_9(name);
+ _loop_10(name);
}
return result;
}
@@ -82123,12 +83223,13 @@ var ts;
var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors);
var raw = parsedConfig.raw;
var options = ts.extend(existingOptions, parsedConfig.options || {});
- options.configFilePath = configFileName;
+ options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
setConfigFileInOptions(options, sourceFile);
- var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
+ var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences;
return {
options: options,
fileNames: fileNames,
+ projectReferences: projectReferences,
typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
raw: raw,
errors: errors,
@@ -82177,9 +83278,32 @@ var ts;
includeSpecs = ["**/*"];
}
var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
- if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) {
+ if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) {
errors.push(getErrorForNoInputFiles(result.spec, configFileName));
}
+ if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) {
+ if (ts.isArray(raw.references)) {
+ var references = [];
+ for (var _i = 0, _a = raw.references; _i < _a.length; _i++) {
+ var ref = _a[_i];
+ if (typeof ref.path !== "string") {
+ createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
+ }
+ else {
+ references.push({
+ path: ts.getNormalizedAbsolutePath(ref.path, basePath),
+ originalPath: ref.path,
+ prepend: ref.prepend,
+ circular: ref.circular
+ });
+ }
+ }
+ result.projectReferences = references;
+ }
+ else {
+ createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array");
+ }
+ }
return result;
}
function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
@@ -82297,7 +83421,7 @@ var ts;
}
}
};
- var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator);
+ var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
if (!typeAcquisition) {
if (typingOptionstypeAcquisition) {
typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
@@ -82332,6 +83456,7 @@ var ts;
return extendedConfigPath;
}
function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) {
+ var _a;
var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
if (sourceFile) {
(sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName);
@@ -82360,7 +83485,6 @@ var ts;
mapPropertiesInRawIfNotUndefined("files");
}
return extendedConfig;
- var _a;
}
function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
@@ -82385,7 +83509,7 @@ var ts;
}
ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
function getDefaultCompilerOptions(configFileName) {
- var options = ts.getBaseFileName(configFileName) === "jsconfig.json"
+ var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
: {};
return options;
@@ -82393,10 +83517,13 @@ var ts;
function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
var options = getDefaultCompilerOptions(configFileName);
convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors);
+ if (configFileName) {
+ options.configFilePath = ts.normalizeSlashes(configFileName);
+ }
return options;
}
function getDefaultTypeAcquisition(configFileName) {
- return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
+ return { enable: configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
}
function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
var options = getDefaultTypeAcquisition(configFileName);
@@ -82557,7 +83684,7 @@ var ts;
// or a recursive directory. This information is used by filesystem watchers to monitor for
// new entries in these paths.
var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
- var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
+ var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
}
/**
@@ -82591,37 +83718,41 @@ var ts;
if (filesSpecs) {
for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) {
var fileName = filesSpecs_1[_i];
- var file = ts.getNormalizedAbsolutePath(fileName, basePath);
- literalFileMap.set(keyMapper(file), file);
+ var file_12 = ts.getNormalizedAbsolutePath(fileName, basePath);
+ literalFileMap.set(keyMapper(file_12), file_12);
}
}
if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
- var file = _b[_a];
+ var file_13 = _b[_a];
// If we have already included a literal or wildcard path with a
// higher priority extension, we should skip this file.
//
// This handles cases where we may encounter both .ts and
// .d.ts (or .js if "allowJs" is enabled) in the same
// directory when they are compilation outputs.
- if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
+ if (hasFileWithHigherPriorityExtension(file_13, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
continue;
}
// We may have included a wildcard path with a lower priority
// extension due to the user-defined order of entries in the
// "include" array. If there is a lower priority extension in the
// same directory, we should remove it.
- removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
- var key = keyMapper(file);
+ removeWildcardFilesWithLowerPriorityExtension(file_13, wildcardFileMap, supportedExtensions, keyMapper);
+ var key = keyMapper(file_13);
if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
- wildcardFileMap.set(key, file);
+ wildcardFileMap.set(key, file_13);
}
}
}
var literalFiles = ts.arrayFrom(literalFileMap.values());
var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
+ var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) {
+ return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) });
+ });
return {
fileNames: literalFiles.concat(wildcardFiles),
+ projectReferences: projectReferences,
wildcardDirectories: wildcardDirectories,
spec: spec
};
@@ -82636,20 +83767,10 @@ var ts;
return diag === undefined;
});
function createDiagnostic(message, spec) {
- if (jsonSourceFile && jsonSourceFile.jsonObject) {
- for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) {
- var property = _a[_i];
- if (ts.isArrayLiteralExpression(property.initializer)) {
- for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) {
- var element = _c[_b];
- if (ts.isStringLiteral(element) && element.text === spec) {
- return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec);
- }
- }
- }
- }
- }
- return ts.createCompilerDiagnostic(message, spec);
+ var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
+ return element ?
+ ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
+ ts.createCompilerDiagnostic(message, spec);
}
}
function specToDiagnostic(spec, allowTrailingRecursion) {
@@ -82682,8 +83803,8 @@ var ts;
if (include !== undefined) {
var recursiveKeys = [];
for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
- var file = include_1[_i];
- var spec = ts.normalizePath(ts.combinePaths(path, file));
+ var file_14 = include_1[_i];
+ var spec = ts.normalizePath(ts.combinePaths(path, file_14));
if (excludeRegex && excludeRegex.test(spec)) {
continue;
}
@@ -82877,6 +83998,17 @@ var ts;
SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName";
SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral";
})(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {}));
+ var OutliningSpanKind;
+ (function (OutliningSpanKind) {
+ /** Single or multi-line comments */
+ OutliningSpanKind["Comment"] = "comment";
+ /** Sections marked by '// #region' and '// #endregion' comments */
+ OutliningSpanKind["Region"] = "region";
+ /** Declarations and expressions */
+ OutliningSpanKind["Code"] = "code";
+ /** Contiguous blocks of import declarations */
+ OutliningSpanKind["Imports"] = "imports";
+ })(OutliningSpanKind = ts.OutliningSpanKind || (ts.OutliningSpanKind = {}));
var OutputFileType;
(function (OutputFileType) {
OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript";
@@ -82972,6 +84104,8 @@ var ts;
*
*/
ScriptElementKind["jsxAttribute"] = "JSX attribute";
+ /** String literal */
+ ScriptElementKind["string"] = "string";
})(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {}));
var ScriptElementKindModifier;
(function (ScriptElementKindModifier) {
@@ -83077,7 +84211,7 @@ var ts;
case 236 /* TypeAliasDeclaration */:
case 165 /* TypeLiteral */:
return 2 /* Type */;
- case 292 /* JSDocTypedefTag */:
+ case 294 /* 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 272 /* EnumMember */:
@@ -83193,6 +84327,8 @@ var ts;
switch (node.parent.kind) {
case 161 /* TypeReference */:
return true;
+ case 178 /* ImportType */:
+ return !node.parent.isTypeOf;
case 206 /* ExpressionWithTypeArguments */:
return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent);
}
@@ -83280,7 +84416,7 @@ var ts;
}
ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration;
function getContainerNode(node) {
- if (node.kind === 292 /* JSDocTypedefTag */) {
+ if (node.kind === 294 /* JSDocTypedefTag */) {
// This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope.
// node.parent = the JSDoc comment, node.parent.parent = the node having the comment.
// Then we get parent again in the loop.
@@ -83349,7 +84485,7 @@ var ts;
case 251 /* ExportSpecifier */:
case 245 /* NamespaceImport */:
return "alias" /* alias */;
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return "type" /* typeElement */;
case 199 /* BinaryExpression */:
var kind = ts.getSpecialPropertyAssignmentKind(node);
@@ -83678,7 +84814,7 @@ var ts;
return findPrecedingToken(position, file);
}
ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition;
- function findNextToken(previousToken, parent) {
+ function findNextToken(previousToken, parent, sourceFile) {
return find(parent);
function find(n) {
if (ts.isToken(n) && n.pos === previousToken.end) {
@@ -83693,7 +84829,7 @@ var ts;
(child.pos <= previousToken.pos && child.end > previousToken.end) ||
// previous token ends exactly at the beginning of child
(child.pos === previousToken.end);
- if (shouldDiveInChildNode && nodeHasTokens(child)) {
+ if (shouldDiveInChildNode && nodeHasTokens(child, sourceFile)) {
return find(child);
}
}
@@ -83724,11 +84860,11 @@ var ts;
if (position < child.end) {
var start = child.getStart(sourceFile, includeJsDoc);
var lookInPreviousChild = (start >= position) || // cursor in the leading trivia
- !nodeHasTokens(child) ||
+ !nodeHasTokens(child, sourceFile) ||
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 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i);
+ var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
return candidate && findRightmostToken(candidate, sourceFile);
}
else {
@@ -83743,7 +84879,7 @@ var ts;
// Try to find the rightmost token in the file without filtering.
// Namely we are skipping the check: 'position < node.end'
if (children.length) {
- var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length);
+ var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile);
return candidate && findRightmostToken(candidate, sourceFile);
}
}
@@ -83757,19 +84893,19 @@ var ts;
return n;
}
var children = n.getChildren(sourceFile);
- var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length);
+ var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile);
return candidate && findRightmostToken(candidate, sourceFile);
}
/**
* Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens.
*/
- function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) {
+ function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) {
for (var i = exclusiveStartPosition - 1; i >= 0; i--) {
var child = children[i];
if (isWhiteSpaceOnlyJsxText(child)) {
ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`");
}
- else if (nodeHasTokens(children[i])) {
+ else if (nodeHasTokens(children[i], sourceFile)) {
return children[i];
}
}
@@ -83881,22 +85017,22 @@ var ts;
remainingLessThanTokens++;
break;
case 18 /* CloseBraceToken */:
- // This can be object type, skip untill we find the matching open brace token
- // Skip untill the matching open brace token
+ // This can be object type, skip until we find the matching open brace token
+ // Skip until the matching open brace token
token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile);
if (!token)
return false;
break;
case 20 /* CloseParenToken */:
- // This can be object type, skip untill we find the matching open brace token
- // Skip untill the matching open brace token
+ // This can be object type, skip until we find the matching open brace token
+ // Skip until the matching open brace token
token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile);
if (!token)
return false;
break;
case 22 /* CloseBracketToken */:
- // This can be object type, skip untill we find the matching open brace token
- // Skip untill the matching open brace token
+ // This can be object type, skip until we find the matching open brace token
+ // Skip until the matching open brace token
token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile);
if (!token)
return false;
@@ -83950,10 +85086,10 @@ var ts;
}
}
ts.hasDocComment = hasDocComment;
- function nodeHasTokens(n) {
+ function nodeHasTokens(n, sourceFile) {
// If we have a token or node that has a non-zero width, it must have tokens.
// Note: getWidth() does not take trivia into account.
- return n.getWidth() !== 0;
+ return n.getWidth(sourceFile) !== 0;
}
function getNodeModifiers(node) {
var flags = ts.getCombinedModifierFlags(node);
@@ -84050,11 +85186,6 @@ var ts;
return false;
}
ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern;
- function hasTrailingDirectorySeparator(path) {
- var lastCharacter = path.charAt(path.length - 1);
- return lastCharacter === "/" || lastCharacter === "\\";
- }
- ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
function isInReferenceComment(sourceFile, position) {
return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) {
var commentText = sourceFile.text.substring(c.pos, c.end);
@@ -84077,6 +85208,10 @@ var ts;
return ts.createTextSpanFromBounds(range.pos, range.end);
}
ts.createTextSpanFromRange = createTextSpanFromRange;
+ function createTextRangeFromSpan(span) {
+ return ts.createTextRange(span.start, span.start + span.length);
+ }
+ ts.createTextRangeFromSpan = createTextRangeFromSpan;
function createTextChangeFromStartLength(start, length, newText) {
return createTextChange(ts.createTextSpan(start, length), newText);
}
@@ -84157,6 +85292,44 @@ var ts;
return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
}
ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
+ function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier) {
+ return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier) : undefined;
+ }
+ ts.makeImportIfNecessary = makeImportIfNecessary;
+ function makeImport(defaultImport, namedImports, moduleSpecifier) {
+ return ts.createImportDeclaration(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, defaultImport || namedImports
+ ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined)
+ : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier) : moduleSpecifier);
+ }
+ ts.makeImport = makeImport;
+ function symbolNameNoDefault(symbol) {
+ var escaped = symbolEscapedNameNoDefault(symbol);
+ return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped);
+ }
+ ts.symbolNameNoDefault = symbolNameNoDefault;
+ function symbolEscapedNameNoDefault(symbol) {
+ if (symbol.escapedName !== "default" /* Default */) {
+ return symbol.escapedName;
+ }
+ return ts.firstDefined(symbol.declarations, function (decl) {
+ var name = ts.getNameOfDeclaration(decl);
+ return name && name.kind === 71 /* Identifier */ ? name.escapedText : undefined;
+ });
+ }
+ ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault;
+ function getPropertySymbolFromBindingElement(checker, bindingElement) {
+ var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
+ var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
+ if (propSymbol && propSymbol.flags & 98304 /* Accessor */) {
+ // See GH#16922
+ ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */));
+ return propSymbol.target;
+ }
+ return propSymbol;
+ }
+ ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement;
})(ts || (ts = {}));
// Display-part writer helpers
/* @internal */
@@ -84489,20 +85662,20 @@ var ts;
* user was before extracting it.
*/
/* @internal */
- function getRenameLocation(edits, renameFilename, name, isDeclaredBeforeUse) {
+ function getRenameLocation(edits, renameFilename, name, preferLastLocation) {
var delta = 0;
var lastPos = -1;
for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
- var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges;
+ var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges;
ts.Debug.assert(fileName === renameFilename);
- for (var _b = 0, textChanges_2 = textChanges_1; _b < textChanges_2.length; _b++) {
- var change = textChanges_2[_b];
+ for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) {
+ var change = textChanges_1[_b];
var span = change.span, newText = change.newText;
var index = newText.indexOf(name);
if (index !== -1) {
lastPos = span.start + delta + index;
// If the reference comes first, return immediately.
- if (!isDeclaredBeforeUse) {
+ if (!preferLastLocation) {
return lastPos;
}
}
@@ -84510,7 +85683,7 @@ var ts;
}
}
// If the declaration comes first, return the position of the last occurrence.
- ts.Debug.assert(isDeclaredBeforeUse);
+ ts.Debug.assert(preferLastLocation);
ts.Debug.assert(lastPos >= 0);
return lastPos;
}
@@ -85158,16 +86331,16 @@ 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 288 /* JSDocParameterTag */:
+ case 290 /* JSDocParameterTag */:
processJSDocParameterTag(tag);
break;
- case 291 /* JSDocTemplateTag */:
+ case 293 /* JSDocTemplateTag */:
processJSDocTemplateTag(tag);
break;
- case 290 /* JSDocTypeTag */:
+ case 292 /* JSDocTypeTag */:
processElement(tag.typeExpression);
break;
- case 289 /* JSDocReturnTag */:
+ case 291 /* JSDocReturnTag */:
processElement(tag.typeExpression);
break;
}
@@ -85413,7 +86586,7 @@ var ts;
var scriptPath = node.getSourceFile().path;
var scriptDirectory = ts.getDirectoryPath(scriptPath);
if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) {
- var extensions = ts.getSupportedExtensions(compilerOptions);
+ var extensions = getSupportedExtensionsForModuleResolution(compilerOptions);
if (compilerOptions.rootDirs) {
return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath);
}
@@ -85426,6 +86599,12 @@ var ts;
return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker);
}
}
+ function getSupportedExtensionsForModuleResolution(compilerOptions) {
+ var extensions = ts.getSupportedExtensions(compilerOptions);
+ return compilerOptions.resolveJsonModule && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ?
+ extensions.concat(".json" /* Json */) :
+ extensions;
+ }
/**
* Takes a script path and returns paths for all potential folders that could be merged with its
* containing folder via the "rootDirs" compiler option
@@ -85464,13 +86643,16 @@ var ts;
* Remove the basename from the path. Note that we don't use the basename to filter completions;
* the client is responsible for refining completions.
*/
- fragment = ts.getDirectoryPath(fragment);
+ if (!ts.hasTrailingDirectorySeparator(fragment)) {
+ fragment = ts.getDirectoryPath(fragment);
+ }
if (fragment === "") {
fragment = "." + ts.directorySeparator;
}
fragment = ts.ensureTrailingDirectorySeparator(fragment);
- var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment));
- var baseDirectory = ts.getDirectoryPath(absolutePath);
+ // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths
+ var absolutePath = ts.resolvePath(scriptPath, fragment);
+ var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath);
var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
if (tryDirectoryExists(host, baseDirectory)) {
// Enumerate the available files if possible
@@ -85489,7 +86671,7 @@ var ts;
if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) {
continue;
}
- var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath));
+ var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath));
if (!foundFiles.has(foundFileName)) {
foundFiles.set(foundFileName, true);
}
@@ -85502,8 +86684,8 @@ var ts;
var directories = tryGetDirectories(host, baseDirectory);
if (directories) {
for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) {
- var directory = directories_1[_a];
- var directoryName = ts.getBaseFileName(ts.normalizePath(directory));
+ var directory_2 = directories_1[_a];
+ var directoryName = ts.getBaseFileName(ts.normalizePath(directory_2));
if (directoryName !== "@types") {
result.push(nameAndKind(directoryName, "directory" /* directory */));
}
@@ -85522,7 +86704,7 @@ var ts;
function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) {
var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths;
var result = [];
- var fileExtensions = ts.getSupportedExtensions(compilerOptions);
+ var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions);
if (baseUrl) {
var projectDir = compilerOptions.project || host.getCurrentDirectory();
var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl);
@@ -85530,7 +86712,7 @@ var ts;
for (var path in paths) {
var patterns = paths[path];
if (paths.hasOwnProperty(path) && patterns) {
- var _loop_10 = function (name, kind) {
+ var _loop_11 = function (name, kind) {
// 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));
@@ -85538,12 +86720,12 @@ var ts;
};
for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) {
var _b = _a[_i], name = _b.name, kind = _b.kind;
- _loop_10(name, kind);
+ _loop_11(name, kind);
}
}
}
}
- var fragmentDirectory = containsSlash(fragment) ? ts.getDirectoryPath(fragment) : undefined;
+ var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined;
for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) {
var ambientName = _d[_c];
result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */));
@@ -85554,7 +86736,7 @@ var ts;
// (But do if we didn't find anything, e.g. 'package.json' missing.)
var foundGlobal = false;
if (fragmentDirectory === undefined) {
- var _loop_11 = function (moduleName) {
+ var _loop_12 = function (moduleName) {
if (!result.some(function (entry) { return entry.name === moduleName; })) {
foundGlobal = true;
result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */));
@@ -85562,7 +86744,7 @@ var ts;
};
for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) {
var moduleName = _f[_e];
- _loop_11(moduleName);
+ _loop_12(moduleName);
}
}
if (!foundGlobal) {
@@ -85598,12 +86780,13 @@ var ts;
}
// The prefix has two effective parts: the directory path and the base component after the filepath that is not a
// full directory component. For example: directory/path/of/prefix/base*
- var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix);
- var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix);
- var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix);
+ var normalizedPrefix = ts.resolvePath(parsed.prefix);
+ var normalizedPrefixDirectory = ts.hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : ts.getDirectoryPath(normalizedPrefix);
+ var normalizedPrefixBase = ts.hasTrailingDirectorySeparator(parsed.prefix) ? "" : ts.getBaseFileName(normalizedPrefix);
var fragmentHasPath = containsSlash(fragment);
+ var fragmentDirectory = fragmentHasPath ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined;
// Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call
- var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory;
+ var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory;
var normalizedSuffix = ts.normalizePath(parsed.suffix);
// Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b".
var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory));
@@ -85764,15 +86947,6 @@ var ts;
}
return false;
}
- function normalizeAndPreserveTrailingSlash(path) {
- if (ts.normalizeSlashes(path) === "./") {
- // normalizePath turns "./" into "". "" + "/" would then be a rooted path instead of a relative one, so avoid this particular case.
- // There is no problem for adding "/" to a non-empty string -- it's only a problem at the beginning.
- return "";
- }
- var norm = ts.normalizePath(path);
- return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(norm) : norm;
- }
/**
* Matches a triple slash reference directive with an incomplete string literal for its path. Used
* to determine if the caret is currently within the string literal and capture the literal fragment
@@ -85892,7 +87066,7 @@ var ts;
return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries };
}
case 2 /* Types */: {
- var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "type" /* typeElement */, sortText: "0" }); });
+ var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); });
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries };
}
default:
@@ -86459,11 +87633,11 @@ var ts;
if (tag.tagName.pos <= position && position <= tag.tagName.end) {
return { kind: 1 /* JsDocTagName */ };
}
- if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 275 /* JSDocTypeExpression */) {
+ if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 277 /* JSDocTypeExpression */) {
currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true);
if (!currentToken ||
(!ts.isDeclarationName(currentToken) &&
- (currentToken.parent.kind !== 293 /* JSDocPropertyTag */ ||
+ (currentToken.parent.kind !== 295 /* JSDocPropertyTag */ ||
currentToken.parent.name !== currentToken))) {
// Use as type location if inside tag's type expression
insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
@@ -86599,12 +87773,8 @@ var ts;
}
else if (isRightOfOpenTag) {
var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined");
- if (tryGetGlobalSymbols()) {
- symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (67216319 /* Value */ | 2097152 /* Alias */)); }));
- }
- else {
- symbols = tagSymbols;
- }
+ tryGetGlobalSymbols();
+ symbols = tagSymbols.concat(symbols);
completionKind = 3 /* MemberLike */;
}
else if (isStartingCloseTag) {
@@ -86628,11 +87798,11 @@ var ts;
return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer };
function isTagWithTypeExpression(tag) {
switch (tag.kind) {
- case 288 /* JSDocParameterTag */:
- case 293 /* JSDocPropertyTag */:
- case 289 /* JSDocReturnTag */:
- case 290 /* JSDocTypeTag */:
- case 292 /* JSDocTypedefTag */:
+ case 290 /* JSDocParameterTag */:
+ case 295 /* JSDocPropertyTag */:
+ case 291 /* JSDocReturnTag */:
+ case 292 /* JSDocTypeTag */:
+ case 294 /* JSDocTypedefTag */:
return true;
}
}
@@ -86894,7 +88064,7 @@ var ts;
var exportedSymbols = typeChecker.getExportsOfModule(symbol);
// If the exported symbols contains type,
// symbol can be referenced at locations where type is allowed
- return ts.forEach(exportedSymbols, symbolCanBeReferencedAtTypeLocation);
+ return exportedSymbols.some(symbolCanBeReferencedAtTypeLocation);
}
}
function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) {
@@ -87670,7 +88840,7 @@ var ts;
function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) {
// class c { method() { } | method2() { } }
switch (location.kind) {
- case 294 /* SyntaxList */:
+ case 296 /* 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);
@@ -87707,6 +88877,10 @@ var ts;
}
function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) {
switch (triggerCharacter) {
+ case ".":
+ case "/":
+ case "@":
+ return true;
case '"':
case "'":
case "`":
@@ -87716,7 +88890,7 @@ var ts;
// Opening JSX tag
return contextToken.kind === 27 /* LessThanToken */ && contextToken.parent.kind !== 199 /* BinaryExpression */;
default:
- return ts.Debug.fail(triggerCharacter);
+ return ts.Debug.assertNever(triggerCharacter);
}
}
function isStringLiteralOrTemplate(node) {
@@ -87811,6 +88985,10 @@ var ts;
case 125 /* GetKeyword */:
case 136 /* SetKeyword */:
return getFromAllDeclarations(ts.isAccessor, [125 /* GetKeyword */, 136 /* SetKeyword */]);
+ case 121 /* AwaitKeyword */:
+ return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences);
+ case 120 /* AsyncKeyword */:
+ return highlightSpans(getAsyncAndAwaitOccurrences(node));
default:
return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent))
? highlightSpans(getModifierOccurrences(node.kind, node.parent))
@@ -88058,6 +89236,29 @@ var ts;
});
return keywords;
}
+ function getAsyncAndAwaitOccurrences(node) {
+ var func = ts.getContainingFunction(node);
+ if (!func) {
+ return undefined;
+ }
+ var keywords = [];
+ if (func.modifiers) {
+ func.modifiers.forEach(function (modifier) {
+ pushKeywordIf(keywords, modifier, 120 /* AsyncKeyword */);
+ });
+ }
+ ts.forEachChild(func, aggregate);
+ return keywords;
+ function aggregate(node) {
+ if (ts.isAwaitExpression(node)) {
+ pushKeywordIf(keywords, node.getFirstToken(), 121 /* AwaitKeyword */);
+ }
+ // Do not cross function boundaries.
+ if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) {
+ ts.forEachChild(node, aggregate);
+ }
+ }
+ }
function getIfElseOccurrences(ifStatement, sourceFile) {
var keywords = getIfElseKeywords(ifStatement, sourceFile);
var result = [];
@@ -88178,9 +89379,10 @@ var ts;
function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) {
var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true);
var entry = bucket.get(path);
+ var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target;
if (!entry) {
// Have never seen this file with these settings. Create a new source file for it.
- var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind);
+ var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind);
entry = {
sourceFile: sourceFile,
languageServiceRefCount: 1,
@@ -88309,6 +89511,8 @@ var ts;
addIndirectUser(direct.getSourceFile());
}
break;
+ case 71 /* Identifier */: // for 'const x = require("y");
+ break; // TODO: GH#23879
case 242 /* ImportEqualsDeclaration */:
handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */));
break;
@@ -88338,6 +89542,17 @@ var ts;
directImports.push(direct);
}
break;
+ case 178 /* ImportType */:
+ if (direct.qualifier) {
+ // `import("foo").x` named import
+ directImports.push(direct);
+ }
+ else {
+ // TODO: GH#23879
+ }
+ break;
+ default:
+ ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct));
}
}
}
@@ -88415,6 +89630,9 @@ var ts;
return;
}
if (decl.kind === 178 /* ImportType */) {
+ if (decl.qualifier) { // TODO: GH#23879
+ singleReferences.push(decl.qualifier.kind === 71 /* Identifier */ ? decl.qualifier : decl.qualifier.right);
+ }
return;
}
// Ignore if there's a grammar error
@@ -88442,7 +89660,7 @@ var ts;
var name = importClause.name;
// If a default import has the same name as the default export, allow to rename it.
// Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that.
- if (name && (!isForRename || name.escapedText === symbolName(exportSymbol))) {
+ if (name && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) {
var defaultImportAlias = checker.getSymbolAtLocation(name);
addSearch(name, defaultImportAlias);
}
@@ -88500,24 +89718,18 @@ var ts;
function findNamespaceReExports(sourceFileLike, name, checker) {
var namespaceImportSymbol = checker.getSymbolAtLocation(name);
return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) {
- if (statement.kind !== 249 /* ExportDeclaration */)
+ if (!ts.isExportDeclaration(statement))
return;
- var _a = statement, exportClause = _a.exportClause, moduleSpecifier = _a.moduleSpecifier;
- if (moduleSpecifier || !exportClause)
- return;
- for (var _i = 0, _b = exportClause.elements; _i < _b.length; _i++) {
- var element = _b[_i];
- if (checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol) {
- return true;
- }
- }
+ var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier;
+ return !moduleSpecifier && exportClause &&
+ exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; });
});
}
function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
var refs = [];
var checker = program.getTypeChecker();
- for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
- var referencingFile = sourceFiles_4[_i];
+ for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
+ var referencingFile = sourceFiles_5[_i];
var searchSourceFile = searchModuleSymbol.valueDeclaration;
if (searchSourceFile.kind === 273 /* SourceFile */) {
for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
@@ -88547,8 +89759,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_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
- var sourceFile = sourceFiles_5[_i];
+ for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
+ var sourceFile = sourceFiles_6[_i];
cancellationToken.throwIfCancellationRequested();
forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
@@ -88653,6 +89865,9 @@ var ts;
else if (ts.isBinaryExpression(parent.parent)) {
return getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ true);
}
+ else if (ts.isJSDocTypedefTag(parent)) {
+ return exportInfo(symbol, 0 /* Named */);
+ }
}
function getExportAssignmentExport(ex) {
// Get the symbol for the `export =` node; its parent is the module it's the export of.
@@ -88697,7 +89912,7 @@ var ts;
// If the import has a different name than the export, do not continue searching.
// If `importedName` is undefined, do continue searching as the export is anonymous.
// (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.)
- var importedName = symbolName(importedSymbol);
+ var importedName = ts.symbolEscapedNameNoDefault(importedSymbol);
if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) {
return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport);
}
@@ -88764,15 +89979,6 @@ var ts;
return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined;
}
FindAllReferences.getExportInfo = getExportInfo;
- function symbolName(symbol) {
- if (symbol.escapedName !== "default" /* Default */) {
- return symbol.escapedName;
- }
- return ts.forEach(symbol.declarations, function (decl) {
- var name = ts.getNameOfDeclaration(decl);
- return name && name.kind === 71 /* Identifier */ && name.escapedText;
- });
- }
/** If at an export specifier, go to the symbol it refers to. */
function skipExportSpecifierSymbol(symbol, checker) {
// For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does.
@@ -88847,9 +90053,9 @@ var ts;
// 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 === 270 /* ShorthandPropertyAssignment */) {
- var result_4 = [];
- FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); });
- return result_4;
+ var result_5 = [];
+ FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); });
+ return result_5;
}
else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
// References to and accesses on the super keyword only have one possible implementation, so no
@@ -88897,7 +90103,7 @@ var ts;
case "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;
+ 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 };
}
case "string": {
@@ -89041,6 +90247,8 @@ var ts;
case 243 /* ImportDeclaration */:
case 249 /* ExportDeclaration */:
return true;
+ case 177 /* LiteralType */:
+ return ts.isImportTypeNode(node.parent.parent);
case 186 /* CallExpression */:
return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) || ts.isImportCall(node.parent);
default:
@@ -89160,7 +90368,6 @@ var ts;
return ts.firstDefined(symbol.declarations, function (decl) {
if (!decl.parent) {
// Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here.
- ts.Debug.assert(decl.kind === 273 /* SourceFile */);
ts.Debug.fail("Unexpected symbol at " + ts.Debug.showSyntaxKind(node) + ": " + ts.Debug.showSymbol(symbol));
}
return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent)
@@ -89279,7 +90486,8 @@ var ts;
for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) {
var singleRef = singleReferences_1[_i];
// At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename.
- if (!(state.options.isForRename && (ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */)) {
+ if (hasMatchingMeaning(singleRef, state) &&
+ !(state.options.isForRename && (ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */)) {
addRef(singleRef);
}
}
@@ -89333,22 +90541,14 @@ var ts;
var bindingElement = ts.getDeclarationOfKind(symbol, 181 /* BindingElement */);
if (bindingElement &&
bindingElement.parent.kind === 179 /* ObjectBindingPattern */ &&
+ ts.isIdentifier(bindingElement.name) &&
!bindingElement.propertyName) {
return bindingElement;
}
}
function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) {
var bindingElement = getObjectBindingElementWithoutPropertyName(symbol);
- if (!bindingElement)
- return undefined;
- var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
- var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
- if (propSymbol && propSymbol.flags & 98304 /* Accessor */) {
- // See GH#16922
- ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */));
- return propSymbol.target;
- }
- return propSymbol;
+ return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement);
}
/**
* Determines the smallest scope in which a symbol may have named references.
@@ -89519,6 +90719,9 @@ var ts;
getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere);
}
}
+ function hasMatchingMeaning(referenceLocation, state) {
+ return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning);
+ }
function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) {
var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (!isValidReferencePosition(referenceLocation, search.text)) {
@@ -89534,9 +90737,8 @@ var ts;
}
return;
}
- if (!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning)) {
+ if (!hasMatchingMeaning(referenceLocation, state))
return;
- }
var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation);
if (!referenceSymbol) {
return;
@@ -90197,7 +91399,9 @@ var ts;
var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration);
// For a function, if this is the original function definition, return just sigInfo.
// If this is the original constructor definition, parent is the class.
- return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; })
+ return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; }) ||
+ // TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias
+ symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })
? [sigInfo]
: [sigInfo].concat(getDefinitionFromSymbol(typeChecker, symbol, node));
}
@@ -90252,14 +91456,14 @@ var ts;
function getReferenceAtPosition(sourceFile, position, program) {
var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position);
if (referencePath) {
- var file = ts.tryResolveScriptReference(program, sourceFile, referencePath);
- return file && { fileName: referencePath.fileName, file: file };
+ var file_15 = ts.tryResolveScriptReference(program, sourceFile, referencePath);
+ return file_15 && { fileName: referencePath.fileName, file: file_15 };
}
var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
if (typeReferenceDirective) {
var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName);
- var file = reference && program.getSourceFile(reference.resolvedFileName);
- return file && { fileName: typeReferenceDirective.fileName, file: file };
+ var file_16 = reference && program.getSourceFile(reference.resolvedFileName);
+ return file_16 && { fileName: typeReferenceDirective.fileName, file: file_16 };
}
return undefined;
}
@@ -90495,9 +91699,9 @@ var ts;
JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
function getCommentHavingNodes(declaration) {
switch (declaration.kind) {
- case 293 /* JSDocPropertyTag */:
+ case 295 /* JSDocPropertyTag */:
return [declaration];
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return [declaration.parent];
default:
return ts.getJSDocCommentsAndTags(declaration);
@@ -90518,15 +91722,15 @@ var ts;
function getCommentText(tag) {
var comment = tag.comment;
switch (tag.kind) {
- case 286 /* JSDocAugmentsTag */:
+ case 288 /* JSDocAugmentsTag */:
return withNode(tag.class);
- case 291 /* JSDocTemplateTag */:
+ case 293 /* JSDocTemplateTag */:
return withList(tag.typeParameters);
- case 290 /* JSDocTypeTag */:
+ case 292 /* JSDocTypeTag */:
return withNode(tag.typeExpression);
- case 292 /* JSDocTypedefTag */:
- case 293 /* JSDocPropertyTag */:
- case 288 /* JSDocParameterTag */:
+ case 294 /* JSDocTypedefTag */:
+ case 295 /* JSDocPropertyTag */:
+ case 290 /* JSDocParameterTag */:
var name = tag.name;
return name ? withNode(name) : comment;
default:
@@ -90915,8 +92119,8 @@ var ts;
getTypingNamesFromSourceFileNames(fileNames);
// add typings for unresolved imports
if (unresolvedImports) {
- var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
- addInferredTypings(module, "Inferred typings from unresolved imports");
+ var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
+ addInferredTypings(module_1, "Inferred typings from unresolved imports");
}
// Add the cached typing locations for inferred typings that are already installed
packageNameToTypingLocation.forEach(function (typing, name) {
@@ -91013,8 +92217,8 @@ var ts;
if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
continue;
}
- var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
- var packageJson = result_5.config;
+ var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
+ var packageJson = result_6.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.
@@ -91114,7 +92318,7 @@ var ts;
if (!patternMatcher)
return ts.emptyArray;
var rawItems = [];
- var _loop_12 = function (sourceFile) {
+ var _loop_13 = function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) {
return "continue";
@@ -91124,9 +92328,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_12(sourceFile);
+ for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) {
+ var sourceFile = sourceFiles_7[_i];
+ _loop_13(sourceFile);
}
rawItems.sort(compareNavigateToItems);
if (maxResultCount !== undefined) {
@@ -91503,7 +92707,7 @@ var ts;
if (ts.hasJSDocNodes(node)) {
ts.forEach(node.jsDoc, function (jsDoc) {
ts.forEach(jsDoc.tags, function (tag) {
- if (tag.kind === 292 /* JSDocTypedefTag */) {
+ if (tag.kind === 294 /* JSDocTypedefTag */) {
addLeafNode(tag);
}
});
@@ -91578,6 +92782,7 @@ var ts;
}
/** Merge source into target. Source should be thrown away after this is called. */
function merge(target, source) {
+ var _a;
target.additionalNodes = target.additionalNodes || [];
target.additionalNodes.push(source.node);
if (source.additionalNodes) {
@@ -91588,7 +92793,6 @@ var ts;
mergeChildren(target.children);
sortChildren(target.children);
}
- var _a;
}
/** Recursively ensure that each NavNode's children are in sorted order. */
function sortChildren(children) {
@@ -91616,7 +92820,7 @@ var ts;
case 192 /* ArrowFunction */:
case 204 /* ClassExpression */:
return getFunctionOrClassName(node);
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return getJSDocTypedefTagName(node);
default:
return undefined;
@@ -91659,7 +92863,7 @@ var ts;
return "()";
case 159 /* IndexSignature */:
return "[]";
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return getJSDocTypedefTagName(node);
default:
return "";
@@ -91707,7 +92911,7 @@ var ts;
case 238 /* ModuleDeclaration */:
case 273 /* SourceFile */:
case 236 /* TypeAliasDeclaration */:
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return true;
case 154 /* Constructor */:
case 153 /* MethodDeclaration */:
@@ -92107,21 +93311,12 @@ var ts;
}
ts.getEditsForFileRename = getEditsForFileRename;
function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) {
- var cfg = program.getCompilerOptions().configFile;
- if (!cfg)
- return;
- var oldFile = cfg.jsonObject && getFilesEntry(cfg.jsonObject, oldFilePath);
+ var configFile = program.getCompilerOptions().configFile;
+ var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath);
if (oldFile) {
- changeTracker.replaceRangeWithText(cfg, createStringRange(oldFile, cfg), newFilePath);
+ changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath);
}
}
- function getFilesEntry(cfg, fileName) {
- var filesProp = ts.find(cfg.properties, function (prop) {
- return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files";
- });
- var files = filesProp && filesProp.initializer;
- return files && ts.isArrayLiteralExpression(files) ? ts.find(files.elements, function (e) { return ts.isStringLiteral(e) && e.text === fileName; }) : undefined;
- }
function isRef(toUpdate) {
return "fileName" in toUpdate;
}
@@ -92142,7 +93337,7 @@ var ts;
if (checker.getSymbolAtLocation(importStringLiteral))
continue;
var resolved = program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
- if (ts.contains(resolved.failedLookupLocations, oldFilePath)) {
+ if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) {
result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral });
}
}
@@ -92151,11 +93346,11 @@ var ts;
}
function getPathUpdater(oldFilePath, newFilePath, host) {
// Get the relative path from old to new location, and append it on to the end of imports and normalize.
- var rel = ts.getRelativePath(newFilePath, ts.getDirectoryPath(oldFilePath), ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host)));
+ var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host)));
return function (oldPath) {
if (!ts.pathIsRelative(oldPath))
return;
- return ts.ensurePathIsRelative(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel)));
+ return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel)));
};
}
function createStringRange(node, sourceFile) {
@@ -92176,7 +93371,27 @@ var ts;
OutliningElementsCollector.collectElements = collectElements;
function addNodeOutliningSpans(sourceFile, cancellationToken, out) {
var depthRemaining = 40;
- sourceFile.forEachChild(function walk(n) {
+ var current = 0;
+ var statements = sourceFile.statements;
+ var n = statements.length;
+ while (current < n) {
+ while (current < n && !ts.isAnyImportSyntax(statements[current])) {
+ visitNonImportNode(statements[current]);
+ current++;
+ }
+ if (current === n)
+ break;
+ var firstImport = current;
+ while (current < n && ts.isAnyImportSyntax(statements[current])) {
+ addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out);
+ current++;
+ }
+ var lastImport = current - 1;
+ if (lastImport !== firstImport) {
+ out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 91 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */));
+ }
+ }
+ function visitNonImportNode(n) {
if (depthRemaining === 0)
return;
cancellationToken.throwIfCancellationRequested();
@@ -92189,17 +93404,17 @@ var ts;
depthRemaining--;
if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) {
// Consider an 'else if' to be on the same depth as the 'if'.
- walk(n.expression);
- walk(n.thenStatement);
+ visitNonImportNode(n.expression);
+ visitNonImportNode(n.thenStatement);
depthRemaining++;
- walk(n.elseStatement);
+ visitNonImportNode(n.elseStatement);
depthRemaining--;
}
else {
- n.forEachChild(walk);
+ n.forEachChild(visitNonImportNode);
}
depthRemaining++;
- });
+ }
}
function addRegionOutliningSpans(sourceFile, out) {
var regions = [];
@@ -92214,7 +93429,7 @@ var ts;
}
if (!result[1]) {
var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
- regions.push(createOutliningSpan(span, span, /*autoCollapse*/ false, result[2] || "#region"));
+ regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region"));
}
else {
var region = regions.pop();
@@ -92248,7 +93463,7 @@ var ts;
break;
case 3 /* MultiLineCommentTrivia */:
combineAndAddMultipleSingleLineComments();
- out.push(createOutliningSpanFromBounds(pos, end));
+ out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */));
singleLineCommentCount = 0;
break;
default:
@@ -92259,12 +93474,12 @@ var ts;
function combineAndAddMultipleSingleLineComments() {
// Only outline spans of two or more consecutive single line comments
if (singleLineCommentCount > 1) {
- out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd));
+ out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */));
}
}
}
- function createOutliningSpanFromBounds(pos, end) {
- return createOutliningSpan(ts.createTextSpanFromBounds(pos, end));
+ function createOutliningSpanFromBounds(pos, end, kind) {
+ return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind);
}
function getOutliningSpanForNode(n, sourceFile) {
switch (n.kind) {
@@ -92298,7 +93513,7 @@ var ts;
default:
// Block was a standalone block. In this case we want to only collapse
// the span of the block, independent of any parent span.
- return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile));
+ return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */);
}
case 239 /* ModuleBlock */:
return spanForNode(n.parent);
@@ -92330,14 +93545,14 @@ var ts;
return undefined;
}
var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd());
- return createOutliningSpan(textSpan, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse);
+ return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse);
}
}
- function createOutliningSpan(textSpan, hintSpan, autoCollapse, bannerText) {
+ function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) {
if (hintSpan === void 0) { hintSpan = textSpan; }
if (autoCollapse === void 0) { autoCollapse = false; }
if (bannerText === void 0) { bannerText = "..."; }
- return { textSpan: textSpan, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse };
+ return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse };
}
})(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {}));
})(ts || (ts = {}));
@@ -92620,13 +93835,13 @@ var ts;
// Assumes 'value' is already lowercase.
function indexOfIgnoringCase(str, value) {
var n = str.length - value.length;
- var _loop_13 = function (start) {
+ var _loop_14 = 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_13(start);
+ var state_4 = _loop_14(start);
if (typeof state_4 === "object")
return state_4.value;
}
@@ -93291,7 +94506,7 @@ var ts;
var nameToDeclarations = sourceFile.getNamedDeclarations();
var declarations = nameToDeclarations.get(name.text);
if (declarations) {
- var _loop_14 = function (declaration) {
+ var _loop_15 = function (declaration) {
var symbol = declaration.symbol;
if (symbol) {
var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration);
@@ -93305,7 +94520,7 @@ var ts;
};
for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) {
var declaration = declarations_12[_b];
- var state_5 = _loop_14(declaration);
+ var state_5 = _loop_15(declaration);
if (typeof state_5 === "object")
return state_5.value;
}
@@ -93694,8 +94909,8 @@ var ts;
var name = importNameForConvertToDefaultImport(importNode);
if (!name)
continue;
- var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
- var resolvedFile = module && program.getSourceFile(module.resolvedFileName);
+ var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
+ var resolvedFile = module_2 && program.getSourceFile(module_2.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));
}
@@ -94434,7 +95649,7 @@ var ts;
return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; });
});
options = ts.cloneCompilerOptions(options);
- var _loop_15 = function (opt) {
+ var _loop_16 = function (opt) {
if (!ts.hasProperty(options, opt.name)) {
return "continue";
}
@@ -94453,7 +95668,7 @@ var ts;
};
for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) {
var opt = commandLineOptionsStringToEnum_1[_i];
- _loop_15(opt);
+ _loop_16(opt);
}
return options;
}
@@ -94857,6 +96072,7 @@ var ts;
rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */),
rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */),
rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */),
+ rule("NoSpaceBetweenImportParenInImportType", 91 /* ImportKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */),
// Special handling of unary operators.
// Prefix operators generally shouldn't have a space between
// them and their target unary expression.
@@ -95317,6 +96533,9 @@ var ts;
function isArrowFunctionContext(context) {
return context.contextNode.kind === 192 /* ArrowFunction */;
}
+ function isImportTypeContext(context) {
+ return context.contextNode.kind === 178 /* ImportType */;
+ }
function isNonJsxSameLineTokenContext(context) {
return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */;
}
@@ -95439,18 +96658,18 @@ var ts;
// This array is used only during construction of the rulesbucket in the map
var rulesBucketConstructionStateList = new Array(map.length);
for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) {
- var rule = rules_1[_i];
- var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific;
- for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) {
+ var rule_1 = rules_1[_i];
+ var specificRule = rule_1.leftTokenRange.isSpecific && rule_1.rightTokenRange.isSpecific;
+ for (var _a = 0, _b = rule_1.leftTokenRange.tokens; _a < _b.length; _a++) {
var left = _b[_a];
- for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) {
+ for (var _c = 0, _d = rule_1.rightTokenRange.tokens; _c < _d.length; _c++) {
var right = _d[_c];
var index = getRuleBucketIndex(left, right);
var rulesBucket = map[index];
if (rulesBucket === undefined) {
rulesBucket = map[index] = [];
}
- addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index);
+ addRule(rulesBucket, rule_1.rule, specificRule, rulesBucketConstructionStateList, index);
}
}
}
@@ -96757,7 +97976,7 @@ var ts;
NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace";
})(NextTokenKind || (NextTokenKind = {}));
function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) {
- var nextToken = ts.findNextToken(precedingToken, current);
+ var nextToken = ts.findNextToken(precedingToken, current, sourceFile);
if (!nextToken) {
return 0 /* Unknown */;
}
@@ -96806,9 +98025,10 @@ var ts;
}
function getContainingList(node, sourceFile) {
if (node.parent) {
+ var end = node.end;
switch (node.parent.kind) {
case 161 /* TypeReference */:
- return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end);
case 183 /* ObjectLiteralExpression */:
return node.parent.properties;
case 182 /* ArrayLiteralExpression */:
@@ -96823,22 +98043,25 @@ var ts;
case 163 /* ConstructorType */:
case 158 /* ConstructSignature */: {
var start = node.getStart(sourceFile);
- return getListIfStartEndIsInListRange(node.parent.typeParameters, start, node.getEnd()) ||
- getListIfStartEndIsInListRange(node.parent.parameters, start, node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) ||
+ getListIfStartEndIsInListRange(node.parent.parameters, start, end);
}
case 234 /* ClassDeclaration */:
- return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), end);
case 187 /* NewExpression */:
case 186 /* CallExpression */: {
var start = node.getStart(sourceFile);
- return getListIfStartEndIsInListRange(node.parent.typeArguments, start, node.getEnd()) ||
- getListIfStartEndIsInListRange(node.parent.arguments, start, node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) ||
+ getListIfStartEndIsInListRange(node.parent.arguments, start, end);
}
case 232 /* VariableDeclarationList */:
- return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end);
case 246 /* NamedImports */:
case 250 /* NamedExports */:
- return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end);
+ case 179 /* ObjectBindingPattern */:
+ case 180 /* ArrayBindingPattern */:
+ return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end);
}
}
return undefined;
@@ -97160,10 +98383,10 @@ var ts;
return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile);
}
function getAdjustedEndPosition(sourceFile, node, options) {
+ var end = node.end;
if (options.useNonAdjustedEndPosition || ts.isExpression(node)) {
- return node.getEnd();
+ return end;
}
- var end = node.getEnd();
var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))
? newEnd
@@ -97188,6 +98411,7 @@ var ts;
this.newLineCharacter = newLineCharacter;
this.formatContext = formatContext;
this.changes = [];
+ this.newFiles = [];
this.deletedNodesInLists = []; // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
this.classesWithNodesInsertedAtStart = ts.createMap(); // Set implemented as Map
}
@@ -97399,20 +98623,34 @@ var ts;
};
ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) {
var clsStart = cls.getStart(sourceFile);
- var prefix = "";
- var suffix = this.newLineCharacter;
- if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) {
- prefix = this.newLineCharacter;
- // For `class C {\n}`, don't add the trailing "\n"
- if (cls.members.length === 0 && !ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile]))) { // TODO: GH#4130 remove 'as any'
- suffix = "";
- }
- }
var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options)
+ this.formatContext.options.indentSize;
- this.insertNodeAt(sourceFile, cls.members.pos, newElement, { indentation: indentation, prefix: prefix, suffix: suffix });
+ this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls)));
+ };
+ ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) {
+ if (cls.members.length === 0) {
+ if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) {
+ // For `class C {\n}`, don't add the trailing "\n"
+ var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any'
+ return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" };
+ }
+ else {
+ return { prefix: "", suffix: this.newLineCharacter };
+ }
+ }
+ else {
+ return { prefix: this.newLineCharacter, suffix: "" };
+ }
};
ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) {
+ var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode);
+ this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
+ };
+ ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) {
+ var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes));
+ this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after));
+ };
+ ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) {
if (needSemicolonBetween(after, newNode)) {
// check if previous statement ends with semicolon
// if not - insert semicolon to preserve the code from changing the meaning due to ASI
@@ -97421,9 +98659,13 @@ var ts;
}
}
var endPosition = getAdjustedEndPosition(sourceFile, after, {});
- return this.replaceRange(sourceFile, ts.createTextRange(endPosition), newNode, this.getInsertNodeAfterOptions(after));
+ return endPosition;
};
- ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) {
+ ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) {
+ var options = this.getInsertNodeAfterOptionsWorker(after);
+ return __assign({}, options, { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix });
+ };
+ ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) {
if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) {
return { prefix: this.newLineCharacter, suffix: this.newLineCharacter };
}
@@ -97468,13 +98710,16 @@ var ts;
this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " });
}
};
+ ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) {
+ this.insertText(sourceFile, node.getStart(sourceFile), "export ");
+ };
/**
* This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range,
* i.e. arguments in arguments lists, parameters in parameter lists etc.
* Note that separators are part of the node in statements and class elements.
*/
- ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) {
- var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile);
+ ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) {
+ if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); }
if (!containingList) {
ts.Debug.fail("node is not a list element");
return this;
@@ -97600,7 +98845,15 @@ var ts;
*/
ChangeTracker.prototype.getChanges = function (validate) {
this.finishClassesWithNodesInsertedAtStart();
- return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
+ var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
+ for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) {
+ var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements;
+ changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter));
+ }
+ return changes;
+ };
+ ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) {
+ this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements });
};
return ChangeTracker;
}());
@@ -97614,15 +98867,16 @@ var ts;
return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) {
var sourceFile = changesInFile[0].sourceFile;
// order changes by start position
- var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; });
- var _loop_16 = function (i) {
+ // 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_17 = 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_16(i);
+ _loop_17(i);
}
var textChanges = normalized.map(function (c) {
return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
@@ -97631,6 +98885,11 @@ var ts;
});
}
changesToText.getTextChangesFromChanges = getTextChangesFromChanges;
+ function newFileChanges(oldFile, fileName, statements, newLineCharacter) {
+ var text = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter);
+ return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)] };
+ }
+ changesToText.newFileChanges = newFileChanges;
function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) {
if (change.kind === ChangeKind.Remove) {
return "";
@@ -97980,10 +99239,11 @@ var ts;
}
refactor_1.getEditsForRefactor = getEditsForRefactor;
})(refactor = ts.refactor || (ts.refactor = {}));
- function getRefactorContextLength(context) {
- return context.endPosition === undefined ? 0 : context.endPosition - context.startPosition;
+ function getRefactorContextSpan(_a) {
+ var startPosition = _a.startPosition, endPosition = _a.endPosition;
+ return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition);
}
- ts.getRefactorContextLength = getRefactorContextLength;
+ ts.getRefactorContextSpan = getRefactorContextSpan;
})(ts || (ts = {}));
/* @internal */
var ts;
@@ -98087,18 +99347,18 @@ var ts;
}
function transformJSDocType(node) {
switch (node.kind) {
- case 276 /* JSDocAllType */:
- case 277 /* JSDocUnknownType */:
+ case 278 /* JSDocAllType */:
+ case 279 /* JSDocUnknownType */:
return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 280 /* JSDocOptionalType */:
+ case 282 /* JSDocOptionalType */:
return transformJSDocOptionalType(node);
- case 279 /* JSDocNonNullableType */:
+ case 281 /* JSDocNonNullableType */:
return transformJSDocType(node.type);
- case 278 /* JSDocNullableType */:
+ case 280 /* JSDocNullableType */:
return transformJSDocNullableType(node);
- case 282 /* JSDocVariadicType */:
+ case 284 /* JSDocVariadicType */:
return transformJSDocVariadicType(node);
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
return transformJSDocFunctionType(node);
case 161 /* TypeReference */:
return transformJSDocTypeReference(node);
@@ -98122,7 +99382,7 @@ var ts;
}
function transformJSDocParameter(node) {
var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 282 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
+ var isRest = node.type.kind === 284 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
var name = node.name || (isRest ? "rest" : "arg" + index);
var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken;
return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
@@ -98403,7 +99663,7 @@ var ts;
var importNode = ts.importFromModuleSpecifier(moduleSpecifier);
switch (importNode.kind) {
case 242 /* ImportEqualsDeclaration */:
- changes.replaceNode(importingFile, importNode, makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier));
+ changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier));
break;
case 186 /* CallExpression */:
if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) {
@@ -98467,7 +99727,7 @@ var ts;
case 186 /* CallExpression */: {
if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) {
// For side-effecting require() call, just make a side-effecting import.
- changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0]));
+ changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0]));
}
return false;
}
@@ -98540,27 +99800,30 @@ var ts;
changes.deleteNode(sourceFile, assignment.parent);
}
else {
- var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined;
- var changedToDefaultExport = false;
- if (!newNodes) {
- (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]);
+ var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right)
+ : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker)
+ : undefined;
+ if (replacement) {
+ changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]);
+ return replacement[1];
+ }
+ else {
+ changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default");
+ return true;
}
- changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes);
- return changedToDefaultExport;
}
}
else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
convertNamedExport(sourceFile, assignment, changes, exports);
}
return false;
- var _a;
}
/**
* Convert `module.exports = { ... }` to individual exports..
* We can't always do this if the module has interesting members -- then it will be a default export instead.
*/
function tryChangeModuleExportsObject(object) {
- return ts.mapAllOrFail(object.properties, function (prop) {
+ var statements = ts.mapAllOrFail(object.properties, function (prop) {
switch (prop.kind) {
case 155 /* GetAccessor */:
case 156 /* SetAccessor */:
@@ -98576,6 +99839,7 @@ var ts;
ts.Debug.assertNever(prop);
}
});
+ return statements && [statements, true];
}
function convertNamedExport(sourceFile, assignment, changes, exports) {
// If "originalKeywordKind" was set, this is e.g. `exports.
@@ -98596,30 +99860,6 @@ var ts;
convertExportsPropertyAssignment(assignment, sourceFile, changes);
}
}
- function convertModuleExportsToExportDefault(exported, checker) {
- var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)];
- switch (exported.kind) {
- case 191 /* FunctionExpression */:
- case 192 /* ArrowFunction */: {
- // `module.exports = function f() {}` --> `export default function f() {}`
- var fn = exported;
- return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true];
- }
- case 204 /* ClassExpression */: {
- // `module.exports = class C {}` --> `export default class C {}`
- var cls = exported;
- return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true];
- }
- case 186 /* CallExpression */:
- if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteralLike*/ true)) {
- return convertReExportAll(exported.arguments[0], checker);
- }
- // falls through
- default:
- // `module.exports = 0;` --> `export default 0;`
- return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true];
- }
- }
function convertReExportAll(reExported, checker) {
// `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";`
var moduleSpecifier = reExported.text;
@@ -98695,7 +99935,7 @@ var ts;
: makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text);
});
if (importSpecifiers) {
- return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)];
+ return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)];
}
}
// falls through -- object destructuring has an interesting pattern and must be a variable declaration
@@ -98706,7 +99946,7 @@ var ts;
*/
var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers);
return [
- makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier),
+ ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier),
makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)),
];
}
@@ -98755,7 +99995,7 @@ var ts;
// If it was unused, ensure that we at least import *something*.
needDefaultImport = true;
}
- return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
+ return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
}
// Identifiers helpers
function makeUniqueName(name, identifiers) {
@@ -98797,17 +100037,9 @@ var ts;
}
function makeSingleImport(localName, propertyName, moduleSpecifier) {
return propertyName === "default"
- ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier)
- : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
+ ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier)
+ : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
}
- function makeImport(name, namedImports, moduleSpecifier) {
- return makeImportDeclaration(name, namedImports, moduleSpecifier);
- }
- function makeImportDeclaration(name, namedImports, moduleSpecifier) {
- var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports));
- return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifier);
- }
- codefix.makeImportDeclaration = makeImportDeclaration;
function makeImportSpecifier(propertyName, name) {
return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name));
}
@@ -99014,11 +100246,11 @@ var ts;
if (context.symbolToken && ts.isIdentifier(context.symbolToken)) {
for (var _i = 0, existingImports_1 = existingImports; _i < existingImports_1.length; _i++) {
var declaration = existingImports_1[_i].declaration;
- var namespace = getNamespaceImportName(declaration);
- if (namespace) {
- var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace));
+ var namespace_2 = getNamespaceImportName(declaration);
+ if (namespace_2) {
+ var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace_2));
if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) {
- useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken));
+ useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace_2.text, context, context.symbolToken));
}
}
}
@@ -99119,7 +100351,7 @@ var ts;
if (global) {
return [global];
}
- var relativePath = removeExtensionAndIndexPostFix(ts.getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), moduleResolutionKind, addJsExtension);
+ var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension);
if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") {
return [relativePath];
}
@@ -99169,7 +100401,7 @@ var ts;
1 < 2 = true
In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a".
*/
- var pathFromSourceToBaseUrl = ts.getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName);
+ var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName));
var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl);
return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath];
});
@@ -99192,11 +100424,14 @@ var ts;
return symlinks.length === 0 ? [fileName] : symlinks;
}
function getRelativePathNParents(relativePath) {
- var count = 0;
- for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) {
- count++;
+ var components = ts.getPathComponents(relativePath);
+ if (components[0] || components.length === 1)
+ return 0;
+ for (var i = 1; i < components.length; i++) {
+ if (components[i] !== "..")
+ return i - 1;
}
- return count;
+ return components.length - 1;
}
function tryGetModuleNameFromAmbientModule(moduleSymbol) {
var decl = moduleSymbol.valueDeclaration;
@@ -99235,7 +100470,7 @@ var ts;
return undefined;
}
var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
- var relativePath = normalizedSourcePath !== undefined ? ts.getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath;
+ var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
return ts.removeFileExtension(relativePath);
}
function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) {
@@ -99295,7 +100530,7 @@ var ts;
return path.substring(parts.topLevelPackageNameIndex + 1);
}
else {
- return ts.getRelativePath(path, sourceDirectory, getCanonicalFileName);
+ return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, path, getCanonicalFileName));
}
}
}
@@ -99848,7 +101083,24 @@ var ts;
/*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName,
/*questionToken*/ undefined, typeNode,
/*initializer*/ undefined);
- changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property);
+ var lastProp = getNodeToInsertPropertyAfter(classDeclaration);
+ if (lastProp) {
+ changeTracker.insertNodeAfter(classDeclarationSourceFile, lastProp, property);
+ }
+ else {
+ changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property);
+ }
+ }
+ // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration.
+ function getNodeToInsertPropertyAfter(cls) {
+ var res;
+ for (var _i = 0, _a = cls.members; _i < _a.length; _i++) {
+ var member = _a[_i];
+ if (!ts.isPropertyDeclaration(member))
+ break;
+ res = member;
+ }
+ return res;
}
function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) {
// Index signatures cannot have the static modifier.
@@ -100160,6 +101412,7 @@ var ts;
ts.Diagnostics._0_is_declared_but_never_used.code,
ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code,
ts.Diagnostics.All_imports_in_import_declaration_are_unused.code,
+ ts.Diagnostics.All_destructured_elements_are_unused.code,
];
codefix.registerCodeFix({
errorCodes: errorCodes,
@@ -100170,6 +101423,10 @@ var ts;
var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); });
return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)];
}
+ var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(t, sourceFile, context.span.start); });
+ if (delDestructure.length) {
+ return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)];
+ }
var token = getToken(sourceFile, ts.textSpanEnd(context.span));
var result = [];
var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token); });
@@ -100198,7 +101455,9 @@ var ts;
changes.deleteNode(sourceFile, importDecl);
}
else {
- tryDeleteDeclaration(changes, sourceFile, token);
+ if (!tryDeleteFullDestructure(changes, sourceFile, diag.start)) {
+ tryDeleteDeclaration(changes, sourceFile, token);
+ }
}
break;
default:
@@ -100211,6 +101470,26 @@ var ts;
var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined;
}
+ function tryDeleteFullDestructure(changes, sourceFile, pos) {
+ var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ if (startToken.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(startToken.parent))
+ return false;
+ var decl = startToken.parent.parent;
+ switch (decl.kind) {
+ case 231 /* VariableDeclaration */:
+ tryDeleteVariableDeclaration(changes, sourceFile, decl);
+ break;
+ case 148 /* Parameter */:
+ changes.deleteNodeInList(sourceFile, decl);
+ break;
+ case 181 /* BindingElement */:
+ changes.deleteNode(sourceFile, decl);
+ break;
+ default:
+ return ts.Debug.assertNever(decl);
+ }
+ return true;
+ }
function getToken(sourceFile, pos) {
var token = ts.findPrecedingToken(pos, sourceFile);
// this handles var ["computed"] = 12;
@@ -100299,6 +101578,20 @@ var ts;
changes.deleteNodeInList(sourceFile, parent);
}
break;
+ case 181 /* BindingElement */: {
+ var pattern = parent.parent;
+ switch (pattern.kind) {
+ case 180 /* ArrayBindingPattern */:
+ changes.deleteNode(sourceFile, parent); // Don't delete ','
+ break;
+ case 179 /* ObjectBindingPattern */:
+ changes.deleteNodeInList(sourceFile, parent);
+ break;
+ default:
+ return ts.Debug.assertNever(pattern);
+ }
+ break;
+ }
// handle case where 'import a = A;'
case 242 /* ImportEqualsDeclaration */:
var importEquals = ts.getAncestor(identifier, 242 /* ImportEqualsDeclaration */);
@@ -100413,7 +101706,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 === 278 /* JSDocNullableType */) {
+ if (typeNode.kind === 280 /* 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, 4096 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
@@ -100433,7 +101726,7 @@ var ts;
if (!info)
return;
var typeNode = info.typeNode, type = info.type;
- var fixedType = typeNode.kind === 278 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type;
+ var fixedType = typeNode.kind === 280 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type;
doChange(changes, sourceFile, typeNode, fixedType, checker);
});
}
@@ -101349,7 +102642,7 @@ var ts;
var opts = context.program.getCompilerOptions();
var variations = [];
// import Bluebird from "bluebird";
- variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier)));
+ variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier)));
if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) {
// import Bluebird = require("bluebird");
variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(
@@ -101575,7 +102868,7 @@ var ts;
}
}
function doChange(changes, sourceFile, info) {
- changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier));
+ changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier));
}
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
@@ -101593,7 +102886,7 @@ var ts;
* Exported for tests.
*/
function getAvailableActions(context) {
- var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) });
+ var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
var targetRange = rangeToExtract.targetRange;
if (targetRange === undefined) {
return undefined;
@@ -101662,7 +102955,7 @@ var ts;
extractSymbol.getAvailableActions = getAvailableActions;
/* Exported for tests */
function getEditsForAction(context, actionName) {
- var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) });
+ var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
var targetRange = rangeToExtract.targetRange;
var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName);
if (parsedFunctionIndexMatch) {
@@ -102797,7 +104090,7 @@ var ts;
: ts.getEnclosingBlockScopeContainer(scopes[0]);
ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
- var _loop_17 = function (i) {
+ var _loop_18 = 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
@@ -102837,7 +104130,7 @@ var ts;
}
};
for (var i = 0; i < scopes.length; i++) {
- _loop_17(i);
+ _loop_18(i);
}
return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
function hasTypeParameters(node) {
@@ -103137,21 +104430,39 @@ var ts;
return undefined;
var isJS = ts.isSourceFileJavaScript(file);
var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var isStatic = fieldInfo.isStatic, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration;
+ var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration;
+ ts.suppressLeadingAndTrailingTrivia(fieldName);
+ ts.suppressLeadingAndTrailingTrivia(declaration);
+ ts.suppressLeadingAndTrailingTrivia(container);
var isInClassLike = ts.isClassLike(container);
+ // avoid Readonly modifier because it will convert to get accessor
+ var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */;
var accessorModifiers = isInClassLike
- ? !declaration.modifiers || ts.getModifierFlags(declaration) & 8 /* Private */ ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */) : declaration.modifiers
+ ? !modifierFlags || modifierFlags & 8 /* Private */
+ ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */)
+ : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags))
: undefined;
var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 112 /* PrivateKeyword */) : undefined;
- updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers, container);
+ updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers);
var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
- var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
+ ts.suppressLeadingAndTrailingTrivia(getAccessor);
insertAccessor(changeTracker, file, getAccessor, declaration, container);
- insertAccessor(changeTracker, file, setAccessor, declaration, container);
+ if (isReadonly) {
+ // readonly modifier only existed in classLikeDeclaration
+ var constructor = ts.getFirstConstructorWithBody(container);
+ if (constructor) {
+ updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName);
+ }
+ }
+ else {
+ var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
+ ts.suppressLeadingAndTrailingTrivia(setAccessor);
+ insertAccessor(changeTracker, file, setAccessor, declaration, container);
+ }
var edits = changeTracker.getChanges();
var renameFilename = file.fileName;
var renameLocationOffset = ts.isIdentifier(fieldName) ? 0 : -1;
- var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, fieldName.text, /*isDeclaredBeforeUse*/ false);
+ var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, fieldName.text, /*preferLastLocation*/ ts.isParameter(declaration));
return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
}
function isConvertableName(name) {
@@ -103174,18 +104485,18 @@ var ts;
function getConvertibleFieldAtPosition(file, startPosition) {
var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration);
- // make sure propertyDeclaration have AccessibilityModifier or Static Modifier
- var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */;
+ // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier
+ var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */;
if (!declaration || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning)
return undefined;
var fieldName = createPropertyName(ts.getUniqueName("_" + declaration.name.text, file.text), declaration.name);
var accessorName = createPropertyName(declaration.name.text, declaration.name);
- ts.suppressLeadingAndTrailingTrivia(fieldName);
- ts.suppressLeadingAndTrailingTrivia(declaration);
return {
isStatic: ts.hasStaticModifier(declaration),
+ isReadonly: ts.hasReadonlyModifier(declaration),
type: ts.getTypeAnnotationNode(declaration),
container: declaration.kind === 148 /* Parameter */ ? declaration.parent.parent : declaration.parent,
+ originalName: declaration.name,
declaration: declaration,
fieldName: fieldName,
accessorName: accessorName,
@@ -103212,16 +104523,11 @@ var ts;
var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer);
changeTracker.replaceNode(file, declaration, property);
}
- function updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, classLikeContainer) {
- var property = ts.createProperty(declaration.decorators, modifiers, fieldName, declaration.questionToken, declaration.type, declaration.initializer);
- changeTracker.insertNodeAtClassStart(file, classLikeContainer, property);
- changeTracker.deleteNodeInList(file, declaration);
- }
function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) {
var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer);
changeTracker.replacePropertyAssignment(file, declaration, assignment);
}
- function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers, container) {
+ function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) {
if (ts.isPropertyDeclaration(declaration)) {
updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers);
}
@@ -103229,7 +104535,7 @@ var ts;
updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName);
}
else {
- updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, container);
+ changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer));
}
}
function insertAccessor(changeTracker, file, accessor, declaration, container) {
@@ -103237,11 +104543,592 @@ var ts;
? changeTracker.insertNodeAtClassStart(file, container, accessor)
: changeTracker.insertNodeAfter(file, declaration, accessor);
}
+ function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) {
+ if (!constructor.body)
+ return;
+ var file = context.file, program = context.program, cancellationToken = context.cancellationToken;
+ var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { return ((entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined); });
+ ts.forEach(referenceEntries, function (entry) {
+ var parent = entry.parent;
+ var accessorName = ts.createIdentifier(fieldName.text);
+ var node = ts.isBinaryExpression(parent)
+ ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken)
+ : ts.isPropertyAccessExpression(parent)
+ ? ts.updatePropertyAccess(parent, parent.expression, accessorName)
+ : ts.Debug.fail("Unexpected write access token");
+ changeTracker.replaceNode(file, parent, node);
+ });
+ }
})(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
/* @internal */
var ts;
+(function (ts) {
+ var refactor;
+ (function (refactor) {
+ var refactorName = "Move to a new file";
+ refactor.registerRefactor(refactorName, {
+ getAvailableActions: function (context) {
+ if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined)
+ return undefined;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file);
+ return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }];
+ },
+ getEditsForAction: function (context, actionName) {
+ ts.Debug.assert(actionName === refactorName);
+ var statements = ts.Debug.assertDefined(getStatementsToMove(context));
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host); });
+ return { edits: edits, renameFilename: undefined, renameLocation: undefined };
+ }
+ });
+ function getStatementsToMove(context) {
+ var file = context.file;
+ var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context));
+ var statements = file.statements;
+ var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; });
+ if (startNodeIndex === -1)
+ return undefined;
+ // Can't only partially include the start node or be partially into the next node
+ if (range.pos > statements[startNodeIndex].getStart(file))
+ return undefined;
+ var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex);
+ // Can't be partially into the next node
+ if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end))
+ return undefined;
+ return statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex);
+ }
+ function doChange(oldFile, program, toMove, changes, host) {
+ var checker = program.getTypeChecker();
+ var usage = getUsageInfo(oldFile, toMove, checker);
+ var currentDirectory = ts.getDirectoryPath(oldFile.fileName);
+ var extension = ts.extensionFromPath(oldFile.fileName);
+ var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host);
+ var newFileNameWithExtension = newModuleName + extension;
+ // If previous file was global, this is easy.
+ changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName));
+ addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host));
+ }
+ function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) {
+ var cfg = program.getCompilerOptions().configFile;
+ if (!cfg)
+ return;
+ var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension));
+ var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName);
+ var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression);
+ var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) {
+ return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files";
+ });
+ if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) {
+ changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements);
+ }
+ }
+ function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName) {
+ var checker = program.getTypeChecker();
+ if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) {
+ changes.deleteNodeRange(oldFile, ts.first(toMove), ts.last(toMove));
+ return toMove;
+ }
+ var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator;
+ var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax);
+ if (importsFromNewFile) {
+ changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, /*blankLineBetween*/ true);
+ }
+ deleteUnusedOldImports(oldFile, toMove, changes, usage.unusedImportsFromOldFile, checker);
+ changes.deleteNodeRange(oldFile, ts.first(toMove), ts.last(toMove));
+ updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName);
+ return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax).concat(addExports(oldFile, toMove, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax));
+ }
+ function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) {
+ for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
+ var statement = _a[_i];
+ if (ts.contains(toMove, statement))
+ continue;
+ forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); });
+ }
+ }
+ function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) {
+ var checker = program.getTypeChecker();
+ var _loop_19 = function (sourceFile) {
+ if (sourceFile === oldFile)
+ return "continue";
+ var _loop_20 = function (statement) {
+ forEachImportInStatement(statement, function (importNode) {
+ var shouldMove = function (name) {
+ var symbol = ts.isBindingElement(name.parent)
+ ? ts.getPropertySymbolFromBindingElement(checker, name.parent)
+ : ts.skipAlias(checker.getSymbolAtLocation(name), checker);
+ return !!symbol && movedSymbols.has(symbol);
+ };
+ deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file
+ var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName);
+ var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove);
+ if (newImportDeclaration)
+ changes.insertNodeAfter(sourceFile, statement, newImportDeclaration);
+ });
+ };
+ for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
+ var statement = _a[_i];
+ _loop_20(statement);
+ }
+ };
+ for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
+ var sourceFile = _a[_i];
+ _loop_19(sourceFile);
+ }
+ }
+ function moduleSpecifierFromImport(i) {
+ return (i.kind === 243 /* ImportDeclaration */ ? i.moduleSpecifier
+ : i.kind === 242 /* ImportEqualsDeclaration */ ? i.moduleReference.expression
+ : i.initializer.arguments[0]);
+ }
+ function forEachImportInStatement(statement, cb) {
+ if (ts.isImportDeclaration(statement)) {
+ if (ts.isStringLiteral(statement.moduleSpecifier))
+ cb(statement);
+ }
+ else if (ts.isImportEqualsDeclaration(statement)) {
+ if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) {
+ cb(statement);
+ }
+ }
+ else if (ts.isVariableStatement(statement)) {
+ for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) {
+ cb(decl);
+ }
+ }
+ }
+ }
+ function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports) {
+ var defaultImport;
+ var imports = [];
+ newFileNeedExport.forEach(function (symbol) {
+ if (symbol.escapedName === "default" /* Default */) {
+ defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol));
+ }
+ else {
+ imports.push(symbol.name);
+ }
+ });
+ return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports);
+ }
+ function makeImportOrRequire(defaultImport, imports, path, useEs6Imports) {
+ path = ts.ensurePathIsNonModuleName(path);
+ if (useEs6Imports) {
+ var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); });
+ return ts.makeImportIfNecessary(defaultImport, specifiers, path);
+ }
+ else {
+ ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module.
+ var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); });
+ return bindingElements.length
+ ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path)))
+ : undefined;
+ }
+ }
+ function makeVariableStatement(name, type, initializer, flags) {
+ if (flags === void 0) { flags = 2 /* Const */; }
+ return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags));
+ }
+ function createRequireCall(moduleSpecifier) {
+ return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]);
+ }
+ function addExports(sourceFile, toMove, needExport, useEs6Exports) {
+ return ts.flatMap(toMove, function (statement) {
+ 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;
+ }
+ return statement;
+ });
+ }
+ function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) {
+ switch (importDecl.kind) {
+ case 243 /* ImportDeclaration */:
+ deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused);
+ break;
+ case 242 /* ImportEqualsDeclaration */:
+ if (isUnused(importDecl.name)) {
+ changes.deleteNode(sourceFile, importDecl);
+ }
+ break;
+ case 231 /* VariableDeclaration */:
+ deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused);
+ break;
+ default:
+ ts.Debug.assertNever(importDecl);
+ }
+ }
+ function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) {
+ if (!importDecl.importClause)
+ return;
+ var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings;
+ var defaultUnused = !name || isUnused(name);
+ var namedBindingsUnused = !namedBindings ||
+ (namedBindings.kind === 245 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.every(function (e) { return isUnused(e.name); }));
+ if (defaultUnused && namedBindingsUnused) {
+ changes.deleteNode(sourceFile, importDecl);
+ }
+ else {
+ if (name && defaultUnused) {
+ changes.deleteNode(sourceFile, name);
+ }
+ if (namedBindings) {
+ if (namedBindingsUnused) {
+ changes.deleteNode(sourceFile, namedBindings);
+ }
+ else if (namedBindings.kind === 246 /* NamedImports */) {
+ for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) {
+ var element = _b[_i];
+ if (isUnused(element.name))
+ changes.deleteNodeInList(sourceFile, element);
+ }
+ }
+ }
+ }
+ }
+ function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) {
+ var name = varDecl.name;
+ switch (name.kind) {
+ case 71 /* Identifier */:
+ if (isUnused(name)) {
+ changes.deleteNode(sourceFile, name);
+ }
+ break;
+ case 180 /* ArrayBindingPattern */:
+ break;
+ case 179 /* ObjectBindingPattern */:
+ if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) {
+ changes.deleteNode(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl);
+ }
+ else {
+ for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
+ var element = _a[_i];
+ if (ts.isIdentifier(element.name) && isUnused(element.name)) {
+ changes.deleteNode(sourceFile, element.name);
+ }
+ }
+ }
+ break;
+ }
+ }
+ function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax) {
+ var copiedOldImports = [];
+ for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
+ var oldStatement = _a[_i];
+ forEachImportInStatement(oldStatement, function (i) {
+ ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); }));
+ });
+ }
+ // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file.
+ var oldFileDefault;
+ var oldFileNamedImports = [];
+ var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`.
+ newFileImportsFromOldFile.forEach(function (symbol) {
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (!isTopLevelDeclaration(decl))
+ continue;
+ var name = nameOfTopLevelDeclaration(decl);
+ if (!name)
+ continue;
+ var top = getTopLevelDeclarationStatement(decl);
+ if (markSeenTop(top)) {
+ addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax);
+ }
+ if (ts.hasModifier(decl, 512 /* Default */)) {
+ oldFileDefault = name;
+ }
+ else {
+ oldFileNamedImports.push(name.text);
+ }
+ }
+ });
+ ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax));
+ return copiedOldImports;
+ }
+ function makeUniqueModuleName(moduleName, extension, inDirectory, host) {
+ var newModuleName = moduleName;
+ for (var i = 1;; i++) {
+ var name = ts.combinePaths(inDirectory, newModuleName + extension);
+ if (!host.fileExists(name))
+ return newModuleName;
+ newModuleName = moduleName + "." + i;
+ }
+ }
+ function getNewModuleName(movedSymbols) {
+ return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile";
+ }
+ function getUsageInfo(oldFile, toMove, checker) {
+ var movedSymbols = new SymbolSet();
+ var oldImportsNeededByNewFile = new SymbolSet();
+ var newFileImportsFromOldFile = new SymbolSet();
+ for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) {
+ var statement = toMove_1[_i];
+ forEachTopLevelDeclaration(statement, function (decl) {
+ movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol));
+ });
+ }
+ for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) {
+ var statement = toMove_2[_a];
+ forEachReference(statement, checker, function (symbol) {
+ if (!symbol.declarations)
+ return;
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (isInImport(decl)) {
+ oldImportsNeededByNewFile.add(symbol);
+ }
+ else if (isTopLevelDeclaration(decl) && !movedSymbols.has(symbol)) {
+ newFileImportsFromOldFile.add(symbol);
+ }
+ }
+ });
+ }
+ var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone();
+ var oldFileImportsFromNewFile = new SymbolSet();
+ for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) {
+ var statement = _c[_b];
+ if (ts.contains(toMove, statement))
+ continue;
+ forEachReference(statement, checker, function (symbol) {
+ if (movedSymbols.has(symbol))
+ oldFileImportsFromNewFile.add(symbol);
+ unusedImportsFromOldFile.delete(symbol);
+ });
+ }
+ return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile };
+ }
+ // Below should all be utilities
+ function isInImport(decl) {
+ switch (decl.kind) {
+ case 242 /* ImportEqualsDeclaration */:
+ case 247 /* ImportSpecifier */:
+ case 244 /* ImportClause */:
+ return true;
+ case 231 /* VariableDeclaration */:
+ return isVariableDeclarationInImport(decl);
+ case 181 /* BindingElement */:
+ return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent);
+ default:
+ return false;
+ }
+ }
+ function isVariableDeclarationInImport(decl) {
+ return ts.isSourceFile(decl.parent.parent.parent) &&
+ ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true);
+ }
+ function filterImport(i, moduleSpecifier, keep) {
+ switch (i.kind) {
+ case 243 /* ImportDeclaration */: {
+ var clause = i.importClause;
+ var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined;
+ var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep);
+ return defaultImport || namedBindings
+ ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier)
+ : undefined;
+ }
+ case 242 /* ImportEqualsDeclaration */:
+ return keep(i.name) ? i : undefined;
+ case 231 /* VariableDeclaration */: {
+ var name = filterBindingName(i.name, keep);
+ return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined;
+ }
+ default:
+ return ts.Debug.assertNever(i);
+ }
+ }
+ function filterNamedBindings(namedBindings, keep) {
+ if (namedBindings.kind === 245 /* NamespaceImport */) {
+ return keep(namedBindings.name) ? namedBindings : undefined;
+ }
+ else {
+ var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); });
+ return newElements.length ? ts.createNamedImports(newElements) : undefined;
+ }
+ }
+ function filterBindingName(name, keep) {
+ switch (name.kind) {
+ case 71 /* Identifier */:
+ return keep(name) ? name : undefined;
+ case 180 /* ArrayBindingPattern */:
+ return name;
+ case 179 /* ObjectBindingPattern */: {
+ // We can't handle nested destructurings or property names well here, so just copy them all.
+ var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); });
+ return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined;
+ }
+ }
+ }
+ function forEachReference(node, checker, onReference) {
+ node.forEachChild(function cb(node) {
+ if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) {
+ var sym = checker.getSymbolAtLocation(node);
+ if (sym)
+ onReference(sym);
+ }
+ else {
+ node.forEachChild(cb);
+ }
+ });
+ }
+ var SymbolSet = /** @class */ (function () {
+ function SymbolSet() {
+ this.map = ts.createMap();
+ }
+ SymbolSet.prototype.add = function (symbol) {
+ this.map.set(String(ts.getSymbolId(symbol)), symbol);
+ };
+ SymbolSet.prototype.has = function (symbol) {
+ return this.map.has(String(ts.getSymbolId(symbol)));
+ };
+ SymbolSet.prototype.delete = function (symbol) {
+ this.map.delete(String(ts.getSymbolId(symbol)));
+ };
+ SymbolSet.prototype.forEach = function (cb) {
+ this.map.forEach(cb);
+ };
+ SymbolSet.prototype.forEachEntry = function (cb) {
+ return ts.forEachEntry(this.map, cb);
+ };
+ SymbolSet.prototype.clone = function () {
+ var clone = new SymbolSet();
+ ts.copyEntries(this.map, clone.map);
+ return clone;
+ };
+ return SymbolSet;
+ }());
+ function isTopLevelDeclaration(node) {
+ return isNonVariableTopLevelDeclaration(node) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent);
+ }
+ function isTopLevelDeclarationStatement(node) {
+ ts.Debug.assert(ts.isSourceFile(node.parent));
+ return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node);
+ }
+ function isNonVariableTopLevelDeclaration(node) {
+ switch (node.kind) {
+ case 233 /* FunctionDeclaration */:
+ case 234 /* ClassDeclaration */:
+ case 238 /* ModuleDeclaration */:
+ case 237 /* EnumDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 242 /* ImportEqualsDeclaration */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ function forEachTopLevelDeclaration(statement, cb) {
+ switch (statement.kind) {
+ case 233 /* FunctionDeclaration */:
+ case 234 /* ClassDeclaration */:
+ case 238 /* ModuleDeclaration */:
+ case 237 /* EnumDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 242 /* ImportEqualsDeclaration */:
+ return cb(statement);
+ case 213 /* VariableStatement */:
+ return ts.forEach(statement.declarationList.declarations, cb);
+ case 215 /* ExpressionStatement */: {
+ var expression = statement.expression;
+ return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */
+ ? cb(statement)
+ : undefined;
+ }
+ }
+ }
+ function nameOfTopLevelDeclaration(d) {
+ return d.kind === 215 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier);
+ }
+ function getTopLevelDeclarationStatement(d) {
+ return ts.isVariableDeclaration(d) ? d.parent.parent : d;
+ }
+ function addExportToChanges(sourceFile, decl, changes, useEs6Exports) {
+ if (isExported(sourceFile, decl, useEs6Exports))
+ return;
+ if (useEs6Exports) {
+ if (!ts.isExpressionStatement(decl))
+ changes.insertExportModifier(sourceFile, decl);
+ }
+ else {
+ var names = getNamesToExportInCommonJS(decl);
+ if (names.length !== 0)
+ changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment));
+ }
+ }
+ function isExported(sourceFile, decl, useEs6Exports) {
+ if (useEs6Exports) {
+ return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */);
+ }
+ else {
+ return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); });
+ }
+ }
+ function addExport(decl, useEs6Exports) {
+ return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl);
+ }
+ function addEs6Export(d) {
+ var modifiers = ts.concatenate([ts.createModifier(84 /* ExportKeyword */)], d.modifiers);
+ switch (d.kind) {
+ case 233 /* FunctionDeclaration */:
+ return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body);
+ case 234 /* ClassDeclaration */:
+ return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
+ case 213 /* VariableStatement */:
+ return ts.updateVariableStatement(d, modifiers, d.declarationList);
+ case 238 /* ModuleDeclaration */:
+ return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body);
+ case 237 /* EnumDeclaration */:
+ return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members);
+ case 236 /* TypeAliasDeclaration */:
+ return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type);
+ case 235 /* InterfaceDeclaration */:
+ return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
+ case 242 /* ImportEqualsDeclaration */:
+ return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference);
+ case 215 /* ExpressionStatement */:
+ return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
+ default:
+ return ts.Debug.assertNever(d);
+ }
+ }
+ function addCommonjsExport(decl) {
+ return [decl].concat(getNamesToExportInCommonJS(decl).map(createExportAssignment));
+ }
+ function getNamesToExportInCommonJS(decl) {
+ switch (decl.kind) {
+ case 233 /* FunctionDeclaration */:
+ case 234 /* ClassDeclaration */:
+ return [decl.name.text];
+ case 213 /* VariableStatement */:
+ return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; });
+ case 238 /* ModuleDeclaration */:
+ case 237 /* EnumDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 242 /* ImportEqualsDeclaration */:
+ return undefined;
+ case 215 /* ExpressionStatement */:
+ return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
+ default:
+ ts.Debug.assertNever(decl);
+ }
+ }
+ /** Creates `exports.x = x;` */
+ function createExportAssignment(name) {
+ return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 58 /* EqualsToken */, ts.createIdentifier(name)));
+ }
+ })(refactor = ts.refactor || (ts.refactor = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
(function (ts) {
var sourcemaps;
(function (sourcemaps) {
@@ -103563,7 +105450,7 @@ var ts;
if (!children.length) {
return undefined;
}
- var child = ts.find(children, function (kid) { return kid.kind < 275 /* FirstJSDocNode */ || kid.kind > 293 /* LastJSDocNode */; });
+ var child = ts.find(children, function (kid) { return kid.kind < 277 /* FirstJSDocNode */ || kid.kind > 295 /* LastJSDocNode */; });
return child.kind < 145 /* FirstNode */ ?
child :
child.getFirstToken(sourceFile);
@@ -103633,7 +105520,7 @@ var ts;
}
}
function createSyntaxList(nodes, parent) {
- var list = createNode(294 /* SyntaxList */, nodes.pos, nodes.end, parent);
+ var list = createNode(296 /* SyntaxList */, nodes.pos, nodes.end, parent);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) {
@@ -104156,6 +106043,9 @@ var ts;
HostCache.prototype.compilationSettings = function () {
return this._compilationSettings;
};
+ HostCache.prototype.getProjectReferences = function () {
+ return this.host.getProjectReferences && this.host.getProjectReferences();
+ };
HostCache.prototype.createEntry = function (fileName, path) {
var entry;
var scriptSnapshot = this.host.getScriptSnapshot(fileName);
@@ -104185,9 +106075,18 @@ var ts;
return ts.isString(info) ? undefined : info;
};
HostCache.prototype.getRootFileNames = function () {
- return ts.arrayFrom(this.fileNameToEntry.values(), function (entry) {
- return ts.isString(entry) ? entry : entry.hostFileName;
+ var names = [];
+ this.fileNameToEntry.forEach(function (entry) {
+ if (ts.isString(entry)) {
+ names.push(entry);
+ }
+ else {
+ if (entry.scriptKind !== 6 /* JSON */) {
+ names.push(entry.hostFileName);
+ }
+ }
});
+ return names;
};
HostCache.prototype.getVersion = function (path) {
var file = this.getHostFileInformation(path);
@@ -104363,6 +106262,7 @@ var ts;
}
ts.createSourceFileLikeCache = createSourceFileLikeCache;
function createLanguageService(host, documentRegistry, syntaxOnly) {
+ var _a;
if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); }
if (syntaxOnly === void 0) { syntaxOnly = false; }
var syntaxTreeCache = new SyntaxTreeCache(host);
@@ -104466,7 +106366,14 @@ var ts;
};
}
var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings);
- program = ts.createProgram(rootFileNames, newSettings, compilerHost, program);
+ var options = {
+ rootNames: rootFileNames,
+ options: newSettings,
+ host: compilerHost,
+ oldProgram: program,
+ projectReferences: hostCache.getProjectReferences()
+ };
+ program = ts.createProgram(options);
// hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point.
// It needs to be cleared to allow all collected snapshots to be released
hostCache = undefined;
@@ -104670,6 +106577,11 @@ var ts;
}
return checker.getSymbolAtLocation(node);
}
+ function toLineColumnOffset(fileName, position) {
+ var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
+ var file = program.getSourceFile(path) || sourcemappedFileCache.get(path);
+ return file.getLineAndCharacterOfPosition(position);
+ }
// Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M])
var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)$/gm;
var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/;
@@ -104744,15 +106656,15 @@ var ts;
function getTargetOfMappedPosition(input) {
var info = extract(input);
if (ts.endsWith(info.fileName, ".d.ts" /* Dts */)) {
- var file = program.getSourceFile(info.fileName);
- if (!file) {
+ var file_17 = program.getSourceFile(info.fileName);
+ if (!file_17) {
var path = ts.toPath(info.fileName, currentDirectory, getCanonicalFileName);
- file = sourcemappedFileCache.get(path);
+ file_17 = sourcemappedFileCache.get(path);
}
- if (!file) {
+ if (!file_17) {
return input;
}
- var mapper = getSourceMapper(info.fileName, file);
+ var mapper = getSourceMapper(info.fileName, file_17);
var newLoc = mapper.getOriginalPosition(info);
if (newLoc === info)
return input;
@@ -105317,8 +107229,8 @@ var ts;
getProgram: getProgram,
getApplicableRefactors: getApplicableRefactors,
getEditsForRefactor: getEditsForRefactor,
+ toLineColumnOffset: toLineColumnOffset
};
- var _a;
}
ts.createLanguageService = createLanguageService;
/* @internal */
@@ -105389,20 +107301,20 @@ var ts;
function getPropertySymbolsFromType(type, propName) {
var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName));
if (name && type) {
- var result_6 = [];
+ var result_7 = [];
var symbol = type.getProperty(name);
if (type.flags & 131072 /* Union */) {
ts.forEach(type.types, function (t) {
var symbol = t.getProperty(name);
if (symbol) {
- result_6.push(symbol);
+ result_7.push(symbol);
}
});
- return result_6;
+ return result_7;
}
if (symbol) {
- result_6.push(symbol);
- return result_6;
+ result_7.push(symbol);
+ return result_7;
}
}
return undefined;
@@ -105469,7 +107381,7 @@ var ts;
return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd());
}
function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) {
- return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent));
+ return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile));
}
function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) {
if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) {
@@ -105484,7 +107396,7 @@ var ts;
return spanInNode(ts.findPrecedingToken(node.pos, sourceFile));
}
function spanInNextNode(node) {
- return spanInNode(ts.findNextToken(node, node.parent));
+ return spanInNode(ts.findNextToken(node, node.parent, sourceFile));
}
function spanInNode(node) {
if (node) {
@@ -106823,5 +108735,3 @@ var TypeScript;
// TODO: it should be moved into a namespace though.
/* @internal */
var toolsVersion = ts.versionMajorMinor;
-
-//# sourceMappingURL=typescriptServices.js.map
diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts
index 6c81f213986..4c0d10cea12 100644
--- a/lib/typescriptServices.d.ts
+++ b/lib/typescriptServices.d.ts
@@ -337,32 +337,34 @@ declare namespace ts {
EnumMember = 272,
SourceFile = 273,
Bundle = 274,
- JSDocTypeExpression = 275,
- JSDocAllType = 276,
- JSDocUnknownType = 277,
- JSDocNullableType = 278,
- JSDocNonNullableType = 279,
- JSDocOptionalType = 280,
- JSDocFunctionType = 281,
- JSDocVariadicType = 282,
- JSDocComment = 283,
- JSDocTypeLiteral = 284,
- JSDocTag = 285,
- JSDocAugmentsTag = 286,
- JSDocClassTag = 287,
- JSDocParameterTag = 288,
- JSDocReturnTag = 289,
- JSDocTypeTag = 290,
- JSDocTemplateTag = 291,
- JSDocTypedefTag = 292,
- JSDocPropertyTag = 293,
- SyntaxList = 294,
- NotEmittedStatement = 295,
- PartiallyEmittedExpression = 296,
- CommaListExpression = 297,
- MergeDeclarationMarker = 298,
- EndOfDeclarationMarker = 299,
- Count = 300,
+ UnparsedSource = 275,
+ InputFiles = 276,
+ JSDocTypeExpression = 277,
+ JSDocAllType = 278,
+ JSDocUnknownType = 279,
+ JSDocNullableType = 280,
+ JSDocNonNullableType = 281,
+ JSDocOptionalType = 282,
+ JSDocFunctionType = 283,
+ JSDocVariadicType = 284,
+ JSDocComment = 285,
+ JSDocTypeLiteral = 286,
+ JSDocTag = 287,
+ JSDocAugmentsTag = 288,
+ JSDocClassTag = 289,
+ JSDocParameterTag = 290,
+ JSDocReturnTag = 291,
+ JSDocTypeTag = 292,
+ JSDocTemplateTag = 293,
+ JSDocTypedefTag = 294,
+ JSDocPropertyTag = 295,
+ SyntaxList = 296,
+ NotEmittedStatement = 297,
+ PartiallyEmittedExpression = 298,
+ CommaListExpression = 299,
+ MergeDeclarationMarker = 300,
+ EndOfDeclarationMarker = 301,
+ Count = 302,
FirstAssignment = 58,
LastAssignment = 70,
FirstCompoundAssignment = 59,
@@ -388,10 +390,10 @@ declare namespace ts {
FirstBinaryOperator = 27,
LastBinaryOperator = 70,
FirstNode = 145,
- FirstJSDocNode = 275,
- LastJSDocNode = 293,
- FirstJSDocTagNode = 285,
- LastJSDocTagNode = 293
+ FirstJSDocNode = 277,
+ LastJSDocNode = 295,
+ FirstJSDocTagNode = 287,
+ LastJSDocTagNode = 295
}
enum NodeFlags {
None = 0,
@@ -415,6 +417,7 @@ declare namespace ts {
ThisNodeOrAnySubNodesHasError = 131072,
HasAggregatedChildData = 262144,
JSDoc = 2097152,
+ JsonFile = 16777216,
BlockScoped = 3,
ReachabilityCheckFlags = 384,
ReachabilityAndEmitFlags = 1408,
@@ -1149,7 +1152,7 @@ declare namespace ts {
kind: SyntaxKind.NotEmittedStatement;
}
/**
- * A list of comma-seperated expressions. This node is only created by transformations.
+ * A list of comma-separated expressions. This node is only created by transformations.
*/
interface CommaListExpression extends Expression {
kind: SyntaxKind.CommaListExpression;
@@ -1644,12 +1647,32 @@ declare namespace ts {
}
interface Bundle extends Node {
kind: SyntaxKind.Bundle;
+ prepends: ReadonlyArray;
sourceFiles: ReadonlyArray;
}
+ interface InputFiles extends Node {
+ kind: SyntaxKind.InputFiles;
+ javascriptText: string;
+ declarationText: string;
+ }
+ interface UnparsedSource extends Node {
+ kind: SyntaxKind.UnparsedSource;
+ text: string;
+ }
interface JsonSourceFile extends SourceFile {
- jsonObject?: ObjectLiteralExpression;
+ statements: NodeArray;
+ }
+ interface TsConfigSourceFile extends JsonSourceFile {
extendedSourceFiles?: string[];
}
+ interface JsonMinusNumericLiteral extends PrefixUnaryExpression {
+ kind: SyntaxKind.PrefixUnaryExpression;
+ operator: SyntaxKind.MinusToken;
+ operand: NumericLiteral;
+ }
+ interface JsonObjectExpressionStatement extends ExpressionStatement {
+ expression: ObjectLiteralExpression | ArrayLiteralExpression | JsonMinusNumericLiteral | NumericLiteral | StringLiteral | BooleanLiteral | NullLiteral;
+ }
interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
getSourceFile(fileName: string): SourceFile | undefined;
@@ -1705,12 +1728,19 @@ declare namespace ts {
*/
getTypeChecker(): TypeChecker;
isSourceFileFromExternalLibrary(file: SourceFile): boolean;
+ getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined;
+ }
+ interface ResolvedProjectReference {
+ commandLine: ParsedCommandLine;
+ sourceFile: SourceFile;
}
interface CustomTransformers {
- /** Custom transformers to evaluate before built-in transformations. */
+ /** Custom transformers to evaluate before built-in .js transformations. */
before?: TransformerFactory[];
- /** Custom transformers to evaluate after built-in transformations. */
+ /** Custom transformers to evaluate after built-in .js transformations. */
after?: TransformerFactory[];
+ /** Custom transformers to evaluate after built-in .d.ts transformations. */
+ afterDeclarations?: TransformerFactory[];
}
interface SourceMapSpan {
/** Line number in the .js file. */
@@ -1853,6 +1883,7 @@ declare namespace ts {
None = 0,
NoTruncation = 1,
WriteArrayAsGenericType = 2,
+ GenerateNamesForShadowedTypeParams = 4,
UseStructuralFallback = 8,
WriteTypeArgumentsOfSignature = 32,
UseFullyQualifiedType = 64,
@@ -2274,7 +2305,9 @@ declare namespace ts {
AlwaysStrict = 64,
PriorityImpliesCombination = 28
}
- interface JsFileExtensionInfo {
+ /** @deprecated Use FileExtensionInfo instead. */
+ type JsFileExtensionInfo = FileExtensionInfo;
+ interface FileExtensionInfo {
extension: string;
isMixedContent: boolean;
scriptKind?: ScriptKind;
@@ -2322,7 +2355,17 @@ declare namespace ts {
interface PluginImport {
name: string;
}
- type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | null | undefined;
+ interface ProjectReference {
+ /** A normalized path on disk */
+ path: string;
+ /** The path as the user originally wrote it */
+ originalPath?: string;
+ /** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */
+ prepend?: boolean;
+ /** True if it is intended that this reference form a circularity */
+ circular?: boolean;
+ }
+ type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined;
interface CompilerOptions {
allowJs?: boolean;
allowSyntheticDefaultImports?: boolean;
@@ -2378,6 +2421,7 @@ declare namespace ts {
project?: string;
reactNamespace?: string;
jsxFactory?: string;
+ composite?: boolean;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
@@ -2393,11 +2437,12 @@ declare namespace ts {
suppressImplicitAnyIndexErrors?: boolean;
target?: ScriptTarget;
traceResolution?: boolean;
+ resolveJsonModule?: boolean;
types?: string[];
/** Paths used to compute primary types search locations */
typeRoots?: string[];
esModuleInterop?: boolean;
- [option: string]: CompilerOptionsValue | JsonSourceFile | undefined;
+ [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined;
}
interface TypeAcquisition {
enableAutoDiscovery?: boolean;
@@ -2437,7 +2482,12 @@ declare namespace ts {
TS = 3,
TSX = 4,
External = 5,
- JSON = 6
+ JSON = 6,
+ /**
+ * Used on extensions that doesn't define the ScriptKind but the content defines it.
+ * Deferred extensions are going to be included in all project contexts.
+ */
+ Deferred = 7
}
enum ScriptTarget {
ES3 = 0,
@@ -2447,6 +2497,7 @@ declare namespace ts {
ES2017 = 4,
ES2018 = 5,
ESNext = 6,
+ JSON = 100,
Latest = 6
}
enum LanguageVariant {
@@ -2458,6 +2509,7 @@ declare namespace ts {
options: CompilerOptions;
typeAcquisition?: TypeAcquisition;
fileNames: string[];
+ projectReferences?: ReadonlyArray;
raw?: any;
errors: Diagnostic[];
wildcardDirectories?: MapLike;
@@ -2469,8 +2521,17 @@ declare namespace ts {
}
interface ExpandResult {
fileNames: string[];
+ projectReferences: ReadonlyArray | undefined;
wildcardDirectories: MapLike;
}
+ interface CreateProgramOptions {
+ rootNames: ReadonlyArray;
+ options: CompilerOptions;
+ projectReferences?: ReadonlyArray;
+ host?: CompilerHost;
+ oldProgram?: Program;
+ configFileParsingDiagnostics?: ReadonlyArray;
+ }
interface ModuleResolutionHost {
fileExists(fileName: string): boolean;
readFile(fileName: string): string | undefined;
@@ -2561,6 +2622,7 @@ declare namespace ts {
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
+ readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[];
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[];
/**
* This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files
@@ -3423,6 +3485,8 @@ declare namespace ts {
function createLiteral(value: boolean): BooleanLiteral;
function createLiteral(value: string | number | boolean): PrimaryExpression;
function createNumericLiteral(value: string): NumericLiteral;
+ function createStringLiteral(text: string): StringLiteral;
+ function createRegularExpressionLiteral(text: string): RegularExpressionLiteral;
function createIdentifier(text: string): Identifier;
function updateIdentifier(node: Identifier): Identifier;
/** Create a unique temporary variable. */
@@ -3727,8 +3791,10 @@ declare namespace ts {
function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression;
function createCommaList(elements: ReadonlyArray): CommaListExpression;
function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression;
- function createBundle(sourceFiles: ReadonlyArray): Bundle;
- function updateBundle(node: Bundle, sourceFiles: ReadonlyArray): Bundle;
+ function createBundle(sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle;
+ function createUnparsedSourceFile(text: string): UnparsedSource;
+ function createInputFiles(javascript: string, declaration: string): InputFiles;
+ function updateBundle(node: Bundle, sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray): CallExpression;
function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray, param: ParameterDeclaration, paramValue: Expression): CallExpression;
function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray): CallExpression;
@@ -3935,6 +4001,7 @@ declare namespace ts {
* @param configFileParsingDiagnostics - error during config file parsing
* @returns A 'Program' object.
*/
+ function createProgram(createProgramOptions: CreateProgramOptions): Program;
function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program;
}
declare namespace ts {
@@ -4074,7 +4141,6 @@ declare namespace ts {
function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram;
}
declare namespace ts {
- type DiagnosticReporter = (diagnostic: Diagnostic) => void;
type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void;
/** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */
type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T;
@@ -4137,15 +4203,6 @@ declare namespace ts {
/** Compiler options */
options: CompilerOptions;
}
- /**
- * Reports config file diagnostics
- */
- interface ConfigFileDiagnosticsReporter {
- /**
- * Reports unrecoverable error when parsing config file
- */
- onUnRecoverableConfigFileDiagnostic: DiagnosticReporter;
- }
/**
* Host to create watch with config file
*/
@@ -4192,6 +4249,26 @@ declare namespace ts {
}
declare namespace ts {
function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine;
+ type DiagnosticReporter = (diagnostic: Diagnostic) => void;
+ /**
+ * Reports config file diagnostics
+ */
+ interface ConfigFileDiagnosticsReporter {
+ /**
+ * Reports unrecoverable error when parsing config file
+ */
+ onUnRecoverableConfigFileDiagnostic: DiagnosticReporter;
+ }
+ /**
+ * Interface extending ParseConfigHost to support ParseConfigFile that reads config file and reports errors
+ */
+ interface ParseConfigFileHost extends ParseConfigHost, ConfigFileDiagnosticsReporter {
+ getCurrentDirectory(): string;
+ }
+ /**
+ * Reads the config file, reports errors if any and exits if the config file cannot be found
+ */
+ function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost): ParsedCommandLine | undefined;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
@@ -4213,7 +4290,7 @@ declare namespace ts {
* Read tsconfig.json file
* @param fileName The path to the config file
*/
- function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): JsonSourceFile;
+ function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile;
/**
* Convert the json syntax tree into the json value
*/
@@ -4225,7 +4302,7 @@ declare namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
- function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine;
+ function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine;
/**
* Parse the contents of a config file (tsconfig.json).
* @param jsonNode The contents of the config file to parse
@@ -4233,7 +4310,7 @@ declare namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
- function parseJsonSourceFileConfigFileContent(sourceFile: JsonSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine;
+ function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine;
function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
@@ -4252,7 +4329,7 @@ declare namespace ts {
getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number;
getFullStart(): number;
getEnd(): number;
- getWidth(sourceFile?: SourceFile): number;
+ getWidth(sourceFile?: SourceFileLike): number;
getFullWidth(): number;
getLeadingTriviaWidth(sourceFile?: SourceFile): number;
getFullText(sourceFile?: SourceFile): string;
@@ -4364,6 +4441,7 @@ declare namespace ts {
getScriptKind?(fileName: string): ScriptKind;
getScriptVersion(fileName: string): string;
getScriptSnapshot(fileName: string): IScriptSnapshot | undefined;
+ getProjectReferences?(): ReadonlyArray | undefined;
getLocalizedDiagnosticMessages?(): any;
getCancellationToken?(): HostCancellationToken;
getCurrentDirectory(): string;
@@ -4393,6 +4471,7 @@ declare namespace ts {
readonly includeCompletionsForModuleExports?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
+ readonly allowTextChangesInNewFiles?: boolean;
}
interface LanguageService {
cleanupSemanticCache(): void;
@@ -4441,6 +4520,7 @@ declare namespace ts {
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean;
getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan;
+ toLineColumnOffset?(fileName: string, position: number): LineAndCharacter;
getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray;
getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions;
applyCodeActionCommand(action: CodeActionCommand): Promise;
@@ -4465,9 +4545,10 @@ declare namespace ts {
fileName: string;
}
type OrganizeImportsScope = CombinedCodeFixScope;
+ type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<";
interface GetCompletionsAtPositionOptions extends UserPreferences {
/** If the editor is asking for completions because a certain character was typed, and not because the user explicitly requested them, this should be set. */
- triggerCharacter?: string;
+ triggerCharacter?: CompletionsTriggerCharacter;
/** @deprecated Use includeCompletionsForModuleExports */
includeExternalModuleExports?: boolean;
/** @deprecated Use includeCompletionsWithInsertText */
@@ -4865,6 +4946,20 @@ declare namespace ts {
* the 'Collapse to Definitions' command is invoked.
*/
autoCollapse: boolean;
+ /**
+ * Classification of the contents of the span
+ */
+ kind: OutliningSpanKind;
+ }
+ enum OutliningSpanKind {
+ /** Single or multi-line comments */
+ Comment = "comment",
+ /** Sections marked by '// #region' and '// #endregion' comments */
+ Region = "region",
+ /** Declarations and expressions */
+ Code = "code",
+ /** Contiguous blocks of import declarations */
+ Imports = "imports"
}
enum OutputFileType {
JavaScript = 0,
@@ -4988,7 +5083,9 @@ declare namespace ts {
/**
*
*/
- jsxAttribute = "JSX attribute"
+ jsxAttribute = "JSX attribute",
+ /** String literal */
+ string = "string"
}
enum ScriptElementKindModifier {
none = "",
diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js
index 86c2e32ef0e..33caf6392fd 100644
--- a/lib/typescriptServices.js
+++ b/lib/typescriptServices.js
@@ -350,38 +350,40 @@ var ts;
// Top-level nodes
SyntaxKind[SyntaxKind["SourceFile"] = 273] = "SourceFile";
SyntaxKind[SyntaxKind["Bundle"] = 274] = "Bundle";
+ SyntaxKind[SyntaxKind["UnparsedSource"] = 275] = "UnparsedSource";
+ SyntaxKind[SyntaxKind["InputFiles"] = 276] = "InputFiles";
// JSDoc nodes
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 275] = "JSDocTypeExpression";
+ SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 277] = "JSDocTypeExpression";
// The * type
- SyntaxKind[SyntaxKind["JSDocAllType"] = 276] = "JSDocAllType";
+ SyntaxKind[SyntaxKind["JSDocAllType"] = 278] = "JSDocAllType";
// The ? type
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 277] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 278] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 279] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 280] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 281] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 282] = "JSDocVariadicType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 283] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 284] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocTag"] = 285] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 286] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocClassTag"] = 287] = "JSDocClassTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 288] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 289] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 290] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 291] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 292] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 293] = "JSDocPropertyTag";
+ SyntaxKind[SyntaxKind["JSDocUnknownType"] = 279] = "JSDocUnknownType";
+ SyntaxKind[SyntaxKind["JSDocNullableType"] = 280] = "JSDocNullableType";
+ SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 281] = "JSDocNonNullableType";
+ SyntaxKind[SyntaxKind["JSDocOptionalType"] = 282] = "JSDocOptionalType";
+ SyntaxKind[SyntaxKind["JSDocFunctionType"] = 283] = "JSDocFunctionType";
+ SyntaxKind[SyntaxKind["JSDocVariadicType"] = 284] = "JSDocVariadicType";
+ SyntaxKind[SyntaxKind["JSDocComment"] = 285] = "JSDocComment";
+ SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 286] = "JSDocTypeLiteral";
+ SyntaxKind[SyntaxKind["JSDocTag"] = 287] = "JSDocTag";
+ SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 288] = "JSDocAugmentsTag";
+ SyntaxKind[SyntaxKind["JSDocClassTag"] = 289] = "JSDocClassTag";
+ SyntaxKind[SyntaxKind["JSDocParameterTag"] = 290] = "JSDocParameterTag";
+ SyntaxKind[SyntaxKind["JSDocReturnTag"] = 291] = "JSDocReturnTag";
+ SyntaxKind[SyntaxKind["JSDocTypeTag"] = 292] = "JSDocTypeTag";
+ SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 293] = "JSDocTemplateTag";
+ SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 294] = "JSDocTypedefTag";
+ SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 295] = "JSDocPropertyTag";
// Synthesized list
- SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList";
+ SyntaxKind[SyntaxKind["SyntaxList"] = 296] = "SyntaxList";
// Transformation nodes
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker";
+ SyntaxKind[SyntaxKind["NotEmittedStatement"] = 297] = "NotEmittedStatement";
+ SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 298] = "PartiallyEmittedExpression";
+ SyntaxKind[SyntaxKind["CommaListExpression"] = 299] = "CommaListExpression";
+ SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 300] = "MergeDeclarationMarker";
+ SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 301] = "EndOfDeclarationMarker";
// Enum value count
- SyntaxKind[SyntaxKind["Count"] = 300] = "Count";
+ SyntaxKind[SyntaxKind["Count"] = 302] = "Count";
// Markers
SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment";
SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment";
@@ -408,10 +410,10 @@ var ts;
SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator";
SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator";
SyntaxKind[SyntaxKind["FirstNode"] = 145] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 275] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 293] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 285] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 293] = "LastJSDocTagNode";
+ SyntaxKind[SyntaxKind["FirstJSDocNode"] = 277] = "FirstJSDocNode";
+ SyntaxKind[SyntaxKind["LastJSDocNode"] = 295] = "LastJSDocNode";
+ SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 287] = "FirstJSDocTagNode";
+ SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 295] = "LastJSDocTagNode";
/* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword";
/* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 144] = "LastContextualKeyword";
})(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
@@ -451,6 +453,7 @@ var ts;
NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc";
/* @internal */ NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient";
/* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement";
+ NodeFlags[NodeFlags["JsonFile"] = 16777216] = "JsonFile";
NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags";
NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags";
@@ -513,10 +516,9 @@ var ts;
GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
// Flags
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 32] = "Optimistic";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 64] = "FileLevel";
+ GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
+ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
+ GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
})(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
/* @internal */
var TokenFlags;
@@ -591,7 +593,7 @@ var ts;
// Options
NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
- // empty space
+ NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams";
NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
// empty space
NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
@@ -1072,6 +1074,11 @@ var ts;
ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
ScriptKind[ScriptKind["External"] = 5] = "External";
ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
+ /**
+ * Used on extensions that doesn't define the ScriptKind but the content defines it.
+ * Deferred extensions are going to be included in all project contexts.
+ */
+ ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
})(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
var ScriptTarget;
(function (ScriptTarget) {
@@ -1082,6 +1089,7 @@ var ts;
ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext";
+ ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest";
})(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
var LanguageVariant;
@@ -1894,8 +1902,8 @@ var ts;
}
ts.findLast = findLast;
/** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */
- function findIndex(array, predicate) {
- for (var i = 0; i < array.length; i++) {
+ function findIndex(array, predicate, startIndex) {
+ for (var i = startIndex || 0; i < array.length; i++) {
if (predicate(array[i], i)) {
return i;
}
@@ -2498,6 +2506,23 @@ var ts;
return to;
}
ts.addRange = addRange;
+ /**
+ * Appends a range of value to begin of an array, returning the array.
+ *
+ * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array
+ * is created if `value` was appended.
+ * @param from The values to append to the array. If `from` is `undefined`, nothing is
+ * appended. If an element of `from` is `undefined`, that element is not appended.
+ */
+ function prependRange(to, from) {
+ if (from === undefined || from.length === 0)
+ return to;
+ if (to === undefined)
+ return from.slice();
+ to.unshift.apply(to, from);
+ return to;
+ }
+ ts.prependRange = prependRange;
/**
* @return Whether the value was added.
*/
@@ -2747,17 +2772,18 @@ var ts;
}
ts.getOwnValues = getOwnValues;
function arrayFrom(iterator, map) {
+ var _a;
var result = [];
- for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) {
result.push(map ? map(value) : value);
}
return result;
- var _b;
}
ts.arrayFrom = arrayFrom;
function forEachEntry(map, callback) {
+ var _a;
var iterator = map.entries();
- for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) {
var key = pair[0], value = pair[1];
var result = callback(value, key);
if (result) {
@@ -2765,19 +2791,18 @@ var ts;
}
}
return undefined;
- var _b;
}
ts.forEachEntry = forEachEntry;
function forEachKey(map, callback) {
+ var _a;
var iterator = map.keys();
- for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) {
var result = callback(key);
if (result) {
return result;
}
}
return undefined;
- var _b;
}
ts.forEachKey = forEachKey;
function copyEntries(source, target) {
@@ -3334,11 +3359,11 @@ var ts;
comparer(a[key], b[key]);
}
ts.compareProperties = compareProperties;
- function getDiagnosticFileName(diagnostic) {
- return diagnostic.file ? diagnostic.file.fileName : undefined;
+ function getDiagnosticFilePath(diagnostic) {
+ return diagnostic.file ? diagnostic.file.path : undefined;
}
function compareDiagnostics(d1, d2) {
- return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) ||
+ return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
compareValues(d1.start, d2.start) ||
compareValues(d1.length, d2.length) ||
compareValues(d1.code, d2.code) ||
@@ -3370,106 +3395,6 @@ var ts;
// We still have one chain remaining. The shorter chain should come first.
return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */;
}
- function normalizeSlashes(path) {
- return path.replace(/\\/g, "/");
- }
- ts.normalizeSlashes = normalizeSlashes;
- /**
- * Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files")
- */
- function getRootLength(path) {
- if (path.charCodeAt(0) === 47 /* slash */) {
- if (path.charCodeAt(1) !== 47 /* slash */)
- return 1;
- var p1 = path.indexOf("/", 2);
- if (p1 < 0)
- return 2;
- var p2 = path.indexOf("/", p1 + 1);
- if (p2 < 0)
- return p1 + 1;
- return p2 + 1;
- }
- if (path.charCodeAt(1) === 58 /* colon */) {
- if (path.charCodeAt(2) === 47 /* slash */ || path.charCodeAt(2) === 92 /* backslash */)
- return 3;
- }
- // Per RFC 1738 'file' URI schema has the shape file:///
- // if is omitted then it is assumed that host value is 'localhost',
- // however slash after the omitted is not removed.
- // file:///folder1/file1 - this is a correct URI
- // file://folder2/file2 - this is an incorrect URI
- if (path.lastIndexOf("file:///", 0) === 0) {
- return "file:///".length;
- }
- var idx = path.indexOf("://");
- if (idx !== -1) {
- return idx + "://".length;
- }
- return 0;
- }
- ts.getRootLength = getRootLength;
- /**
- * Internally, we represent paths as strings with '/' as the directory separator.
- * When we make system calls (eg: LanguageServiceHost.getDirectory()),
- * we expect the host to correctly handle paths in our specified format.
- */
- ts.directorySeparator = "/";
- var directorySeparatorCharCode = 47 /* slash */;
- function getNormalizedParts(normalizedSlashedPath, rootLength) {
- var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator);
- var normalized = [];
- for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
- var part = parts_1[_i];
- if (part !== ".") {
- if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") {
- normalized.pop();
- }
- else {
- // A part may be an empty string (which is 'falsy') if the path had consecutive slashes,
- // e.g. "path//file.ts". Drop these before re-joining the parts.
- if (part) {
- normalized.push(part);
- }
- }
- }
- }
- return normalized;
- }
- function normalizePath(path) {
- return normalizePathAndParts(path).path;
- }
- ts.normalizePath = normalizePath;
- function normalizePathAndParts(path) {
- path = normalizeSlashes(path);
- var rootLength = getRootLength(path);
- var root = path.substr(0, rootLength);
- var parts = getNormalizedParts(path, rootLength);
- if (parts.length) {
- var joinedParts = root + parts.join(ts.directorySeparator);
- return { path: pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts, parts: parts };
- }
- else {
- return { path: root, parts: parts };
- }
- }
- ts.normalizePathAndParts = normalizePathAndParts;
- /** A path ending with '/' refers to a directory only, never a file. */
- function pathEndsWithDirectorySeparator(path) {
- return path.charCodeAt(path.length - 1) === directorySeparatorCharCode;
- }
- ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator;
- function getDirectoryPath(path) {
- return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator)));
- }
- ts.getDirectoryPath = getDirectoryPath;
- function isUrl(path) {
- return path && !isRootedDiskPath(path) && stringContains(path, "://");
- }
- ts.isUrl = isUrl;
- function pathIsRelative(path) {
- return /^\.\.?($|[\\/])/.test(path);
- }
- ts.pathIsRelative = pathIsRelative;
function getEmitScriptTarget(compilerOptions) {
return compilerOptions.target || 0 /* ES3 */;
}
@@ -3501,6 +3426,10 @@ var ts;
: moduleKind === ts.ModuleKind.System;
}
ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
+ function getEmitDeclarations(compilerOptions) {
+ return !!(compilerOptions.declaration || compilerOptions.composite);
+ }
+ ts.getEmitDeclarations = getEmitDeclarations;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag];
}
@@ -3521,202 +3450,455 @@ var ts;
return true;
}
ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
+ //
+ // Paths
+ //
+ /**
+ * Internally, we represent paths as strings with '/' as the directory separator.
+ * When we make system calls (eg: LanguageServiceHost.getDirectory()),
+ * we expect the host to correctly handle paths in our specified format.
+ */
+ ts.directorySeparator = "/";
+ var altDirectorySeparator = "\\";
+ var urlSchemeSeparator = "://";
+ var backslashRegExp = /\\/g;
+ /**
+ * Normalize path separators.
+ */
+ function normalizeSlashes(path) {
+ return path.replace(backslashRegExp, ts.directorySeparator);
+ }
+ ts.normalizeSlashes = normalizeSlashes;
+ function isVolumeCharacter(charCode) {
+ return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
+ (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
+ }
+ function getFileUrlVolumeSeparatorEnd(url, start) {
+ var ch0 = url.charCodeAt(start);
+ if (ch0 === 58 /* colon */)
+ return start + 1;
+ if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
+ var ch2 = url.charCodeAt(start + 2);
+ if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
+ return start + 3;
+ }
+ return -1;
+ }
+ /**
+ * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
+ * If the root is part of a URL, the twos-complement of the root length is returned.
+ */
+ function getEncodedRootLength(path) {
+ if (!path)
+ return 0;
+ var ch0 = path.charCodeAt(0);
+ // POSIX or UNC
+ if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
+ if (path.charCodeAt(1) !== ch0)
+ return 1; // POSIX: "/" (or non-normalized "\")
+ var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2);
+ if (p1 < 0)
+ return path.length; // UNC: "//server" or "\\server"
+ return p1 + 1; // UNC: "//server/" or "\\server\"
+ }
+ // DOS
+ if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
+ var ch2 = path.charCodeAt(2);
+ if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
+ return 3; // DOS: "c:/" or "c:\"
+ if (path.length === 2)
+ return 2; // DOS: "c:" (but not "c:d")
+ }
+ // URL
+ var schemeEnd = path.indexOf(urlSchemeSeparator);
+ if (schemeEnd !== -1) {
+ var authorityStart = schemeEnd + urlSchemeSeparator.length;
+ var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
+ if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
+ // For local "file" URLs, include the leading DOS volume (if present).
+ // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
+ // special case interpreted as "the machine from which the URL is being interpreted".
+ var scheme = path.slice(0, schemeEnd);
+ var authority = path.slice(authorityStart, authorityEnd);
+ if (scheme === "file" && (authority === "" || authority === "localhost") &&
+ isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
+ var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
+ if (volumeSeparatorEnd !== -1) {
+ if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
+ // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
+ return ~(volumeSeparatorEnd + 1);
+ }
+ if (volumeSeparatorEnd === path.length) {
+ // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
+ // but not "file:///c:d" or "file:///c%3ad"
+ return ~volumeSeparatorEnd;
+ }
+ }
+ }
+ return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
+ }
+ return ~path.length; // URL: "file://server", "http://server"
+ }
+ // relative
+ return 0;
+ }
+ /**
+ * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
+ *
+ * For example:
+ * ```ts
+ * getRootLength("a") === 0 // ""
+ * getRootLength("/") === 1 // "/"
+ * getRootLength("c:") === 2 // "c:"
+ * getRootLength("c:d") === 0 // ""
+ * getRootLength("c:/") === 3 // "c:/"
+ * getRootLength("c:\\") === 3 // "c:\\"
+ * getRootLength("//server") === 7 // "//server"
+ * getRootLength("//server/share") === 8 // "//server/"
+ * getRootLength("\\\\server") === 7 // "\\\\server"
+ * getRootLength("\\\\server\\share") === 8 // "\\\\server\\"
+ * getRootLength("file:///path") === 8 // "file:///"
+ * getRootLength("file:///c:") === 10 // "file:///c:"
+ * getRootLength("file:///c:d") === 8 // "file:///"
+ * getRootLength("file:///c:/path") === 11 // "file:///c:/"
+ * getRootLength("file://server") === 13 // "file://server"
+ * getRootLength("file://server/path") === 14 // "file://server/"
+ * getRootLength("http://server") === 13 // "http://server"
+ * getRootLength("http://server/path") === 14 // "http://server/"
+ * ```
+ */
+ function getRootLength(path) {
+ var rootLength = getEncodedRootLength(path);
+ return rootLength < 0 ? ~rootLength : rootLength;
+ }
+ ts.getRootLength = getRootLength;
+ // TODO(rbuckton): replace references with `resolvePath`
+ function normalizePath(path) {
+ return resolvePath(path);
+ }
+ ts.normalizePath = normalizePath;
+ function normalizePathAndParts(path) {
+ path = normalizeSlashes(path);
+ var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
+ if (parts.length) {
+ var joinedParts = root + parts.join(ts.directorySeparator);
+ return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
+ }
+ else {
+ return { path: root, parts: parts };
+ }
+ }
+ ts.normalizePathAndParts = normalizePathAndParts;
+ function getDirectoryPath(path) {
+ path = normalizeSlashes(path);
+ // If the path provided is itself the root, then return it.
+ var rootLength = getRootLength(path);
+ if (rootLength === path.length)
+ return path;
+ // return the leading portion of the path up to the last (non-terminal) directory separator
+ // but not including any trailing directory separator.
+ path = removeTrailingDirectorySeparator(path);
+ return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
+ }
+ ts.getDirectoryPath = getDirectoryPath;
+ function isUrl(path) {
+ return getEncodedRootLength(path) < 0;
+ }
+ ts.isUrl = isUrl;
+ function pathIsRelative(path) {
+ return /^\.\.?($|[\\/])/.test(path);
+ }
+ ts.pathIsRelative = pathIsRelative;
+ /**
+ * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path
+ * like `c:`, `c:\` or `c:/`).
+ */
function isRootedDiskPath(path) {
- return path && getRootLength(path) !== 0;
+ return getEncodedRootLength(path) > 0;
}
ts.isRootedDiskPath = isRootedDiskPath;
+ /**
+ * Determines whether a path consists only of a path root.
+ */
+ function isDiskPathRoot(path) {
+ var rootLength = getEncodedRootLength(path);
+ return rootLength > 0 && rootLength === path.length;
+ }
+ ts.isDiskPathRoot = isDiskPathRoot;
function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
return !isRootedDiskPath(absoluteOrRelativePath)
? absoluteOrRelativePath
: getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
}
ts.convertToRelativePath = convertToRelativePath;
- function normalizedPathComponents(path, rootLength) {
- var normalizedParts = getNormalizedParts(path, rootLength);
- return [path.substr(0, rootLength)].concat(normalizedParts);
+ function pathComponents(path, rootLength) {
+ var root = path.substring(0, rootLength);
+ var rest = path.substring(rootLength).split(ts.directorySeparator);
+ if (rest.length && !lastOrUndefined(rest))
+ rest.pop();
+ return [root].concat(rest);
}
- function getNormalizedPathComponents(path, currentDirectory) {
- path = normalizeSlashes(path);
+ /**
+ * Parse a path into an array containing a root component (at index 0) and zero or more path
+ * components (at indices > 0). The result is not normalized.
+ * If the path is relative, the root component is `""`.
+ * If the path is absolute, the root component includes the first path separator (`/`).
+ */
+ function getPathComponents(path, currentDirectory) {
+ if (currentDirectory === void 0) { currentDirectory = ""; }
+ path = combinePaths(currentDirectory, path);
var rootLength = getRootLength(path);
- if (rootLength === 0) {
- // If the path is not rooted it is relative to current directory
- path = combinePaths(normalizeSlashes(currentDirectory), path);
- rootLength = getRootLength(path);
+ return pathComponents(path, rootLength);
+ }
+ ts.getPathComponents = getPathComponents;
+ /**
+ * Reduce an array of path components to a more simplified path by navigating any
+ * `"."` or `".."` entries in the path.
+ */
+ function reducePathComponents(components) {
+ if (!some(components))
+ return [];
+ var reduced = [components[0]];
+ for (var i = 1; i < components.length; i++) {
+ var component = components[i];
+ if (!component)
+ continue;
+ if (component === ".")
+ continue;
+ if (component === "..") {
+ if (reduced.length > 1) {
+ if (reduced[reduced.length - 1] !== "..") {
+ reduced.pop();
+ continue;
+ }
+ }
+ else if (reduced[0])
+ continue;
+ }
+ reduced.push(component);
}
- return normalizedPathComponents(path, rootLength);
+ return reduced;
+ }
+ ts.reducePathComponents = reducePathComponents;
+ /**
+ * Parse a path into an array containing a root component (at index 0) and zero or more path
+ * components (at indices > 0). The result is normalized.
+ * If the path is relative, the root component is `""`.
+ * If the path is absolute, the root component includes the first path separator (`/`).
+ */
+ function getNormalizedPathComponents(path, currentDirectory) {
+ return reducePathComponents(getPathComponents(path, currentDirectory));
}
ts.getNormalizedPathComponents = getNormalizedPathComponents;
function getNormalizedAbsolutePath(fileName, currentDirectory) {
- return getNormalizedPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
+ return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
}
ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
- function getNormalizedPathFromPathComponents(pathComponents) {
- if (pathComponents && pathComponents.length) {
- return pathComponents[0] + pathComponents.slice(1).join(ts.directorySeparator);
- }
+ /**
+ * Formats a parsed path consisting of a root component (at index 0) and zero or more path
+ * segments (at indices > 0).
+ */
+ function getPathFromPathComponents(pathComponents) {
+ if (pathComponents.length === 0)
+ return "";
+ var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
+ if (pathComponents.length === 1)
+ return root;
+ return root + pathComponents.slice(1).join(ts.directorySeparator);
}
- ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents;
- function getNormalizedPathComponentsOfUrl(url) {
- // Get root length of http://www.website.com/folder1/folder2/
- // In this example the root is: http://www.website.com/
- // normalized path components should be ["http://www.website.com/", "folder1", "folder2"]
- var urlLength = url.length;
- // Initial root length is http:// part
- var rootLength = url.indexOf("://") + "://".length;
- while (rootLength < urlLength) {
- // Consume all immediate slashes in the protocol
- // eg.initial rootlength is just file:// but it needs to consume another "/" in file:///
- if (url.charCodeAt(rootLength) === 47 /* slash */) {
- rootLength++;
- }
- else {
- // non slash character means we continue proceeding to next component of root search
+ ts.getPathFromPathComponents = getPathFromPathComponents;
+ function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
+ var fromComponents = reducePathComponents(getPathComponents(from));
+ var toComponents = reducePathComponents(getPathComponents(to));
+ var start;
+ for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
+ var fromComponent = getCanonicalFileName(fromComponents[start]);
+ var toComponent = getCanonicalFileName(toComponents[start]);
+ var comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer;
+ if (!comparer(fromComponent, toComponent))
break;
- }
}
- // there are no parts after http:// just return current string as the pathComponent
- if (rootLength === urlLength) {
- return [url];
+ if (start === 0) {
+ return toComponents;
}
- // Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://)
- var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength);
- if (indexOfNextSlash !== -1) {
- // Found the "/" after the website.com so the root is length of http://www.website.com/
- // and get components after the root normally like any other folder components
- rootLength = indexOfNextSlash + 1;
- return normalizedPathComponents(url, rootLength);
- }
- else {
- // Can't find the host assume the rest of the string as component
- // but make sure we append "/" to it as root is not joined using "/"
- // eg. if url passed in was http://website.com we want to use root as [http://website.com/]
- // so that other path manipulations will be correct and it can be merged with relative paths correctly
- return [url + ts.directorySeparator];
+ var components = toComponents.slice(start);
+ var relative = [];
+ for (; start < fromComponents.length; start++) {
+ relative.push("..");
}
+ return [""].concat(relative, components);
}
- function getNormalizedPathOrUrlComponents(pathOrUrl, currentDirectory) {
- if (isUrl(pathOrUrl)) {
- return getNormalizedPathComponentsOfUrl(pathOrUrl);
- }
- else {
- return getNormalizedPathComponents(pathOrUrl, currentDirectory);
- }
+ function getRelativePathFromFile(from, to, getCanonicalFileName) {
+ return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
}
+ ts.getRelativePathFromFile = getRelativePathFromFile;
+ function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
+ Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
+ var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : identity;
+ var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
+ var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive, getCanonicalFileName);
+ return getPathFromPathComponents(pathComponents);
+ }
+ ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
- var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory);
- var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory);
- if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") {
- // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name
- // that is ["test", "cases", ""] needs to be actually ["test", "cases"]
- directoryComponents.pop();
+ var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), equateStringsCaseSensitive, getCanonicalFileName);
+ var firstComponent = pathComponents[0];
+ if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
+ var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
+ pathComponents[0] = prefix + firstComponent;
}
- // Find the component that differs
- var joinStartIndex;
- for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) {
- if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) {
- break;
- }
- }
- // Get the relative path
- if (joinStartIndex) {
- var relativePath = "";
- var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length);
- for (; joinStartIndex < directoryComponents.length; joinStartIndex++) {
- if (directoryComponents[joinStartIndex] !== "") {
- relativePath = relativePath + ".." + ts.directorySeparator;
- }
- }
- return relativePath + relativePathComponents.join(ts.directorySeparator);
- }
- // Cant find the relative path, get the absolute path
- var absolutePath = getNormalizedPathFromPathComponents(pathComponents);
- if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) {
- absolutePath = "file:///" + absolutePath;
- }
- return absolutePath;
+ return getPathFromPathComponents(pathComponents);
}
ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
- function getRelativePath(path, directoryPath, getCanonicalFileName) {
- var relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
- return ensurePathIsRelative(relativePath);
+ /**
+ * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
+ * with `./` or `../`) so as not to be confused with an unprefixed module name.
+ */
+ function ensurePathIsNonModuleName(path) {
+ return getRootLength(path) === 0 && !pathIsRelative(path) ? "./" + path : path;
}
- ts.getRelativePath = getRelativePath;
- function ensurePathIsRelative(path) {
- return !pathIsRelative(path) ? "./" + path : path;
- }
- ts.ensurePathIsRelative = ensurePathIsRelative;
- function getBaseFileName(path) {
- if (path === undefined) {
- return undefined;
- }
- var i = path.lastIndexOf(ts.directorySeparator);
- return i < 0 ? path : path.substring(i + 1);
+ ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
+ function getBaseFileName(path, extensions, ignoreCase) {
+ path = normalizeSlashes(path);
+ // if the path provided is itself the root, then it has not file name.
+ var rootLength = getRootLength(path);
+ if (rootLength === path.length)
+ return "";
+ // return the trailing portion of the path starting after the last (non-terminal) directory
+ // separator but not including any trailing directory separator.
+ path = removeTrailingDirectorySeparator(path);
+ var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
+ var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
+ return extension ? name.slice(0, name.length - extension.length) : name;
}
ts.getBaseFileName = getBaseFileName;
- function combinePaths(path1, path2) {
- if (!(path1 && path1.length))
- return path2;
- if (!(path2 && path2.length))
- return path1;
- if (getRootLength(path2) !== 0)
- return path2;
- if (path1.charAt(path1.length - 1) === ts.directorySeparator)
- return path1 + path2;
- return path1 + ts.directorySeparator + path2;
+ /**
+ * Combines paths. If a path is absolute, it replaces any previous path.
+ */
+ function combinePaths(path) {
+ var paths = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ paths[_i - 1] = arguments[_i];
+ }
+ if (path)
+ path = normalizeSlashes(path);
+ for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
+ var relativePath = paths_1[_a];
+ if (!relativePath)
+ continue;
+ relativePath = normalizeSlashes(relativePath);
+ if (!path || getRootLength(relativePath) !== 0) {
+ path = relativePath;
+ }
+ else {
+ path = ensureTrailingDirectorySeparator(path) + relativePath;
+ }
+ }
+ return path;
}
ts.combinePaths = combinePaths;
+ /**
+ * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
+ * `.` and `..` path components are resolved.
+ */
+ function resolvePath(path) {
+ var paths = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ paths[_i - 1] = arguments[_i];
+ }
+ var combined = some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : normalizeSlashes(path);
+ var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(combined)));
+ return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized;
+ }
+ ts.resolvePath = resolvePath;
+ /**
+ * Determines whether a path has a trailing separator (`/` or `\\`).
+ */
+ function hasTrailingDirectorySeparator(path) {
+ if (path.length === 0)
+ return false;
+ var ch = path.charCodeAt(path.length - 1);
+ return ch === 47 /* slash */ || ch === 92 /* backslash */;
+ }
+ ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
function removeTrailingDirectorySeparator(path) {
- if (path.charAt(path.length - 1) === ts.directorySeparator) {
+ if (hasTrailingDirectorySeparator(path)) {
return path.substr(0, path.length - 1);
}
return path;
}
ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
function ensureTrailingDirectorySeparator(path) {
- if (path.charAt(path.length - 1) !== ts.directorySeparator) {
+ if (!hasTrailingDirectorySeparator(path)) {
return path + ts.directorySeparator;
}
return path;
}
ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
- function comparePaths(a, b, currentDirectory, ignoreCase) {
+ function comparePathsWorker(a, b, componentComparer) {
if (a === b)
return 0 /* EqualTo */;
if (a === undefined)
return -1 /* LessThan */;
if (b === undefined)
return 1 /* GreaterThan */;
- a = removeTrailingDirectorySeparator(a);
- b = removeTrailingDirectorySeparator(b);
- var aComponents = getNormalizedPathComponents(a, currentDirectory);
- var bComponents = getNormalizedPathComponents(b, currentDirectory);
+ var aComponents = reducePathComponents(getPathComponents(a));
+ var bComponents = reducePathComponents(getPathComponents(b));
var sharedLength = Math.min(aComponents.length, bComponents.length);
- var comparer = getStringComparer(ignoreCase);
for (var i = 0; i < sharedLength; i++) {
- var result = comparer(aComponents[i], bComponents[i]);
+ var stringComparer = i === 0 ? compareStringsCaseInsensitive : componentComparer;
+ var result = stringComparer(aComponents[i], bComponents[i]);
if (result !== 0 /* EqualTo */) {
return result;
}
}
return compareValues(aComponents.length, bComponents.length);
}
+ /**
+ * Performs a case-sensitive comparison of two paths.
+ */
+ function comparePathsCaseSensitive(a, b) {
+ return comparePathsWorker(a, b, compareStringsCaseSensitive);
+ }
+ ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
+ /**
+ * Performs a case-insensitive comparison of two paths.
+ */
+ function comparePathsCaseInsensitive(a, b) {
+ return comparePathsWorker(a, b, compareStringsCaseInsensitive);
+ }
+ ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
+ function comparePaths(a, b, currentDirectory, ignoreCase) {
+ if (typeof currentDirectory === "string") {
+ a = combinePaths(currentDirectory, a);
+ b = combinePaths(currentDirectory, b);
+ }
+ else if (typeof currentDirectory === "boolean") {
+ ignoreCase = currentDirectory;
+ }
+ return comparePathsWorker(a, b, getStringComparer(ignoreCase));
+ }
ts.comparePaths = comparePaths;
function containsPath(parent, child, currentDirectory, ignoreCase) {
+ if (typeof currentDirectory === "string") {
+ parent = combinePaths(currentDirectory, parent);
+ child = combinePaths(currentDirectory, child);
+ }
+ else if (typeof currentDirectory === "boolean") {
+ ignoreCase = currentDirectory;
+ }
if (parent === undefined || child === undefined)
return false;
if (parent === child)
return true;
- parent = removeTrailingDirectorySeparator(parent);
- child = removeTrailingDirectorySeparator(child);
- if (parent === child)
- return true;
- var parentComponents = getNormalizedPathComponents(parent, currentDirectory);
- var childComponents = getNormalizedPathComponents(child, currentDirectory);
+ var parentComponents = reducePathComponents(getPathComponents(parent));
+ var childComponents = reducePathComponents(getPathComponents(child));
if (childComponents.length < parentComponents.length) {
return false;
}
- var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive;
+ var componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive;
for (var i = 0; i < parentComponents.length; i++) {
+ var equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer;
if (!equalityComparer(parentComponents[i], childComponents[i])) {
return false;
}
@@ -4050,13 +4232,17 @@ var ts;
ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions);
function getSupportedExtensions(options, extraFileExtensions) {
- var needAllExtensions = options && options.allowJs;
- if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) {
- return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
+ var needJsExtensions = options && options.allowJs;
+ if (!extraFileExtensions || extraFileExtensions.length === 0) {
+ return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
}
- return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive);
+ var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; }));
+ return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive);
}
ts.getSupportedExtensions = getSupportedExtensions;
+ function isJavaScriptLike(scriptKind) {
+ return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
+ }
function hasJavaScriptFileExtension(fileName) {
return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
}
@@ -4128,7 +4314,7 @@ var ts;
}
}
ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
- var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */];
+ var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
function removeFileExtension(path) {
for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
var ext = extensionsToRemove_1[_i];
@@ -4149,9 +4335,14 @@ var ts;
}
ts.removeExtension = removeExtension;
function changeExtension(path, newExtension) {
- return (removeFileExtension(path) + newExtension);
+ return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
}
ts.changeExtension = changeExtension;
+ function changeAnyExtension(path, ext, extensions, ignoreCase) {
+ var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
+ return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path;
+ }
+ ts.changeAnyExtension = changeAnyExtension;
/**
* Takes a string like "jquery-min.4.2.3" and returns "jquery"
*/
@@ -4437,6 +4628,10 @@ var ts;
return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
}
ts.extensionIsTypeScript = extensionIsTypeScript;
+ function resolutionExtensionIsTypeScriptOrJson(ext) {
+ return extensionIsTypeScript(ext) || ext === ".json" /* Json */;
+ }
+ ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson;
/**
* Gets the extension from a path.
* Path must have a valid extension.
@@ -4457,14 +4652,34 @@ var ts;
return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); });
}
ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
- // Retrieves any string from the final "." onwards from a base file name.
- // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
- function getAnyExtensionFromPath(path) {
+ function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
+ if (typeof extensions === "string")
+ extensions = [extensions];
+ for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
+ var extension = extensions_2[_i];
+ if (!startsWith(extension, "."))
+ extension = "." + extension;
+ if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") {
+ var pathExtension = path.slice(path.length - extension.length);
+ if (stringEqualityComparer(pathExtension, extension)) {
+ return pathExtension;
+ }
+ }
+ }
+ return "";
+ }
+ function getAnyExtensionFromPath(path, extensions, ignoreCase) {
+ // Retrieves any string from the final "." onwards from a base file name.
+ // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
+ if (extensions) {
+ return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive);
+ }
var baseFileName = getBaseFileName(path);
var extensionIndex = baseFileName.lastIndexOf(".");
if (extensionIndex >= 0) {
return baseFileName.substring(extensionIndex);
}
+ return "";
}
ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
@@ -4566,12 +4781,12 @@ var ts;
/* @internal */
ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
function createPollingIntervalBasedLevels(levels) {
+ var _a;
return _a = {},
_a[PollingInterval.Low] = levels.Low,
_a[PollingInterval.Medium] = levels.Medium,
_a[PollingInterval.High] = levels.High,
_a;
- var _a;
}
var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
@@ -5685,7 +5900,7 @@ var ts;
Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."),
Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."),
Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."),
- Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."),
+ Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."),
Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."),
Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."),
Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"),
@@ -6162,6 +6377,7 @@ var ts;
Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."),
Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."),
Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."),
+ Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."),
Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."),
Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."),
Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
@@ -6345,6 +6561,17 @@ var ts;
Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."),
Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."),
_0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true),
+ Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
+ All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
+ Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
+ Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
+ Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"),
+ Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."),
+ Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."),
+ Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."),
+ File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."),
+ Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"),
+ Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"),
Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."),
Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."),
Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."),
@@ -6443,6 +6670,7 @@ var ts;
Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
+ Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"),
Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""),
@@ -6506,6 +6734,7 @@ var ts;
Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
+ Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
};
})(ts || (ts = {}));
var ts;
@@ -8666,7 +8895,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 === 294 /* SyntaxList */ && node._children.length > 0) {
+ if (node.kind === 296 /* SyntaxList */ && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -8868,12 +9097,12 @@ var ts;
case 159 /* IndexSignature */:
case 162 /* FunctionType */:
case 163 /* ConstructorType */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
case 234 /* ClassDeclaration */:
case 204 /* ClassExpression */:
case 235 /* InterfaceDeclaration */:
case 236 /* TypeAliasDeclaration */:
- case 291 /* JSDocTemplateTag */:
+ case 293 /* JSDocTemplateTag */:
case 233 /* FunctionDeclaration */:
case 153 /* MethodDeclaration */:
case 154 /* Constructor */:
@@ -8903,6 +9132,12 @@ var ts;
case 243 /* ImportDeclaration */:
case 242 /* ImportEqualsDeclaration */:
case 213 /* VariableStatement */:
+ case 234 /* ClassDeclaration */:
+ case 233 /* FunctionDeclaration */:
+ case 238 /* ModuleDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 237 /* EnumDeclaration */:
return true;
default:
return false;
@@ -9040,6 +9275,8 @@ var ts;
case 155 /* GetAccessor */:
case 156 /* SetAccessor */:
case 236 /* TypeAliasDeclaration */:
+ case 151 /* PropertyDeclaration */:
+ case 150 /* PropertySignature */:
errorNode = node.name;
break;
case 192 /* ArrowFunction */:
@@ -9070,6 +9307,10 @@ var ts;
return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
}
ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
+ function isJsonSourceFile(file) {
+ return file.scriptKind === 6 /* JSON */;
+ }
+ ts.isJsonSourceFile = isJsonSourceFile;
function isConstEnumDeclaration(node) {
return node.kind === 237 /* EnumDeclaration */ && isConst(node);
}
@@ -9409,6 +9650,23 @@ var ts;
});
}
ts.getPropertyAssignment = getPropertyAssignment;
+ function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
+ if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
+ var expression = tsConfigSourceFile.statements[0].expression;
+ return ts.isObjectLiteralExpression(expression) && expression;
+ }
+ }
+ ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
+ function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
+ var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
+ return jsonObjectLiteral &&
+ ts.firstDefined(getPropertyAssignment(jsonObjectLiteral, propKey), function (property) {
+ return ts.isArrayLiteralExpression(property.initializer) ?
+ ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
+ undefined;
+ });
+ }
+ ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
function getContainingFunction(node) {
return ts.findAncestor(node.parent, ts.isFunctionLike);
}
@@ -9786,6 +10044,10 @@ var ts;
return node && !!(node.flags & 65536 /* JavaScriptFile */);
}
ts.isInJavaScriptFile = isInJavaScriptFile;
+ function isInJsonFile(node) {
+ return node && !!(node.flags & 16777216 /* JsonFile */);
+ }
+ ts.isInJsonFile = isInJsonFile;
function isInJSDoc(node) {
return node && !!(node.flags & 2097152 /* JSDoc */);
}
@@ -10073,7 +10335,7 @@ var ts;
}
ts.hasQuestionToken = hasQuestionToken;
function isJSDocConstructSignature(node) {
- return node.kind === 281 /* JSDocFunctionType */ &&
+ return node.kind === 283 /* JSDocFunctionType */ &&
node.parameters.length > 0 &&
node.parameters[0].name &&
node.parameters[0].name.escapedText === "new";
@@ -10187,8 +10449,8 @@ var ts;
}
ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
function getJSDocHost(node) {
- while (node.parent.kind === 284 /* JSDocTypeLiteral */) {
- if (node.parent.parent.kind === 292 /* JSDocTypedefTag */) {
+ while (node.parent.kind === 286 /* JSDocTypeLiteral */) {
+ if (node.parent.parent.kind === 294 /* JSDocTypedefTag */) {
node = node.parent.parent;
}
else {
@@ -10196,7 +10458,7 @@ var ts;
node = node.parent.parent.parent;
}
}
- ts.Debug.assert(node.parent.kind === 283 /* JSDocComment */);
+ ts.Debug.assert(node.parent.kind === 285 /* JSDocComment */);
return node.parent.parent;
}
ts.getJSDocHost = getJSDocHost;
@@ -10212,7 +10474,7 @@ var ts;
}
ts.hasRestParameter = hasRestParameter;
function isRestParameter(node) {
- return node.dotDotDotToken !== undefined || node.type && node.type.kind === 282 /* JSDocVariadicType */;
+ return node.dotDotDotToken !== undefined || node.type && node.type.kind === 284 /* JSDocVariadicType */;
}
ts.isRestParameter = isRestParameter;
var AssignmentKind;
@@ -10354,8 +10616,14 @@ var ts;
if (ts.isDeclaration(name.parent)) {
return name.parent.name === name;
}
- var binExp = name.parent.parent;
- return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name;
+ else if (ts.isQualifiedName(name.parent)) {
+ var tag = name.parent.parent;
+ return ts.isJSDocParameterTag(tag) && tag.name === name.parent;
+ }
+ else {
+ var binExp = name.parent.parent;
+ return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name;
+ }
default:
return false;
}
@@ -10735,7 +11003,7 @@ var ts;
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 297 /* CommaListExpression */:
+ case 299 /* CommaListExpression */:
return 0;
case 203 /* SpreadElement */:
return 1;
@@ -12664,8 +12932,8 @@ var ts;
break;
case 71 /* Identifier */:
return declaration;
- case 293 /* JSDocPropertyTag */:
- case 288 /* JSDocParameterTag */: {
+ case 295 /* JSDocPropertyTag */:
+ case 290 /* JSDocParameterTag */: {
var name = declaration.name;
if (name.kind === 145 /* QualifiedName */) {
return name.right;
@@ -12684,7 +12952,7 @@ var ts;
return undefined;
}
}
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return getNameOfJSDocTypedef(declaration);
case 248 /* ExportAssignment */: {
var expression = declaration.expression;
@@ -12935,6 +13203,11 @@ var ts;
return node.kind === 159 /* IndexSignature */;
}
ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
+ /* @internal */
+ function isGetOrSetAccessorDeclaration(node) {
+ return node.kind === 156 /* SetAccessor */ || node.kind === 155 /* GetAccessor */;
+ }
+ ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
// Type
function isTypePredicateNode(node) {
return node.kind === 160 /* TypePredicate */;
@@ -13063,7 +13336,7 @@ var ts;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 296 /* PartiallyEmittedExpression */) {
+ while (node.kind === 298 /* PartiallyEmittedExpression */) {
node = node.expression;
}
return node;
@@ -13419,79 +13692,79 @@ var ts;
ts.isBundle = isBundle;
// JSDoc
function isJSDocTypeExpression(node) {
- return node.kind === 275 /* JSDocTypeExpression */;
+ return node.kind === 277 /* JSDocTypeExpression */;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 276 /* JSDocAllType */;
+ return node.kind === 278 /* JSDocAllType */;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 277 /* JSDocUnknownType */;
+ return node.kind === 279 /* JSDocUnknownType */;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 278 /* JSDocNullableType */;
+ return node.kind === 280 /* JSDocNullableType */;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 279 /* JSDocNonNullableType */;
+ return node.kind === 281 /* JSDocNonNullableType */;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 280 /* JSDocOptionalType */;
+ return node.kind === 282 /* JSDocOptionalType */;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 281 /* JSDocFunctionType */;
+ return node.kind === 283 /* JSDocFunctionType */;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 282 /* JSDocVariadicType */;
+ return node.kind === 284 /* JSDocVariadicType */;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 283 /* JSDocComment */;
+ return node.kind === 285 /* JSDocComment */;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 286 /* JSDocAugmentsTag */;
+ return node.kind === 288 /* JSDocAugmentsTag */;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 287 /* JSDocClassTag */;
+ return node.kind === 289 /* JSDocClassTag */;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocParameterTag(node) {
- return node.kind === 288 /* JSDocParameterTag */;
+ return node.kind === 290 /* JSDocParameterTag */;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 289 /* JSDocReturnTag */;
+ return node.kind === 291 /* JSDocReturnTag */;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 290 /* JSDocTypeTag */;
+ return node.kind === 292 /* JSDocTypeTag */;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 291 /* JSDocTemplateTag */;
+ return node.kind === 293 /* JSDocTemplateTag */;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 292 /* JSDocTypedefTag */;
+ return node.kind === 294 /* JSDocTypedefTag */;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 293 /* JSDocPropertyTag */;
+ return node.kind === 295 /* JSDocPropertyTag */;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 293 /* JSDocPropertyTag */ || node.kind === 288 /* JSDocParameterTag */;
+ return node.kind === 295 /* JSDocPropertyTag */ || node.kind === 290 /* JSDocParameterTag */;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 284 /* JSDocTypeLiteral */;
+ return node.kind === 286 /* JSDocTypeLiteral */;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
})(ts || (ts = {}));
@@ -13502,7 +13775,7 @@ var ts;
(function (ts) {
/* @internal */
function isSyntaxList(n) {
- return n.kind === 294 /* SyntaxList */;
+ return n.kind === 296 /* SyntaxList */;
}
ts.isSyntaxList = isSyntaxList;
/* @internal */
@@ -13650,7 +13923,7 @@ var ts;
case 158 /* ConstructSignature */:
case 159 /* IndexSignature */:
case 162 /* FunctionType */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
case 163 /* ConstructorType */:
return true;
default:
@@ -13734,13 +14007,13 @@ var ts;
|| kind === 95 /* NullKeyword */
|| kind === 131 /* NeverKeyword */
|| kind === 206 /* ExpressionWithTypeArguments */
- || kind === 276 /* JSDocAllType */
- || kind === 277 /* JSDocUnknownType */
- || kind === 278 /* JSDocNullableType */
- || kind === 279 /* JSDocNonNullableType */
- || kind === 280 /* JSDocOptionalType */
- || kind === 281 /* JSDocFunctionType */
- || kind === 282 /* JSDocVariadicType */;
+ || kind === 278 /* JSDocAllType */
+ || kind === 279 /* JSDocUnknownType */
+ || kind === 280 /* JSDocNullableType */
+ || kind === 281 /* JSDocNonNullableType */
+ || kind === 282 /* JSDocOptionalType */
+ || kind === 283 /* JSDocFunctionType */
+ || kind === 284 /* JSDocVariadicType */;
}
/**
* Node test that determines whether a node is a valid type node.
@@ -13962,8 +14235,8 @@ var ts;
case 203 /* SpreadElement */:
case 207 /* AsExpression */:
case 205 /* OmittedExpression */:
- case 297 /* CommaListExpression */:
- case 296 /* PartiallyEmittedExpression */:
+ case 299 /* CommaListExpression */:
+ case 298 /* PartiallyEmittedExpression */:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -13977,12 +14250,12 @@ var ts;
ts.isAssertionExpression = isAssertionExpression;
/* @internal */
function isPartiallyEmittedExpression(node) {
- return node.kind === 296 /* PartiallyEmittedExpression */;
+ return node.kind === 298 /* PartiallyEmittedExpression */;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
/* @internal */
function isNotEmittedStatement(node) {
- return node.kind === 295 /* NotEmittedStatement */;
+ return node.kind === 297 /* NotEmittedStatement */;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
/* @internal */
@@ -14093,7 +14366,8 @@ var ts;
|| kind === 236 /* TypeAliasDeclaration */
|| kind === 147 /* TypeParameter */
|| kind === 231 /* VariableDeclaration */
- || kind === 292 /* JSDocTypedefTag */;
+ || kind === 294 /* JSDocTypedefTag */
+ || kind === 295 /* JSDocPropertyTag */;
}
function isDeclarationStatementKind(kind) {
return kind === 233 /* FunctionDeclaration */
@@ -14128,14 +14402,14 @@ var ts;
|| kind === 213 /* VariableStatement */
|| kind === 218 /* WhileStatement */
|| kind === 225 /* WithStatement */
- || kind === 295 /* NotEmittedStatement */
- || kind === 299 /* EndOfDeclarationMarker */
- || kind === 298 /* MergeDeclarationMarker */;
+ || kind === 297 /* NotEmittedStatement */
+ || kind === 301 /* EndOfDeclarationMarker */
+ || kind === 300 /* MergeDeclarationMarker */;
}
/* @internal */
function isDeclaration(node) {
if (node.kind === 147 /* TypeParameter */) {
- return node.parent.kind !== 291 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node);
+ return node.parent.kind !== 293 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -14230,18 +14504,18 @@ var ts;
/** True if node is of some JSDoc syntax kind. */
/* @internal */
function isJSDocNode(node) {
- return node.kind >= 275 /* FirstJSDocNode */ && node.kind <= 293 /* LastJSDocNode */;
+ return node.kind >= 277 /* FirstJSDocNode */ && node.kind <= 295 /* LastJSDocNode */;
}
ts.isJSDocNode = isJSDocNode;
/** True if node is of a kind that may contain comment text. */
function isJSDocCommentContainingNode(node) {
- return node.kind === 283 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node);
+ return node.kind === 285 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node);
}
ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
// TODO: determine what this does before making it public.
/* @internal */
function isJSDocTag(node) {
- return node.kind >= 285 /* FirstJSDocTagNode */ && node.kind <= 293 /* LastJSDocTagNode */;
+ return node.kind >= 287 /* FirstJSDocTagNode */ && node.kind <= 295 /* LastJSDocTagNode */;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -14292,12 +14566,12 @@ var ts;
case 231 /* VariableDeclaration */:
case 233 /* FunctionDeclaration */:
case 236 /* TypeAliasDeclaration */:
- case 275 /* JSDocTypeExpression */:
- case 278 /* JSDocNullableType */:
- case 279 /* JSDocNonNullableType */:
- case 280 /* JSDocOptionalType */:
- case 281 /* JSDocFunctionType */:
- case 282 /* JSDocVariadicType */:
+ case 277 /* JSDocTypeExpression */:
+ case 280 /* JSDocNullableType */:
+ case 281 /* JSDocNonNullableType */:
+ case 282 /* JSDocOptionalType */:
+ case 283 /* JSDocFunctionType */:
+ case 284 /* JSDocVariadicType */:
return true;
}
return false;
@@ -14787,7 +15061,7 @@ var ts;
return visitNode(cbNode, node.expression);
case 252 /* MissingDeclaration */:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 297 /* CommaListExpression */:
+ case 299 /* CommaListExpression */:
return visitNodes(cbNode, cbNodes, node.elements);
case 254 /* JsxElement */:
return visitNode(cbNode, node.openingElement) ||
@@ -14814,23 +15088,23 @@ var ts;
visitNode(cbNode, node.expression);
case 257 /* JsxClosingElement */:
return visitNode(cbNode, node.tagName);
- case 275 /* JSDocTypeExpression */:
+ case 277 /* JSDocTypeExpression */:
return visitNode(cbNode, node.type);
- case 279 /* JSDocNonNullableType */:
+ case 281 /* JSDocNonNullableType */:
return visitNode(cbNode, node.type);
- case 278 /* JSDocNullableType */:
+ case 280 /* JSDocNullableType */:
return visitNode(cbNode, node.type);
- case 280 /* JSDocOptionalType */:
+ case 282 /* JSDocOptionalType */:
return visitNode(cbNode, node.type);
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
return visitNodes(cbNode, cbNodes, node.parameters) ||
visitNode(cbNode, node.type);
- case 282 /* JSDocVariadicType */:
+ case 284 /* JSDocVariadicType */:
return visitNode(cbNode, node.type);
- case 283 /* JSDocComment */:
+ case 285 /* JSDocComment */:
return visitNodes(cbNode, cbNodes, node.tags);
- case 288 /* JSDocParameterTag */:
- case 293 /* JSDocPropertyTag */:
+ case 290 /* JSDocParameterTag */:
+ case 295 /* JSDocPropertyTag */:
if (node.isNameFirst) {
return visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression);
@@ -14839,17 +15113,17 @@ var ts;
return visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name);
}
- case 289 /* JSDocReturnTag */:
+ case 291 /* JSDocReturnTag */:
return visitNode(cbNode, node.typeExpression);
- case 290 /* JSDocTypeTag */:
+ case 292 /* JSDocTypeTag */:
return visitNode(cbNode, node.typeExpression);
- case 286 /* JSDocAugmentsTag */:
+ case 288 /* JSDocAugmentsTag */:
return visitNode(cbNode, node.class);
- case 291 /* JSDocTemplateTag */:
+ case 293 /* JSDocTemplateTag */:
return visitNodes(cbNode, cbNodes, node.typeParameters);
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
if (node.typeExpression &&
- node.typeExpression.kind === 275 /* JSDocTypeExpression */) {
+ node.typeExpression.kind === 277 /* JSDocTypeExpression */) {
return visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName);
}
@@ -14857,7 +15131,7 @@ var ts;
return visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
}
- case 284 /* JSDocTypeLiteral */:
+ case 286 /* JSDocTypeLiteral */:
if (node.jsDocPropertyTags) {
for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) {
var tag = _a[_i];
@@ -14865,7 +15139,7 @@ var ts;
}
}
return;
- case 296 /* PartiallyEmittedExpression */:
+ case 298 /* PartiallyEmittedExpression */:
return visitNode(cbNode, node.expression);
}
}
@@ -14873,7 +15147,13 @@ var ts;
function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
if (setParentNodes === void 0) { setParentNodes = false; }
ts.performance.mark("beforeParse");
- var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
+ var result;
+ if (languageVersion === 100 /* JSON */) {
+ result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes);
+ }
+ else {
+ result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
+ }
ts.performance.mark("afterParse");
ts.performance.measure("Parse", "beforeParse", "afterParse");
return result;
@@ -15033,6 +15313,13 @@ var ts;
var parseErrorBeforeNextFinishedNode = false;
function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
scriptKind = ts.ensureScriptKind(fileName, scriptKind);
+ if (scriptKind === 6 /* JSON */) {
+ var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
+ ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
+ result_1.typeReferenceDirectives = ts.emptyArray;
+ result_1.amdDependencies = ts.emptyArray;
+ return result_1;
+ }
initializeState(sourceText, languageVersion, syntaxCursor, scriptKind);
var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind);
clearState();
@@ -15050,25 +15337,57 @@ var ts;
return isInvalid ? entityName : undefined;
}
Parser.parseIsolatedEntityName = parseIsolatedEntityName;
- function parseJsonText(fileName, sourceText) {
- initializeState(sourceText, 2 /* ES2015 */, /*syntaxCursor*/ undefined, 6 /* JSON */);
+ function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
+ if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; }
+ initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
// Set source file so that errors will be reported with this file name
sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false);
- var result = sourceFile;
// Prime the scanner.
nextToken();
+ var pos = getNodePos();
if (token() === 1 /* EndOfFileToken */) {
+ sourceFile.statements = createNodeArray([], pos, pos);
sourceFile.endOfFileToken = parseTokenNode();
}
- else if (token() === 17 /* OpenBraceToken */ ||
- lookAhead(function () { return token() === 9 /* StringLiteral */; })) {
- result.jsonObject = parseObjectLiteralExpression();
+ else {
+ var statement = createNode(215 /* ExpressionStatement */);
+ switch (token()) {
+ case 21 /* OpenBracketToken */:
+ statement.expression = parseArrayLiteralExpression();
+ break;
+ case 101 /* TrueKeyword */:
+ case 86 /* FalseKeyword */:
+ case 95 /* NullKeyword */:
+ statement.expression = parseTokenNode();
+ break;
+ case 38 /* MinusToken */:
+ if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 56 /* ColonToken */; })) {
+ statement.expression = parsePrefixUnaryExpression();
+ }
+ else {
+ statement.expression = parseObjectLiteralExpression();
+ }
+ break;
+ case 8 /* NumericLiteral */:
+ case 9 /* StringLiteral */:
+ if (lookAhead(function () { return nextToken() !== 56 /* ColonToken */; })) {
+ statement.expression = parseLiteralNode();
+ break;
+ }
+ // falls through
+ default:
+ statement.expression = parseObjectLiteralExpression();
+ break;
+ }
+ finishNode(statement);
+ sourceFile.statements = createNodeArray([statement], pos);
sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
}
- else {
- parseExpected(17 /* OpenBraceToken */);
+ if (setParentNodes) {
+ fixupParentReferences(sourceFile);
}
sourceFile.parseDiagnostics = parseDiagnostics;
+ var result = sourceFile;
clearState();
return result;
}
@@ -15092,9 +15411,11 @@ var ts;
switch (scriptKind) {
case 1 /* JS */:
case 2 /* JSX */:
- case 6 /* JSON */:
contextFlags = 65536 /* JavaScriptFile */;
break;
+ case 6 /* JSON */:
+ contextFlags = 65536 /* JavaScriptFile */ | 16777216 /* JsonFile */;
+ break;
default:
contextFlags = 0 /* None */;
break;
@@ -16340,9 +16661,9 @@ var ts;
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(276 /* JSDocAllType */);
+ var result = createNode(278 /* JSDocAllType */);
if (postFixEquals) {
- return createJSDocPostfixType(280 /* JSDocOptionalType */, result);
+ return createJSDocPostfixType(282 /* JSDocOptionalType */, result);
}
else {
nextToken();
@@ -16350,7 +16671,7 @@ var ts;
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(279 /* JSDocNonNullableType */);
+ var result = createNode(281 /* JSDocNonNullableType */);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -16374,18 +16695,18 @@ var ts;
token() === 29 /* GreaterThanToken */ ||
token() === 58 /* EqualsToken */ ||
token() === 49 /* BarToken */) {
- var result = createNode(277 /* JSDocUnknownType */, pos);
+ var result = createNode(279 /* JSDocUnknownType */, pos);
return finishNode(result);
}
else {
- var result = createNode(278 /* JSDocNullableType */, pos);
+ var result = createNode(280 /* JSDocNullableType */, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(281 /* JSDocFunctionType */);
+ var result = createNodeWithJSDoc(283 /* JSDocFunctionType */);
nextToken();
fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
return finishNode(result);
@@ -16407,12 +16728,12 @@ var ts;
var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */);
var type = parseType();
if (dotdotdot) {
- var variadic = createNode(282 /* JSDocVariadicType */, dotdotdot.pos);
+ var variadic = createNode(284 /* JSDocVariadicType */, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 58 /* EqualsToken */) {
- return createJSDocPostfixType(280 /* JSDocOptionalType */, type);
+ return createJSDocPostfixType(282 /* JSDocOptionalType */, type);
}
return type;
}
@@ -16947,14 +17268,14 @@ var ts;
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 51 /* ExclamationToken */:
- type = createJSDocPostfixType(279 /* JSDocNonNullableType */, type);
+ type = createJSDocPostfixType(281 /* JSDocNonNullableType */, type);
break;
case 55 /* 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 = createJSDocPostfixType(278 /* JSDocNullableType */, type);
+ type = createJSDocPostfixType(280 /* JSDocNullableType */, type);
break;
case 21 /* OpenBracketToken */:
parseExpected(21 /* OpenBracketToken */);
@@ -17518,7 +17839,7 @@ var ts;
// 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
if (token() === 120 /* AsyncKeyword */) {
nextToken();
- // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function
+ // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
// but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) {
return 0 /* False */;
@@ -19905,7 +20226,7 @@ var ts;
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
// Parses out a JSDoc type expression.
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(275 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var result = createNode(277 /* JSDocTypeExpression */, scanner.getTokenPos());
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */);
result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -19925,6 +20246,7 @@ var ts;
}
JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
function parseJSDocComment(parent, start, length) {
+ var _a;
var saveToken = currentToken;
var saveParseDiagnosticsLength = parseDiagnostics.length;
var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
@@ -19942,7 +20264,6 @@ var ts;
parseDiagnostics.length = saveParseDiagnosticsLength;
parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
return comment;
- var _a;
}
JSDocParser.parseJSDocComment = parseJSDocComment;
var JSDocState;
@@ -20076,7 +20397,7 @@ var ts;
}
}
function createJSDocComment() {
- var result = createNode(283 /* JSDocComment */, start);
+ var result = createNode(285 /* JSDocComment */, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
@@ -20201,7 +20522,7 @@ var ts;
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(atToken, tagName) {
- var result = createNode(285 /* JSDocTag */, atToken.pos);
+ var result = createNode(287 /* JSDocTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
return finishNode(result);
@@ -20258,8 +20579,8 @@ var ts;
typeExpression = tryParseTypeExpression();
}
var result = target === 1 /* Parameter */ ?
- createNode(288 /* JSDocParameterTag */, atToken.pos) :
- createNode(293 /* JSDocPropertyTag */, atToken.pos);
+ createNode(290 /* JSDocParameterTag */, atToken.pos) :
+ createNode(295 /* JSDocPropertyTag */, atToken.pos);
var comment;
if (indent !== undefined)
comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos);
@@ -20279,18 +20600,18 @@ var ts;
}
function parseNestedTypeLiteral(typeExpression, name, target) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(275 /* JSDocTypeExpression */, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(277 /* 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, name); })) {
- if (child.kind === 288 /* JSDocParameterTag */ || child.kind === 293 /* JSDocPropertyTag */) {
+ if (child.kind === 290 /* JSDocParameterTag */ || child.kind === 295 /* JSDocPropertyTag */) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(284 /* JSDocTypeLiteral */, start_2);
+ jsdocTypeLiteral = createNode(286 /* JSDocTypeLiteral */, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 166 /* ArrayType */) {
jsdocTypeLiteral.isArrayType = true;
@@ -20301,27 +20622,27 @@ var ts;
}
}
function parseReturnTag(atToken, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 289 /* JSDocReturnTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 291 /* JSDocReturnTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(289 /* JSDocReturnTag */, atToken.pos);
+ var result = createNode(291 /* JSDocReturnTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(atToken, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 290 /* JSDocTypeTag */; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 292 /* JSDocTypeTag */; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(290 /* JSDocTypeTag */, atToken.pos);
+ var result = createNode(292 /* JSDocTypeTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
return finishNode(result);
}
function parseAugmentsTag(atToken, tagName) {
- var result = createNode(286 /* JSDocAugmentsTag */, atToken.pos);
+ var result = createNode(288 /* JSDocAugmentsTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
@@ -20349,7 +20670,7 @@ var ts;
return node;
}
function parseClassTag(atToken, tagName) {
- var tag = createNode(287 /* JSDocClassTag */, atToken.pos);
+ var tag = createNode(289 /* JSDocClassTag */, atToken.pos);
tag.atToken = atToken;
tag.tagName = tagName;
return finishNode(tag);
@@ -20357,7 +20678,7 @@ var ts;
function parseTypedefTag(atToken, tagName) {
var typeExpression = tryParseTypeExpression();
skipWhitespace();
- var typedefTag = createNode(292 /* JSDocTypedefTag */, atToken.pos);
+ var typedefTag = createNode(294 /* JSDocTypedefTag */, atToken.pos);
typedefTag.atToken = atToken;
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0);
@@ -20382,9 +20703,9 @@ var ts;
var start_3 = scanner.getStartPos();
while (child = tryParse(function () { return parseChildPropertyTag(); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(284 /* JSDocTypeLiteral */, start_3);
+ jsdocTypeLiteral = createNode(286 /* JSDocTypeLiteral */, start_3);
}
- if (child.kind === 290 /* JSDocTypeTag */) {
+ if (child.kind === 292 /* JSDocTypeTag */) {
if (childTypeTag) {
break;
}
@@ -20445,7 +20766,7 @@ var ts;
case 57 /* AtToken */:
if (canParseTag) {
var child = tryParseChildTag(target);
- if (child && child.kind === 288 /* JSDocParameterTag */ &&
+ if (child && child.kind === 290 /* JSDocParameterTag */ &&
(ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
}
@@ -20530,7 +20851,7 @@ var ts;
break;
}
}
- var result = createNode(291 /* JSDocTemplateTag */, atToken.pos);
+ var result = createNode(293 /* JSDocTemplateTag */, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -21523,6 +21844,10 @@ var ts;
return "__index" /* Index */;
case 249 /* ExportDeclaration */:
return "__export" /* ExportStar */;
+ case 273 /* SourceFile */:
+ // json file should behave as
+ // module.exports = ...
+ return "export=" /* ExportEquals */;
case 199 /* BinaryExpression */:
if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) {
// module.exports = ...
@@ -21530,16 +21855,16 @@ var ts;
}
ts.Debug.fail("Unknown binary declaration kind");
break;
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
case 148 /* 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 === 281 /* 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 === 283 /* 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;
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
var name_2 = ts.getNameOfJSDocTypedef(node);
return typeof name_2 !== "undefined" ? name_2.escapedText : undefined;
}
@@ -21679,7 +22004,7 @@ var ts;
// during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
// and this case is specially handled. Module augmentations should only be merged with original module definition
// and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
- if (node.kind === 292 /* JSDocTypedefTag */)
+ if (node.kind === 294 /* JSDocTypedefTag */)
ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypedefTag(node)) {
if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) {
@@ -21928,10 +22253,10 @@ var ts;
case 186 /* CallExpression */:
bindCallExpressionFlow(node);
break;
- case 283 /* JSDocComment */:
+ case 285 /* JSDocComment */:
bindJSDocComment(node);
break;
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
bindJSDocTypedefTag(node);
break;
// In source files and blocks, bind functions first to match hoisting that occurs at runtime
@@ -22550,7 +22875,7 @@ var ts;
}
function bindJSDocComment(node) {
ts.forEachChild(node, function (n) {
- if (n.kind !== 292 /* JSDocTypedefTag */) {
+ if (n.kind !== 294 /* JSDocTypedefTag */) {
bind(n);
}
});
@@ -22596,7 +22921,7 @@ var ts;
case 237 /* EnumDeclaration */:
case 183 /* ObjectLiteralExpression */:
case 165 /* TypeLiteral */:
- case 284 /* JSDocTypeLiteral */:
+ case 286 /* JSDocTypeLiteral */:
case 262 /* JsxAttributes */:
return 1 /* IsContainer */;
case 235 /* InterfaceDeclaration */:
@@ -22618,7 +22943,7 @@ var ts;
case 155 /* GetAccessor */:
case 156 /* SetAccessor */:
case 157 /* CallSignature */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
case 162 /* FunctionType */:
case 158 /* ConstructSignature */:
case 159 /* IndexSignature */:
@@ -22680,7 +23005,7 @@ var ts;
case 237 /* EnumDeclaration */:
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
case 165 /* TypeLiteral */:
- case 284 /* JSDocTypeLiteral */:
+ case 286 /* JSDocTypeLiteral */:
case 183 /* ObjectLiteralExpression */:
case 235 /* InterfaceDeclaration */:
case 262 /* JsxAttributes */:
@@ -22703,7 +23028,7 @@ var ts;
case 233 /* FunctionDeclaration */:
case 191 /* FunctionExpression */:
case 192 /* ArrowFunction */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
case 236 /* TypeAliasDeclaration */:
case 176 /* MappedType */:
// All the children of these container types are never visible through another
@@ -23091,7 +23416,7 @@ var ts;
}
for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) {
var tag = _c[_b];
- if (tag.kind === 292 /* JSDocTypedefTag */) {
+ if (tag.kind === 294 /* JSDocTypedefTag */) {
var savedParent = parent;
parent = jsDoc;
bind(tag);
@@ -23130,7 +23455,7 @@ var ts;
// current "blockScopeContainer" needs to be set to its immediate namespace parent.
if (node.isInJSDocNamespace) {
var parentNode = node.parent;
- while (parentNode && parentNode.kind !== 292 /* JSDocTypedefTag */) {
+ while (parentNode && parentNode.kind !== 294 /* JSDocTypedefTag */) {
parentNode = parentNode.parent;
}
bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */);
@@ -23232,11 +23557,11 @@ var ts;
case 156 /* SetAccessor */:
return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */);
case 162 /* FunctionType */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
case 163 /* ConstructorType */:
return bindFunctionOrConstructorType(node);
case 165 /* TypeLiteral */:
- case 284 /* JSDocTypeLiteral */:
+ case 286 /* JSDocTypeLiteral */:
case 176 /* MappedType */:
return bindAnonymousTypeWorker(node);
case 183 /* ObjectLiteralExpression */:
@@ -23292,18 +23617,18 @@ var ts;
// falls through
case 239 /* ModuleBlock */:
return updateStrictModeStatementList(node.statements);
- case 288 /* JSDocParameterTag */:
- if (node.parent.kind !== 284 /* JSDocTypeLiteral */) {
+ case 290 /* JSDocParameterTag */:
+ if (node.parent.kind !== 286 /* JSDocTypeLiteral */) {
break;
}
// falls through
- case 293 /* JSDocPropertyTag */:
+ case 295 /* JSDocPropertyTag */:
var propTag = node;
- var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 280 /* JSDocOptionalType */ ?
+ var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 282 /* JSDocOptionalType */ ?
4 /* Property */ | 16777216 /* Optional */ :
4 /* Property */;
return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
- case 292 /* JSDocTypedefTag */: {
+ case 294 /* JSDocTypedefTag */: {
var fullName = node.fullName;
if (!fullName || fullName.kind === 71 /* Identifier */) {
(delayedTypedefs || (delayedTypedefs = [])).push({ typedef: node, container: container, lastContainer: lastContainer, blockScopeContainer: blockScopeContainer, parent: parent });
@@ -23323,6 +23648,13 @@ var ts;
if (ts.isExternalModule(file)) {
bindSourceFileAsExternalModule();
}
+ else if (ts.isJsonSourceFile(file)) {
+ bindSourceFileAsExternalModule();
+ // Create symbol equivalent for the module.exports = {}
+ var originalSymbol = file.symbol;
+ declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
+ file.symbol = originalSymbol;
+ }
}
function bindSourceFileAsExternalModule() {
bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
@@ -23999,7 +24331,7 @@ var ts;
else {
// A ClassDeclaration is ES6 syntax.
transformFlags = subtreeFlags | 192 /* AssertES2015 */;
- // A class with a parameter property assignment, property initializer, or decorator is
+ // A class with a parameter property assignment, property initializer, computed property name, or decorator is
// TypeScript syntax.
// An exported declaration may be TypeScript syntax, but is handled by the visitor
// for a namespace declaration.
@@ -24136,9 +24468,9 @@ var ts;
function computePropertyDeclaration(node, subtreeFlags) {
// A PropertyDeclaration is TypeScript syntax.
var transformFlags = subtreeFlags | 3 /* AssertTypeScript */;
- // If the PropertyDeclaration has an initializer, we need to inform its ancestor
+ // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor
// so that it handle the transformation.
- if (node.initializer) {
+ if (node.initializer || ts.isComputedPropertyName(node.name)) {
transformFlags |= 8192 /* ContainsPropertyInitializer */;
}
node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
@@ -24362,7 +24694,7 @@ var ts;
break;
case 189 /* TypeAssertionExpression */:
case 207 /* AsExpression */:
- case 296 /* PartiallyEmittedExpression */:
+ case 298 /* PartiallyEmittedExpression */:
// These nodes are TypeScript syntax.
transformFlags |= 3 /* AssertTypeScript */;
excludeFlags = 536872257 /* OuterExpressionExcludes */;
@@ -24634,7 +24966,7 @@ var ts;
return 940049729 /* BindingPatternExcludes */;
case 189 /* TypeAssertionExpression */:
case 207 /* AsExpression */:
- case 296 /* PartiallyEmittedExpression */:
+ case 298 /* PartiallyEmittedExpression */:
case 190 /* ParenthesizedExpression */:
case 97 /* SuperKeyword */:
return 536872257 /* OuterExpressionExcludes */;
@@ -24850,7 +25182,8 @@ var ts;
(function (Extensions) {
Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
- Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; /** Only '.d.ts' */
+ Extensions[Extensions["Json"] = 2] = "Json";
+ Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; /** Only '.d.ts' */
})(Extensions || (Extensions = {}));
/** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
function resolvedTypeScriptOnly(resolved) {
@@ -24894,7 +25227,13 @@ var ts;
function readJson(path, host) {
try {
var jsonText = host.readFile(path);
- return jsonText ? JSON.parse(jsonText) : {};
+ if (!jsonText)
+ return {};
+ var result = ts.parseConfigFileTextToJson(path, jsonText);
+ if (result.error) {
+ return {};
+ }
+ return result.config;
}
catch (e) {
// gracefully handle if readFile fails or returns not JSON
@@ -25425,7 +25764,11 @@ var ts;
var traceEnabled = isTraceEnabled(compilerOptions, host);
var failedLookupLocations = [];
var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled };
- var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript));
+ var result = jsOnly ?
+ tryResolve(Extensions.JavaScript) :
+ (tryResolve(Extensions.TypeScript) ||
+ tryResolve(Extensions.JavaScript) ||
+ (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined));
if (result && result.value) {
var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport;
return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations);
@@ -25480,7 +25823,7 @@ var ts;
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
}
- if (!ts.pathEndsWithDirectorySeparator(candidate)) {
+ if (!ts.hasTrailingDirectorySeparator(candidate)) {
if (!onlyRecordFailures) {
var parentOfCandidate = ts.getDirectoryPath(candidate);
if (!directoryProbablyExists(parentOfCandidate, state.host)) {
@@ -25565,6 +25908,10 @@ var ts;
* in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
*/
function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) {
+ if (extensions === Extensions.Json) {
+ var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
+ return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state);
+ }
// First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state);
if (resolvedByAddingExtension) {
@@ -25585,9 +25932,9 @@ var ts;
function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) {
if (!onlyRecordFailures) {
// check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
- var directory = ts.getDirectoryPath(candidate);
- if (directory) {
- onlyRecordFailures = !directoryProbablyExists(directory, state.host);
+ var directory_1 = ts.getDirectoryPath(candidate);
+ if (directory_1) {
+ onlyRecordFailures = !directoryProbablyExists(directory_1, state.host);
}
}
switch (extensions) {
@@ -25597,6 +25944,8 @@ var ts;
return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
case Extensions.JavaScript:
return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
+ case Extensions.Json:
+ return tryExtension(".json" /* Json */);
}
function tryExtension(ext) {
var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state);
@@ -25683,7 +26032,7 @@ var ts;
}
}
function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) {
- var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state);
+ var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state);
if (!file) {
return undefined;
}
@@ -25718,6 +26067,8 @@ var ts;
switch (extensions) {
case Extensions.JavaScript:
return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
+ case Extensions.Json:
+ return extension === ".json" /* Json */;
case Extensions.TypeScript:
return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
case Extensions.DtsOnly:
@@ -25788,7 +26139,7 @@ var ts;
if (packageResult) {
return packageResult;
}
- if (extensions !== Extensions.JavaScript) {
+ if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) {
var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
var nodeModulesAtTypesExists = nodeModulesFolderExists;
if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
@@ -26639,17 +26990,17 @@ var ts;
}
function getJsxNamespace(location) {
if (location) {
- var file = ts.getSourceFileOfNode(location);
- if (file) {
- if (file.localJsxNamespace) {
- return file.localJsxNamespace;
+ var file_1 = ts.getSourceFileOfNode(location);
+ if (file_1) {
+ if (file_1.localJsxNamespace) {
+ return file_1.localJsxNamespace;
}
- var jsxPragma = file.pragmas.get("jsx");
+ var jsxPragma = file_1.pragmas.get("jsx");
if (jsxPragma) {
var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
- file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
- if (file.localJsxFactory) {
- return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText;
+ file_1.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
+ if (file_1.localJsxFactory) {
+ return file_1.localJsxNamespace = getFirstIdentifier(file_1.localJsxFactory).escapedText;
}
}
}
@@ -27070,7 +27421,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 & 67901928 /* Type */ && lastLocation.kind !== 283 /* JSDocComment */) {
+ if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 285 /* JSDocComment */) {
useResult = result.flags & 262144 /* TypeParameter */
// type parameters are visible in parameter list, return type and type parameter list
? lastLocation === location.type ||
@@ -27597,8 +27948,8 @@ var ts;
else {
exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias);
}
- var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
- var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias);
+ var file_2 = ts.find(moduleSymbol.declarations, ts.isSourceFile);
+ var hasSyntheticDefault = canHaveSyntheticDefault(file_2, moduleSymbol, dontResolveAlias);
if (!exportDefaultSymbol && !hasSyntheticDefault) {
error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
}
@@ -27859,40 +28210,40 @@ var ts;
else if (name.kind === 145 /* QualifiedName */ || name.kind === 184 /* PropertyAccessExpression */) {
var left = name.kind === 145 /* QualifiedName */ ? name.left : name.expression;
var right = name.kind === 145 /* QualifiedName */ ? name.right : name.name;
- var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
- if (!namespace || ts.nodeIsMissing(right)) {
+ var namespace_1 = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
+ if (!namespace_1 || ts.nodeIsMissing(right)) {
return undefined;
}
- else if (namespace === unknownSymbol) {
- return namespace;
+ else if (namespace_1 === unknownSymbol) {
+ return namespace_1;
}
if (ts.isInJavaScriptFile(name)) {
- var initializer = ts.getDeclaredJavascriptInitializer(namespace.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace.valueDeclaration);
+ var initializer = ts.getDeclaredJavascriptInitializer(namespace_1.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace_1.valueDeclaration);
if (initializer) {
- namespace = getSymbolOfNode(initializer);
+ namespace_1 = getSymbolOfNode(initializer);
}
// Currently, IIFEs may not have a symbol and we don't know about their contents. Give up in this case.
- if (!namespace) {
+ if (!namespace_1) {
return undefined;
}
- if (namespace.valueDeclaration &&
- ts.isVariableDeclaration(namespace.valueDeclaration) &&
- namespace.valueDeclaration.initializer &&
- isCommonJsRequire(namespace.valueDeclaration.initializer)) {
- var moduleName = namespace.valueDeclaration.initializer.arguments[0];
+ if (namespace_1.valueDeclaration &&
+ ts.isVariableDeclaration(namespace_1.valueDeclaration) &&
+ namespace_1.valueDeclaration.initializer &&
+ isCommonJsRequire(namespace_1.valueDeclaration.initializer)) {
+ var moduleName = namespace_1.valueDeclaration.initializer.arguments[0];
var moduleSym = resolveExternalModuleName(moduleName, moduleName);
if (moduleSym) {
var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
if (resolvedModuleSymbol) {
- namespace = resolvedModuleSymbol;
+ namespace_1 = resolvedModuleSymbol;
}
}
}
}
- symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning);
+ symbol = getSymbol(getExportsOfSymbol(namespace_1), right.escapedText, meaning);
if (!symbol) {
if (!ignoreErrors) {
- error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right));
+ error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace_1), ts.declarationNameToString(right));
}
return undefined;
}
@@ -27970,7 +28321,7 @@ var ts;
}
}
// May be an untyped module. If so, ignore resolutionDiagnostic.
- if (resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) {
+ if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) {
if (isForAugmentation) {
var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
@@ -27982,7 +28333,22 @@ var ts;
return undefined;
}
if (moduleNotFoundError) {
- // report errors only if it was requested
+ // For relative paths, see if this was possibly a projectReference redirect
+ if (ts.pathIsRelative(moduleReference)) {
+ var sourceFile_1 = ts.getSourceFileOfNode(location);
+ var redirects = sourceFile_1.redirectedReferences;
+ if (redirects) {
+ var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName));
+ for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) {
+ var ext = _a[_i];
+ var probePath = normalizedTargetPath + ext;
+ if (redirects.indexOf(probePath) >= 0) {
+ error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath);
+ return undefined;
+ }
+ }
+ }
+ }
if (resolutionDiagnostic) {
error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
}
@@ -28429,7 +28795,7 @@ var ts;
* @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible
*/
function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
- if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) {
+ if (symbol && enclosingDeclaration) {
var initialSymbol = symbol;
var meaningToLook = meaning;
while (symbol) {
@@ -28511,6 +28877,11 @@ var ts;
isDeclarationVisible(declaration.parent.parent.parent)) {
return addVisibleAlias(declaration, declaration.parent.parent);
}
+ else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement
+ && !ts.hasModifier(declaration, 1 /* Export */)
+ && isDeclarationVisible(declaration.parent)) {
+ return addVisibleAlias(declaration, declaration);
+ }
// Declaration is not visible
return false;
}
@@ -28770,7 +29141,15 @@ var ts;
}
if (type.flags & 32768 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
if (type.flags & 32768 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) {
- return ts.createInferTypeNode(ts.createTypeParameterDeclaration(getNameOfSymbolAsWritten(type.symbol)));
+ return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined));
+ }
+ if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
+ type.flags & 32768 /* TypeParameter */ &&
+ ts.length(type.symbol.declarations) &&
+ ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
+ typeParameterShadowsNameInScope(type, context) &&
+ !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
+ return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined);
}
var name = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?");
// Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
@@ -28828,7 +29207,16 @@ var ts;
ts.Debug.assert(!!(type.flags & 65536 /* Object */));
var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined;
var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined;
- var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type));
+ var appropriateConstraintTypeNode;
+ if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
+ // We have a { [P in keyof T]: X }
+ // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType`
+ appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context));
+ }
+ else {
+ appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context);
+ }
+ var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context);
var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode);
return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
@@ -29168,17 +29556,29 @@ var ts;
}
return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments);
}
- function typeParameterToDeclaration(type, context, constraint) {
- if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); }
+ function typeParameterShadowsNameInScope(type, context) {
+ return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false);
+ }
+ function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
var savedContextFlags = context.flags;
context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
- var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true);
- var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
+ var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
+ type.symbol.declarations[0] &&
+ ts.isTypeParameterDeclaration(type.symbol.declarations[0]) &&
+ typeParameterShadowsNameInScope(type, context);
+ var name = shouldUseGeneratedName
+ ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */)
+ : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true);
var defaultParameter = getDefaultFromTypeParameter(type);
var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
context.flags = savedContextFlags;
return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
}
+ function typeParameterToDeclaration(type, context, constraint) {
+ if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); }
+ var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
+ return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
+ }
function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) {
var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 148 /* Parameter */);
ts.Debug.assert(!!parameterDeclaration || isTransientSymbol(parameterSymbol) && !!parameterSymbol.isRestParameter);
@@ -29281,6 +29681,15 @@ var ts;
}
return typeParameterNodes;
}
+ /**
+ * Given A[B][C][D], finds A[B]
+ */
+ function getTopmostIndexedAccessType(top) {
+ if (ts.isIndexedAccessTypeNode(top.objectType)) {
+ return getTopmostIndexedAccessType(top.objectType);
+ }
+ return top;
+ }
function symbolToTypeNode(symbol, context, meaning) {
var chain = lookupSymbolChain(symbol, context, meaning);
context.flags |= 16777216 /* InInitialEntityName */;
@@ -29289,13 +29698,24 @@ var ts;
var isTypeOf = meaning === 67216319 /* Value */;
if (ambientModuleSymbolRegex.test(rootName)) {
// module is root, must use `ImportTypeNode`
- var nonRootParts = chain.length > 1 ? createEntityNameFromSymbolChain(chain, chain.length - 1, 1) : undefined;
+ var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
var typeParameterNodes = lookupTypeParameterNodes(chain, 0, context);
- return ts.createImportTypeNode(ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1))), nonRootParts, typeParameterNodes, isTypeOf);
+ var lit = ts.createLiteralTypeNode(ts.createLiteral(rootName.substring(1, rootName.length - 1)));
+ if (!nonRootParts || ts.isEntityName(nonRootParts)) {
+ return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf);
+ }
+ else {
+ var splitNode = getTopmostIndexedAccessType(nonRootParts);
+ var qualifier = splitNode.objectType.typeName;
+ return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
+ }
+ }
+ var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
+ if (ts.isIndexedAccessTypeNode(entityName)) {
+ return entityName; // Indexed accesses can never be `typeof`
}
- var entityName = createEntityNameFromSymbolChain(chain, chain.length - 1, 0);
return isTypeOf ? ts.createTypeQueryNode(entityName) : ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined);
- function createEntityNameFromSymbolChain(chain, index, stopper) {
+ function createAccessFromSymbolChain(chain, index, stopper) {
var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
var symbol = chain[index];
if (index === 0) {
@@ -29305,9 +29725,27 @@ var ts;
if (index === 0) {
context.flags ^= 16777216 /* InInitialEntityName */;
}
+ var parent = chain[index - 1];
+ if (parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) {
+ // Should use an indexed access
+ var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
+ if (ts.isIndexedAccessTypeNode(LHS)) {
+ return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
+ }
+ else {
+ return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
+ }
+ }
var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
identifier.symbol = symbol;
- return index > stopper ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1, stopper), identifier) : identifier;
+ if (index > stopper) {
+ var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
+ if (!ts.isEntityName(LHS)) {
+ return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
+ }
+ return ts.createQualifiedName(LHS, identifier);
+ }
+ return identifier;
}
}
function symbolToName(symbol, context, meaning, expectsIdentifier) {
@@ -30219,6 +30657,10 @@ var ts;
return links.type = anyType;
}
// Handle export default expressions
+ if (ts.isSourceFile(declaration)) {
+ var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile);
+ return links.type = jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType;
+ }
if (declaration.kind === 248 /* ExportAssignment */) {
return links.type = checkExpression(declaration.expression);
}
@@ -30510,13 +30952,13 @@ var ts;
case 152 /* MethodSignature */:
case 162 /* FunctionType */:
case 163 /* ConstructorType */:
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
case 233 /* FunctionDeclaration */:
case 153 /* MethodDeclaration */:
case 191 /* FunctionExpression */:
case 192 /* ArrowFunction */:
case 236 /* TypeAliasDeclaration */:
- case 291 /* JSDocTemplateTag */:
+ case 293 /* JSDocTemplateTag */:
case 176 /* MappedType */:
case 170 /* ConditionalType */:
var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
@@ -30828,9 +31270,9 @@ var ts;
return unknownType;
}
var declaration = ts.find(symbol.declarations, function (d) {
- return d.kind === 292 /* JSDocTypedefTag */ || d.kind === 236 /* TypeAliasDeclaration */;
+ return d.kind === 294 /* JSDocTypedefTag */ || d.kind === 236 /* TypeAliasDeclaration */;
});
- var typeNode = declaration.kind === 292 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type;
+ var typeNode = declaration.kind === 294 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type;
// If typeNode is missing, we will error in checkJSDocTypedefTag.
var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType;
if (popTypeResolution()) {
@@ -31084,6 +31526,9 @@ var ts;
var symbol = type.symbol;
var members = getMembersOfSymbol(symbol);
type.declaredProperties = getNamedMembers(members);
+ // Start with signatures at empty array in case of recursive types
+ type.declaredCallSignatures = ts.emptyArray;
+ type.declaredConstructSignatures = ts.emptyArray;
type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
@@ -31644,10 +32089,8 @@ var ts;
var templateType = getTemplateTypeFromMappedType(type.target || type);
var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
var templateModifiers = getMappedTypeModifiers(type);
- var constraintDeclaration = type.declaration.typeParameter.constraint;
var include = keyofStringsOnly ? 32 /* StringLiteral */ : 1120 /* StringOrNumberLiteralOrUnique */;
- if (constraintDeclaration.kind === 174 /* TypeOperator */ &&
- constraintDeclaration.operator === 128 /* KeyOfKeyword */) {
+ if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
// We have a { [P in keyof T]: X }
for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) {
var prop = _a[_i];
@@ -31720,15 +32163,21 @@ var ts;
instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper || identityMapper) :
unknownType);
}
+ function getConstraintDeclarationForMappedType(type) {
+ return type.declaration.typeParameter.constraint;
+ }
+ function isMappedTypeWithKeyofConstraintDeclaration(type) {
+ var constraintDeclaration = getConstraintDeclarationForMappedType(type);
+ return constraintDeclaration.kind === 174 /* TypeOperator */ &&
+ constraintDeclaration.operator === 128 /* KeyOfKeyword */;
+ }
function getModifiersTypeFromMappedType(type) {
if (!type.modifiersType) {
- var constraintDeclaration = type.declaration.typeParameter.constraint;
- if (constraintDeclaration.kind === 174 /* TypeOperator */ &&
- constraintDeclaration.operator === 128 /* KeyOfKeyword */) {
+ if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
// If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
// AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
// 'keyof T' to a literal union type and we can't recover T from that type.
- type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper);
+ type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper);
}
else {
// Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
@@ -31889,9 +32338,9 @@ var ts;
// over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
// removes 'undefined' from T.
if (type.root.isDistributive) {
- var constraint = getConstraintOfType(type.checkType);
+ var constraint = getConstraintOfType(getSimplifiedType(type.checkType));
if (constraint) {
- var mapper = createTypeMapper([type.root.checkType], [constraint]);
+ var mapper = makeUnaryTypeMapper(type.root.checkType, constraint);
var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper));
if (!(instantiated.flags & 16384 /* Never */)) {
return instantiated;
@@ -32295,10 +32744,10 @@ var ts;
function isJSDocOptionalParameter(node) {
return ts.isInJavaScriptFile(node) && (
// node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
- node.type && node.type.kind === 280 /* JSDocOptionalType */
+ node.type && node.type.kind === 282 /* JSDocOptionalType */
|| ts.getJSDocParameterTags(node).some(function (_a) {
var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
- return isBracketed || !!typeExpression && typeExpression.type.kind === 280 /* JSDocOptionalType */;
+ return isBracketed || !!typeExpression && typeExpression.type.kind === 282 /* JSDocOptionalType */;
}));
}
function tryFindAmbientModule(moduleName, withAugmentations) {
@@ -32384,7 +32833,7 @@ var ts;
for (var i = numTypeArguments; i < numTypeParameters; i++) {
var mapper = createTypeMapper(typeParameters, typeArguments);
var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
- if (defaultType && isTypeIdenticalTo(defaultType, emptyObjectType) && isJavaScriptImplicitAny) {
+ if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) {
defaultType = anyType;
}
typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny);
@@ -32859,7 +33308,7 @@ var ts;
var isJs = ts.isInJavaScriptFile(node);
var isJsImplicitAny = !noImplicitAny && isJs;
if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
- var missingAugmentsTag = isJs && node.parent.kind !== 286 /* JSDocAugmentsTag */;
+ var missingAugmentsTag = isJs && node.parent.kind !== 288 /* JSDocAugmentsTag */;
var diag = minTypeArgumentCount === typeParameters.length
? missingAugmentsTag
? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag
@@ -33939,14 +34388,14 @@ var ts;
var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 7897088 /* Instantiable */);
var combinedMapper;
if (root.inferTypeParameters) {
- var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
+ var context_1 = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
if (!isDeferred) {
// We don't want inferences from constraints as they may cause us to eagerly resolve the
// conditional type instead of deferring resolution. Also, we always want strict function
// types rules (i.e. proper contravariance) for inferences.
- inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */);
+ inferTypes(context_1.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */);
}
- combinedMapper = combineTypeMappers(mapper, context);
+ combinedMapper = combineTypeMappers(mapper, context_1);
}
if (!isDeferred) {
// Return union of trueType and falseType for 'any' since it matches anything
@@ -34321,8 +34770,8 @@ var ts;
function getTypeFromTypeNode(node) {
switch (node.kind) {
case 119 /* AnyKeyword */:
- case 276 /* JSDocAllType */:
- case 277 /* JSDocUnknownType */:
+ case 278 /* JSDocAllType */:
+ case 279 /* JSDocUnknownType */:
return anyType;
case 137 /* StringKeyword */:
return stringType;
@@ -34363,21 +34812,21 @@ var ts;
return getTypeFromUnionTypeNode(node);
case 169 /* IntersectionType */:
return getTypeFromIntersectionTypeNode(node);
- case 278 /* JSDocNullableType */:
+ case 280 /* JSDocNullableType */:
return getTypeFromJSDocNullableTypeNode(node);
- case 280 /* JSDocOptionalType */:
+ case 282 /* JSDocOptionalType */:
return addOptionality(getTypeFromTypeNode(node.type));
case 172 /* ParenthesizedType */:
- case 279 /* JSDocNonNullableType */:
- case 275 /* JSDocTypeExpression */:
+ case 281 /* JSDocNonNullableType */:
+ case 277 /* JSDocTypeExpression */:
return getTypeFromTypeNode(node.type);
- case 282 /* JSDocVariadicType */:
+ case 284 /* JSDocVariadicType */:
return getTypeFromJSDocVariadicType(node);
case 162 /* FunctionType */:
case 163 /* ConstructorType */:
case 165 /* TypeLiteral */:
- case 284 /* JSDocTypeLiteral */:
- case 281 /* JSDocFunctionType */:
+ case 286 /* JSDocTypeLiteral */:
+ case 283 /* JSDocFunctionType */:
return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
case 174 /* TypeOperator */:
return getTypeFromTypeOperatorNode(node);
@@ -35802,7 +36251,7 @@ var ts;
}
}
var constraint = getConstraintForRelation(source);
- if (!constraint || constraint.flags & 1 /* Any */) {
+ if (!constraint || (source.flags & 32768 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
// A type variable with no constraint is not related to the non-primitive object type.
if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~134217728 /* NonPrimitive */))) {
errorInfo = saveErrorInfo;
@@ -35939,10 +36388,10 @@ var ts;
var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
if (modifiersRelated) {
- var result_1;
- if (result_1 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) {
+ var result_2;
+ if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) {
var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
- return result_1 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
+ return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
}
}
return 0 /* False */;
@@ -39285,7 +39734,7 @@ var ts;
}
function getTypeForThisExpressionFromJSDoc(node) {
var jsdocType = ts.getJSDocType(node);
- if (jsdocType && jsdocType.kind === 281 /* JSDocFunctionType */) {
+ if (jsdocType && jsdocType.kind === 283 /* JSDocFunctionType */) {
var jsDocFunctionType = jsdocType;
if (jsDocFunctionType.parameters.length > 0 &&
jsDocFunctionType.parameters[0].name &&
@@ -39721,7 +40170,7 @@ var ts;
// except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}`
var type = getContextualType(binaryExpression);
return !type && node === right && !ts.getDeclaredJavascriptInitializer(binaryExpression.parent) && !ts.getAssignedJavascriptInitializer(binaryExpression) ?
- getTypeOfExpression(left, /*cache*/ true) : type;
+ getTypeOfExpression(left) : type;
case 53 /* AmpersandAmpersandToken */:
case 26 /* CommaToken */:
return node === right ? getContextualType(binaryExpression) : undefined;
@@ -40312,7 +40761,7 @@ var ts;
var contextualType = getApparentTypeOfContextualType(node);
var contextualTypeHasPattern = contextualType && contextualType.pattern &&
(contextualType.pattern.kind === 179 /* ObjectBindingPattern */ || contextualType.pattern.kind === 183 /* ObjectLiteralExpression */);
- var isInJSFile = ts.isInJavaScriptFile(node);
+ var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node);
var isJSObjectLiteral = !contextualType && isInJSFile;
var typeFlags = 0;
var patternWithComputedProperties = false;
@@ -43251,8 +43700,8 @@ var ts;
if (allowSyntheticDefaultImports && type && type !== unknownType) {
var synthType = type;
if (!synthType.syntheticType) {
- var file = ts.find(originalSymbol.declarations, ts.isSourceFile);
- var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false);
+ var file_3 = ts.find(originalSymbol.declarations, ts.isSourceFile);
+ var hasSyntheticDefault = canHaveSyntheticDefault(file_3, originalSymbol, /*dontResolveAlias*/ false);
if (hasSyntheticDefault) {
var memberTable = ts.createSymbolTable();
var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
@@ -45036,7 +45485,7 @@ var ts;
checkAsyncFunctionReturnType(node);
}
}
- if (node.kind !== 159 /* IndexSignature */ && node.kind !== 281 /* JSDocFunctionType */) {
+ if (node.kind !== 159 /* IndexSignature */ && node.kind !== 283 /* JSDocFunctionType */) {
registerForUnusedIdentifiersCheck(node);
}
}
@@ -45499,7 +45948,7 @@ var ts;
n.parent.kind !== 234 /* ClassDeclaration */ &&
n.parent.kind !== 204 /* ClassExpression */ &&
n.flags & 4194304 /* Ambient */) {
- if (!(flags & 2 /* Ambient */)) {
+ if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) {
// It is nested in an ambient context, which means it is automatically exported
flags |= 1 /* Export */;
}
@@ -45770,7 +46219,7 @@ var ts;
case 235 /* InterfaceDeclaration */:
case 236 /* TypeAliasDeclaration */:
// A jsdoc typedef is, by definition, a type alias
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return 2 /* ExportType */;
case 238 /* ModuleDeclaration */:
return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
@@ -45792,10 +46241,10 @@ var ts;
case 242 /* ImportEqualsDeclaration */:
case 245 /* NamespaceImport */:
case 244 /* ImportClause */:
- var result_2 = 0 /* None */;
+ var result_3 = 0 /* None */;
var target = resolveAlias(getSymbolOfNode(d));
- ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); });
- return result_2;
+ ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); });
+ return result_3;
case 231 /* VariableDeclaration */:
case 181 /* BindingElement */:
case 233 /* FunctionDeclaration */:
@@ -46373,10 +46822,6 @@ var ts;
for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) {
var node = potentiallyUnusedIdentifiers_1[_i];
switch (node.kind) {
- case 273 /* SourceFile */:
- case 238 /* ModuleDeclaration */:
- checkUnusedModuleMembers(node, addDiagnostic);
- break;
case 234 /* ClassDeclaration */:
case 204 /* ClassExpression */:
checkUnusedClassMembers(node, addDiagnostic);
@@ -46385,6 +46830,8 @@ var ts;
case 235 /* InterfaceDeclaration */:
checkUnusedTypeParameters(node, addDiagnostic);
break;
+ case 273 /* SourceFile */:
+ case 238 /* ModuleDeclaration */:
case 212 /* Block */:
case 240 /* CaseBlock */:
case 219 /* ForStatement */:
@@ -46417,33 +46864,6 @@ var ts;
}
}
}
- function checkUnusedLocalsAndParameters(node, addDiagnostic) {
- if (!(node.flags & 4194304 /* Ambient */)) {
- node.locals.forEach(function (local) {
- // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
- // If it's a type parameter merged with a parameter, check if the parameter-side is used.
- if (local.flags & 262144 /* TypeParameter */ ? (local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : !local.isReferenced) {
- if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 148 /* Parameter */) {
- var parameter = ts.getRootDeclaration(local.valueDeclaration);
- var name = ts.getNameOfDeclaration(local.valueDeclaration);
- if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) {
- addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
- }
- }
- else {
- ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.symbolName(local), addDiagnostic); });
- }
- }
- });
- }
- }
- function isRemovedPropertyFromObjectSpread(node) {
- if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) {
- var lastElement = ts.lastOrUndefined(node.parent.elements);
- return lastElement !== node && !!lastElement.dotDotDotToken;
- }
- return false;
- }
function errorUnusedLocal(declaration, name, addDiagnostic) {
var node = ts.getNameOfDeclaration(declaration) || declaration;
if (isIdentifierThatStartsWithUnderScore(node)) {
@@ -46453,10 +46873,8 @@ var ts;
return;
}
}
- if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) {
- var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
- addDiagnostic(0 /* Local */, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name));
- }
+ var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
+ addDiagnostic(0 /* Local */, ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, message, name));
}
function parameterNameStartsWithUnderscore(parameterName) {
return parameterName && isIdentifierThatStartsWithUnderScore(parameterName);
@@ -46513,50 +46931,91 @@ var ts;
}
}
}
- function checkUnusedModuleMembers(node, addDiagnostic) {
- if (!(node.flags & 4194304 /* Ambient */)) {
- // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value.
- var unusedImports_1 = ts.createMap();
- node.locals.forEach(function (local) {
- if (local.isReferenced || local.exportSymbol)
- return;
- for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
- var declaration = _a[_i];
- if (ts.isAmbientModule(declaration))
- continue;
- if (isImportedDeclaration(declaration)) {
- var importClause = importClauseFromImported(declaration);
- var key = String(getNodeId(importClause));
- var group_1 = unusedImports_1.get(key);
- if (group_1) {
- group_1[1].push(declaration);
- }
- else {
- unusedImports_1.set(key, [importClause, [declaration]]);
+ function addToGroup(map, key, value, getKey) {
+ var keyString = String(getKey(key));
+ var group = map.get(keyString);
+ if (group) {
+ group[1].push(value);
+ }
+ else {
+ map.set(keyString, [key, [value]]);
+ }
+ }
+ function tryGetRootParameterDeclaration(node) {
+ return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
+ }
+ function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
+ if (nodeWithLocals.flags & 4194304 /* Ambient */)
+ return;
+ // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value.
+ var unusedImports = ts.createMap();
+ var unusedDestructures = ts.createMap();
+ nodeWithLocals.locals.forEach(function (local) {
+ // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
+ // If it's a type parameter merged with a parameter, check if the parameter-side is used.
+ if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
+ return;
+ }
+ for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
+ var declaration = _a[_i];
+ if (ts.isAmbientModule(declaration))
+ continue;
+ if (isImportedDeclaration(declaration)) {
+ addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
+ }
+ else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) {
+ // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though.
+ var lastElement = ts.last(declaration.parent.elements);
+ if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) {
+ addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
+ }
+ }
+ else {
+ var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
+ if (parameter) {
+ var name = ts.getNameOfDeclaration(local.valueDeclaration);
+ if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) {
+ addDiagnostic(1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
}
}
else {
errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic);
}
}
- });
- unusedImports_1.forEach(function (_a) {
- var importClause = _a[0], unuseds = _a[1];
- var importDecl = importClause.parent;
- if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) {
- for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
- var unused = unuseds_1[_i];
- errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
- }
+ }
+ });
+ unusedImports.forEach(function (_a) {
+ var importClause = _a[0], unuseds = _a[1];
+ var importDecl = importClause.parent;
+ if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) {
+ for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
+ var unused = unuseds_1[_i];
+ errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
}
- else if (unuseds.length === 1) {
- addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)));
+ }
+ else if (unuseds.length === 1) {
+ addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)));
+ }
+ else {
+ addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused));
+ }
+ });
+ unusedDestructures.forEach(function (_a) {
+ var bindingPattern = _a[0], bindingElements = _a[1];
+ var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
+ if (!bindingPattern.elements.every(function (e) { return ts.contains(bindingElements, e); })) {
+ for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) {
+ var e = bindingElements_1[_i];
+ addDiagnostic(kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, getBindingElementNameText(e)));
}
- else {
- addDiagnostic(0 /* Local */, ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused, ts.showModuleSpecifier(importDecl)));
- }
- });
- }
+ }
+ else if (bindingElements.length === 1) {
+ addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, getBindingElementNameText(ts.first(bindingElements))));
+ }
+ else {
+ addDiagnostic(kind, ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused));
+ }
+ });
}
function isImportedDeclaration(node) {
return node.kind === 244 /* ImportClause */ || node.kind === 247 /* ImportSpecifier */ || node.kind === 245 /* NamespaceImport */;
@@ -48747,9 +49206,9 @@ var ts;
}
}
// Checks for export * conflicts
- var exports = getExportsOfModule(moduleSymbol);
- if (exports) {
- exports.forEach(function (_a, id) {
+ var exports_1 = getExportsOfModule(moduleSymbol);
+ if (exports_1) {
+ exports_1.forEach(function (_a, id) {
var declarations = _a.declarations, flags = _a.flags;
if (id === "__export") {
return;
@@ -48855,27 +49314,27 @@ var ts;
return checkInferType(node);
case 178 /* ImportType */:
return checkImportType(node);
- case 286 /* JSDocAugmentsTag */:
+ case 288 /* JSDocAugmentsTag */:
return checkJSDocAugmentsTag(node);
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return checkJSDocTypedefTag(node);
- case 288 /* JSDocParameterTag */:
+ case 290 /* JSDocParameterTag */:
return checkJSDocParameterTag(node);
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
checkSignatureDeclaration(node);
// falls through
- case 279 /* JSDocNonNullableType */:
- case 278 /* JSDocNullableType */:
- case 276 /* JSDocAllType */:
- case 277 /* JSDocUnknownType */:
- case 284 /* JSDocTypeLiteral */:
+ case 281 /* JSDocNonNullableType */:
+ case 280 /* JSDocNullableType */:
+ case 278 /* JSDocAllType */:
+ case 279 /* JSDocUnknownType */:
+ case 286 /* JSDocTypeLiteral */:
checkJSDocTypeIsInJsFile(node);
ts.forEachChild(node, checkSourceElement);
return;
- case 282 /* JSDocVariadicType */:
+ case 284 /* JSDocVariadicType */:
checkJSDocVariadicType(node);
return;
- case 275 /* JSDocTypeExpression */:
+ case 277 /* JSDocTypeExpression */:
return checkSourceElement(node.type);
case 175 /* IndexedAccessType */:
return checkIndexedAccessType(node);
@@ -49388,10 +49847,10 @@ var ts;
return entityNameSymbol;
}
}
- if (entityName.parent.kind === 288 /* JSDocParameterTag */) {
+ if (entityName.parent.kind === 290 /* JSDocParameterTag */) {
return ts.getParameterSymbolFromJSDoc(entityName.parent);
}
- if (entityName.parent.kind === 147 /* TypeParameter */ && entityName.parent.parent.kind === 291 /* JSDocTemplateTag */) {
+ if (entityName.parent.kind === 147 /* TypeParameter */ && entityName.parent.parent.kind === 293 /* JSDocTemplateTag */) {
ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true.
var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent);
return typeParameter && typeParameter.symbol;
@@ -50181,7 +50640,22 @@ var ts;
var symbol = node && getSymbolOfNode(node);
return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */);
},
- getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }
+ getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; },
+ getAllAccessorDeclarations: function (accessor) {
+ accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration);
+ var otherKind = accessor.kind === 156 /* SetAccessor */ ? 155 /* GetAccessor */ : 156 /* SetAccessor */;
+ var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind);
+ var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor;
+ var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor;
+ var setAccessor = accessor.kind === 156 /* SetAccessor */ ? accessor : otherAccessor;
+ var getAccessor = accessor.kind === 155 /* GetAccessor */ ? accessor : otherAccessor;
+ return {
+ firstAccessor: firstAccessor,
+ secondAccessor: secondAccessor,
+ setAccessor: setAccessor,
+ getAccessor: getAccessor
+ };
+ }
};
function isInHeritageClause(node) {
return node.parent && node.parent.kind === 206 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 267 /* HeritageClause */;
@@ -50217,8 +50691,8 @@ var ts;
var decl = _a[_i];
// check meaning of the local symbol to see if declaration needs to be analyzed further
if (decl.symbol && decl.symbol.flags & meaning) {
- var file = ts.getSourceFileOfNode(decl);
- var typeReferenceDirective = fileToDirective.get(file.path);
+ var file_4 = ts.getSourceFileOfNode(decl);
+ var typeReferenceDirective = fileToDirective.get(file_4.path);
if (typeReferenceDirective) {
(typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective);
}
@@ -50253,8 +50727,8 @@ var ts;
// check that at least one declaration of top level symbol originates from type declaration file
for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
var decl = _a[_i];
- var file = ts.getSourceFileOfNode(decl);
- if (fileToDirective.has(file.path)) {
+ var file_5 = ts.getSourceFileOfNode(decl);
+ if (fileToDirective.has(file_5.path)) {
return true;
}
}
@@ -50272,25 +50746,25 @@ var ts;
function initializeTypeChecker() {
// Bind all source files and propagate errors
for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
- var file = _a[_i];
- ts.bindSourceFile(file, compilerOptions);
+ var file_6 = _a[_i];
+ ts.bindSourceFile(file_6, compilerOptions);
}
// Initialize global symbol table
var augmentations;
for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
- var file = _c[_b];
- if (!ts.isExternalOrCommonJsModule(file)) {
- mergeSymbolTable(globals, file.locals);
+ var file_7 = _c[_b];
+ if (!ts.isExternalOrCommonJsModule(file_7)) {
+ mergeSymbolTable(globals, file_7.locals);
}
- if (file.patternAmbientModules && file.patternAmbientModules.length) {
- patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules);
+ if (file_7.patternAmbientModules && file_7.patternAmbientModules.length) {
+ patternAmbientModules = ts.concatenate(patternAmbientModules, file_7.patternAmbientModules);
}
- if (file.moduleAugmentations.length) {
- (augmentations || (augmentations = [])).push(file.moduleAugmentations);
+ if (file_7.moduleAugmentations.length) {
+ (augmentations || (augmentations = [])).push(file_7.moduleAugmentations);
}
- if (file.symbol && file.symbol.globalExports) {
+ if (file_7.symbol && file_7.symbol.globalExports) {
// Merge in UMD exports with first-in-wins semantics (see #9771)
- var source = file.symbol.globalExports;
+ var source = file_7.symbol.globalExports;
source.forEach(function (sourceSymbol, id) {
if (!globals.has(id)) {
globals.set(id, sourceSymbol);
@@ -51578,7 +52052,7 @@ var ts;
}
function checkGrammarImportCallExpression(node) {
if (moduleKind === ts.ModuleKind.ES2015) {
- return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules);
+ return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext);
}
if (node.typeArguments) {
return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments);
@@ -51657,10 +52131,8 @@ var ts;
if (!elements || elements === ts.emptyArray) {
elements = [];
}
- else {
- if (ts.isNodeArray(elements)) {
- return elements;
- }
+ else if (ts.isNodeArray(elements)) {
+ return elements;
}
var array = elements;
array.pos = -1;
@@ -51720,6 +52192,13 @@ var ts;
node.text = text;
return node;
}
+ ts.createStringLiteral = createStringLiteral;
+ function createRegularExpressionLiteral(text) {
+ var node = createSynthesizedNode(12 /* RegularExpressionLiteral */);
+ node.text = text;
+ return node;
+ }
+ ts.createRegularExpressionLiteral = createRegularExpressionLiteral;
function createLiteralFromNode(sourceNode) {
var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode));
node.textSourceNode = sourceNode;
@@ -51753,7 +52232,7 @@ var ts;
recordTempVariable(name);
}
if (reservedInNestedScopes) {
- name.autoGenerateFlags |= 16 /* ReservedInNestedScopes */;
+ name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
}
return name;
}
@@ -51779,7 +52258,7 @@ var ts;
/** Create a unique name based on the supplied text. */
function createOptimisticUniqueName(text) {
var name = createIdentifier(text);
- name.autoGenerateFlags = 3 /* Unique */ | 32 /* Optimistic */;
+ name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */;
name.autoGenerateId = nextAutoGenerateId;
nextAutoGenerateId++;
return name;
@@ -51788,18 +52267,15 @@ var ts;
/** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */
function createFileLevelUniqueName(text) {
var name = createOptimisticUniqueName(text);
- name.autoGenerateFlags |= 64 /* FileLevel */;
+ name.autoGenerateFlags |= 32 /* FileLevel */;
return name;
}
ts.createFileLevelUniqueName = createFileLevelUniqueName;
- function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) {
- var name = createIdentifier("");
- name.autoGenerateFlags = 4 /* Node */;
+ function getGeneratedNameForNode(node, flags) {
+ var name = createIdentifier(ts.isIdentifier(node) ? ts.idText(node) : "");
+ name.autoGenerateFlags = 4 /* Node */ | flags;
name.autoGenerateId = nextAutoGenerateId;
name.original = node;
- if (shouldSkipNameGenerationScope) {
- name.autoGenerateFlags |= 8 /* SkipNameGenerationScope */;
- }
nextAutoGenerateId++;
return name;
}
@@ -51890,7 +52366,7 @@ var ts;
ts.updateQualifiedName = updateQualifiedName;
function parenthesizeForComputedName(expression) {
return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */) ||
- expression.kind === 297 /* CommaListExpression */ ?
+ expression.kind === 299 /* CommaListExpression */ ?
createParen(expression) :
expression;
}
@@ -52940,6 +53416,13 @@ var ts;
return block;
}
ts.createBlock = createBlock;
+ /* @internal */
+ function createExpressionStatement(expression) {
+ var node = createSynthesizedNode(215 /* ExpressionStatement */);
+ node.expression = expression;
+ return node;
+ }
+ ts.createExpressionStatement = createExpressionStatement;
function updateBlock(node, statements) {
return node.statements !== statements
? updateNode(createBlock(statements, node.multiLine), node)
@@ -52966,9 +53449,7 @@ var ts;
}
ts.createEmptyStatement = createEmptyStatement;
function createStatement(expression) {
- var node = createSynthesizedNode(215 /* ExpressionStatement */);
- node.expression = ts.parenthesizeExpressionForExpressionStatement(expression);
- return node;
+ return createExpressionStatement(ts.parenthesizeExpressionForExpressionStatement(expression));
}
ts.createStatement = createStatement;
function updateStatement(node, expression) {
@@ -53864,7 +54345,7 @@ var ts;
* @param original The original statement.
*/
function createNotEmittedStatement(original) {
- var node = createSynthesizedNode(295 /* NotEmittedStatement */);
+ var node = createSynthesizedNode(297 /* NotEmittedStatement */);
node.original = original;
setTextRange(node, original);
return node;
@@ -53876,7 +54357,7 @@ var ts;
*/
/* @internal */
function createEndOfDeclarationMarker(original) {
- var node = createSynthesizedNode(299 /* EndOfDeclarationMarker */);
+ var node = createSynthesizedNode(301 /* EndOfDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -53888,7 +54369,7 @@ var ts;
*/
/* @internal */
function createMergeDeclarationMarker(original) {
- var node = createSynthesizedNode(298 /* MergeDeclarationMarker */);
+ var node = createSynthesizedNode(300 /* MergeDeclarationMarker */);
node.emitNode = {};
node.original = original;
return node;
@@ -53903,7 +54384,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(296 /* PartiallyEmittedExpression */);
+ var node = createSynthesizedNode(298 /* PartiallyEmittedExpression */);
node.expression = expression;
node.original = original;
setTextRange(node, original);
@@ -53919,7 +54400,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 === 297 /* CommaListExpression */) {
+ if (node.kind === 299 /* CommaListExpression */) {
return node.elements;
}
if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) {
@@ -53929,7 +54410,7 @@ var ts;
return node;
}
function createCommaList(elements) {
- var node = createSynthesizedNode(297 /* CommaListExpression */);
+ var node = createSynthesizedNode(299 /* CommaListExpression */);
node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
return node;
}
@@ -53940,15 +54421,31 @@ var ts;
: node;
}
ts.updateCommaList = updateCommaList;
- function createBundle(sourceFiles) {
+ function createBundle(sourceFiles, prepends) {
+ if (prepends === void 0) { prepends = ts.emptyArray; }
var node = ts.createNode(274 /* Bundle */);
+ node.prepends = prepends;
node.sourceFiles = sourceFiles;
return node;
}
ts.createBundle = createBundle;
- function updateBundle(node, sourceFiles) {
- if (node.sourceFiles !== sourceFiles) {
- return createBundle(sourceFiles);
+ function createUnparsedSourceFile(text) {
+ var node = ts.createNode(275 /* UnparsedSource */);
+ node.text = text;
+ return node;
+ }
+ ts.createUnparsedSourceFile = createUnparsedSourceFile;
+ function createInputFiles(javascript, declaration) {
+ var node = ts.createNode(276 /* InputFiles */);
+ node.javascriptText = javascript;
+ node.declarationText = declaration;
+ return node;
+ }
+ ts.createInputFiles = createInputFiles;
+ function updateBundle(node, sourceFiles, prepends) {
+ if (prepends === void 0) { prepends = ts.emptyArray; }
+ if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) {
+ return createBundle(sourceFiles, prepends);
}
return node;
}
@@ -55192,7 +55689,7 @@ var ts;
// if should be wrapped in parens since comma operator has the lowest precedence
var emittedExpression = ts.skipPartiallyEmittedExpressions(e);
return emittedExpression.kind === 199 /* BinaryExpression */ && emittedExpression.operatorToken.kind === 26 /* CommaToken */ ||
- emittedExpression.kind === 297 /* CommaListExpression */
+ emittedExpression.kind === 299 /* CommaListExpression */
? ts.createParen(e)
: e;
}
@@ -55212,7 +55709,7 @@ var ts;
var check = ts.skipPartiallyEmittedExpressions(e);
return (check.kind === 204 /* ClassExpression */ ||
check.kind === 191 /* FunctionExpression */ ||
- check.kind === 297 /* CommaListExpression */ ||
+ check.kind === 299 /* CommaListExpression */ ||
ts.isBinaryExpression(check) && check.operatorToken.kind === 26 /* CommaToken */)
? ts.createParen(e)
: e;
@@ -55333,6 +55830,7 @@ var ts;
switch (member.kind) {
case 164 /* TypeQuery */:
case 174 /* TypeOperator */:
+ case 171 /* InferType */:
return ts.createParenthesizedType(member);
}
return parenthesizeElementTypeMember(member);
@@ -55376,7 +55874,7 @@ var ts;
case 184 /* PropertyAccessExpression */:
node = node.expression;
continue;
- case 296 /* PartiallyEmittedExpression */:
+ case 298 /* PartiallyEmittedExpression */:
node = node.expression;
continue;
}
@@ -55406,7 +55904,7 @@ var ts;
case 207 /* AsExpression */:
case 208 /* NonNullExpression */:
return (kinds & 2 /* Assertions */) !== 0;
- case 296 /* PartiallyEmittedExpression */:
+ case 298 /* PartiallyEmittedExpression */:
return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0;
}
return false;
@@ -55443,7 +55941,7 @@ var ts;
case 189 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
case 207 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
case 208 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
- case 296 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
+ case 298 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
}
}
/**
@@ -55931,7 +56429,7 @@ var ts;
statements = ts.setTextRange(ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements)), statements);
}
var declarations = context.endLexicalEnvironment();
- return ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements);
+ return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements);
}
ts.visitLexicalEnvironment = visitLexicalEnvironment;
/**
@@ -56228,9 +56726,9 @@ var ts;
case 273 /* SourceFile */:
return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
// Transformation nodes
- case 296 /* PartiallyEmittedExpression */:
+ case 298 /* PartiallyEmittedExpression */:
return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
- case 297 /* CommaListExpression */:
+ case 299 /* CommaListExpression */:
return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
default:
// No need to visit nodes with no children.
@@ -56286,7 +56784,7 @@ var ts;
case 214 /* EmptyStatement */:
case 205 /* OmittedExpression */:
case 230 /* DebuggerStatement */:
- case 295 /* NotEmittedStatement */:
+ case 297 /* NotEmittedStatement */:
// No need to visit nodes with no children.
break;
// Names
@@ -56665,10 +57163,10 @@ var ts;
result = reduceNodes(node.statements, cbNodes, result);
break;
// Transformation nodes
- case 296 /* PartiallyEmittedExpression */:
+ case 298 /* PartiallyEmittedExpression */:
result = reduceNode(node.expression, cbNode, result);
break;
- case 297 /* CommaListExpression */:
+ case 299 /* CommaListExpression */:
result = reduceNodes(node.elements, cbNodes, result);
break;
default:
@@ -56682,8 +57180,8 @@ var ts;
return statements;
}
return ts.isNodeArray(statements)
- ? ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements)
- : ts.addRange(statements, declarations);
+ ? ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements)
+ : ts.prependRange(statements, declarations);
}
ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
/**
@@ -56833,16 +57331,6 @@ var ts;
return node ? ts.getNodeId(node) : 0;
}
ts.getOriginalNodeId = getOriginalNodeId;
- function getNamedImportCount(node) {
- if (!(node.importClause && node.importClause.namedBindings))
- return 0;
- var names = node.importClause.namedBindings;
- if (!names)
- return 0;
- if (!ts.isNamedImports(names))
- return 0;
- return names.elements.length;
- }
function containsDefaultReference(node) {
if (!node)
return false;
@@ -56853,12 +57341,40 @@ var ts;
function isNamedDefaultReference(e) {
return e.propertyName && e.propertyName.escapedText === "default" /* Default */;
}
+ function chainBundle(transformSourceFile) {
+ return transformSourceFileOrBundle;
+ function transformSourceFileOrBundle(node) {
+ return node.kind === 273 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
+ }
+ function transformBundle(node) {
+ return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
+ }
+ }
+ ts.chainBundle = chainBundle;
function getImportNeedsImportStarHelper(node) {
- return !!ts.getNamespaceDeclarationNode(node) || (getNamedImportCount(node) > 1 && containsDefaultReference(node.importClause.namedBindings));
+ if (!!ts.getNamespaceDeclarationNode(node)) {
+ return true;
+ }
+ var bindings = node.importClause && node.importClause.namedBindings;
+ if (!bindings) {
+ return false;
+ }
+ if (!ts.isNamedImports(bindings))
+ return false;
+ var defaultRefCount = 0;
+ for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) {
+ var binding = _a[_i];
+ if (isNamedDefaultReference(binding)) {
+ defaultRefCount++;
+ }
+ }
+ // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import
+ return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node));
}
ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper;
function getImportNeedsImportDefaultHelper(node) {
- return ts.isDefaultImport(node) || (getNamedImportCount(node) === 1 && containsDefaultReference(node.importClause.namedBindings));
+ // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested)
+ return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings)));
}
ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper;
function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) {
@@ -57595,7 +58111,21 @@ var ts;
* at the next execution site, in document order
*/
var pendingExpressions;
- return transformSourceFile;
+ return transformSourceFileOrBundle;
+ function transformSourceFileOrBundle(node) {
+ if (node.kind === 274 /* 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 === 276 /* InputFiles */) {
+ return ts.createUnparsedSourceFile(prepend.javascriptText);
+ }
+ return prepend;
+ }));
+ }
/**
* Transform TypeScript-specific syntax in a SourceFile.
*
@@ -58085,7 +58615,7 @@ var ts;
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addRange(statements, context.endLexicalEnvironment());
+ ts.prependRange(statements, context.endLexicalEnvironment());
var iife = ts.createImmediatelyInvokedArrowFunction(statements);
ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
var varStatement = ts.createVariableStatement(
@@ -58290,7 +58820,7 @@ var ts;
// record an alias as the class name is not in scope for statics.
enableSubstitutionForClassAliases();
var alias = ts.getSynthesizedClone(temp);
- alias.autoGenerateFlags &= ~16 /* ReservedInNestedScopes */;
+ alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */;
classAliases[ts.getOriginalNodeId(node)] = alias;
}
// To preserve the behavior of the old emitter, we explicitly indent
@@ -58567,7 +59097,7 @@ var ts;
function transformInitializedProperty(property, receiver) {
// We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression)
- ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name, !ts.hasModifier(property, 32 /* Static */)))
+ ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name))
: property.name;
var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression);
var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName);
@@ -59702,8 +60232,9 @@ var ts;
currentNamespaceContainerName = localName;
var statements = [];
startLexicalEnvironment();
- ts.addRange(statements, ts.map(node.members, transformEnumMember));
- ts.addRange(statements, endLexicalEnvironment());
+ var members = ts.map(node.members, transformEnumMember);
+ ts.prependRange(statements, endLexicalEnvironment());
+ ts.addRange(statements, members);
currentNamespaceContainerName = savedCurrentNamespaceLocalName;
return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members),
/*multiLine*/ true);
@@ -59943,7 +60474,7 @@ var ts;
var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
}
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
currentNamespaceContainerName = savedCurrentNamespaceContainerName;
currentNamespace = savedCurrentNamespace;
currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
@@ -60480,7 +61011,7 @@ var ts;
// Set new transformation hooks.
context.onEmitNode = onEmitNode;
context.onSubstituteNode = onSubstituteNode;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -60752,7 +61283,7 @@ var ts;
var statements = [];
var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var block = ts.createBlock(statements, /*multiLine*/ true);
ts.setTextRange(block, node.body);
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
@@ -60774,7 +61305,7 @@ var ts;
var declarations = endLexicalEnvironment();
if (ts.some(declarations)) {
var block = ts.convertToFunctionBody(expression);
- result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements));
+ result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements));
}
else {
result = expression;
@@ -60964,7 +61495,7 @@ var ts;
var enabledSubstitutions;
var enclosingFunctionFlags;
var enclosingSuperContainerFlags = 0;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -61042,9 +61573,14 @@ var ts;
return ts.visitEachChild(node, visitor, context);
}
function visitYieldExpression(node) {
- if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ && node.asteriskToken) {
- var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
- return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node);
+ if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
+ if (node.asteriskToken) {
+ var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
+ return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node);
+ }
+ return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression
+ ? ts.visitNode(node.expression, visitor, ts.isExpression)
+ : ts.createVoidZero())), node), node);
}
return ts.visitEachChild(node, visitor, context);
}
@@ -61346,7 +61882,7 @@ var ts;
/*typeParameters*/ undefined,
/*parameters*/ [],
/*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))))));
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var block = ts.updateBlock(node.body, statements);
// Minor optimization, emit `_super` helper to capture `super` access in an arrow.
// This step isn't needed if we eventually transform this to ES5.
@@ -61371,11 +61907,11 @@ var ts;
statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
}
ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
- var trailingStatements = endLexicalEnvironment();
- if (statementOffset > 0 || ts.some(statements) || ts.some(trailingStatements)) {
+ var leadingStatements = endLexicalEnvironment();
+ if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
+ ts.prependRange(statements, leadingStatements);
ts.addRange(statements, block.statements.slice(statementOffset));
- ts.addRange(statements, trailingStatements);
return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
}
return body;
@@ -61575,7 +62111,7 @@ var ts;
function transformJsx(context) {
var compilerOptions = context.getCompilerOptions();
var currentSourceFile;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
/**
* Transform JSX-specific syntax in a SourceFile.
*
@@ -62083,7 +62619,7 @@ var ts;
(function (ts) {
function transformES2016(context) {
var hoistVariableDeclaration = context.hoistVariableDeclaration;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -62291,7 +62827,7 @@ var ts;
* be reset.
*/
var enabledSubstitutions;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -62467,7 +63003,7 @@ var ts;
if (taggedTemplateStringDeclarations) {
statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
}
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
}
@@ -62721,7 +63257,7 @@ var ts;
statement.pos = closingBraceLocation.pos;
ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
statements.push(statement);
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
ts.setEmitFlags(block, 1536 /* NoComments */);
return block;
@@ -62834,7 +63370,7 @@ var ts;
&& !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) {
statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
}
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
if (constructor) {
prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false);
}
@@ -63476,7 +64012,7 @@ var ts;
closeBraceLocation = body;
}
var lexicalEnvironment = context.endLexicalEnvironment();
- ts.addRange(statements, lexicalEnvironment);
+ ts.prependRange(statements, lexicalEnvironment);
prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false);
// If we added any final generated statements, this must be a multi-line block
if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) {
@@ -64057,7 +64593,7 @@ var ts;
if (loopOutParameters.length) {
copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4);
}
- ts.addRange(statements_4, lexicalEnvironment);
+ ts.prependRange(statements_4, lexicalEnvironment);
loopBody = ts.createBlock(statements_4, /*multiline*/ true);
}
if (ts.isBlock(loopBody)) {
@@ -64510,10 +65046,12 @@ var ts;
// We skip any outer expressions in a number of places to get to the innermost
// expression, but we will restore them later to preserve comments and source maps.
var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock);
- // The class statements are the statements generated by visiting the first statement of the
+ // The class statements are the statements generated by visiting the first statement with initializer of the
// body (1), while all other statements are added to remainingStatements (2)
- var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1);
- var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1);
+ var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.firstOrUndefined(stmt.declarationList.declarations).initializer; };
+ var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement);
+ var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer);
+ var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); });
var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement);
// We know there is only one variable declaration here as we verified this in an
// earlier call to isTypeScriptClassWrapper
@@ -64523,6 +65061,7 @@ var ts;
// we see as an assignment, for example:
//
// (function () {
+ // var C_1;
// var C = C_1 = (function () {
// function C() {
// }
@@ -64531,7 +65070,6 @@ var ts;
// }());
// C = C_1 = __decorate([dec], C);
// return C;
- // var C_1;
// }())
//
var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression);
@@ -65161,7 +65699,7 @@ var ts;
context.onSubstituteNode = onSubstituteNode;
context.enableSubstitution(184 /* PropertyAccessExpression */);
context.enableSubstitution(269 /* PropertyAssignment */);
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
/**
* Transforms an ES5 source file to ES3.
*
@@ -65473,7 +66011,7 @@ var ts;
var exceptionBlockStack; // A stack of containing exception blocks.
var currentExceptionBlock; // The current exception block.
var withBlockStack; // A stack containing `with` blocks.
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
return node;
@@ -65730,7 +66268,7 @@ var ts;
var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
transformAndEmitStatements(body.statements, statementOffset);
var buildResult = build();
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
statements.push(ts.createReturn(buildResult));
// Restore previous generator state
inGeneratorFunctionBody = savedInGeneratorFunctionBody;
@@ -67923,7 +68461,7 @@ var ts;
var currentModuleInfo; // The ExternalModuleInfo for the current file.
var noSubstitution; // Set of nodes for which substitution rules should be ignored.
var needUMDDynamicImportHelper;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
/**
* Transforms the module aspects of a SourceFile.
*
@@ -67966,7 +68504,7 @@ var ts;
ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
// If we have any `export * from ...` declarations
@@ -68189,7 +68727,7 @@ var ts;
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
// End the lexical environment for the module body
// and merge any new lexical declarations.
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var body = ts.createBlock(statements, /*multiLine*/ true);
if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) {
// If we have any `export * from ...` declarations
@@ -68211,7 +68749,7 @@ var ts;
*/
function addExportEqualsIfNeeded(statements, emitAsReturn) {
if (currentModuleInfo.exportEquals) {
- var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, importCallExpressionVisitor);
+ var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor);
if (expressionResult) {
if (emitAsReturn) {
var statement = ts.createReturn(expressionResult);
@@ -68252,29 +68790,84 @@ var ts;
return visitFunctionDeclaration(node);
case 234 /* ClassDeclaration */:
return visitClassDeclaration(node);
- case 298 /* MergeDeclarationMarker */:
+ case 300 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 299 /* EndOfDeclarationMarker */:
+ case 301 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
- return ts.visitEachChild(node, importCallExpressionVisitor, context);
+ return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
}
}
- function importCallExpressionVisitor(node) {
- // This visitor does not need to descend into the tree if there is no dynamic import,
+ function moduleExpressionElementVisitor(node) {
+ // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
// as export/import statements are only transformed at the top level of a file.
- if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */)) {
+ if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) {
return node;
}
if (ts.isImportCall(node)) {
return visitImportCallExpression(node);
}
+ else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) {
+ return visitDestructuringAssignment(node);
+ }
else {
- return ts.visitEachChild(node, importCallExpressionVisitor, context);
+ return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
}
}
+ function destructuringNeedsFlattening(node) {
+ if (ts.isObjectLiteralExpression(node)) {
+ for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
+ var elem = _a[_i];
+ switch (elem.kind) {
+ case 269 /* PropertyAssignment */:
+ if (destructuringNeedsFlattening(elem.initializer)) {
+ return true;
+ }
+ break;
+ case 270 /* ShorthandPropertyAssignment */:
+ if (destructuringNeedsFlattening(elem.name)) {
+ return true;
+ }
+ break;
+ case 271 /* SpreadAssignment */:
+ if (destructuringNeedsFlattening(elem.expression)) {
+ return true;
+ }
+ break;
+ case 153 /* MethodDeclaration */:
+ case 155 /* GetAccessor */:
+ case 156 /* SetAccessor */:
+ return false;
+ default: ts.Debug.assertNever(elem, "Unhandled object member kind");
+ }
+ }
+ }
+ else if (ts.isArrayLiteralExpression(node)) {
+ for (var _b = 0, _c = node.elements; _b < _c.length; _b++) {
+ var elem = _c[_b];
+ if (ts.isSpreadElement(elem)) {
+ if (destructuringNeedsFlattening(elem.expression)) {
+ return true;
+ }
+ }
+ else if (destructuringNeedsFlattening(elem)) {
+ return true;
+ }
+ }
+ }
+ else if (ts.isIdentifier(node)) {
+ return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0);
+ }
+ return false;
+ }
+ function visitDestructuringAssignment(node) {
+ if (destructuringNeedsFlattening(node.left)) {
+ return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions);
+ }
+ return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
+ }
function visitImportCallExpression(node) {
- var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor);
+ var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */);
switch (compilerOptions.module) {
case ts.ModuleKind.AMD:
@@ -68568,10 +69161,10 @@ var ts;
if (original && hasAssociatedEndOfDeclarationMarker(original)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
var id = ts.getOriginalNodeId(node);
- deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true);
+ deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
}
else {
- statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true);
+ statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
}
return ts.singleOrMany(statements);
}
@@ -68585,13 +69178,13 @@ var ts;
if (ts.hasModifier(node, 1 /* Export */)) {
statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
/*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
- /*typeParameters*/ undefined, ts.visitNodes(node.parameters, importCallExpressionVisitor),
- /*type*/ undefined, ts.visitEachChild(node.body, importCallExpressionVisitor, context)),
+ /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor),
+ /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)),
/*location*/ node),
/*original*/ node));
}
else {
- statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context));
+ statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
@@ -68613,10 +69206,10 @@ var ts;
if (ts.hasModifier(node, 1 /* Export */)) {
statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(
/*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
- /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, importCallExpressionVisitor), ts.visitNodes(node.members, importCallExpressionVisitor)), node), node));
+ /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node));
}
else {
- statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context));
+ statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
@@ -68661,7 +69254,7 @@ var ts;
}
}
else {
- statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context));
+ statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
@@ -68673,6 +69266,21 @@ var ts;
}
return ts.singleOrMany(statements);
}
+ function createAllExportExpressions(name, value, location) {
+ var exportedNames = getExports(name);
+ if (exportedNames) {
+ // For each additional export of the declaration, apply an export assignment.
+ var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value);
+ for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
+ var exportName = exportedNames_1[_i];
+ // Mark the node to prevent triggering substitution.
+ ts.setEmitFlags(expression, 4 /* NoSubstitution */);
+ expression = createExportExpression(exportName, expression, /*location*/ location);
+ }
+ return expression;
+ }
+ return ts.createAssignment(name, value);
+ }
/**
* Transforms an exported variable with an initializer into an expression.
*
@@ -68680,13 +69288,13 @@ var ts;
*/
function transformInitializedVariable(node) {
if (ts.isBindingPattern(node.name)) {
- return ts.flattenDestructuringAssignment(ts.visitNode(node, importCallExpressionVisitor),
+ return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor),
/*visitor*/ undefined, context, 0 /* All */,
- /*needsValue*/ false, createExportExpression);
+ /*needsValue*/ false, createAllExportExpressions);
}
else {
return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name),
- /*location*/ node.name), ts.visitNode(node.initializer, importCallExpressionVisitor));
+ /*location*/ node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor));
}
}
/**
@@ -69090,8 +69698,8 @@ var ts;
if (exportedNames) {
// For each additional export of the declaration, apply an export assignment.
var expression = node;
- for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
- var exportName = exportedNames_1[_i];
+ for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
+ var exportName = exportedNames_2[_i];
// Mark the node to prevent triggering this rule again.
noSubstitution[ts.getNodeId(expression)] = true;
expression = createExportExpression(exportName, expression, /*location*/ node);
@@ -69127,8 +69735,8 @@ var ts;
? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)),
/*location*/ node)
: node;
- for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
- var exportName = exportedNames_2[_i];
+ for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
+ var exportName = exportedNames_3[_i];
// Mark the node to prevent triggering this rule again.
noSubstitution[ts.getNodeId(expression)] = true;
expression = createExportExpression(exportName, expression);
@@ -69215,7 +69823,7 @@ var ts;
var hoistedStatements;
var enclosingBlockScopedContainer;
var noSubstitution; // Set of nodes for which substitution rules should be ignored.
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
/**
* Transforms the module aspects of a SourceFile.
*
@@ -69388,7 +69996,7 @@ var ts;
// We emit hoisted variables early to align roughly with our previous emit output.
// Two key differences in this approach are:
// - Temporary variables will appear at the top rather than at the bottom of the file
- ts.addRange(statements, endLexicalEnvironment());
+ ts.prependRange(statements, endLexicalEnvironment());
var exportStarFunction = addExportStarIfNeeded(statements);
var moduleObject = ts.createObjectLiteral([
ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
@@ -69518,12 +70126,12 @@ var ts;
function createSettersArray(exportStarFunction, dependencyGroups) {
var setters = [];
for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
- var group_2 = dependencyGroups_1[_i];
+ var group_1 = dependencyGroups_1[_i];
// derive a unique name for parameter from the first named entry in the group
- var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); });
+ var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); });
var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName("");
var statements = [];
- for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) {
+ for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) {
var entry = _b[_a];
var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile);
switch (entry.kind) {
@@ -70116,9 +70724,9 @@ var ts;
return visitCatchClause(node);
case 212 /* Block */:
return visitBlock(node);
- case 298 /* MergeDeclarationMarker */:
+ case 300 /* MergeDeclarationMarker */:
return visitMergeDeclarationMarker(node);
- case 299 /* EndOfDeclarationMarker */:
+ case 301 /* EndOfDeclarationMarker */:
return visitEndOfDeclarationMarker(node);
default:
return destructuringAndImportCallVisitor(node);
@@ -70551,8 +71159,8 @@ var ts;
if (exportedNames) {
// For each additional export of the declaration, apply an export assignment.
var expression = node;
- for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
- var exportName = exportedNames_3[_i];
+ for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
+ var exportName = exportedNames_4[_i];
expression = createExportExpression(exportName, preventSubstitution(expression));
}
return expression;
@@ -70585,8 +71193,8 @@ var ts;
var expression = node.kind === 198 /* PostfixUnaryExpression */
? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node)
: node;
- for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
- var exportName = exportedNames_4[_i];
+ for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) {
+ var exportName = exportedNames_5[_i];
expression = createExportExpression(exportName, preventSubstitution(expression));
}
if (node.kind === 198 /* PostfixUnaryExpression */) {
@@ -70653,7 +71261,7 @@ var ts;
context.enableEmitNotification(273 /* SourceFile */);
context.enableSubstitution(71 /* Identifier */);
var currentSourceFile;
- return transformSourceFile;
+ return ts.chainBundle(transformSourceFile);
function transformSourceFile(node) {
if (node.isDeclarationFile) {
return node;
@@ -71160,7 +71768,12 @@ var ts;
return result.diagnostics;
}
ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
- var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */;
+ var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
+ 2048 /* WriteClassExpressionAsTypeLiteral */ |
+ 4096 /* UseTypeOfFunction */ |
+ 8 /* UseStructuralFallback */ |
+ 524288 /* AllowEmptyTuple */ |
+ 4 /* GenerateNamesForShadowedTypeParams */;
/**
* Transforms a ts file into a .d.ts file
* This process requires type information, which is retrieved through the emit resolver. Because of this,
@@ -71234,6 +71847,8 @@ var ts;
}
}
function trackSymbol(symbol, enclosingDeclaration, meaning) {
+ if (symbol.flags & 262144 /* TypeParameter */)
+ return;
handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
}
@@ -71277,12 +71892,16 @@ var ts;
resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
needsDeclare = false;
var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
- var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false);
+ var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false);
return newFile;
}
needsDeclare = true;
var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
- return ts.updateSourceFileNode(sourceFile, filterCandidateImports(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false);
+ return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false);
+ }), ts.mapDefined(node.prepends, function (prepend) {
+ if (prepend.kind === 276 /* InputFiles */) {
+ return ts.createUnparsedSourceFile(prepend.declarationText);
+ }
}));
bundle.syntheticFileReferences = [];
bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
@@ -71311,7 +71930,7 @@ var ts;
var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
refs.forEach(referenceVisitor);
var statements = ts.visitNodes(node.statements, visitDeclarationStatements);
- var combinedStatements = ts.setTextRange(ts.createNodeArray(filterCandidateImports(statements)), node.statements);
+ var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements);
@@ -71366,7 +71985,7 @@ var ts;
ts.forEach(sourceFile.referencedFiles, function (f) {
var elem = ts.tryResolveScriptReference(host, sourceFile, f);
if (elem) {
- ret.set("" + ts.getNodeId(elem), elem);
+ ret.set("" + ts.getOriginalNodeId(elem), elem);
}
});
return ret;
@@ -71583,7 +72202,7 @@ var ts;
}
// Nothing visible
}
- function filterCandidateImports(statements) {
+ function transformAndReplaceLatePaintedStatements(statements) {
// This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during
// error handling which must now be included in the output and themselves checked for errors.
// For example:
@@ -71598,62 +72217,45 @@ var ts;
// In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must
// be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of
// dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
- var unconsideredStatements = [];
while (ts.length(lateMarkedStatements)) {
var i = lateMarkedStatements.shift();
- if ((ts.isSourceFile(i.parent) ? i.parent : i.parent.parent) !== enclosingDeclaration) { // Filter to only declarations in the current scope
- unconsideredStatements.push(i);
- continue;
- }
if (!ts.isLateVisibilityPaintedStatement(i)) {
- return ts.Debug.fail("Late replaced statement was foudn which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind));
- }
- switch (i.kind) {
- case 242 /* ImportEqualsDeclaration */: {
- var result = transformImportEqualsDeclaration(i);
- lateStatementReplacementMap.set("" + ts.getNodeId(i), result);
- break;
- }
- case 243 /* ImportDeclaration */: {
- var result = transformImportDeclaration(i);
- lateStatementReplacementMap.set("" + ts.getNodeId(i), result);
- break;
- }
- case 213 /* VariableStatement */: {
- var result = transformVariableStatement(i, /*privateDeclaration*/ true); // Transform the statement (potentially again, possibly revealing more sub-nodes)
- lateStatementReplacementMap.set("" + ts.getNodeId(i), result);
- break;
- }
- default: ts.Debug.assertNever(i, "Unhandled late painted statement!");
+ return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind));
}
+ var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true);
+ lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result);
}
- // Filtering available imports is the last thing done within a scope, so the possible set becomes those which could not
- // be considered in the child scope
- lateMarkedStatements = unconsideredStatements;
// And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list
// (and remove them from the set to examine for outter declarations)
return ts.visitNodes(statements, visitLateVisibilityMarkedStatements);
- }
- function visitLateVisibilityMarkedStatements(statement) {
- if (ts.isLateVisibilityPaintedStatement(statement)) {
- var key = "" + ts.getNodeId(statement);
- if (lateStatementReplacementMap.has(key)) {
- var result = lateStatementReplacementMap.get(key);
- lateStatementReplacementMap.delete(key);
- if (result && ts.isSourceFile(statement.parent) && !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */)) {
- // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
- needsScopeFixMarker = true;
+ function visitLateVisibilityMarkedStatements(statement) {
+ if (ts.isLateVisibilityPaintedStatement(statement)) {
+ var key = "" + ts.getOriginalNodeId(statement);
+ if (lateStatementReplacementMap.has(key)) {
+ var result = lateStatementReplacementMap.get(key);
+ lateStatementReplacementMap.delete(key);
+ if (result && ts.isSourceFile(statement.parent)) {
+ if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) {
+ // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
+ needsScopeFixMarker = true;
+ }
+ if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) {
+ resultHasExternalModuleIndicator = true;
+ }
+ }
+ return result;
}
- return result;
}
- else {
- return ts.getParseTreeNode(statement) ? undefined : statement;
- }
- }
- else {
return statement;
}
}
+ function isExternalModuleIndicator(result) {
+ // Exported top-level member indicates moduleness
+ return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */);
+ }
+ function needsScopeMarker(result) {
+ return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
+ }
function visitDeclarationSubtree(input) {
if (shouldStripInternal(input))
return;
@@ -71851,13 +72453,21 @@ var ts;
return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
}
}
- case 242 /* ImportEqualsDeclaration */:
+ }
+ var result = transformTopLevelDeclaration(input);
+ // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass
+ lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result);
+ return input;
+ }
+ function transformTopLevelDeclaration(input, isPrivate) {
+ if (shouldStripInternal(input))
+ return;
+ switch (input.kind) {
+ case 242 /* ImportEqualsDeclaration */: {
+ return transformImportEqualsDeclaration(input);
+ }
case 243 /* ImportDeclaration */: {
- // Different parts of the import may be marked visible at different times (via visibility checking), so we defer our first look until later
- // to reduce the likelihood we need to rewrite it
- lateMarkedStatements = lateMarkedStatements || [];
- ts.pushIfUnique(lateMarkedStatements, input);
- return input;
+ return transformImportDeclaration(input);
}
}
if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input))
@@ -71870,52 +72480,53 @@ var ts;
previousEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = input;
}
- var previousNeedsDeclare;
var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
var oldDiag = getSymbolAccessibilityDiagnostic;
if (canProdiceDiagnostic) {
getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
}
- var oldPossibleImports;
+ var previousNeedsDeclare = needsDeclare;
switch (input.kind) {
case 236 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all
return cleanup(ts.updateTypeAliasDeclaration(input,
- /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
+ /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
case 235 /* InterfaceDeclaration */: {
return cleanup(ts.updateInterfaceDeclaration(input,
- /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
+ /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
}
case 233 /* FunctionDeclaration */: {
// Generators lose their generator-ness, excepting their return type
return cleanup(ts.updateFunctionDeclaration(input,
- /*decorators*/ undefined, ensureModifiers(input),
+ /*decorators*/ undefined, ensureModifiers(input, isPrivate),
/*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type),
/*body*/ undefined));
}
case 238 /* ModuleDeclaration */: {
- previousNeedsDeclare = needsDeclare;
needsDeclare = false;
- oldPossibleImports = lateMarkedStatements;
- lateMarkedStatements = undefined;
var inner = input.body;
if (inner && inner.kind === 239 /* ModuleBlock */) {
var statements = ts.visitNodes(inner.statements, visitDeclarationStatements);
- var body = ts.updateModuleBlock(inner, filterCandidateImports(statements));
+ var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements));
needsDeclare = previousNeedsDeclare;
- var mods = ensureModifiers(input);
+ var mods = ensureModifiers(input, isPrivate);
return cleanup(ts.updateModuleDeclaration(input,
/*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body));
}
else {
needsDeclare = previousNeedsDeclare;
- var mods = ensureModifiers(input);
+ var mods = ensureModifiers(input, isPrivate);
needsDeclare = false;
+ ts.visitNode(inner, visitDeclarationStatements);
+ // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
+ var id = "" + ts.getOriginalNodeId(inner);
+ var body = lateStatementReplacementMap.get(id);
+ lateStatementReplacementMap.delete(id);
return cleanup(ts.updateModuleDeclaration(input,
- /*decorators*/ undefined, mods, input.name, ts.visitNode(inner, visitDeclarationStatements)));
+ /*decorators*/ undefined, mods, input.name, body));
}
}
case 234 /* ClassDeclaration */: {
- var modifiers = ts.createNodeArray(ensureModifiers(input));
+ var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate));
var typeParameters = ensureTypeParams(input, input.typeParameters);
var ctor = ts.getFirstConstructorWithBody(input);
var parameterProperties = void 0;
@@ -71985,12 +72596,10 @@ var ts;
}
}
case 213 /* VariableStatement */: {
- var result = transformVariableStatement(input);
- lateStatementReplacementMap.set("" + ts.getNodeId(input), result); // Don't actually elide yet; just leave as original node - will be elided/swapped by late pass
- return cleanup(input);
+ return cleanup(transformVariableStatement(input, isPrivate));
}
case 237 /* EnumDeclaration */: {
- return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) {
+ return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) {
if (shouldStripInternal(m))
return;
// Rewrite enum values to their constants, if available
@@ -72001,27 +72610,20 @@ var ts;
}
// Anything left unhandled is an error, so this should be unreachable
return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]);
- function cleanup(returnValue) {
+ function cleanup(node) {
if (isEnclosingDeclaration(input)) {
enclosingDeclaration = previousEnclosingDeclaration;
}
- if (input.kind === 238 /* ModuleDeclaration */) {
- needsDeclare = previousNeedsDeclare;
- lateMarkedStatements = ts.concatenate(oldPossibleImports, lateMarkedStatements);
- }
if (canProdiceDiagnostic) {
getSymbolAccessibilityDiagnostic = oldDiag;
}
- if (returnValue && (!ts.isLateVisibilityPaintedStatement(input) || lateStatementReplacementMap.get("" + ts.getNodeId(input)))) {
- if (!resultHasExternalModuleIndicator && ts.hasModifier(input, 1 /* Export */) && ts.isSourceFile(input.parent)) {
- // Exported top-level member indicates moduleness
- resultHasExternalModuleIndicator = true;
- }
+ if (input.kind === 238 /* ModuleDeclaration */) {
+ needsDeclare = previousNeedsDeclare;
}
- if (returnValue === input) {
- return returnValue;
+ if (node === input) {
+ return node;
}
- return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input);
+ return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
}
}
function transformVariableStatement(input, privateDeclaration) {
@@ -72098,7 +72700,7 @@ var ts;
return maskModifierFlags(node, mask, additions);
}
function ensureAccessor(node) {
- var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
+ var accessors = resolver.getAllAccessorDeclarations(node);
if (node.kind !== accessors.firstAccessor.kind) {
return;
}
@@ -72287,7 +72889,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(300 /* Count */);
+ var enabledSyntaxKindFeatures = new Array(302 /* Count */);
var lexicalEnvironmentVariableDeclarations;
var lexicalEnvironmentFunctionDeclarations;
var lexicalEnvironmentVariableDeclarationsStack = [];
@@ -72782,7 +73384,7 @@ var ts;
source = undefined;
if (source)
setSourceFile(source);
- if (node.kind !== 295 /* NotEmittedStatement */
+ if (node.kind !== 297 /* NotEmittedStatement */
&& (emitFlags & 16 /* NoLeadingSourceMap */) === 0
&& pos >= 0) {
emitPos(skipSourceTrivia(pos));
@@ -72799,7 +73401,7 @@ var ts;
}
if (source)
setSourceFile(source);
- if (node.kind !== 295 /* NotEmittedStatement */
+ if (node.kind !== 297 /* NotEmittedStatement */
&& (emitFlags & 32 /* NoTrailingSourceMap */) === 0
&& end >= 0) {
emitPos(end);
@@ -72975,7 +73577,7 @@ var ts;
if (extendedDiagnostics) {
ts.performance.mark("preEmitNodeWithComment");
}
- var isEmittedNode = node.kind !== 295 /* NotEmittedStatement */;
+ var isEmittedNode = node.kind !== 297 /* 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 === 10 /* JsxText */;
@@ -73299,6 +73901,7 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
+ var infoExtension = ".tsbundleinfo";
var brackets = createBracketsMap();
/*@internal*/
/**
@@ -73315,7 +73918,7 @@ var ts;
var options = host.getCompilerOptions();
if (options.outFile || options.out) {
if (sourceFiles.length) {
- var bundle = ts.createBundle(sourceFiles);
+ var bundle = ts.createBundle(sourceFiles, host.getPrependNodes());
var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle);
if (result) {
return result;
@@ -73341,7 +73944,8 @@ var ts;
var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options);
var declarationFilePath = (forceDtsPaths || options.declaration) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined;
var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath };
+ var bundleInfoPath = options.references && jsFilePath && (ts.removeFileExtension(jsFilePath) + infoExtension);
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath };
}
else {
var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options));
@@ -73350,17 +73954,27 @@ var ts;
var isJs = ts.isSourceFileJavaScript(sourceFile);
var declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined;
var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
- return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath };
+ return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: 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
+ /* @internal */
function getOutputExtension(sourceFile, options) {
+ if (ts.isJsonSourceFile(sourceFile)) {
+ return ".json" /* Json */;
+ }
if (options.jsx === 1 /* Preserve */) {
if (ts.isSourceFileJavaScript(sourceFile)) {
if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) {
@@ -73374,9 +73988,10 @@ var ts;
}
return ".js" /* Js */;
}
+ 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) {
+ function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) {
var compilerOptions = host.getCompilerOptions();
var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
@@ -73390,6 +74005,7 @@ var ts;
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
});
+ var bundleInfo = createDefaultBundleInfo();
var emitSkipped = false;
// Emit each output file
ts.performance.mark("beforePrint");
@@ -73402,8 +74018,8 @@ var ts;
sourceMaps: sourceMapDataList
};
function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
- var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
- emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath);
+ var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath;
+ emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath);
emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath);
if (!emitSkipped && emittedFilesList) {
if (!emitOnlyDtsFiles) {
@@ -73415,10 +74031,12 @@ var ts;
if (declarationFilePath) {
emittedFilesList.push(declarationFilePath);
}
+ if (bundleInfoPath) {
+ emittedFilesList.push(bundleInfoPath);
+ }
}
}
- function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) {
- var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
+ function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) {
// Make sure not to write js file and source map file if any of them cannot be written
if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) {
emitSkipped = true;
@@ -73428,7 +74046,7 @@ var ts;
return;
}
// Transform the source files
- var transform = ts.transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, /*allowDtsFiles*/ false);
+ var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false);
// Create a printer to print the nodes
var printer = createPrinter(__assign({}, compilerOptions, { noEmitHelpers: compilerOptions.noEmitHelpers }), {
// resolver hooks
@@ -73443,7 +74061,8 @@ var ts;
// emitter hooks
onSetSourceFile: setSourceFile,
});
- printSourceFileOrBundle(jsFilePath, sourceMapFilePath, ts.isSourceFile(sourceFileOrBundle) ? transform.transformed[0] : ts.createBundle(transform.transformed), printer, sourceMap);
+ ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
+ printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap);
// Clean up emit nodes on parse tree
transform.dispose();
}
@@ -73454,8 +74073,8 @@ var ts;
var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
// Setup and perform the transformation to retrieve declarations from the input files
var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript);
- var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles)] : nonJsFiles;
- var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, [ts.transformDeclarations], /*allowDtsFiles*/ false);
+ var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles;
+ var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), /*allowDtsFiles*/ false);
if (ts.length(declarationTransform.diagnostics)) {
for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) {
var diagnostic = _b[_a];
@@ -73477,17 +74096,18 @@ var ts;
var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
emitSkipped = emitSkipped || declBlocked;
if (!declBlocked || emitOnlyDtsFiles) {
- printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, declarationSourceMap);
+ 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, declarationSourceMap);
}
declarationTransform.dispose();
}
- function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapRecorder) {
+ function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) {
var bundle = sourceFileOrBundle.kind === 274 /* Bundle */ ? sourceFileOrBundle : undefined;
var sourceFile = sourceFileOrBundle.kind === 273 /* SourceFile */ ? sourceFileOrBundle : undefined;
var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList);
if (bundle) {
- printer.writeBundle(bundle, writer);
+ printer.writeBundle(bundle, writer, bundleInfo);
}
else {
printer.writeFile(sourceFile, writer);
@@ -73503,9 +74123,15 @@ 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
mapRecorder.reset();
writer.clear();
+ bundleInfo = createDefaultBundleInfo();
}
function setSourceFile(node) {
sourceMap.setSourceFile(node);
@@ -73515,6 +74141,13 @@ var ts;
}
}
ts.emitFiles = emitFiles;
+ var PipelinePhase;
+ (function (PipelinePhase) {
+ PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
+ PipelinePhase[PipelinePhase["Comments"] = 1] = "Comments";
+ PipelinePhase[PipelinePhase["SourceMaps"] = 2] = "SourceMaps";
+ PipelinePhase[PipelinePhase["Emit"] = 3] = "Emit";
+ })(PipelinePhase || (PipelinePhase = {}));
function createPrinter(printerOptions, handlers) {
if (printerOptions === void 0) { printerOptions = {}; }
if (handlers === void 0) { handlers = {}; }
@@ -73572,6 +74205,7 @@ var ts;
switch (node.kind) {
case 273 /* SourceFile */: return printFile(node);
case 274 /* Bundle */: return printBundle(node);
+ case 275 /* UnparsedSource */: return printUnparsedSource(node);
}
writeNode(hint, node, sourceFile, beginPrint());
return endPrint();
@@ -73588,6 +74222,10 @@ var ts;
writeFile(sourceFile, beginPrint());
return endPrint();
}
+ function printUnparsedSource(unparsed) {
+ writeUnparsedSource(unparsed, beginPrint());
+ return endPrint();
+ }
function writeNode(hint, node, sourceFile, output) {
var previousWriter = writer;
setWriter(output);
@@ -73605,7 +74243,7 @@ var ts;
reset();
writer = previousWriter;
}
- function writeBundle(bundle, output) {
+ function writeBundle(bundle, output, bundleInfo) {
isOwnFileEmit = false;
var previousWriter = writer;
setWriter(output);
@@ -73613,13 +74251,28 @@ var ts;
emitPrologueDirectivesIfNeeded(bundle);
emitHelpers(bundle);
emitSyntheticTripleSlashReferencesIfNeeded(bundle);
- for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
- var sourceFile = _b[_a];
+ for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) {
+ var prepend = _b[_a];
+ print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
+ writeLine();
+ }
+ if (bundleInfo) {
+ bundleInfo.originalOffset = writer.getTextPos();
+ }
+ for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) {
+ var sourceFile = _d[_c];
print(0 /* SourceFile */, sourceFile, sourceFile);
}
reset();
writer = previousWriter;
}
+ function writeUnparsedSource(unparsed, output) {
+ var previousWriter = writer;
+ setWriter(output);
+ print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined);
+ reset();
+ writer = previousWriter;
+ }
function writeFile(sourceFile, output) {
isOwnFileEmit = true;
var previousWriter = writer;
@@ -73642,7 +74295,8 @@ var ts;
if (sourceFile) {
setSourceFile(sourceFile);
}
- pipelineEmitWithNotification(hint, node);
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, hint);
+ pipelinePhase(hint, node);
}
function setSourceFile(sourceFile) {
currentSourceFile = sourceFile;
@@ -73665,417 +74319,422 @@ var ts;
comments.reset();
setWriter(/*output*/ undefined);
}
- // TODO: Should this just be `emit`?
- // See https://github.com/Microsoft/TypeScript/pull/18284#discussion_r137611034
- function emitIfPresent(node) {
- if (node) {
- emit(node);
- }
- }
function emit(node) {
- pipelineEmitWithNotification(4 /* Unspecified */, node);
+ if (!node)
+ return;
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, 4 /* Unspecified */);
+ pipelinePhase(4 /* Unspecified */, node);
}
function emitIdentifierName(node) {
- pipelineEmitWithNotification(2 /* IdentifierName */, node);
+ if (!node)
+ return;
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, 2 /* IdentifierName */);
+ pipelinePhase(2 /* IdentifierName */, node);
}
function emitExpression(node) {
- pipelineEmitWithNotification(1 /* Expression */, node);
+ if (!node)
+ return;
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */);
+ pipelinePhase(1 /* Expression */, node);
+ }
+ function getPipelinePhase(phase, hint) {
+ switch (phase) {
+ case 0 /* Notification */:
+ if (onEmitNode) {
+ return pipelineEmitWithNotification;
+ }
+ // falls through
+ case 1 /* Comments */:
+ if (emitNodeWithComments && hint !== 0 /* SourceFile */) {
+ return pipelineEmitWithComments;
+ }
+ return pipelineEmitWithoutComments;
+ case 2 /* SourceMaps */:
+ if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) {
+ return pipelineEmitWithSourceMap;
+ }
+ // falls through
+ case 3 /* Emit */:
+ return pipelineEmitWithHint;
+ default:
+ return ts.Debug.assertNever(phase, "Unexpected value for PipelinePhase: " + phase);
+ }
+ }
+ function getNextPipelinePhase(currentPhase, hint) {
+ return getPipelinePhase(currentPhase + 1, hint);
}
function pipelineEmitWithNotification(hint, node) {
- if (onEmitNode) {
- onEmitNode(hint, node, pipelineEmitWithComments);
- }
- else {
- pipelineEmitWithComments(hint, node);
- }
+ ts.Debug.assertDefined(onEmitNode);
+ onEmitNode(hint, node, getNextPipelinePhase(0 /* Notification */, hint));
}
function pipelineEmitWithComments(hint, node) {
- node = trySubstituteNode(hint, node);
- if (emitNodeWithComments && hint !== 0 /* SourceFile */) {
- emitNodeWithComments(hint, node, pipelineEmitWithSourceMap);
- }
- else {
- pipelineEmitWithSourceMap(hint, node);
- }
+ ts.Debug.assertDefined(emitNodeWithComments);
+ ts.Debug.assert(hint !== 0 /* SourceFile */);
+ emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(1 /* Comments */, hint));
+ }
+ function pipelineEmitWithoutComments(hint, node) {
+ var pipelinePhase = getNextPipelinePhase(1 /* Comments */, hint);
+ pipelinePhase(hint, trySubstituteNode(hint, node));
}
function pipelineEmitWithSourceMap(hint, node) {
- if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) {
- onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint);
- }
- else {
- pipelineEmitWithHint(hint, node);
- }
+ ts.Debug.assertDefined(onEmitSourceMapOfNode);
+ ts.Debug.assert(hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */);
+ onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint);
}
function pipelineEmitWithHint(hint, node) {
- switch (hint) {
- case 0 /* SourceFile */: return pipelineEmitSourceFile(node);
- case 2 /* IdentifierName */: return pipelineEmitIdentifierName(node);
- case 1 /* Expression */: return pipelineEmitExpression(node);
- case 3 /* MappedTypeParameter */: return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
- case 4 /* Unspecified */: return pipelineEmitUnspecified(node);
+ if (hint === 0 /* SourceFile */)
+ return emitSourceFile(ts.cast(node, ts.isSourceFile));
+ if (hint === 2 /* IdentifierName */)
+ return emitIdentifier(ts.cast(node, ts.isIdentifier));
+ if (hint === 3 /* MappedTypeParameter */)
+ return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
+ if (hint === 4 /* Unspecified */) {
+ if (ts.isKeyword(node.kind))
+ return writeTokenNode(node, writeKeyword);
+ switch (node.kind) {
+ // Pseudo-literals
+ case 14 /* TemplateHead */:
+ case 15 /* TemplateMiddle */:
+ case 16 /* TemplateTail */:
+ return emitLiteral(node);
+ case 275 /* UnparsedSource */:
+ return emitUnparsedSource(node);
+ // Identifiers
+ case 71 /* Identifier */:
+ return emitIdentifier(node);
+ // Parse tree nodes
+ // Names
+ case 145 /* QualifiedName */:
+ return emitQualifiedName(node);
+ case 146 /* ComputedPropertyName */:
+ return emitComputedPropertyName(node);
+ // Signature elements
+ case 147 /* TypeParameter */:
+ return emitTypeParameter(node);
+ case 148 /* Parameter */:
+ return emitParameter(node);
+ case 149 /* Decorator */:
+ return emitDecorator(node);
+ // Type members
+ case 150 /* PropertySignature */:
+ return emitPropertySignature(node);
+ case 151 /* PropertyDeclaration */:
+ return emitPropertyDeclaration(node);
+ case 152 /* MethodSignature */:
+ return emitMethodSignature(node);
+ case 153 /* MethodDeclaration */:
+ return emitMethodDeclaration(node);
+ case 154 /* Constructor */:
+ return emitConstructor(node);
+ case 155 /* GetAccessor */:
+ case 156 /* SetAccessor */:
+ return emitAccessorDeclaration(node);
+ case 157 /* CallSignature */:
+ return emitCallSignature(node);
+ case 158 /* ConstructSignature */:
+ return emitConstructSignature(node);
+ case 159 /* IndexSignature */:
+ return emitIndexSignature(node);
+ // Types
+ case 160 /* TypePredicate */:
+ return emitTypePredicate(node);
+ case 161 /* TypeReference */:
+ return emitTypeReference(node);
+ case 162 /* FunctionType */:
+ return emitFunctionType(node);
+ case 283 /* JSDocFunctionType */:
+ return emitJSDocFunctionType(node);
+ case 163 /* ConstructorType */:
+ return emitConstructorType(node);
+ case 164 /* TypeQuery */:
+ return emitTypeQuery(node);
+ case 165 /* TypeLiteral */:
+ return emitTypeLiteral(node);
+ case 166 /* ArrayType */:
+ return emitArrayType(node);
+ case 167 /* TupleType */:
+ return emitTupleType(node);
+ case 168 /* UnionType */:
+ return emitUnionType(node);
+ case 169 /* IntersectionType */:
+ return emitIntersectionType(node);
+ case 170 /* ConditionalType */:
+ return emitConditionalType(node);
+ case 171 /* InferType */:
+ return emitInferType(node);
+ case 172 /* ParenthesizedType */:
+ return emitParenthesizedType(node);
+ case 206 /* ExpressionWithTypeArguments */:
+ return emitExpressionWithTypeArguments(node);
+ case 173 /* ThisType */:
+ return emitThisType();
+ case 174 /* TypeOperator */:
+ return emitTypeOperator(node);
+ case 175 /* IndexedAccessType */:
+ return emitIndexedAccessType(node);
+ case 176 /* MappedType */:
+ return emitMappedType(node);
+ case 177 /* LiteralType */:
+ return emitLiteralType(node);
+ case 178 /* ImportType */:
+ return emitImportTypeNode(node);
+ case 278 /* JSDocAllType */:
+ write("*");
+ return;
+ case 279 /* JSDocUnknownType */:
+ write("?");
+ return;
+ case 280 /* JSDocNullableType */:
+ return emitJSDocNullableType(node);
+ case 281 /* JSDocNonNullableType */:
+ return emitJSDocNonNullableType(node);
+ case 282 /* JSDocOptionalType */:
+ return emitJSDocOptionalType(node);
+ case 284 /* JSDocVariadicType */:
+ return emitJSDocVariadicType(node);
+ // Binding patterns
+ case 179 /* ObjectBindingPattern */:
+ return emitObjectBindingPattern(node);
+ case 180 /* ArrayBindingPattern */:
+ return emitArrayBindingPattern(node);
+ case 181 /* BindingElement */:
+ return emitBindingElement(node);
+ // Misc
+ case 210 /* TemplateSpan */:
+ return emitTemplateSpan(node);
+ case 211 /* SemicolonClassElement */:
+ return emitSemicolonClassElement();
+ // Statements
+ case 212 /* Block */:
+ return emitBlock(node);
+ case 213 /* VariableStatement */:
+ return emitVariableStatement(node);
+ case 214 /* EmptyStatement */:
+ return emitEmptyStatement();
+ case 215 /* ExpressionStatement */:
+ return emitExpressionStatement(node);
+ case 216 /* IfStatement */:
+ return emitIfStatement(node);
+ case 217 /* DoStatement */:
+ return emitDoStatement(node);
+ case 218 /* WhileStatement */:
+ return emitWhileStatement(node);
+ case 219 /* ForStatement */:
+ return emitForStatement(node);
+ case 220 /* ForInStatement */:
+ return emitForInStatement(node);
+ case 221 /* ForOfStatement */:
+ return emitForOfStatement(node);
+ case 222 /* ContinueStatement */:
+ return emitContinueStatement(node);
+ case 223 /* BreakStatement */:
+ return emitBreakStatement(node);
+ case 224 /* ReturnStatement */:
+ return emitReturnStatement(node);
+ case 225 /* WithStatement */:
+ return emitWithStatement(node);
+ case 226 /* SwitchStatement */:
+ return emitSwitchStatement(node);
+ case 227 /* LabeledStatement */:
+ return emitLabeledStatement(node);
+ case 228 /* ThrowStatement */:
+ return emitThrowStatement(node);
+ case 229 /* TryStatement */:
+ return emitTryStatement(node);
+ case 230 /* DebuggerStatement */:
+ return emitDebuggerStatement(node);
+ // Declarations
+ case 231 /* VariableDeclaration */:
+ return emitVariableDeclaration(node);
+ case 232 /* VariableDeclarationList */:
+ return emitVariableDeclarationList(node);
+ case 233 /* FunctionDeclaration */:
+ return emitFunctionDeclaration(node);
+ case 234 /* ClassDeclaration */:
+ return emitClassDeclaration(node);
+ case 235 /* InterfaceDeclaration */:
+ return emitInterfaceDeclaration(node);
+ case 236 /* TypeAliasDeclaration */:
+ return emitTypeAliasDeclaration(node);
+ case 237 /* EnumDeclaration */:
+ return emitEnumDeclaration(node);
+ case 238 /* ModuleDeclaration */:
+ return emitModuleDeclaration(node);
+ case 239 /* ModuleBlock */:
+ return emitModuleBlock(node);
+ case 240 /* CaseBlock */:
+ return emitCaseBlock(node);
+ case 241 /* NamespaceExportDeclaration */:
+ return emitNamespaceExportDeclaration(node);
+ case 242 /* ImportEqualsDeclaration */:
+ return emitImportEqualsDeclaration(node);
+ case 243 /* ImportDeclaration */:
+ return emitImportDeclaration(node);
+ case 244 /* ImportClause */:
+ return emitImportClause(node);
+ case 245 /* NamespaceImport */:
+ return emitNamespaceImport(node);
+ case 246 /* NamedImports */:
+ return emitNamedImports(node);
+ case 247 /* ImportSpecifier */:
+ return emitImportSpecifier(node);
+ case 248 /* ExportAssignment */:
+ return emitExportAssignment(node);
+ case 249 /* ExportDeclaration */:
+ return emitExportDeclaration(node);
+ case 250 /* NamedExports */:
+ return emitNamedExports(node);
+ case 251 /* ExportSpecifier */:
+ return emitExportSpecifier(node);
+ case 252 /* MissingDeclaration */:
+ return;
+ // Module references
+ case 253 /* ExternalModuleReference */:
+ return emitExternalModuleReference(node);
+ // JSX (non-expression)
+ case 10 /* JsxText */:
+ return emitJsxText(node);
+ case 256 /* JsxOpeningElement */:
+ case 259 /* JsxOpeningFragment */:
+ return emitJsxOpeningElementOrFragment(node);
+ case 257 /* JsxClosingElement */:
+ case 260 /* JsxClosingFragment */:
+ return emitJsxClosingElementOrFragment(node);
+ case 261 /* JsxAttribute */:
+ return emitJsxAttribute(node);
+ case 262 /* JsxAttributes */:
+ return emitJsxAttributes(node);
+ case 263 /* JsxSpreadAttribute */:
+ return emitJsxSpreadAttribute(node);
+ case 264 /* JsxExpression */:
+ return emitJsxExpression(node);
+ // Clauses
+ case 265 /* CaseClause */:
+ return emitCaseClause(node);
+ case 266 /* DefaultClause */:
+ return emitDefaultClause(node);
+ case 267 /* HeritageClause */:
+ return emitHeritageClause(node);
+ case 268 /* CatchClause */:
+ return emitCatchClause(node);
+ // Property assignments
+ case 269 /* PropertyAssignment */:
+ return emitPropertyAssignment(node);
+ case 270 /* ShorthandPropertyAssignment */:
+ return emitShorthandPropertyAssignment(node);
+ case 271 /* SpreadAssignment */:
+ return emitSpreadAssignment(node);
+ // Enum
+ case 272 /* EnumMember */:
+ return emitEnumMember(node);
+ // JSDoc nodes (ignored)
+ // Transformation nodes (ignored)
+ }
+ if (ts.isExpression(node)) {
+ hint = 1 /* Expression */;
+ node = trySubstituteNode(1 /* Expression */, node);
+ }
+ else if (ts.isToken(node)) {
+ return writeTokenNode(node, writePunctuation);
+ }
+ }
+ if (hint === 1 /* Expression */) {
+ switch (node.kind) {
+ // Literals
+ case 8 /* NumericLiteral */:
+ return emitNumericLiteral(node);
+ case 9 /* StringLiteral */:
+ case 12 /* RegularExpressionLiteral */:
+ case 13 /* NoSubstitutionTemplateLiteral */:
+ return emitLiteral(node);
+ // Identifiers
+ case 71 /* Identifier */:
+ return emitIdentifier(node);
+ // Reserved words
+ case 86 /* FalseKeyword */:
+ case 95 /* NullKeyword */:
+ case 97 /* SuperKeyword */:
+ case 101 /* TrueKeyword */:
+ case 99 /* ThisKeyword */:
+ case 91 /* ImportKeyword */:
+ writeTokenNode(node, writeKeyword);
+ return;
+ // Expressions
+ case 182 /* ArrayLiteralExpression */:
+ return emitArrayLiteralExpression(node);
+ case 183 /* ObjectLiteralExpression */:
+ return emitObjectLiteralExpression(node);
+ case 184 /* PropertyAccessExpression */:
+ return emitPropertyAccessExpression(node);
+ case 185 /* ElementAccessExpression */:
+ return emitElementAccessExpression(node);
+ case 186 /* CallExpression */:
+ return emitCallExpression(node);
+ case 187 /* NewExpression */:
+ return emitNewExpression(node);
+ case 188 /* TaggedTemplateExpression */:
+ return emitTaggedTemplateExpression(node);
+ case 189 /* TypeAssertionExpression */:
+ return emitTypeAssertionExpression(node);
+ case 190 /* ParenthesizedExpression */:
+ return emitParenthesizedExpression(node);
+ case 191 /* FunctionExpression */:
+ return emitFunctionExpression(node);
+ case 192 /* ArrowFunction */:
+ return emitArrowFunction(node);
+ case 193 /* DeleteExpression */:
+ return emitDeleteExpression(node);
+ case 194 /* TypeOfExpression */:
+ return emitTypeOfExpression(node);
+ case 195 /* VoidExpression */:
+ return emitVoidExpression(node);
+ case 196 /* AwaitExpression */:
+ return emitAwaitExpression(node);
+ case 197 /* PrefixUnaryExpression */:
+ return emitPrefixUnaryExpression(node);
+ case 198 /* PostfixUnaryExpression */:
+ return emitPostfixUnaryExpression(node);
+ case 199 /* BinaryExpression */:
+ return emitBinaryExpression(node);
+ case 200 /* ConditionalExpression */:
+ return emitConditionalExpression(node);
+ case 201 /* TemplateExpression */:
+ return emitTemplateExpression(node);
+ case 202 /* YieldExpression */:
+ return emitYieldExpression(node);
+ case 203 /* SpreadElement */:
+ return emitSpreadExpression(node);
+ case 204 /* ClassExpression */:
+ return emitClassExpression(node);
+ case 205 /* OmittedExpression */:
+ return;
+ case 207 /* AsExpression */:
+ return emitAsExpression(node);
+ case 208 /* NonNullExpression */:
+ return emitNonNullExpression(node);
+ case 209 /* MetaProperty */:
+ return emitMetaProperty(node);
+ // JSX
+ case 254 /* JsxElement */:
+ return emitJsxElement(node);
+ case 255 /* JsxSelfClosingElement */:
+ return emitJsxSelfClosingElement(node);
+ case 258 /* JsxFragment */:
+ return emitJsxFragment(node);
+ // Transformation nodes
+ case 298 /* PartiallyEmittedExpression */:
+ return emitPartiallyEmittedExpression(node);
+ case 299 /* CommaListExpression */:
+ return emitCommaList(node);
+ }
}
- }
- function pipelineEmitSourceFile(node) {
- ts.Debug.assertNode(node, ts.isSourceFile);
- emitSourceFile(node);
- }
- function pipelineEmitIdentifierName(node) {
- ts.Debug.assertNode(node, ts.isIdentifier);
- emitIdentifier(node);
}
function emitMappedTypeParameter(node) {
emit(node.name);
writeSpace();
writeKeyword("in");
writeSpace();
- emitIfPresent(node.constraint);
- }
- function pipelineEmitUnspecified(node) {
- var kind = node.kind;
- // Reserved words
- // Strict mode reserved words
- // Contextual keywords
- if (ts.isKeyword(kind)) {
- writeTokenNode(node, writeKeyword);
- return;
- }
- switch (kind) {
- // Pseudo-literals
- case 14 /* TemplateHead */:
- case 15 /* TemplateMiddle */:
- case 16 /* TemplateTail */:
- return emitLiteral(node);
- // Identifiers
- case 71 /* Identifier */:
- return emitIdentifier(node);
- // Parse tree nodes
- // Names
- case 145 /* QualifiedName */:
- return emitQualifiedName(node);
- case 146 /* ComputedPropertyName */:
- return emitComputedPropertyName(node);
- // Signature elements
- case 147 /* TypeParameter */:
- return emitTypeParameter(node);
- case 148 /* Parameter */:
- return emitParameter(node);
- case 149 /* Decorator */:
- return emitDecorator(node);
- // Type members
- case 150 /* PropertySignature */:
- return emitPropertySignature(node);
- case 151 /* PropertyDeclaration */:
- return emitPropertyDeclaration(node);
- case 152 /* MethodSignature */:
- return emitMethodSignature(node);
- case 153 /* MethodDeclaration */:
- return emitMethodDeclaration(node);
- case 154 /* Constructor */:
- return emitConstructor(node);
- case 155 /* GetAccessor */:
- case 156 /* SetAccessor */:
- return emitAccessorDeclaration(node);
- case 157 /* CallSignature */:
- return emitCallSignature(node);
- case 158 /* ConstructSignature */:
- return emitConstructSignature(node);
- case 159 /* IndexSignature */:
- return emitIndexSignature(node);
- // Types
- case 160 /* TypePredicate */:
- return emitTypePredicate(node);
- case 161 /* TypeReference */:
- return emitTypeReference(node);
- case 162 /* FunctionType */:
- return emitFunctionType(node);
- case 281 /* JSDocFunctionType */:
- return emitJSDocFunctionType(node);
- case 163 /* ConstructorType */:
- return emitConstructorType(node);
- case 164 /* TypeQuery */:
- return emitTypeQuery(node);
- case 165 /* TypeLiteral */:
- return emitTypeLiteral(node);
- case 166 /* ArrayType */:
- return emitArrayType(node);
- case 167 /* TupleType */:
- return emitTupleType(node);
- case 168 /* UnionType */:
- return emitUnionType(node);
- case 169 /* IntersectionType */:
- return emitIntersectionType(node);
- case 170 /* ConditionalType */:
- return emitConditionalType(node);
- case 171 /* InferType */:
- return emitInferType(node);
- case 172 /* ParenthesizedType */:
- return emitParenthesizedType(node);
- case 206 /* ExpressionWithTypeArguments */:
- return emitExpressionWithTypeArguments(node);
- case 173 /* ThisType */:
- return emitThisType();
- case 174 /* TypeOperator */:
- return emitTypeOperator(node);
- case 175 /* IndexedAccessType */:
- return emitIndexedAccessType(node);
- case 176 /* MappedType */:
- return emitMappedType(node);
- case 177 /* LiteralType */:
- return emitLiteralType(node);
- case 178 /* ImportType */:
- return emitImportTypeNode(node);
- case 276 /* JSDocAllType */:
- write("*");
- return;
- case 277 /* JSDocUnknownType */:
- write("?");
- return;
- case 278 /* JSDocNullableType */:
- return emitJSDocNullableType(node);
- case 279 /* JSDocNonNullableType */:
- return emitJSDocNonNullableType(node);
- case 280 /* JSDocOptionalType */:
- return emitJSDocOptionalType(node);
- case 282 /* JSDocVariadicType */:
- return emitJSDocVariadicType(node);
- // Binding patterns
- case 179 /* ObjectBindingPattern */:
- return emitObjectBindingPattern(node);
- case 180 /* ArrayBindingPattern */:
- return emitArrayBindingPattern(node);
- case 181 /* BindingElement */:
- return emitBindingElement(node);
- // Misc
- case 210 /* TemplateSpan */:
- return emitTemplateSpan(node);
- case 211 /* SemicolonClassElement */:
- return emitSemicolonClassElement();
- // Statements
- case 212 /* Block */:
- return emitBlock(node);
- case 213 /* VariableStatement */:
- return emitVariableStatement(node);
- case 214 /* EmptyStatement */:
- return emitEmptyStatement();
- case 215 /* ExpressionStatement */:
- return emitExpressionStatement(node);
- case 216 /* IfStatement */:
- return emitIfStatement(node);
- case 217 /* DoStatement */:
- return emitDoStatement(node);
- case 218 /* WhileStatement */:
- return emitWhileStatement(node);
- case 219 /* ForStatement */:
- return emitForStatement(node);
- case 220 /* ForInStatement */:
- return emitForInStatement(node);
- case 221 /* ForOfStatement */:
- return emitForOfStatement(node);
- case 222 /* ContinueStatement */:
- return emitContinueStatement(node);
- case 223 /* BreakStatement */:
- return emitBreakStatement(node);
- case 224 /* ReturnStatement */:
- return emitReturnStatement(node);
- case 225 /* WithStatement */:
- return emitWithStatement(node);
- case 226 /* SwitchStatement */:
- return emitSwitchStatement(node);
- case 227 /* LabeledStatement */:
- return emitLabeledStatement(node);
- case 228 /* ThrowStatement */:
- return emitThrowStatement(node);
- case 229 /* TryStatement */:
- return emitTryStatement(node);
- case 230 /* DebuggerStatement */:
- return emitDebuggerStatement(node);
- // Declarations
- case 231 /* VariableDeclaration */:
- return emitVariableDeclaration(node);
- case 232 /* VariableDeclarationList */:
- return emitVariableDeclarationList(node);
- case 233 /* FunctionDeclaration */:
- return emitFunctionDeclaration(node);
- case 234 /* ClassDeclaration */:
- return emitClassDeclaration(node);
- case 235 /* InterfaceDeclaration */:
- return emitInterfaceDeclaration(node);
- case 236 /* TypeAliasDeclaration */:
- return emitTypeAliasDeclaration(node);
- case 237 /* EnumDeclaration */:
- return emitEnumDeclaration(node);
- case 238 /* ModuleDeclaration */:
- return emitModuleDeclaration(node);
- case 239 /* ModuleBlock */:
- return emitModuleBlock(node);
- case 240 /* CaseBlock */:
- return emitCaseBlock(node);
- case 241 /* NamespaceExportDeclaration */:
- return emitNamespaceExportDeclaration(node);
- case 242 /* ImportEqualsDeclaration */:
- return emitImportEqualsDeclaration(node);
- case 243 /* ImportDeclaration */:
- return emitImportDeclaration(node);
- case 244 /* ImportClause */:
- return emitImportClause(node);
- case 245 /* NamespaceImport */:
- return emitNamespaceImport(node);
- case 246 /* NamedImports */:
- return emitNamedImports(node);
- case 247 /* ImportSpecifier */:
- return emitImportSpecifier(node);
- case 248 /* ExportAssignment */:
- return emitExportAssignment(node);
- case 249 /* ExportDeclaration */:
- return emitExportDeclaration(node);
- case 250 /* NamedExports */:
- return emitNamedExports(node);
- case 251 /* ExportSpecifier */:
- return emitExportSpecifier(node);
- case 252 /* MissingDeclaration */:
- return;
- // Module references
- case 253 /* ExternalModuleReference */:
- return emitExternalModuleReference(node);
- // JSX (non-expression)
- case 10 /* JsxText */:
- return emitJsxText(node);
- case 256 /* JsxOpeningElement */:
- case 259 /* JsxOpeningFragment */:
- return emitJsxOpeningElementOrFragment(node);
- case 257 /* JsxClosingElement */:
- case 260 /* JsxClosingFragment */:
- return emitJsxClosingElementOrFragment(node);
- case 261 /* JsxAttribute */:
- return emitJsxAttribute(node);
- case 262 /* JsxAttributes */:
- return emitJsxAttributes(node);
- case 263 /* JsxSpreadAttribute */:
- return emitJsxSpreadAttribute(node);
- case 264 /* JsxExpression */:
- return emitJsxExpression(node);
- // Clauses
- case 265 /* CaseClause */:
- return emitCaseClause(node);
- case 266 /* DefaultClause */:
- return emitDefaultClause(node);
- case 267 /* HeritageClause */:
- return emitHeritageClause(node);
- case 268 /* CatchClause */:
- return emitCatchClause(node);
- // Property assignments
- case 269 /* PropertyAssignment */:
- return emitPropertyAssignment(node);
- case 270 /* ShorthandPropertyAssignment */:
- return emitShorthandPropertyAssignment(node);
- case 271 /* SpreadAssignment */:
- return emitSpreadAssignment(node);
- // Enum
- case 272 /* EnumMember */:
- return emitEnumMember(node);
- // JSDoc nodes (ignored)
- // Transformation nodes (ignored)
- }
- // If the node is an expression, try to emit it as an expression with
- // substitution.
- if (ts.isExpression(node)) {
- return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node));
- }
- if (ts.isToken(node)) {
- writeTokenNode(node, writePunctuation);
- return;
- }
- }
- function pipelineEmitExpression(node) {
- var kind = node.kind;
- switch (kind) {
- // Literals
- case 8 /* NumericLiteral */:
- return emitNumericLiteral(node);
- case 9 /* StringLiteral */:
- case 12 /* RegularExpressionLiteral */:
- case 13 /* NoSubstitutionTemplateLiteral */:
- return emitLiteral(node);
- // Identifiers
- case 71 /* Identifier */:
- return emitIdentifier(node);
- // Reserved words
- case 86 /* FalseKeyword */:
- case 95 /* NullKeyword */:
- case 97 /* SuperKeyword */:
- case 101 /* TrueKeyword */:
- case 99 /* ThisKeyword */:
- case 91 /* ImportKeyword */:
- writeTokenNode(node, writeKeyword);
- return;
- // Expressions
- case 182 /* ArrayLiteralExpression */:
- return emitArrayLiteralExpression(node);
- case 183 /* ObjectLiteralExpression */:
- return emitObjectLiteralExpression(node);
- case 184 /* PropertyAccessExpression */:
- return emitPropertyAccessExpression(node);
- case 185 /* ElementAccessExpression */:
- return emitElementAccessExpression(node);
- case 186 /* CallExpression */:
- return emitCallExpression(node);
- case 187 /* NewExpression */:
- return emitNewExpression(node);
- case 188 /* TaggedTemplateExpression */:
- return emitTaggedTemplateExpression(node);
- case 189 /* TypeAssertionExpression */:
- return emitTypeAssertionExpression(node);
- case 190 /* ParenthesizedExpression */:
- return emitParenthesizedExpression(node);
- case 191 /* FunctionExpression */:
- return emitFunctionExpression(node);
- case 192 /* ArrowFunction */:
- return emitArrowFunction(node);
- case 193 /* DeleteExpression */:
- return emitDeleteExpression(node);
- case 194 /* TypeOfExpression */:
- return emitTypeOfExpression(node);
- case 195 /* VoidExpression */:
- return emitVoidExpression(node);
- case 196 /* AwaitExpression */:
- return emitAwaitExpression(node);
- case 197 /* PrefixUnaryExpression */:
- return emitPrefixUnaryExpression(node);
- case 198 /* PostfixUnaryExpression */:
- return emitPostfixUnaryExpression(node);
- case 199 /* BinaryExpression */:
- return emitBinaryExpression(node);
- case 200 /* ConditionalExpression */:
- return emitConditionalExpression(node);
- case 201 /* TemplateExpression */:
- return emitTemplateExpression(node);
- case 202 /* YieldExpression */:
- return emitYieldExpression(node);
- case 203 /* SpreadElement */:
- return emitSpreadExpression(node);
- case 204 /* ClassExpression */:
- return emitClassExpression(node);
- case 205 /* OmittedExpression */:
- return;
- case 207 /* AsExpression */:
- return emitAsExpression(node);
- case 208 /* NonNullExpression */:
- return emitNonNullExpression(node);
- case 209 /* MetaProperty */:
- return emitMetaProperty(node);
- // JSX
- case 254 /* JsxElement */:
- return emitJsxElement(node);
- case 255 /* JsxSelfClosingElement */:
- return emitJsxSelfClosingElement(node);
- case 258 /* JsxFragment */:
- return emitJsxFragment(node);
- // Transformation nodes
- case 296 /* PartiallyEmittedExpression */:
- return emitPartiallyEmittedExpression(node);
- case 297 /* CommaListExpression */:
- return emitCommaList(node);
- }
+ emit(node.constraint);
}
function trySubstituteNode(hint, node) {
return node && substituteNode && substituteNode(hint, node) || node;
@@ -74151,6 +74810,10 @@ var ts;
writeStringLiteral(text);
}
}
+ // SyntaxKind.UnparsedSource
+ function emitUnparsedSource(unparsed) {
+ write(unparsed.text);
+ }
//
// Identifiers
//
@@ -74201,13 +74864,11 @@ var ts;
function emitParameter(node) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
- emitIfPresent(node.dotDotDotToken);
- if (node.name) {
- emitNodeWithWriter(node.name, writeParameter);
- }
- emitIfPresent(node.questionToken);
- if (node.parent && node.parent.kind === 281 /* JSDocFunctionType */ && !node.name) {
- emitIfPresent(node.type);
+ emit(node.dotDotDotToken);
+ emitNodeWithWriter(node.name, writeParameter);
+ emit(node.questionToken);
+ if (node.parent && node.parent.kind === 283 /* JSDocFunctionType */ && !node.name) {
+ emit(node.type);
}
else {
emitTypeAnnotation(node.type);
@@ -74226,7 +74887,7 @@ var ts;
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emitNodeWithWriter(node.name, writeProperty);
- emitIfPresent(node.questionToken);
+ emit(node.questionToken);
emitTypeAnnotation(node.type);
writeSemicolon();
}
@@ -74234,28 +74895,30 @@ var ts;
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emit(node.name);
- emitIfPresent(node.questionToken);
- emitIfPresent(node.exclamationToken);
+ emit(node.questionToken);
+ emit(node.exclamationToken);
emitTypeAnnotation(node.type);
emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
writeSemicolon();
}
function emitMethodSignature(node) {
+ pushNameGenerationScope(node);
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emit(node.name);
- emitIfPresent(node.questionToken);
+ emit(node.questionToken);
emitTypeParameters(node, node.typeParameters);
emitParameters(node, node.parameters);
emitTypeAnnotation(node.type);
writeSemicolon();
+ popNameGenerationScope(node);
}
function emitMethodDeclaration(node) {
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
- emitIfPresent(node.asteriskToken);
+ emit(node.asteriskToken);
emit(node.name);
- emitIfPresent(node.questionToken);
+ emit(node.questionToken);
emitSignatureAndBody(node, emitSignatureHead);
}
function emitConstructor(node) {
@@ -74272,14 +74935,17 @@ var ts;
emitSignatureAndBody(node, emitSignatureHead);
}
function emitCallSignature(node) {
+ pushNameGenerationScope(node);
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
emitTypeParameters(node, node.typeParameters);
emitParameters(node, node.parameters);
emitTypeAnnotation(node.type);
writeSemicolon();
+ popNameGenerationScope(node);
}
function emitConstructSignature(node) {
+ pushNameGenerationScope(node);
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
writeKeyword("new");
@@ -74288,6 +74954,7 @@ var ts;
emitParameters(node, node.parameters);
emitTypeAnnotation(node.type);
writeSemicolon();
+ popNameGenerationScope(node);
}
function emitIndexSignature(node) {
emitDecorators(node, node.decorators);
@@ -74314,18 +74981,20 @@ var ts;
emitTypeArguments(node, node.typeArguments);
}
function emitFunctionType(node) {
+ pushNameGenerationScope(node);
emitTypeParameters(node, node.typeParameters);
emitParametersForArrow(node, node.parameters);
writeSpace();
writePunctuation("=>");
writeSpace();
- emitIfPresent(node.type);
+ emit(node.type);
+ popNameGenerationScope(node);
}
function emitJSDocFunctionType(node) {
write("function");
emitParameters(node, node.parameters);
write(":");
- emitIfPresent(node.type);
+ emit(node.type);
}
function emitJSDocNullableType(node) {
write("?");
@@ -74340,6 +75009,7 @@ var ts;
write("=");
}
function emitConstructorType(node) {
+ pushNameGenerationScope(node);
writeKeyword("new");
writeSpace();
emitTypeParameters(node, node.typeParameters);
@@ -74347,7 +75017,8 @@ var ts;
writeSpace();
writePunctuation("=>");
writeSpace();
- emitIfPresent(node.type);
+ emit(node.type);
+ popNameGenerationScope(node);
}
function emitTypeQuery(node) {
writeKeyword("typeof");
@@ -74437,7 +75108,8 @@ var ts;
writeSpace();
}
writePunctuation("[");
- pipelineEmitWithNotification(3 /* MappedTypeParameter */, node.typeParameter);
+ var pipelinePhase = getPipelinePhase(0 /* Notification */, 3 /* MappedTypeParameter */);
+ pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter);
writePunctuation("]");
if (node.questionToken) {
emit(node.questionToken);
@@ -74447,7 +75119,7 @@ var ts;
}
writePunctuation(":");
writeSpace();
- emitIfPresent(node.type);
+ emit(node.type);
writeSemicolon();
if (emitFlags & 1 /* SingleLine */) {
writeSpace();
@@ -74490,7 +75162,7 @@ var ts;
writePunctuation("]");
}
function emitBindingElement(node) {
- emitIfPresent(node.dotDotDotToken);
+ emit(node.dotDotDotToken);
if (node.propertyName) {
emit(node.propertyName);
writePunctuation(":");
@@ -74508,6 +75180,7 @@ var ts;
emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine);
}
function emitObjectLiteralExpression(node) {
+ ts.forEach(node.properties, generateMemberNames);
var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
if (indentedFlag) {
increaseIndent();
@@ -74597,6 +75270,7 @@ var ts;
emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
}
function emitFunctionExpression(node) {
+ generateNameIfNeeded(node.name);
emitFunctionDeclarationOrExpression(node);
}
function emitArrowFunction(node) {
@@ -74696,7 +75370,7 @@ var ts;
}
function emitYieldExpression(node) {
emitTokenWithComment(116 /* YieldKeyword */, node.pos, writeKeyword, node);
- emitIfPresent(node.asteriskToken);
+ emit(node.asteriskToken);
emitExpressionWithLeadingSpace(node.expression);
}
function emitSpreadExpression(node) {
@@ -74704,6 +75378,7 @@ var ts;
emitExpression(node.expression);
}
function emitClassExpression(node) {
+ generateNameIfNeeded(node.name);
emitClassDeclarationOrExpression(node);
}
function emitExpressionWithTypeArguments(node) {
@@ -74757,7 +75432,9 @@ var ts;
}
function emitExpressionStatement(node) {
emitExpression(node.expression);
- writeSemicolon();
+ if (!ts.isJsonSourceFile(currentSourceFile)) {
+ writeSemicolon();
+ }
}
function emitIfStatement(node) {
var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node);
@@ -74953,7 +75630,7 @@ var ts;
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
writeKeyword("function");
- emitIfPresent(node.asteriskToken);
+ emit(node.asteriskToken);
writeSpace();
emitIdentifierName(node.name);
emitSignatureAndBody(node, emitSignatureHead);
@@ -74970,6 +75647,8 @@ var ts;
increaseIndent();
}
pushNameGenerationScope(node);
+ ts.forEach(node.parameters, generateNames);
+ generateNames(node.body);
emitSignatureHead(node);
if (onEmitNode) {
onEmitNode(4 /* Unspecified */, body, emitBlockCallback);
@@ -75065,6 +75744,7 @@ var ts;
emitClassDeclarationOrExpression(node);
}
function emitClassDeclarationOrExpression(node) {
+ ts.forEach(node.members, generateMemberNames);
emitDecorators(node, node.decorators);
emitModifiers(node, node.modifiers);
writeKeyword("class");
@@ -75142,6 +75822,7 @@ var ts;
}
function emitModuleBlock(node) {
pushNameGenerationScope(node);
+ ts.forEach(node.statements, generateNames);
emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
popNameGenerationScope(node);
}
@@ -75183,12 +75864,12 @@ var ts;
writeSemicolon();
}
function emitImportClause(node) {
- emitIfPresent(node.name);
+ emit(node.name);
if (node.name && node.namedBindings) {
emitTokenWithComment(26 /* CommaToken */, node.name.end, writePunctuation, node);
writeSpace();
}
- emitIfPresent(node.namedBindings);
+ emit(node.namedBindings);
}
function emitNamespaceImport(node) {
var asPos = emitTokenWithComment(39 /* AsteriskToken */, node.pos, writePunctuation, node);
@@ -75330,7 +76011,7 @@ var ts;
function emitJsxExpression(node) {
if (node.expression) {
writePunctuation("{");
- emitIfPresent(node.dotDotDotToken);
+ emit(node.dotDotDotToken);
emitExpression(node.expression);
writePunctuation("}");
}
@@ -75495,6 +76176,7 @@ var ts;
function emitSourceFileWorker(node) {
var statements = node.statements;
pushNameGenerationScope(node);
+ ts.forEach(node.statements, generateNames);
emitHelpers(node);
var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
emitTripleSlashDirectivesIfNeeded(node);
@@ -75571,6 +76253,8 @@ var ts;
// Helpers
//
function emitNodeWithWriter(node, writer) {
+ if (!node)
+ return;
var savedWrite = write;
write = writer;
emit(node);
@@ -76060,7 +76744,7 @@ var ts;
if (ts.isGeneratedIdentifier(node)) {
return generateName(node);
}
- else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
+ else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) {
return ts.idText(node);
}
else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) {
@@ -76112,6 +76796,113 @@ var ts;
}
reservedNames.set(name, true);
}
+ function generateNames(node) {
+ if (!node)
+ return;
+ switch (node.kind) {
+ case 212 /* Block */:
+ ts.forEach(node.statements, generateNames);
+ break;
+ case 227 /* LabeledStatement */:
+ case 225 /* WithStatement */:
+ case 217 /* DoStatement */:
+ case 218 /* WhileStatement */:
+ generateNames(node.statement);
+ break;
+ case 216 /* IfStatement */:
+ generateNames(node.thenStatement);
+ generateNames(node.elseStatement);
+ break;
+ case 219 /* ForStatement */:
+ case 221 /* ForOfStatement */:
+ case 220 /* ForInStatement */:
+ generateNames(node.initializer);
+ generateNames(node.statement);
+ break;
+ case 226 /* SwitchStatement */:
+ generateNames(node.caseBlock);
+ break;
+ case 240 /* CaseBlock */:
+ ts.forEach(node.clauses, generateNames);
+ break;
+ case 265 /* CaseClause */:
+ case 266 /* DefaultClause */:
+ ts.forEach(node.statements, generateNames);
+ break;
+ case 229 /* TryStatement */:
+ generateNames(node.tryBlock);
+ generateNames(node.catchClause);
+ generateNames(node.finallyBlock);
+ break;
+ case 268 /* CatchClause */:
+ generateNames(node.variableDeclaration);
+ generateNames(node.block);
+ break;
+ case 213 /* VariableStatement */:
+ generateNames(node.declarationList);
+ break;
+ case 232 /* VariableDeclarationList */:
+ ts.forEach(node.declarations, generateNames);
+ break;
+ case 231 /* VariableDeclaration */:
+ case 148 /* Parameter */:
+ case 181 /* BindingElement */:
+ case 234 /* ClassDeclaration */:
+ generateNameIfNeeded(node.name);
+ break;
+ case 233 /* FunctionDeclaration */:
+ generateNameIfNeeded(node.name);
+ if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
+ ts.forEach(node.parameters, generateNames);
+ generateNames(node.body);
+ }
+ break;
+ case 179 /* ObjectBindingPattern */:
+ case 180 /* ArrayBindingPattern */:
+ ts.forEach(node.elements, generateNames);
+ break;
+ case 243 /* ImportDeclaration */:
+ generateNames(node.importClause);
+ break;
+ case 244 /* ImportClause */:
+ generateNameIfNeeded(node.name);
+ generateNames(node.namedBindings);
+ break;
+ case 245 /* NamespaceImport */:
+ generateNameIfNeeded(node.name);
+ break;
+ case 246 /* NamedImports */:
+ ts.forEach(node.elements, generateNames);
+ break;
+ case 247 /* ImportSpecifier */:
+ generateNameIfNeeded(node.propertyName || node.name);
+ break;
+ }
+ }
+ function generateMemberNames(node) {
+ if (!node)
+ return;
+ switch (node.kind) {
+ case 269 /* PropertyAssignment */:
+ case 270 /* ShorthandPropertyAssignment */:
+ case 151 /* PropertyDeclaration */:
+ case 153 /* MethodDeclaration */:
+ case 155 /* GetAccessor */:
+ case 156 /* SetAccessor */:
+ generateNameIfNeeded(node.name);
+ break;
+ }
+ }
+ function generateNameIfNeeded(name) {
+ if (name) {
+ if (ts.isGeneratedIdentifier(name)) {
+ generateName(name);
+ }
+ else if (ts.isBindingPattern(name)) {
+ generateNames(name);
+ }
+ }
+ }
/**
* Generate the text for a generated identifier.
*/
@@ -76119,17 +76910,7 @@ var ts;
if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) {
// Node names generate unique names based on their original node
// and are cached based on that node's id.
- if (name.autoGenerateFlags & 8 /* SkipNameGenerationScope */) {
- var savedTempFlags = tempFlags;
- popNameGenerationScope(/*node*/ undefined);
- var result = generateNameCached(getNodeForGeneratedName(name));
- pushNameGenerationScope(/*node*/ undefined);
- tempFlags = savedTempFlags;
- return result;
- }
- else {
- return generateNameCached(getNodeForGeneratedName(name));
- }
+ return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags);
}
else {
// Auto, Loop, and Unique names are cached based on their unique
@@ -76138,9 +76919,9 @@ var ts;
return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
}
}
- function generateNameCached(node) {
+ function generateNameCached(node, flags) {
var nodeId = ts.getNodeId(node);
- return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node));
+ return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags));
}
/**
* Returns a value indicating whether a name is unique globally, within the current file,
@@ -76155,7 +76936,7 @@ var ts;
* Returns a value indicating whether a name is unique globally or within the current file.
*/
function isFileLevelUniqueName(name) {
- return ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName);
+ return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
}
/**
* Returns a value indicating whether a name is unique within a container.
@@ -76212,11 +76993,16 @@ var ts;
* makeUniqueName are guaranteed to never conflict.
* If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1'
*/
- function makeUniqueName(baseName, checkFn, optimistic) {
+ function makeUniqueName(baseName, checkFn, optimistic, scoped) {
if (checkFn === void 0) { checkFn = isUniqueName; }
if (optimistic) {
if (checkFn(baseName)) {
- generatedNames.set(baseName, true);
+ if (scoped) {
+ reserveNameInNestedScopes(baseName);
+ }
+ else {
+ generatedNames.set(baseName, true);
+ }
return baseName;
}
}
@@ -76228,7 +77014,12 @@ var ts;
while (true) {
var generatedName = baseName + i;
if (checkFn(generatedName)) {
- generatedNames.set(generatedName, true);
+ if (scoped) {
+ reserveNameInNestedScopes(generatedName);
+ }
+ else {
+ generatedNames.set(generatedName, true);
+ }
return generatedName;
}
i++;
@@ -76275,10 +77066,10 @@ var ts;
/**
* Generates a unique name from a node.
*/
- function generateNameForNode(node) {
+ function generateNameForNode(node, flags) {
switch (node.kind) {
case 71 /* Identifier */:
- return makeUniqueName(getTextOfNode(node));
+ return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */));
case 238 /* ModuleDeclaration */:
case 237 /* EnumDeclaration */:
return generateNameForModuleOrEnum(node);
@@ -76305,11 +77096,11 @@ var ts;
function makeName(name) {
switch (name.autoGenerateFlags & 7 /* KindMask */) {
case 1 /* Auto */:
- return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */));
+ return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
case 2 /* Loop */:
- return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */));
+ return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
case 3 /* Unique */:
- return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 64 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 32 /* Optimistic */));
+ return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
}
ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
}
@@ -76325,7 +77116,7 @@ var ts;
// if "node" is a different generated name (having a different
// "autoGenerateId"), use it and stop traversing.
if (ts.isIdentifier(node)
- && node.autoGenerateFlags === 4 /* Node */
+ && !!(node.autoGenerateFlags & 4 /* Node */)
&& node.autoGenerateId !== autoGenerateId) {
break;
}
@@ -76384,7 +77175,7 @@ var ts;
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
}
function getCachedFileSystemEntries(rootDirPath) {
- return cachedReadDirectoryResult.get(rootDirPath);
+ return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath));
}
function getCachedFileSystemEntriesForBaseDir(path) {
return getCachedFileSystemEntries(ts.getDirectoryPath(path));
@@ -76397,7 +77188,7 @@ var ts;
files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [],
directories: host.getDirectories(rootDir) || []
};
- cachedReadDirectoryResult.set(rootDirPath, resultFromHost);
+ cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
return resultFromHost;
}
/**
@@ -76406,6 +77197,7 @@ var ts;
* The host request is done under try catch block to avoid caching incorrect result
*/
function tryReadDirectory(rootDir, rootDirPath) {
+ rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath);
var cachedResult = getCachedFileSystemEntries(rootDirPath);
if (cachedResult) {
return cachedResult;
@@ -76415,7 +77207,7 @@ var ts;
}
catch (_e) {
// If there is exception to read directories, dont cache the result and direct the calls to host
- ts.Debug.assert(!cachedReadDirectoryResult.has(rootDirPath));
+ ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath)));
return undefined;
}
}
@@ -76451,7 +77243,7 @@ var ts;
}
function directoryExists(dirPath) {
var path = toPath(dirPath);
- return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath);
+ return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
}
function createDirectory(dirPath) {
var path = toPath(dirPath);
@@ -76725,7 +77517,7 @@ var ts;
if (!commonPathComponents) { // Can happen when all input files are .d.ts files
return currentDirectory;
}
- return ts.getNormalizedPathFromPathComponents(commonPathComponents);
+ return ts.getPathFromPathComponents(commonPathComponents);
}
ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
function createCompilerHost(options, setParentNodes) {
@@ -76832,7 +77624,8 @@ var ts;
directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); },
getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; },
getDirectories: function (path) { return ts.sys.getDirectories(path); },
- realpath: realpath
+ realpath: realpath,
+ readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }
};
}
ts.createCompilerHost = createCompilerHost;
@@ -76900,52 +77693,52 @@ var ts;
var output = "";
for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
var diagnostic = diagnostics_2[_i];
- var context = "";
+ var context_2 = "";
if (diagnostic.file) {
- var start = diagnostic.start, length_4 = diagnostic.length, file = diagnostic.file;
- var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
- var _b = ts.getLineAndCharacterOfPosition(file, start + length_4), lastLine = _b.line, lastLineChar = _b.character;
- var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
- var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
+ var start = diagnostic.start, length_4 = diagnostic.length, file_8 = diagnostic.file;
+ var _a = ts.getLineAndCharacterOfPosition(file_8, start), firstLine = _a.line, firstLineChar = _a.character;
+ var _b = ts.getLineAndCharacterOfPosition(file_8, start + length_4), lastLine = _b.line, lastLineChar = _b.character;
+ var lastLineInFile = ts.getLineAndCharacterOfPosition(file_8, file_8.text.length).line;
+ var relativeFileName = host ? ts.convertToRelativePath(file_8.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file_8.fileName;
var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
var gutterWidth = (lastLine + 1 + "").length;
if (hasMoreThanFiveLines) {
gutterWidth = Math.max(ellipsis.length, gutterWidth);
}
for (var i = firstLine; i <= lastLine; i++) {
- context += host.getNewLine();
+ context_2 += host.getNewLine();
// If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
// so we'll skip ahead to the second-to-last line.
if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
- context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
+ context_2 += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
i = lastLine - 1;
}
- var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0);
- var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
- var lineContent = file.text.slice(lineStart, lineEnd);
+ var lineStart = ts.getPositionOfLineAndCharacter(file_8, i, 0);
+ var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file_8, i + 1, 0) : file_8.text.length;
+ var lineContent = file_8.text.slice(lineStart, lineEnd);
lineContent = lineContent.replace(/\s+$/g, ""); // trim from end
lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces
// Output the gutter and the actual contents of the line.
- context += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
- context += lineContent + host.getNewLine();
+ context_2 += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
+ context_2 += lineContent + host.getNewLine();
// Output the gutter and the error span for the line using tildes.
- context += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
- context += ForegroundColorEscapeSequences.Red;
+ context_2 += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
+ context_2 += ForegroundColorEscapeSequences.Red;
if (i === firstLine) {
// If we're on the last line, then limit it to the last character of the last line.
// Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
var lastCharForLine = i === lastLine ? lastLineChar : undefined;
- context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
- context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
+ context_2 += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
+ context_2 += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
}
else if (i === lastLine) {
- context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
+ context_2 += lineContent.slice(0, lastLineChar).replace(/./g, "~");
}
else {
// Squiggle the entire line.
- context += lineContent.replace(/./g, "~");
+ context_2 += lineContent.replace(/./g, "~");
}
- context += resetEscapeSequence;
+ context_2 += resetEscapeSequence;
}
output += formatColorAndReset(relativeFileName, ForegroundColorEscapeSequences.Cyan);
output += ":";
@@ -76959,7 +77752,7 @@ var ts;
output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
if (diagnostic.file) {
output += host.getNewLine();
- output += context;
+ output += context_2;
}
output += host.getNewLine();
}
@@ -77069,21 +77862,19 @@ var ts;
oldOptions.baseUrl !== newOptions.baseUrl ||
!ts.equalOwnProperties(oldOptions.paths, newOptions.paths));
}
- /**
- * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions'
- * that represent a compilation unit.
- *
- * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and
- * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in.
- *
- * @param rootNames - A set of root files.
- * @param options - The compiler options which should be used.
- * @param host - The host interacts with the underlying file system.
- * @param oldProgram - Reuses an old program structure.
- * @param configFileParsingDiagnostics - error during config file parsing
- * @returns A 'Program' object.
- */
- function createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
+ function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
+ return {
+ rootNames: rootNames,
+ options: options,
+ host: host,
+ oldProgram: oldProgram,
+ configFileParsingDiagnostics: configFileParsingDiagnostics
+ };
+ }
+ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
+ var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions;
+ var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
+ var host = createProgramOptions.host, oldProgram = createProgramOptions.oldProgram;
var program;
var files = [];
var commonSourceDirectory;
@@ -77111,6 +77902,7 @@ var ts;
var sourceFilesFoundSearchingNodeModules = ts.createMap();
ts.performance.mark("beforeProgram");
host = host || createCompilerHost(options);
+ var configParsingHost = parseConfigHostFromCompilerHost(host);
var skipDefaultLib = options.noLib;
var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); });
var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName());
@@ -77120,6 +77912,7 @@ var ts;
// Map storing if there is emit blocking diagnostics for given input
var hasEmitBlockingDiagnostics = ts.createMap();
var _compilerOptionsObjectLiteralSyntax;
+ var _referencesArrayLiteralSyntax;
var moduleResolutionCache;
var resolveModuleNamesWorker;
var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
@@ -77159,6 +77952,23 @@ var ts;
// stores 'filename -> file association' ignoring case
// used to track cases when two file names differ only in casing
var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined;
+ // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
+ var resolvedProjectReferences = projectReferences ? [] : undefined;
+ var projectReferenceRedirects = ts.createMap();
+ if (projectReferences) {
+ for (var _i = 0, projectReferences_1 = projectReferences; _i < projectReferences_1.length; _i++) {
+ var ref = projectReferences_1[_i];
+ var parsedRef = parseProjectReferenceConfigFile(ref);
+ resolvedProjectReferences.push(parsedRef);
+ if (parsedRef) {
+ if (parsedRef.commandLine.options.outFile) {
+ var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts");
+ processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*packageId*/ undefined);
+ }
+ addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects);
+ }
+ }
+ }
var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
var structuralIsReused = tryReuseStructureFromOldProgram();
if (structuralIsReused !== 2 /* Completely */) {
@@ -77198,8 +78008,8 @@ var ts;
// not part of the new program.
if (oldProgram && host.onReleaseOldSourceFile) {
var oldSourceFiles = oldProgram.getSourceFiles();
- for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) {
- var oldSourceFile = oldSourceFiles_1[_i];
+ for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) {
+ var oldSourceFile = oldSourceFiles_1[_a];
if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) {
host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions());
}
@@ -77240,6 +78050,7 @@ var ts;
isEmittedFile: isEmittedFile,
getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics,
getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
+ getProjectReferences: getProjectReferences
};
verifyCompilerOptions();
ts.performance.mark("afterProgram");
@@ -77255,9 +78066,14 @@ var ts;
if (commonSourceDirectory === undefined) {
var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); });
if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
- // If a rootDir is specified and is valid use it as the commonSourceDirectory
+ // If a rootDir is specified use it as the commonSourceDirectory
commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
}
+ else if (options.composite) {
+ // Project compilations never infer their root from the input source paths
+ commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
+ checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory);
+ }
else {
commonSourceDirectory = computeCommonSourceDirectory(emittedFiles);
}
@@ -77295,16 +78111,16 @@ var ts;
// We only set `file.resolvedModules` via work from the current function,
// so it is defined iff we already called the current function on `file`.
// That call happened no later than the creation of the `file` object,
- // which per above occured during the current program creation.
+ // which per above occurred during the current program creation.
// Since we assume the filesystem does not change during program creation,
// it is safe to reuse resolutions from the earlier call.
- var result_3 = [];
+ var result_4 = [];
for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
var moduleName = moduleNames_1[_i];
var resolvedModule = file.resolvedModules.get(moduleName);
- result_3.push(resolvedModule);
+ result_4.push(resolvedModule);
}
- return result_3;
+ return result_4;
}
// At this point, we know at least one of the following hold:
// - file has local declarations for ambient modules
@@ -77435,6 +78251,34 @@ var ts;
if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) {
return oldProgram.structureIsReused = 0 /* Not */;
}
+ // Check if any referenced project tsconfig files are different
+ var oldRefs = oldProgram.getProjectReferences();
+ if (projectReferences) {
+ if (!oldRefs) {
+ return oldProgram.structureIsReused = 0 /* Not */;
+ }
+ for (var i = 0; i < projectReferences.length; i++) {
+ var oldRef = oldRefs[i];
+ if (oldRef) {
+ var newRef = parseProjectReferenceConfigFile(projectReferences[i]);
+ if (!newRef || newRef.sourceFile !== oldRef.sourceFile) {
+ // Resolved project reference has gone missing or changed
+ return oldProgram.structureIsReused = 0 /* Not */;
+ }
+ }
+ else {
+ // A previously-unresolved reference may be resolved now
+ if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) {
+ return oldProgram.structureIsReused = 0 /* Not */;
+ }
+ }
+ }
+ }
+ else {
+ if (oldRefs) {
+ return oldProgram.structureIsReused = 0 /* Not */;
+ }
+ }
// check if program source files has changed in the way that can affect structure of the program
var newSourceFiles = [];
var filePaths = [];
@@ -77602,6 +78446,7 @@ var ts;
}
function getEmitHost(writeFileCallback) {
return {
+ getPrependNodes: getPrependNodes,
getCanonicalFileName: getCanonicalFileName,
getCommonSourceDirectory: program.getCommonSourceDirectory,
getCompilerOptions: program.getCompilerOptions,
@@ -77615,6 +78460,32 @@ var ts;
isEmitBlocked: isEmitBlocked,
};
}
+ function getProjectReferences() {
+ if (!resolvedProjectReferences)
+ return;
+ return resolvedProjectReferences;
+ }
+ 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) {
+ // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
+ if (!resolvedRefOpts.options.outFile)
+ continue;
+ var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts");
+ var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n";
+ var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n";
+ var node = ts.createInputFiles(js, dts);
+ nodes.push(node);
+ }
+ }
+ return nodes;
+ }
function isSourceFileFromExternalLibrary(file) {
return sourceFilesFoundSearchingNodeModules.get(file.path);
}
@@ -77685,7 +78556,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, emitOnlyDtsFiles, transformers);
+ 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;
@@ -77769,9 +78640,9 @@ var ts;
var typeChecker = getDiagnosticsProducingTypeChecker();
ts.Debug.assert(!!sourceFile.bindDiagnostics);
var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options);
- // By default, only type-check .ts, .tsx, and 'External' files (external files are added by plugins)
+ // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ ||
- sourceFile.scriptKind === 5 /* External */ || isCheckJs;
+ sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */;
var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray;
var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray;
var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
@@ -78147,7 +79018,13 @@ var ts;
var sourceFile = getSourceFile(fileName);
if (fail) {
if (!sourceFile) {
- fail(ts.Diagnostics.File_0_not_found, fileName);
+ var redirect = getProjectReferenceRedirect(fileName);
+ if (redirect) {
+ fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
+ }
+ else {
+ fail(ts.Diagnostics.File_0_not_found, fileName);
+ }
}
else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) {
fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
@@ -78208,31 +79085,45 @@ var ts;
// Get source file from normalized fileName
function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd, packageId) {
if (filesByName.has(path)) {
- var file_1 = filesByName.get(path);
+ var file_9 = filesByName.get(path);
// try to check if we've already seen this file but with a different casing in path
// NOTE: this only makes sense for case-insensitive file systems
- if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
- reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd);
+ if (file_9 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_9.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) {
+ reportFileNamesDifferOnlyInCasingError(fileName, file_9.fileName, refFile, refPos, refEnd);
}
// If the file was previously found via a node_modules search, but is now being processed as a root file,
// then everything it sucks in may also be marked incorrectly, and needs to be checked again.
- if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) {
- sourceFilesFoundSearchingNodeModules.set(file_1.path, false);
+ if (file_9 && sourceFilesFoundSearchingNodeModules.get(file_9.path) && currentNodeModulesDepth === 0) {
+ sourceFilesFoundSearchingNodeModules.set(file_9.path, false);
if (!options.noResolve) {
- processReferencedFiles(file_1, isDefaultLib);
- processTypeReferenceDirectives(file_1);
+ processReferencedFiles(file_9, isDefaultLib);
+ processTypeReferenceDirectives(file_9);
}
- modulesWithElidedImports.set(file_1.path, false);
- processImportedModules(file_1);
+ modulesWithElidedImports.set(file_9.path, false);
+ processImportedModules(file_9);
}
// See if we need to reprocess the imports due to prior skipped imports
- else if (file_1 && modulesWithElidedImports.get(file_1.path)) {
+ else if (file_9 && modulesWithElidedImports.get(file_9.path)) {
if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
- modulesWithElidedImports.set(file_1.path, false);
- processImportedModules(file_1);
+ modulesWithElidedImports.set(file_9.path, false);
+ processImportedModules(file_9);
}
}
- return file_1;
+ return file_9;
+ }
+ var redirectedPath;
+ if (refFile) {
+ var redirect = getProjectReferenceRedirect(fileName);
+ if (redirect) {
+ (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName);
+ fileName = redirect;
+ // Once we start redirecting to a file, we can potentially come back to it
+ // via a back-reference from another file in the .d.ts folder. If that happens we'll
+ // end up trying to add it to the program *again* because we were tracking it via its
+ // original (un-redirected) name. So we have to map both the original path and the redirected path
+ // to the source file we're about to find/create
+ redirectedPath = toPath(redirect);
+ }
}
// We haven't looked for this file, do so now and cache result
var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) {
@@ -78263,6 +79154,9 @@ var ts;
}
}
filesByName.set(path, file);
+ if (redirectedPath) {
+ filesByName.set(redirectedPath, file);
+ }
if (file) {
sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
file.path = path;
@@ -78293,6 +79187,22 @@ var ts;
}
return file;
}
+ function getProjectReferenceRedirect(fileName) {
+ var path = toPath(fileName);
+ // If this file is produced by a referenced project, we need to rewrite it to
+ // look in the output folder of the referenced project rather than the input
+ var normalized = ts.getNormalizedAbsolutePath(fileName, path);
+ var result;
+ projectReferenceRedirects.forEach(function (v, k) {
+ if (result !== undefined) {
+ return undefined;
+ }
+ if (normalized.indexOf(k) === 0) {
+ result = ts.changeExtension(fileName.replace(k, v), ".d.ts");
+ }
+ });
+ return result;
+ }
function processReferencedFiles(file, isDefaultLib) {
ts.forEach(file.referencedFiles, function (ref) {
var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName);
@@ -78302,6 +79212,9 @@ var ts;
function processTypeReferenceDirectives(file) {
// We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); });
+ if (!typeDirectives) {
+ return;
+ }
var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName);
for (var i = 0; i < typeDirectives.length; i++) {
var ref = file.typeReferenceDirectives[i];
@@ -78381,7 +79294,7 @@ var ts;
continue;
}
var isFromNodeModulesSearch = resolution.isExternalLibraryImport;
- var isJsFile = !ts.extensionIsTypeScript(resolution.extension);
+ var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension);
var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
var resolvedFileName = resolution.resolvedFileName;
if (isFromNodeModulesSearch) {
@@ -78423,9 +79336,9 @@ var ts;
function computeCommonSourceDirectory(sourceFiles) {
var fileNames = [];
for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
- var file = sourceFiles_2[_i];
- if (!file.isDeclarationFile) {
- fileNames.push(file.fileName);
+ var file_10 = sourceFiles_2[_i];
+ if (!file_10.isDeclarationFile) {
+ fileNames.push(file_10.fileName);
}
}
return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
@@ -78447,6 +79360,27 @@ var ts;
}
return allFilesBelongToPath;
}
+ function parseProjectReferenceConfigFile(ref) {
+ // The actual filename (i.e. add "/tsconfig.json" if necessary)
+ var refPath = resolveProjectReferencePath(host, ref);
+ // An absolute path pointing to the containing directory of the config file
+ var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
+ var sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
+ if (sourceFile === undefined) {
+ return undefined;
+ }
+ var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath);
+ return { commandLine: commandLine, sourceFile: sourceFile };
+ }
+ function addProjectReferenceRedirects(referencedProject, target) {
+ var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath));
+ target.set(rootDir, getDeclarationOutputDirectory(referencedProject));
+ }
+ function getDeclarationOutputDirectory(proj) {
+ return proj.options.declarationDir ||
+ proj.options.outDir ||
+ ts.getDirectoryPath(proj.options.configFilePath);
+ }
function verifyCompilerOptions() {
if (options.strictPropertyInitialization && !options.strictNullChecks) {
createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
@@ -78476,6 +79410,48 @@ var ts;
if (options.paths && options.baseUrl === undefined) {
createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths");
}
+ if (options.composite) {
+ if (options.declaration === false) {
+ createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
+ }
+ }
+ if (projectReferences) {
+ for (var i = 0; i < projectReferences.length; i++) {
+ var ref = projectReferences[i];
+ var resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options;
+ if (resolvedRefOpts === undefined) {
+ createDiagnosticForReference(i, ts.Diagnostics.File_0_does_not_exist, ref.path);
+ continue;
+ }
+ if (!resolvedRefOpts.composite) {
+ createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
+ }
+ if (ref.prepend) {
+ if (resolvedRefOpts.outFile) {
+ if (!host.fileExists(resolvedRefOpts.outFile)) {
+ createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path);
+ }
+ }
+ else {
+ createDiagnosticForReference(i, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
+ }
+ }
+ }
+ }
+ // List of collected files is complete; validate exhautiveness if this is a project with a file list
+ if (options.composite && rootNames.length < files.length) {
+ var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); });
+ var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); });
+ var _loop_9 = function (file_11) {
+ if (normalizedRootNames.every(function (r) { return r !== file_11; })) {
+ programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file_11));
+ }
+ };
+ for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
+ var file_11 = sourceFiles_4[_i];
+ _loop_9(file_11);
+ }
+ }
if (options.paths) {
for (var key in options.paths) {
if (!ts.hasProperty(options.paths, key)) {
@@ -78567,6 +79543,11 @@ var ts;
programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile"));
}
}
+ if (options.resolveJsonModule) {
+ if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
+ createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
+ }
+ }
// there has to be common source directory if user specified --outdir || --sourceRoot
// if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
if (options.outDir || // there is --outDir specified
@@ -78679,12 +79660,15 @@ var ts;
programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0));
}
}
- function getOptionPathsSyntax() {
+ function getOptionsSyntaxByName(name) {
var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
if (compilerOptionsObjectLiteralSyntax) {
- return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths");
+ return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
}
- return ts.emptyArray;
+ return undefined;
+ }
+ function getOptionPathsSyntax() {
+ return getOptionsSyntaxByName("paths") || ts.emptyArray;
}
function createDiagnosticForOptionName(message, option1, option2, option3) {
createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
@@ -78692,6 +79676,15 @@ var ts;
function createOptionValueDiagnostic(option1, message, arg0) {
createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0);
}
+ function createDiagnosticForReference(index, message, arg0, arg1) {
+ var referencesSyntax = getProjectReferencesSyntax();
+ if (referencesSyntax) {
+ if (createOptionDiagnosticInArrayLiteralSyntax(referencesSyntax, index, message, arg0, arg1)) {
+ return;
+ }
+ }
+ programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1));
+ }
function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) {
var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
@@ -78700,11 +79693,28 @@ var ts;
programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
}
}
+ function getProjectReferencesSyntax() {
+ if (_referencesArrayLiteralSyntax === undefined) {
+ _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword
+ if (options.configFile) {
+ var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
+ for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) {
+ var prop = _a[_i];
+ if (ts.isArrayLiteralExpression(prop.initializer)) {
+ _referencesArrayLiteralSyntax = prop.initializer;
+ break;
+ }
+ }
+ }
+ }
+ return _referencesArrayLiteralSyntax;
+ }
function getCompilerOptionsObjectLiteralSyntax() {
if (_compilerOptionsObjectLiteralSyntax === undefined) {
_compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword
- if (options.configFile && options.configFile.jsonObject) {
- for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) {
+ var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
+ if (jsonObjectLiteral) {
+ for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
var prop = _a[_i];
if (ts.isObjectLiteralExpression(prop.initializer)) {
_compilerOptionsObjectLiteralSyntax = prop.initializer;
@@ -78723,6 +79733,13 @@ var ts;
}
return !!props.length;
}
+ function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral, index, message, arg0, arg1, arg2) {
+ if (arrayLiteral.elements.length <= index) {
+ // Out-of-bounds
+ return false;
+ }
+ programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2));
+ }
function blockEmittingOfFile(emitFileName, diag) {
hasEmitBlockingDiagnostics.set(toPath(emitFileName), true);
programDiagnostics.add(diag);
@@ -78759,6 +79776,27 @@ var ts;
}
ts.createProgram = createProgram;
/* @internal */
+ function parseConfigHostFromCompilerHost(host) {
+ return {
+ fileExists: function (f) { return host.fileExists(f); },
+ readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; },
+ readFile: function (f) { return host.readFile(f); },
+ useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
+ getCurrentDirectory: function () { return host.getCurrentDirectory(); },
+ onUnRecoverableConfigFileDiagnostic: function () { return undefined; }
+ };
+ }
+ ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost;
+ /**
+ * Returns the target config filename of a project reference
+ */
+ function resolveProjectReferencePath(host, ref) {
+ if (!host.fileExists(ref.path)) {
+ return ts.combinePaths(ref.path, "tsconfig.json");
+ }
+ return ref.path;
+ }
+ /* @internal */
/**
* Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
* The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
@@ -78769,6 +79807,7 @@ var ts;
switch (extension) {
case ".ts" /* Ts */:
case ".d.ts" /* Dts */:
+ case ".json" /* Json */: // Since module is resolved to json file only when --resolveJsonModule, we dont need further check
// These are always allowed.
return undefined;
case ".tsx" /* Tsx */:
@@ -78969,6 +80008,7 @@ var ts;
* Get all the dependencies of the sourceFile
*/
function getAllDependencies(state, programOfThisState, sourceFile) {
+ var _a;
var compilerOptions = programOfThisState.getCompilerOptions();
// With --out or --outFile all outputs go into single file, all files depend on each other
if (compilerOptions.outFile || compilerOptions.out) {
@@ -78988,7 +80028,7 @@ var ts;
var references = state.referencedMap.get(path);
if (references) {
var iterator = references.keys();
- for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) {
queue.push(value);
}
}
@@ -78998,7 +80038,6 @@ var ts;
var file = programOfThisState.getSourceFileByPath(path);
return file ? file.fileName : path;
}));
- var _b;
}
BuilderState.getAllDependencies = getAllDependencies;
/**
@@ -79443,8 +80482,8 @@ var ts;
}
var diagnostics;
for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) {
- var sourceFile_1 = _a[_i];
- diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
+ var sourceFile_2 = _a[_i];
+ diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken));
}
return diagnostics || ts.emptyArray;
}
@@ -79741,17 +80780,19 @@ var ts;
return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath));
}
// Use some ancestor of the root directory
+ var subDirectory;
if (rootPath !== undefined) {
while (!isInDirectoryPath(dirPath, rootPath)) {
var parentPath = ts.getDirectoryPath(dirPath);
if (parentPath === dirPath) {
break;
}
+ subDirectory = dirPath.slice(parentPath.length + ts.directorySeparator.length);
dirPath = parentPath;
dir = ts.getDirectoryPath(dir);
}
}
- return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath);
+ return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath, subDirectory: subDirectory }, dirPath);
}
function isPathWithDefaultFailedLookupExtension(path) {
return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
@@ -79771,7 +80812,7 @@ var ts;
for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
var failedLookupLocation = failedLookupLocations_1[_i];
var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
- var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore;
+ var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore, subDirectory = _a.subDirectory;
if (!ignore) {
// If the failed lookup location path is not one of the supported extensions,
// store it in the custom path
@@ -79783,7 +80824,7 @@ var ts;
setAtRoot = true;
}
else {
- setDirectoryWatcher(dir, dirPath);
+ setDirectoryWatcher(dir, dirPath, subDirectory);
}
}
}
@@ -79791,13 +80832,19 @@ var ts;
setDirectoryWatcher(rootDir, rootPath);
}
}
- function setDirectoryWatcher(dir, dirPath) {
+ function setDirectoryWatcher(dir, dirPath, subDirectory) {
var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
if (dirWatcher) {
dirWatcher.refCount++;
}
else {
- directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 });
+ dirWatcher = { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 };
+ directoryWatchesOfFailedLookups.set(dirPath, dirWatcher);
+ }
+ if (subDirectory) {
+ var subDirectoryMap = dirWatcher.subDirectoryMap || (dirWatcher.subDirectoryMap = ts.createMap());
+ var existing = subDirectoryMap.get(subDirectory) || 0;
+ subDirectoryMap.set(subDirectory, existing + 1);
}
}
function stopWatchFailedLookupLocationOfResolution(resolution) {
@@ -79813,7 +80860,7 @@ var ts;
for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
var failedLookupLocation = failedLookupLocations_2[_i];
var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
- var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore;
+ var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _a.dirPath, ignore = _a.ignore, subDirectory = _a.subDirectory;
if (!ignore) {
var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
if (refCount) {
@@ -79829,7 +80876,7 @@ var ts;
removeAtRoot = true;
}
else {
- removeDirectoryWatcher(dirPath);
+ removeDirectoryWatcher(dirPath, subDirectory);
}
}
}
@@ -79837,22 +80884,40 @@ var ts;
removeDirectoryWatcher(rootPath);
}
}
- function removeDirectoryWatcher(dirPath) {
+ function removeDirectoryWatcher(dirPath, subDirectory) {
var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
+ if (subDirectory) {
+ var existing = dirWatcher.subDirectoryMap.get(subDirectory);
+ if (existing === 1) {
+ dirWatcher.subDirectoryMap.delete(subDirectory);
+ }
+ else {
+ dirWatcher.subDirectoryMap.set(subDirectory, existing - 1);
+ }
+ }
// Do not close the watcher yet since it might be needed by other failed lookup locations.
dirWatcher.refCount--;
}
+ function inWatchedSubdirectory(dirPath, fileOrDirectoryPath) {
+ var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
+ if (!dirWatcher || !dirWatcher.subDirectoryMap)
+ return false;
+ return ts.forEachKey(dirWatcher.subDirectoryMap, function (subDirectory) {
+ var fullSubDirectory = dirPath + "/" + subDirectory;
+ return fullSubDirectory === fileOrDirectoryPath || isInDirectoryPath(fullSubDirectory, fileOrDirectoryPath);
+ });
+ }
function createDirectoryWatcher(directory, dirPath) {
return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
if (cachedDirectoryStructureHost) {
- // Since the file existance changed, update the sourceFiles cache
+ // Since the file existence changed, update the sourceFiles cache
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
// If the files are added to project root or node_modules directory, always run through the invalidation process
// Otherwise run through invalidation only if adding to the immediate directory
if (!allFilesHaveInvalidatedResolution &&
- dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) {
+ (dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath || inWatchedSubdirectory(dirPath, fileOrDirectoryPath))) {
if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
resolutionHost.onInvalidatedResolution();
}
@@ -79976,7 +81041,7 @@ var ts;
return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) {
var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
if (cachedDirectoryStructureHost) {
- // Since the file existance changed, update the sourceFiles cache
+ // Since the file existence changed, update the sourceFiles cache
cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
}
// For now just recompile
@@ -80112,34 +81177,11 @@ var ts;
function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) {
var host = system;
host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); };
- var result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host);
+ var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host);
host.onUnRecoverableConfigFileDiagnostic = undefined;
return result;
}
ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
- /**
- * Reads the config file, reports errors if any and exits if the config file cannot be found
- */
- function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) {
- var configFileText;
- try {
- configFileText = host.readFile(configFileName);
- }
- catch (e) {
- var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message);
- host.onUnRecoverableConfigFileDiagnostic(error);
- return undefined;
- }
- if (!configFileText) {
- var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
- host.onUnRecoverableConfigFileDiagnostic(error);
- return undefined;
- }
- var result = ts.parseJsonText(configFileName, configFileText);
- var cwd = host.getCurrentDirectory();
- return ts.parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd));
- }
- ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
/**
* Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
*/
@@ -80221,12 +81263,12 @@ var ts;
watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; },
watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; },
setTimeout: system.setTimeout ? (function (callback, ms) {
+ var _a;
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args));
- var _a;
}) : ts.noop,
clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop,
trace: function (s) { return system.write(s); },
@@ -80986,6 +82028,13 @@ var ts;
category: ts.Diagnostics.Basic_Options,
description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
},
+ {
+ name: "composite",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_project_compilation,
+ },
{
name: "removeComments",
type: "boolean",
@@ -81246,6 +82295,12 @@ var ts;
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
},
+ {
+ name: "resolveJsonModule",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Include_modules_imported_with_json_extension
+ },
{
name: "listFiles",
type: "boolean",
@@ -81539,11 +82594,13 @@ var ts;
function parseCommandLine(commandLine, readFile) {
var options = {};
var fileNames = [];
+ var projectReferences = undefined;
var errors = [];
parseStrings(commandLine);
return {
options: options,
fileNames: fileNames,
+ projectReferences: projectReferences,
errors: errors
};
function parseStrings(args) {
@@ -81656,6 +82713,29 @@ var ts;
}
return optionNameMap.get(optionName);
}
+ /**
+ * Reads the config file, reports errors if any and exits if the config file cannot be found
+ */
+ function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) {
+ var configFileText;
+ try {
+ configFileText = host.readFile(configFileName);
+ }
+ catch (e) {
+ var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message);
+ host.onUnRecoverableConfigFileDiagnostic(error);
+ return undefined;
+ }
+ if (!configFileText) {
+ var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
+ host.onUnRecoverableConfigFileDiagnostic(error);
+ return undefined;
+ }
+ var result = ts.parseJsonText(configFileName, configFileText);
+ var cwd = host.getCurrentDirectory();
+ return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd));
+ }
+ ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
@@ -81703,55 +82783,67 @@ var ts;
var _tsconfigRootOptions;
function getTsconfigRootOptionsMap() {
if (_tsconfigRootOptions === undefined) {
- _tsconfigRootOptions = commandLineOptionsToMap([
- {
- name: "compilerOptions",
- type: "object",
- elementOptions: commandLineOptionsToMap(ts.optionDeclarations),
- extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0
- },
- {
- name: "typingOptions",
- type: "object",
- elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
- extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
- },
- {
- name: "typeAcquisition",
- type: "object",
- elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
- extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
- },
- {
- name: "extends",
- type: "string"
- },
- {
- name: "files",
- type: "list",
- element: {
+ _tsconfigRootOptions = {
+ name: undefined,
+ type: "object",
+ elementOptions: commandLineOptionsToMap([
+ {
+ name: "compilerOptions",
+ type: "object",
+ elementOptions: commandLineOptionsToMap(ts.optionDeclarations),
+ extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0
+ },
+ {
+ name: "typingOptions",
+ type: "object",
+ elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
+ extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
+ },
+ {
+ name: "typeAcquisition",
+ type: "object",
+ elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
+ extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
+ },
+ {
+ name: "extends",
+ type: "string"
+ },
+ {
+ name: "references",
+ type: "list",
+ element: {
+ name: "references",
+ type: "object"
+ }
+ },
+ {
name: "files",
- type: "string"
- }
- },
- {
- name: "include",
- type: "list",
- element: {
+ type: "list",
+ element: {
+ name: "files",
+ type: "string"
+ }
+ },
+ {
name: "include",
- type: "string"
- }
- },
- {
- name: "exclude",
- type: "list",
- element: {
+ type: "list",
+ element: {
+ name: "include",
+ type: "string"
+ }
+ },
+ {
name: "exclude",
- type: "string"
- }
- },
- ts.compileOnSaveCommandLineOption
- ]);
+ type: "list",
+ element: {
+ name: "exclude",
+ type: "string"
+ }
+ },
+ ts.compileOnSaveCommandLineOption
+ ])
+ };
}
return _tsconfigRootOptions;
}
@@ -81759,20 +82851,25 @@ var ts;
* Convert the json syntax tree into the json value
*/
function convertToObject(sourceFile, errors) {
- return convertToObjectWorker(sourceFile, errors, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
+ return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
}
ts.convertToObject = convertToObject;
/**
- * Convert the json syntax tree into the json value
+ * Convert the json syntax tree into the json value and report errors
+ * This returns the json value (apart from checking errors) only if returnValue provided is true.
+ * Otherwise it just checks the errors and returns undefined
*/
- function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) {
- if (!sourceFile.jsonObject) {
- return {};
+ /*@internal*/
+ function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
+ if (!sourceFile.statements.length) {
+ return returnValue ? {} : undefined;
+ }
+ return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
+ function isRootOptionMap(knownOptions) {
+ return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
}
- return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions,
- /*extraKeyDiagnosticMessage*/ undefined, /*parentOption*/ undefined);
function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) {
- var result = {};
+ var result = returnValue ? {} : undefined;
for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
var element = _a[_i];
if (element.kind !== 269 /* PropertyAssignment */) {
@@ -81792,11 +82889,13 @@ var ts;
}
var value = convertPropertyValueToJson(element.initializer, option);
if (typeof keyText !== "undefined") {
- result[keyText] = value;
+ if (returnValue) {
+ result[keyText] = value;
+ }
// Notify key value set, if user asked for it
if (jsonConversionNotifier &&
// Current callbacks are only on known parent option or if we are setting values in the root
- (parentOption || knownOptions === knownRootOptions)) {
+ (parentOption || isRootOptionMap(knownOptions))) {
var isValidOptionValue = isCompilerOptionsValue(option, value);
if (parentOption) {
if (isValidOptionValue) {
@@ -81804,7 +82903,7 @@ var ts;
jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
}
}
- else if (knownOptions === knownRootOptions) {
+ else if (isRootOptionMap(knownOptions)) {
if (isValidOptionValue) {
// Notify about the valid root key value being set
jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
@@ -81820,7 +82919,7 @@ var ts;
return result;
}
function convertArrayLiteralExpressionToJson(elements, elementOption) {
- return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); });
+ return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); });
}
function convertPropertyValueToJson(valueExpression, option) {
switch (valueExpression.kind) {
@@ -81895,6 +82994,7 @@ var ts;
return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
}
}
+ ts.convertToObjectWorker = convertToObjectWorker;
function getCompilerOptionValueTypeString(option) {
return option.type === "list" ?
"Array" :
@@ -81944,7 +83044,7 @@ var ts;
function serializeCompilerOptions(options) {
var result = ts.createMap();
var optionsNameMap = getOptionNameMap().optionNameMap;
- var _loop_9 = function (name) {
+ var _loop_10 = function (name) {
if (ts.hasProperty(options, name)) {
// tsconfig only options cannot be specified via command line,
// so we can assume that only types that can appear here string | number | boolean
@@ -81973,7 +83073,7 @@ var ts;
}
};
for (var name in options) {
- _loop_9(name);
+ _loop_10(name);
}
return result;
}
@@ -82123,12 +83223,13 @@ var ts;
var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors);
var raw = parsedConfig.raw;
var options = ts.extend(existingOptions, parsedConfig.options || {});
- options.configFilePath = configFileName;
+ options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
setConfigFileInOptions(options, sourceFile);
- var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
+ var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences;
return {
options: options,
fileNames: fileNames,
+ projectReferences: projectReferences,
typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
raw: raw,
errors: errors,
@@ -82177,9 +83278,32 @@ var ts;
includeSpecs = ["**/*"];
}
var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
- if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) {
+ if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) {
errors.push(getErrorForNoInputFiles(result.spec, configFileName));
}
+ if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) {
+ if (ts.isArray(raw.references)) {
+ var references = [];
+ for (var _i = 0, _a = raw.references; _i < _a.length; _i++) {
+ var ref = _a[_i];
+ if (typeof ref.path !== "string") {
+ createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
+ }
+ else {
+ references.push({
+ path: ts.getNormalizedAbsolutePath(ref.path, basePath),
+ originalPath: ref.path,
+ prepend: ref.prepend,
+ circular: ref.circular
+ });
+ }
+ }
+ result.projectReferences = references;
+ }
+ else {
+ createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array");
+ }
+ }
return result;
}
function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
@@ -82297,7 +83421,7 @@ var ts;
}
}
};
- var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator);
+ var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
if (!typeAcquisition) {
if (typingOptionstypeAcquisition) {
typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
@@ -82332,6 +83456,7 @@ var ts;
return extendedConfigPath;
}
function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) {
+ var _a;
var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
if (sourceFile) {
(sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName);
@@ -82360,7 +83485,6 @@ var ts;
mapPropertiesInRawIfNotUndefined("files");
}
return extendedConfig;
- var _a;
}
function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
@@ -82385,7 +83509,7 @@ var ts;
}
ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
function getDefaultCompilerOptions(configFileName) {
- var options = ts.getBaseFileName(configFileName) === "jsconfig.json"
+ var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
: {};
return options;
@@ -82393,10 +83517,13 @@ var ts;
function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
var options = getDefaultCompilerOptions(configFileName);
convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors);
+ if (configFileName) {
+ options.configFilePath = ts.normalizeSlashes(configFileName);
+ }
return options;
}
function getDefaultTypeAcquisition(configFileName) {
- return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
+ return { enable: configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
}
function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
var options = getDefaultTypeAcquisition(configFileName);
@@ -82557,7 +83684,7 @@ var ts;
// or a recursive directory. This information is used by filesystem watchers to monitor for
// new entries in these paths.
var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
- var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
+ var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
}
/**
@@ -82591,37 +83718,41 @@ var ts;
if (filesSpecs) {
for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) {
var fileName = filesSpecs_1[_i];
- var file = ts.getNormalizedAbsolutePath(fileName, basePath);
- literalFileMap.set(keyMapper(file), file);
+ var file_12 = ts.getNormalizedAbsolutePath(fileName, basePath);
+ literalFileMap.set(keyMapper(file_12), file_12);
}
}
if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
- var file = _b[_a];
+ var file_13 = _b[_a];
// If we have already included a literal or wildcard path with a
// higher priority extension, we should skip this file.
//
// This handles cases where we may encounter both .ts and
// .d.ts (or .js if "allowJs" is enabled) in the same
// directory when they are compilation outputs.
- if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
+ if (hasFileWithHigherPriorityExtension(file_13, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
continue;
}
// We may have included a wildcard path with a lower priority
// extension due to the user-defined order of entries in the
// "include" array. If there is a lower priority extension in the
// same directory, we should remove it.
- removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
- var key = keyMapper(file);
+ removeWildcardFilesWithLowerPriorityExtension(file_13, wildcardFileMap, supportedExtensions, keyMapper);
+ var key = keyMapper(file_13);
if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
- wildcardFileMap.set(key, file);
+ wildcardFileMap.set(key, file_13);
}
}
}
var literalFiles = ts.arrayFrom(literalFileMap.values());
var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
+ var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) {
+ return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) });
+ });
return {
fileNames: literalFiles.concat(wildcardFiles),
+ projectReferences: projectReferences,
wildcardDirectories: wildcardDirectories,
spec: spec
};
@@ -82636,20 +83767,10 @@ var ts;
return diag === undefined;
});
function createDiagnostic(message, spec) {
- if (jsonSourceFile && jsonSourceFile.jsonObject) {
- for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) {
- var property = _a[_i];
- if (ts.isArrayLiteralExpression(property.initializer)) {
- for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) {
- var element = _c[_b];
- if (ts.isStringLiteral(element) && element.text === spec) {
- return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec);
- }
- }
- }
- }
- }
- return ts.createCompilerDiagnostic(message, spec);
+ var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
+ return element ?
+ ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
+ ts.createCompilerDiagnostic(message, spec);
}
}
function specToDiagnostic(spec, allowTrailingRecursion) {
@@ -82682,8 +83803,8 @@ var ts;
if (include !== undefined) {
var recursiveKeys = [];
for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
- var file = include_1[_i];
- var spec = ts.normalizePath(ts.combinePaths(path, file));
+ var file_14 = include_1[_i];
+ var spec = ts.normalizePath(ts.combinePaths(path, file_14));
if (excludeRegex && excludeRegex.test(spec)) {
continue;
}
@@ -82877,6 +83998,17 @@ var ts;
SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName";
SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral";
})(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {}));
+ var OutliningSpanKind;
+ (function (OutliningSpanKind) {
+ /** Single or multi-line comments */
+ OutliningSpanKind["Comment"] = "comment";
+ /** Sections marked by '// #region' and '// #endregion' comments */
+ OutliningSpanKind["Region"] = "region";
+ /** Declarations and expressions */
+ OutliningSpanKind["Code"] = "code";
+ /** Contiguous blocks of import declarations */
+ OutliningSpanKind["Imports"] = "imports";
+ })(OutliningSpanKind = ts.OutliningSpanKind || (ts.OutliningSpanKind = {}));
var OutputFileType;
(function (OutputFileType) {
OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript";
@@ -82972,6 +84104,8 @@ var ts;
*
*/
ScriptElementKind["jsxAttribute"] = "JSX attribute";
+ /** String literal */
+ ScriptElementKind["string"] = "string";
})(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {}));
var ScriptElementKindModifier;
(function (ScriptElementKindModifier) {
@@ -83077,7 +84211,7 @@ var ts;
case 236 /* TypeAliasDeclaration */:
case 165 /* TypeLiteral */:
return 2 /* Type */;
- case 292 /* JSDocTypedefTag */:
+ case 294 /* 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 272 /* EnumMember */:
@@ -83193,6 +84327,8 @@ var ts;
switch (node.parent.kind) {
case 161 /* TypeReference */:
return true;
+ case 178 /* ImportType */:
+ return !node.parent.isTypeOf;
case 206 /* ExpressionWithTypeArguments */:
return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent);
}
@@ -83280,7 +84416,7 @@ var ts;
}
ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration;
function getContainerNode(node) {
- if (node.kind === 292 /* JSDocTypedefTag */) {
+ if (node.kind === 294 /* JSDocTypedefTag */) {
// This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope.
// node.parent = the JSDoc comment, node.parent.parent = the node having the comment.
// Then we get parent again in the loop.
@@ -83349,7 +84485,7 @@ var ts;
case 251 /* ExportSpecifier */:
case 245 /* NamespaceImport */:
return "alias" /* alias */;
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return "type" /* typeElement */;
case 199 /* BinaryExpression */:
var kind = ts.getSpecialPropertyAssignmentKind(node);
@@ -83678,7 +84814,7 @@ var ts;
return findPrecedingToken(position, file);
}
ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition;
- function findNextToken(previousToken, parent) {
+ function findNextToken(previousToken, parent, sourceFile) {
return find(parent);
function find(n) {
if (ts.isToken(n) && n.pos === previousToken.end) {
@@ -83693,7 +84829,7 @@ var ts;
(child.pos <= previousToken.pos && child.end > previousToken.end) ||
// previous token ends exactly at the beginning of child
(child.pos === previousToken.end);
- if (shouldDiveInChildNode && nodeHasTokens(child)) {
+ if (shouldDiveInChildNode && nodeHasTokens(child, sourceFile)) {
return find(child);
}
}
@@ -83724,11 +84860,11 @@ var ts;
if (position < child.end) {
var start = child.getStart(sourceFile, includeJsDoc);
var lookInPreviousChild = (start >= position) || // cursor in the leading trivia
- !nodeHasTokens(child) ||
+ !nodeHasTokens(child, sourceFile) ||
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 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i);
+ var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile);
return candidate && findRightmostToken(candidate, sourceFile);
}
else {
@@ -83743,7 +84879,7 @@ var ts;
// Try to find the rightmost token in the file without filtering.
// Namely we are skipping the check: 'position < node.end'
if (children.length) {
- var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length);
+ var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile);
return candidate && findRightmostToken(candidate, sourceFile);
}
}
@@ -83757,19 +84893,19 @@ var ts;
return n;
}
var children = n.getChildren(sourceFile);
- var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length);
+ var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile);
return candidate && findRightmostToken(candidate, sourceFile);
}
/**
* Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens.
*/
- function findRightmostChildNodeWithTokens(children, exclusiveStartPosition) {
+ function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) {
for (var i = exclusiveStartPosition - 1; i >= 0; i--) {
var child = children[i];
if (isWhiteSpaceOnlyJsxText(child)) {
ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`");
}
- else if (nodeHasTokens(children[i])) {
+ else if (nodeHasTokens(children[i], sourceFile)) {
return children[i];
}
}
@@ -83881,22 +85017,22 @@ var ts;
remainingLessThanTokens++;
break;
case 18 /* CloseBraceToken */:
- // This can be object type, skip untill we find the matching open brace token
- // Skip untill the matching open brace token
+ // This can be object type, skip until we find the matching open brace token
+ // Skip until the matching open brace token
token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile);
if (!token)
return false;
break;
case 20 /* CloseParenToken */:
- // This can be object type, skip untill we find the matching open brace token
- // Skip untill the matching open brace token
+ // This can be object type, skip until we find the matching open brace token
+ // Skip until the matching open brace token
token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile);
if (!token)
return false;
break;
case 22 /* CloseBracketToken */:
- // This can be object type, skip untill we find the matching open brace token
- // Skip untill the matching open brace token
+ // This can be object type, skip until we find the matching open brace token
+ // Skip until the matching open brace token
token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile);
if (!token)
return false;
@@ -83950,10 +85086,10 @@ var ts;
}
}
ts.hasDocComment = hasDocComment;
- function nodeHasTokens(n) {
+ function nodeHasTokens(n, sourceFile) {
// If we have a token or node that has a non-zero width, it must have tokens.
// Note: getWidth() does not take trivia into account.
- return n.getWidth() !== 0;
+ return n.getWidth(sourceFile) !== 0;
}
function getNodeModifiers(node) {
var flags = ts.getCombinedModifierFlags(node);
@@ -84050,11 +85186,6 @@ var ts;
return false;
}
ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern;
- function hasTrailingDirectorySeparator(path) {
- var lastCharacter = path.charAt(path.length - 1);
- return lastCharacter === "/" || lastCharacter === "\\";
- }
- ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
function isInReferenceComment(sourceFile, position) {
return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) {
var commentText = sourceFile.text.substring(c.pos, c.end);
@@ -84077,6 +85208,10 @@ var ts;
return ts.createTextSpanFromBounds(range.pos, range.end);
}
ts.createTextSpanFromRange = createTextSpanFromRange;
+ function createTextRangeFromSpan(span) {
+ return ts.createTextRange(span.start, span.start + span.length);
+ }
+ ts.createTextRangeFromSpan = createTextRangeFromSpan;
function createTextChangeFromStartLength(start, length, newText) {
return createTextChange(ts.createTextSpan(start, length), newText);
}
@@ -84157,6 +85292,44 @@ var ts;
return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
}
ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
+ function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier) {
+ return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier) : undefined;
+ }
+ ts.makeImportIfNecessary = makeImportIfNecessary;
+ function makeImport(defaultImport, namedImports, moduleSpecifier) {
+ return ts.createImportDeclaration(
+ /*decorators*/ undefined,
+ /*modifiers*/ undefined, defaultImport || namedImports
+ ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined)
+ : undefined, typeof moduleSpecifier === "string" ? ts.createLiteral(moduleSpecifier) : moduleSpecifier);
+ }
+ ts.makeImport = makeImport;
+ function symbolNameNoDefault(symbol) {
+ var escaped = symbolEscapedNameNoDefault(symbol);
+ return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped);
+ }
+ ts.symbolNameNoDefault = symbolNameNoDefault;
+ function symbolEscapedNameNoDefault(symbol) {
+ if (symbol.escapedName !== "default" /* Default */) {
+ return symbol.escapedName;
+ }
+ return ts.firstDefined(symbol.declarations, function (decl) {
+ var name = ts.getNameOfDeclaration(decl);
+ return name && name.kind === 71 /* Identifier */ ? name.escapedText : undefined;
+ });
+ }
+ ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault;
+ function getPropertySymbolFromBindingElement(checker, bindingElement) {
+ var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
+ var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
+ if (propSymbol && propSymbol.flags & 98304 /* Accessor */) {
+ // See GH#16922
+ ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */));
+ return propSymbol.target;
+ }
+ return propSymbol;
+ }
+ ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement;
})(ts || (ts = {}));
// Display-part writer helpers
/* @internal */
@@ -84489,20 +85662,20 @@ var ts;
* user was before extracting it.
*/
/* @internal */
- function getRenameLocation(edits, renameFilename, name, isDeclaredBeforeUse) {
+ function getRenameLocation(edits, renameFilename, name, preferLastLocation) {
var delta = 0;
var lastPos = -1;
for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) {
- var _a = edits_1[_i], fileName = _a.fileName, textChanges_1 = _a.textChanges;
+ var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges;
ts.Debug.assert(fileName === renameFilename);
- for (var _b = 0, textChanges_2 = textChanges_1; _b < textChanges_2.length; _b++) {
- var change = textChanges_2[_b];
+ for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) {
+ var change = textChanges_1[_b];
var span = change.span, newText = change.newText;
var index = newText.indexOf(name);
if (index !== -1) {
lastPos = span.start + delta + index;
// If the reference comes first, return immediately.
- if (!isDeclaredBeforeUse) {
+ if (!preferLastLocation) {
return lastPos;
}
}
@@ -84510,7 +85683,7 @@ var ts;
}
}
// If the declaration comes first, return the position of the last occurrence.
- ts.Debug.assert(isDeclaredBeforeUse);
+ ts.Debug.assert(preferLastLocation);
ts.Debug.assert(lastPos >= 0);
return lastPos;
}
@@ -85158,16 +86331,16 @@ 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 288 /* JSDocParameterTag */:
+ case 290 /* JSDocParameterTag */:
processJSDocParameterTag(tag);
break;
- case 291 /* JSDocTemplateTag */:
+ case 293 /* JSDocTemplateTag */:
processJSDocTemplateTag(tag);
break;
- case 290 /* JSDocTypeTag */:
+ case 292 /* JSDocTypeTag */:
processElement(tag.typeExpression);
break;
- case 289 /* JSDocReturnTag */:
+ case 291 /* JSDocReturnTag */:
processElement(tag.typeExpression);
break;
}
@@ -85413,7 +86586,7 @@ var ts;
var scriptPath = node.getSourceFile().path;
var scriptDirectory = ts.getDirectoryPath(scriptPath);
if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) {
- var extensions = ts.getSupportedExtensions(compilerOptions);
+ var extensions = getSupportedExtensionsForModuleResolution(compilerOptions);
if (compilerOptions.rootDirs) {
return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath);
}
@@ -85426,6 +86599,12 @@ var ts;
return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker);
}
}
+ function getSupportedExtensionsForModuleResolution(compilerOptions) {
+ var extensions = ts.getSupportedExtensions(compilerOptions);
+ return compilerOptions.resolveJsonModule && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ?
+ extensions.concat(".json" /* Json */) :
+ extensions;
+ }
/**
* Takes a script path and returns paths for all potential folders that could be merged with its
* containing folder via the "rootDirs" compiler option
@@ -85464,13 +86643,16 @@ var ts;
* Remove the basename from the path. Note that we don't use the basename to filter completions;
* the client is responsible for refining completions.
*/
- fragment = ts.getDirectoryPath(fragment);
+ if (!ts.hasTrailingDirectorySeparator(fragment)) {
+ fragment = ts.getDirectoryPath(fragment);
+ }
if (fragment === "") {
fragment = "." + ts.directorySeparator;
}
fragment = ts.ensureTrailingDirectorySeparator(fragment);
- var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment));
- var baseDirectory = ts.getDirectoryPath(absolutePath);
+ // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths
+ var absolutePath = ts.resolvePath(scriptPath, fragment);
+ var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath);
var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
if (tryDirectoryExists(host, baseDirectory)) {
// Enumerate the available files if possible
@@ -85489,7 +86671,7 @@ var ts;
if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) {
continue;
}
- var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath));
+ var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath));
if (!foundFiles.has(foundFileName)) {
foundFiles.set(foundFileName, true);
}
@@ -85502,8 +86684,8 @@ var ts;
var directories = tryGetDirectories(host, baseDirectory);
if (directories) {
for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) {
- var directory = directories_1[_a];
- var directoryName = ts.getBaseFileName(ts.normalizePath(directory));
+ var directory_2 = directories_1[_a];
+ var directoryName = ts.getBaseFileName(ts.normalizePath(directory_2));
if (directoryName !== "@types") {
result.push(nameAndKind(directoryName, "directory" /* directory */));
}
@@ -85522,7 +86704,7 @@ var ts;
function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) {
var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths;
var result = [];
- var fileExtensions = ts.getSupportedExtensions(compilerOptions);
+ var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions);
if (baseUrl) {
var projectDir = compilerOptions.project || host.getCurrentDirectory();
var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl);
@@ -85530,7 +86712,7 @@ var ts;
for (var path in paths) {
var patterns = paths[path];
if (paths.hasOwnProperty(path) && patterns) {
- var _loop_10 = function (name, kind) {
+ var _loop_11 = function (name, kind) {
// 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));
@@ -85538,12 +86720,12 @@ var ts;
};
for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) {
var _b = _a[_i], name = _b.name, kind = _b.kind;
- _loop_10(name, kind);
+ _loop_11(name, kind);
}
}
}
}
- var fragmentDirectory = containsSlash(fragment) ? ts.getDirectoryPath(fragment) : undefined;
+ var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined;
for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) {
var ambientName = _d[_c];
result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */));
@@ -85554,7 +86736,7 @@ var ts;
// (But do if we didn't find anything, e.g. 'package.json' missing.)
var foundGlobal = false;
if (fragmentDirectory === undefined) {
- var _loop_11 = function (moduleName) {
+ var _loop_12 = function (moduleName) {
if (!result.some(function (entry) { return entry.name === moduleName; })) {
foundGlobal = true;
result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */));
@@ -85562,7 +86744,7 @@ var ts;
};
for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) {
var moduleName = _f[_e];
- _loop_11(moduleName);
+ _loop_12(moduleName);
}
}
if (!foundGlobal) {
@@ -85598,12 +86780,13 @@ var ts;
}
// The prefix has two effective parts: the directory path and the base component after the filepath that is not a
// full directory component. For example: directory/path/of/prefix/base*
- var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix);
- var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix);
- var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix);
+ var normalizedPrefix = ts.resolvePath(parsed.prefix);
+ var normalizedPrefixDirectory = ts.hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : ts.getDirectoryPath(normalizedPrefix);
+ var normalizedPrefixBase = ts.hasTrailingDirectorySeparator(parsed.prefix) ? "" : ts.getBaseFileName(normalizedPrefix);
var fragmentHasPath = containsSlash(fragment);
+ var fragmentDirectory = fragmentHasPath ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined;
// Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call
- var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory;
+ var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory;
var normalizedSuffix = ts.normalizePath(parsed.suffix);
// Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b".
var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory));
@@ -85764,15 +86947,6 @@ var ts;
}
return false;
}
- function normalizeAndPreserveTrailingSlash(path) {
- if (ts.normalizeSlashes(path) === "./") {
- // normalizePath turns "./" into "". "" + "/" would then be a rooted path instead of a relative one, so avoid this particular case.
- // There is no problem for adding "/" to a non-empty string -- it's only a problem at the beginning.
- return "";
- }
- var norm = ts.normalizePath(path);
- return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(norm) : norm;
- }
/**
* Matches a triple slash reference directive with an incomplete string literal for its path. Used
* to determine if the caret is currently within the string literal and capture the literal fragment
@@ -85892,7 +87066,7 @@ var ts;
return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries };
}
case 2 /* Types */: {
- var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "type" /* typeElement */, sortText: "0" }); });
+ var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); });
return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries };
}
default:
@@ -86459,11 +87633,11 @@ var ts;
if (tag.tagName.pos <= position && position <= tag.tagName.end) {
return { kind: 1 /* JsDocTagName */ };
}
- if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 275 /* JSDocTypeExpression */) {
+ if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 277 /* JSDocTypeExpression */) {
currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true);
if (!currentToken ||
(!ts.isDeclarationName(currentToken) &&
- (currentToken.parent.kind !== 293 /* JSDocPropertyTag */ ||
+ (currentToken.parent.kind !== 295 /* JSDocPropertyTag */ ||
currentToken.parent.name !== currentToken))) {
// Use as type location if inside tag's type expression
insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression);
@@ -86599,12 +87773,8 @@ var ts;
}
else if (isRightOfOpenTag) {
var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined");
- if (tryGetGlobalSymbols()) {
- symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (67216319 /* Value */ | 2097152 /* Alias */)); }));
- }
- else {
- symbols = tagSymbols;
- }
+ tryGetGlobalSymbols();
+ symbols = tagSymbols.concat(symbols);
completionKind = 3 /* MemberLike */;
}
else if (isStartingCloseTag) {
@@ -86628,11 +87798,11 @@ var ts;
return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer };
function isTagWithTypeExpression(tag) {
switch (tag.kind) {
- case 288 /* JSDocParameterTag */:
- case 293 /* JSDocPropertyTag */:
- case 289 /* JSDocReturnTag */:
- case 290 /* JSDocTypeTag */:
- case 292 /* JSDocTypedefTag */:
+ case 290 /* JSDocParameterTag */:
+ case 295 /* JSDocPropertyTag */:
+ case 291 /* JSDocReturnTag */:
+ case 292 /* JSDocTypeTag */:
+ case 294 /* JSDocTypedefTag */:
return true;
}
}
@@ -86894,7 +88064,7 @@ var ts;
var exportedSymbols = typeChecker.getExportsOfModule(symbol);
// If the exported symbols contains type,
// symbol can be referenced at locations where type is allowed
- return ts.forEach(exportedSymbols, symbolCanBeReferencedAtTypeLocation);
+ return exportedSymbols.some(symbolCanBeReferencedAtTypeLocation);
}
}
function getSymbolsFromOtherSourceFileExports(symbols, tokenText, target) {
@@ -87670,7 +88840,7 @@ var ts;
function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) {
// class c { method() { } | method2() { } }
switch (location.kind) {
- case 294 /* SyntaxList */:
+ case 296 /* 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);
@@ -87707,6 +88877,10 @@ var ts;
}
function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) {
switch (triggerCharacter) {
+ case ".":
+ case "/":
+ case "@":
+ return true;
case '"':
case "'":
case "`":
@@ -87716,7 +88890,7 @@ var ts;
// Opening JSX tag
return contextToken.kind === 27 /* LessThanToken */ && contextToken.parent.kind !== 199 /* BinaryExpression */;
default:
- return ts.Debug.fail(triggerCharacter);
+ return ts.Debug.assertNever(triggerCharacter);
}
}
function isStringLiteralOrTemplate(node) {
@@ -87811,6 +88985,10 @@ var ts;
case 125 /* GetKeyword */:
case 136 /* SetKeyword */:
return getFromAllDeclarations(ts.isAccessor, [125 /* GetKeyword */, 136 /* SetKeyword */]);
+ case 121 /* AwaitKeyword */:
+ return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences);
+ case 120 /* AsyncKeyword */:
+ return highlightSpans(getAsyncAndAwaitOccurrences(node));
default:
return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent))
? highlightSpans(getModifierOccurrences(node.kind, node.parent))
@@ -88058,6 +89236,29 @@ var ts;
});
return keywords;
}
+ function getAsyncAndAwaitOccurrences(node) {
+ var func = ts.getContainingFunction(node);
+ if (!func) {
+ return undefined;
+ }
+ var keywords = [];
+ if (func.modifiers) {
+ func.modifiers.forEach(function (modifier) {
+ pushKeywordIf(keywords, modifier, 120 /* AsyncKeyword */);
+ });
+ }
+ ts.forEachChild(func, aggregate);
+ return keywords;
+ function aggregate(node) {
+ if (ts.isAwaitExpression(node)) {
+ pushKeywordIf(keywords, node.getFirstToken(), 121 /* AwaitKeyword */);
+ }
+ // Do not cross function boundaries.
+ if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) {
+ ts.forEachChild(node, aggregate);
+ }
+ }
+ }
function getIfElseOccurrences(ifStatement, sourceFile) {
var keywords = getIfElseKeywords(ifStatement, sourceFile);
var result = [];
@@ -88178,9 +89379,10 @@ var ts;
function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) {
var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true);
var entry = bucket.get(path);
+ var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target;
if (!entry) {
// Have never seen this file with these settings. Create a new source file for it.
- var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind);
+ var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind);
entry = {
sourceFile: sourceFile,
languageServiceRefCount: 1,
@@ -88309,6 +89511,8 @@ var ts;
addIndirectUser(direct.getSourceFile());
}
break;
+ case 71 /* Identifier */: // for 'const x = require("y");
+ break; // TODO: GH#23879
case 242 /* ImportEqualsDeclaration */:
handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */));
break;
@@ -88338,6 +89542,17 @@ var ts;
directImports.push(direct);
}
break;
+ case 178 /* ImportType */:
+ if (direct.qualifier) {
+ // `import("foo").x` named import
+ directImports.push(direct);
+ }
+ else {
+ // TODO: GH#23879
+ }
+ break;
+ default:
+ ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct));
}
}
}
@@ -88415,6 +89630,9 @@ var ts;
return;
}
if (decl.kind === 178 /* ImportType */) {
+ if (decl.qualifier) { // TODO: GH#23879
+ singleReferences.push(decl.qualifier.kind === 71 /* Identifier */ ? decl.qualifier : decl.qualifier.right);
+ }
return;
}
// Ignore if there's a grammar error
@@ -88442,7 +89660,7 @@ var ts;
var name = importClause.name;
// If a default import has the same name as the default export, allow to rename it.
// Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that.
- if (name && (!isForRename || name.escapedText === symbolName(exportSymbol))) {
+ if (name && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) {
var defaultImportAlias = checker.getSymbolAtLocation(name);
addSearch(name, defaultImportAlias);
}
@@ -88500,24 +89718,18 @@ var ts;
function findNamespaceReExports(sourceFileLike, name, checker) {
var namespaceImportSymbol = checker.getSymbolAtLocation(name);
return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) {
- if (statement.kind !== 249 /* ExportDeclaration */)
+ if (!ts.isExportDeclaration(statement))
return;
- var _a = statement, exportClause = _a.exportClause, moduleSpecifier = _a.moduleSpecifier;
- if (moduleSpecifier || !exportClause)
- return;
- for (var _i = 0, _b = exportClause.elements; _i < _b.length; _i++) {
- var element = _b[_i];
- if (checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol) {
- return true;
- }
- }
+ var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier;
+ return !moduleSpecifier && exportClause &&
+ exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; });
});
}
function findModuleReferences(program, sourceFiles, searchModuleSymbol) {
var refs = [];
var checker = program.getTypeChecker();
- for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) {
- var referencingFile = sourceFiles_4[_i];
+ for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
+ var referencingFile = sourceFiles_5[_i];
var searchSourceFile = searchModuleSymbol.valueDeclaration;
if (searchSourceFile.kind === 273 /* SourceFile */) {
for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) {
@@ -88547,8 +89759,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_5 = sourceFiles; _i < sourceFiles_5.length; _i++) {
- var sourceFile = sourceFiles_5[_i];
+ for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) {
+ var sourceFile = sourceFiles_6[_i];
cancellationToken.throwIfCancellationRequested();
forEachImport(sourceFile, function (importDecl, moduleSpecifier) {
var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier);
@@ -88653,6 +89865,9 @@ var ts;
else if (ts.isBinaryExpression(parent.parent)) {
return getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ true);
}
+ else if (ts.isJSDocTypedefTag(parent)) {
+ return exportInfo(symbol, 0 /* Named */);
+ }
}
function getExportAssignmentExport(ex) {
// Get the symbol for the `export =` node; its parent is the module it's the export of.
@@ -88697,7 +89912,7 @@ var ts;
// If the import has a different name than the export, do not continue searching.
// If `importedName` is undefined, do continue searching as the export is anonymous.
// (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.)
- var importedName = symbolName(importedSymbol);
+ var importedName = ts.symbolEscapedNameNoDefault(importedSymbol);
if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) {
return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport);
}
@@ -88764,15 +89979,6 @@ var ts;
return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined;
}
FindAllReferences.getExportInfo = getExportInfo;
- function symbolName(symbol) {
- if (symbol.escapedName !== "default" /* Default */) {
- return symbol.escapedName;
- }
- return ts.forEach(symbol.declarations, function (decl) {
- var name = ts.getNameOfDeclaration(decl);
- return name && name.kind === 71 /* Identifier */ && name.escapedText;
- });
- }
/** If at an export specifier, go to the symbol it refers to. */
function skipExportSpecifierSymbol(symbol, checker) {
// For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does.
@@ -88847,9 +90053,9 @@ var ts;
// 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 === 270 /* ShorthandPropertyAssignment */) {
- var result_4 = [];
- FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); });
- return result_4;
+ var result_5 = [];
+ FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_5.push(nodeEntry(node)); });
+ return result_5;
}
else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) {
// References to and accesses on the super keyword only have one possible implementation, so no
@@ -88897,7 +90103,7 @@ var ts;
case "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;
+ 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 };
}
case "string": {
@@ -89041,6 +90247,8 @@ var ts;
case 243 /* ImportDeclaration */:
case 249 /* ExportDeclaration */:
return true;
+ case 177 /* LiteralType */:
+ return ts.isImportTypeNode(node.parent.parent);
case 186 /* CallExpression */:
return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) || ts.isImportCall(node.parent);
default:
@@ -89160,7 +90368,6 @@ var ts;
return ts.firstDefined(symbol.declarations, function (decl) {
if (!decl.parent) {
// Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here.
- ts.Debug.assert(decl.kind === 273 /* SourceFile */);
ts.Debug.fail("Unexpected symbol at " + ts.Debug.showSyntaxKind(node) + ": " + ts.Debug.showSymbol(symbol));
}
return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent)
@@ -89279,7 +90486,8 @@ var ts;
for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) {
var singleRef = singleReferences_1[_i];
// At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename.
- if (!(state.options.isForRename && (ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */)) {
+ if (hasMatchingMeaning(singleRef, state) &&
+ !(state.options.isForRename && (ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */)) {
addRef(singleRef);
}
}
@@ -89333,22 +90541,14 @@ var ts;
var bindingElement = ts.getDeclarationOfKind(symbol, 181 /* BindingElement */);
if (bindingElement &&
bindingElement.parent.kind === 179 /* ObjectBindingPattern */ &&
+ ts.isIdentifier(bindingElement.name) &&
!bindingElement.propertyName) {
return bindingElement;
}
}
function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) {
var bindingElement = getObjectBindingElementWithoutPropertyName(symbol);
- if (!bindingElement)
- return undefined;
- var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent);
- var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text);
- if (propSymbol && propSymbol.flags & 98304 /* Accessor */) {
- // See GH#16922
- ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */));
- return propSymbol.target;
- }
- return propSymbol;
+ return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement);
}
/**
* Determines the smallest scope in which a symbol may have named references.
@@ -89519,6 +90719,9 @@ var ts;
getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere);
}
}
+ function hasMatchingMeaning(referenceLocation, state) {
+ return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning);
+ }
function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) {
var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true);
if (!isValidReferencePosition(referenceLocation, search.text)) {
@@ -89534,9 +90737,8 @@ var ts;
}
return;
}
- if (!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning)) {
+ if (!hasMatchingMeaning(referenceLocation, state))
return;
- }
var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation);
if (!referenceSymbol) {
return;
@@ -90197,7 +91399,9 @@ var ts;
var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration);
// For a function, if this is the original function definition, return just sigInfo.
// If this is the original constructor definition, parent is the class.
- return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; })
+ return typeChecker.getRootSymbols(symbol).some(function (s) { return calledDeclaration.symbol === s || calledDeclaration.symbol.parent === s; }) ||
+ // TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias
+ symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })
? [sigInfo]
: [sigInfo].concat(getDefinitionFromSymbol(typeChecker, symbol, node));
}
@@ -90252,14 +91456,14 @@ var ts;
function getReferenceAtPosition(sourceFile, position, program) {
var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position);
if (referencePath) {
- var file = ts.tryResolveScriptReference(program, sourceFile, referencePath);
- return file && { fileName: referencePath.fileName, file: file };
+ var file_15 = ts.tryResolveScriptReference(program, sourceFile, referencePath);
+ return file_15 && { fileName: referencePath.fileName, file: file_15 };
}
var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
if (typeReferenceDirective) {
var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName);
- var file = reference && program.getSourceFile(reference.resolvedFileName);
- return file && { fileName: typeReferenceDirective.fileName, file: file };
+ var file_16 = reference && program.getSourceFile(reference.resolvedFileName);
+ return file_16 && { fileName: typeReferenceDirective.fileName, file: file_16 };
}
return undefined;
}
@@ -90495,9 +91699,9 @@ var ts;
JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations;
function getCommentHavingNodes(declaration) {
switch (declaration.kind) {
- case 293 /* JSDocPropertyTag */:
+ case 295 /* JSDocPropertyTag */:
return [declaration];
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return [declaration.parent];
default:
return ts.getJSDocCommentsAndTags(declaration);
@@ -90518,15 +91722,15 @@ var ts;
function getCommentText(tag) {
var comment = tag.comment;
switch (tag.kind) {
- case 286 /* JSDocAugmentsTag */:
+ case 288 /* JSDocAugmentsTag */:
return withNode(tag.class);
- case 291 /* JSDocTemplateTag */:
+ case 293 /* JSDocTemplateTag */:
return withList(tag.typeParameters);
- case 290 /* JSDocTypeTag */:
+ case 292 /* JSDocTypeTag */:
return withNode(tag.typeExpression);
- case 292 /* JSDocTypedefTag */:
- case 293 /* JSDocPropertyTag */:
- case 288 /* JSDocParameterTag */:
+ case 294 /* JSDocTypedefTag */:
+ case 295 /* JSDocPropertyTag */:
+ case 290 /* JSDocParameterTag */:
var name = tag.name;
return name ? withNode(name) : comment;
default:
@@ -90915,8 +92119,8 @@ var ts;
getTypingNamesFromSourceFileNames(fileNames);
// add typings for unresolved imports
if (unresolvedImports) {
- var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
- addInferredTypings(module, "Inferred typings from unresolved imports");
+ var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
+ addInferredTypings(module_1, "Inferred typings from unresolved imports");
}
// Add the cached typing locations for inferred typings that are already installed
packageNameToTypingLocation.forEach(function (typing, name) {
@@ -91013,8 +92217,8 @@ var ts;
if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
continue;
}
- var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
- var packageJson = result_5.config;
+ var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
+ var packageJson = result_6.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.
@@ -91114,7 +92318,7 @@ var ts;
if (!patternMatcher)
return ts.emptyArray;
var rawItems = [];
- var _loop_12 = function (sourceFile) {
+ var _loop_13 = function (sourceFile) {
cancellationToken.throwIfCancellationRequested();
if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) {
return "continue";
@@ -91124,9 +92328,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_12(sourceFile);
+ for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) {
+ var sourceFile = sourceFiles_7[_i];
+ _loop_13(sourceFile);
}
rawItems.sort(compareNavigateToItems);
if (maxResultCount !== undefined) {
@@ -91503,7 +92707,7 @@ var ts;
if (ts.hasJSDocNodes(node)) {
ts.forEach(node.jsDoc, function (jsDoc) {
ts.forEach(jsDoc.tags, function (tag) {
- if (tag.kind === 292 /* JSDocTypedefTag */) {
+ if (tag.kind === 294 /* JSDocTypedefTag */) {
addLeafNode(tag);
}
});
@@ -91578,6 +92782,7 @@ var ts;
}
/** Merge source into target. Source should be thrown away after this is called. */
function merge(target, source) {
+ var _a;
target.additionalNodes = target.additionalNodes || [];
target.additionalNodes.push(source.node);
if (source.additionalNodes) {
@@ -91588,7 +92793,6 @@ var ts;
mergeChildren(target.children);
sortChildren(target.children);
}
- var _a;
}
/** Recursively ensure that each NavNode's children are in sorted order. */
function sortChildren(children) {
@@ -91616,7 +92820,7 @@ var ts;
case 192 /* ArrowFunction */:
case 204 /* ClassExpression */:
return getFunctionOrClassName(node);
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return getJSDocTypedefTagName(node);
default:
return undefined;
@@ -91659,7 +92863,7 @@ var ts;
return "()";
case 159 /* IndexSignature */:
return "[]";
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return getJSDocTypedefTagName(node);
default:
return "";
@@ -91707,7 +92911,7 @@ var ts;
case 238 /* ModuleDeclaration */:
case 273 /* SourceFile */:
case 236 /* TypeAliasDeclaration */:
- case 292 /* JSDocTypedefTag */:
+ case 294 /* JSDocTypedefTag */:
return true;
case 154 /* Constructor */:
case 153 /* MethodDeclaration */:
@@ -92107,21 +93311,12 @@ var ts;
}
ts.getEditsForFileRename = getEditsForFileRename;
function updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath) {
- var cfg = program.getCompilerOptions().configFile;
- if (!cfg)
- return;
- var oldFile = cfg.jsonObject && getFilesEntry(cfg.jsonObject, oldFilePath);
+ var configFile = program.getCompilerOptions().configFile;
+ var oldFile = ts.getTsConfigPropArrayElementValue(configFile, "files", oldFilePath);
if (oldFile) {
- changeTracker.replaceRangeWithText(cfg, createStringRange(oldFile, cfg), newFilePath);
+ changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath);
}
}
- function getFilesEntry(cfg, fileName) {
- var filesProp = ts.find(cfg.properties, function (prop) {
- return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files";
- });
- var files = filesProp && filesProp.initializer;
- return files && ts.isArrayLiteralExpression(files) ? ts.find(files.elements, function (e) { return ts.isStringLiteral(e) && e.text === fileName; }) : undefined;
- }
function isRef(toUpdate) {
return "fileName" in toUpdate;
}
@@ -92142,7 +93337,7 @@ var ts;
if (checker.getSymbolAtLocation(importStringLiteral))
continue;
var resolved = program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
- if (ts.contains(resolved.failedLookupLocations, oldFilePath)) {
+ if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) {
result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral });
}
}
@@ -92151,11 +93346,11 @@ var ts;
}
function getPathUpdater(oldFilePath, newFilePath, host) {
// Get the relative path from old to new location, and append it on to the end of imports and normalize.
- var rel = ts.getRelativePath(newFilePath, ts.getDirectoryPath(oldFilePath), ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host)));
+ var rel = ts.getRelativePathFromFile(oldFilePath, newFilePath, ts.createGetCanonicalFileName(ts.hostUsesCaseSensitiveFileNames(host)));
return function (oldPath) {
if (!ts.pathIsRelative(oldPath))
return;
- return ts.ensurePathIsRelative(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel)));
+ return ts.ensurePathIsNonModuleName(ts.normalizePath(ts.combinePaths(ts.getDirectoryPath(oldPath), rel)));
};
}
function createStringRange(node, sourceFile) {
@@ -92176,7 +93371,27 @@ var ts;
OutliningElementsCollector.collectElements = collectElements;
function addNodeOutliningSpans(sourceFile, cancellationToken, out) {
var depthRemaining = 40;
- sourceFile.forEachChild(function walk(n) {
+ var current = 0;
+ var statements = sourceFile.statements;
+ var n = statements.length;
+ while (current < n) {
+ while (current < n && !ts.isAnyImportSyntax(statements[current])) {
+ visitNonImportNode(statements[current]);
+ current++;
+ }
+ if (current === n)
+ break;
+ var firstImport = current;
+ while (current < n && ts.isAnyImportSyntax(statements[current])) {
+ addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out);
+ current++;
+ }
+ var lastImport = current - 1;
+ if (lastImport !== firstImport) {
+ out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 91 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */));
+ }
+ }
+ function visitNonImportNode(n) {
if (depthRemaining === 0)
return;
cancellationToken.throwIfCancellationRequested();
@@ -92189,17 +93404,17 @@ var ts;
depthRemaining--;
if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) {
// Consider an 'else if' to be on the same depth as the 'if'.
- walk(n.expression);
- walk(n.thenStatement);
+ visitNonImportNode(n.expression);
+ visitNonImportNode(n.thenStatement);
depthRemaining++;
- walk(n.elseStatement);
+ visitNonImportNode(n.elseStatement);
depthRemaining--;
}
else {
- n.forEachChild(walk);
+ n.forEachChild(visitNonImportNode);
}
depthRemaining++;
- });
+ }
}
function addRegionOutliningSpans(sourceFile, out) {
var regions = [];
@@ -92214,7 +93429,7 @@ var ts;
}
if (!result[1]) {
var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd);
- regions.push(createOutliningSpan(span, span, /*autoCollapse*/ false, result[2] || "#region"));
+ regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region"));
}
else {
var region = regions.pop();
@@ -92248,7 +93463,7 @@ var ts;
break;
case 3 /* MultiLineCommentTrivia */:
combineAndAddMultipleSingleLineComments();
- out.push(createOutliningSpanFromBounds(pos, end));
+ out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */));
singleLineCommentCount = 0;
break;
default:
@@ -92259,12 +93474,12 @@ var ts;
function combineAndAddMultipleSingleLineComments() {
// Only outline spans of two or more consecutive single line comments
if (singleLineCommentCount > 1) {
- out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd));
+ out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */));
}
}
}
- function createOutliningSpanFromBounds(pos, end) {
- return createOutliningSpan(ts.createTextSpanFromBounds(pos, end));
+ function createOutliningSpanFromBounds(pos, end, kind) {
+ return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind);
}
function getOutliningSpanForNode(n, sourceFile) {
switch (n.kind) {
@@ -92298,7 +93513,7 @@ var ts;
default:
// Block was a standalone block. In this case we want to only collapse
// the span of the block, independent of any parent span.
- return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile));
+ return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */);
}
case 239 /* ModuleBlock */:
return spanForNode(n.parent);
@@ -92330,14 +93545,14 @@ var ts;
return undefined;
}
var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd());
- return createOutliningSpan(textSpan, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse);
+ return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse);
}
}
- function createOutliningSpan(textSpan, hintSpan, autoCollapse, bannerText) {
+ function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) {
if (hintSpan === void 0) { hintSpan = textSpan; }
if (autoCollapse === void 0) { autoCollapse = false; }
if (bannerText === void 0) { bannerText = "..."; }
- return { textSpan: textSpan, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse };
+ return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse };
}
})(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {}));
})(ts || (ts = {}));
@@ -92620,13 +93835,13 @@ var ts;
// Assumes 'value' is already lowercase.
function indexOfIgnoringCase(str, value) {
var n = str.length - value.length;
- var _loop_13 = function (start) {
+ var _loop_14 = 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_13(start);
+ var state_4 = _loop_14(start);
if (typeof state_4 === "object")
return state_4.value;
}
@@ -93291,7 +94506,7 @@ var ts;
var nameToDeclarations = sourceFile.getNamedDeclarations();
var declarations = nameToDeclarations.get(name.text);
if (declarations) {
- var _loop_14 = function (declaration) {
+ var _loop_15 = function (declaration) {
var symbol = declaration.symbol;
if (symbol) {
var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration);
@@ -93305,7 +94520,7 @@ var ts;
};
for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) {
var declaration = declarations_12[_b];
- var state_5 = _loop_14(declaration);
+ var state_5 = _loop_15(declaration);
if (typeof state_5 === "object")
return state_5.value;
}
@@ -93694,8 +94909,8 @@ var ts;
var name = importNameForConvertToDefaultImport(importNode);
if (!name)
continue;
- var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
- var resolvedFile = module && program.getSourceFile(module.resolvedFileName);
+ var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text);
+ var resolvedFile = module_2 && program.getSourceFile(module_2.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));
}
@@ -94434,7 +95649,7 @@ var ts;
return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; });
});
options = ts.cloneCompilerOptions(options);
- var _loop_15 = function (opt) {
+ var _loop_16 = function (opt) {
if (!ts.hasProperty(options, opt.name)) {
return "continue";
}
@@ -94453,7 +95668,7 @@ var ts;
};
for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) {
var opt = commandLineOptionsStringToEnum_1[_i];
- _loop_15(opt);
+ _loop_16(opt);
}
return options;
}
@@ -94857,6 +96072,7 @@ var ts;
rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */),
rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */),
rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */),
+ rule("NoSpaceBetweenImportParenInImportType", 91 /* ImportKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */),
// Special handling of unary operators.
// Prefix operators generally shouldn't have a space between
// them and their target unary expression.
@@ -95317,6 +96533,9 @@ var ts;
function isArrowFunctionContext(context) {
return context.contextNode.kind === 192 /* ArrowFunction */;
}
+ function isImportTypeContext(context) {
+ return context.contextNode.kind === 178 /* ImportType */;
+ }
function isNonJsxSameLineTokenContext(context) {
return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */;
}
@@ -95439,18 +96658,18 @@ var ts;
// This array is used only during construction of the rulesbucket in the map
var rulesBucketConstructionStateList = new Array(map.length);
for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) {
- var rule = rules_1[_i];
- var specificRule = rule.leftTokenRange.isSpecific && rule.rightTokenRange.isSpecific;
- for (var _a = 0, _b = rule.leftTokenRange.tokens; _a < _b.length; _a++) {
+ var rule_1 = rules_1[_i];
+ var specificRule = rule_1.leftTokenRange.isSpecific && rule_1.rightTokenRange.isSpecific;
+ for (var _a = 0, _b = rule_1.leftTokenRange.tokens; _a < _b.length; _a++) {
var left = _b[_a];
- for (var _c = 0, _d = rule.rightTokenRange.tokens; _c < _d.length; _c++) {
+ for (var _c = 0, _d = rule_1.rightTokenRange.tokens; _c < _d.length; _c++) {
var right = _d[_c];
var index = getRuleBucketIndex(left, right);
var rulesBucket = map[index];
if (rulesBucket === undefined) {
rulesBucket = map[index] = [];
}
- addRule(rulesBucket, rule.rule, specificRule, rulesBucketConstructionStateList, index);
+ addRule(rulesBucket, rule_1.rule, specificRule, rulesBucketConstructionStateList, index);
}
}
}
@@ -96757,7 +97976,7 @@ var ts;
NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace";
})(NextTokenKind || (NextTokenKind = {}));
function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) {
- var nextToken = ts.findNextToken(precedingToken, current);
+ var nextToken = ts.findNextToken(precedingToken, current, sourceFile);
if (!nextToken) {
return 0 /* Unknown */;
}
@@ -96806,9 +98025,10 @@ var ts;
}
function getContainingList(node, sourceFile) {
if (node.parent) {
+ var end = node.end;
switch (node.parent.kind) {
case 161 /* TypeReference */:
- return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end);
case 183 /* ObjectLiteralExpression */:
return node.parent.properties;
case 182 /* ArrayLiteralExpression */:
@@ -96823,22 +98043,25 @@ var ts;
case 163 /* ConstructorType */:
case 158 /* ConstructSignature */: {
var start = node.getStart(sourceFile);
- return getListIfStartEndIsInListRange(node.parent.typeParameters, start, node.getEnd()) ||
- getListIfStartEndIsInListRange(node.parent.parameters, start, node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) ||
+ getListIfStartEndIsInListRange(node.parent.parameters, start, end);
}
case 234 /* ClassDeclaration */:
- return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), end);
case 187 /* NewExpression */:
case 186 /* CallExpression */: {
var start = node.getStart(sourceFile);
- return getListIfStartEndIsInListRange(node.parent.typeArguments, start, node.getEnd()) ||
- getListIfStartEndIsInListRange(node.parent.arguments, start, node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) ||
+ getListIfStartEndIsInListRange(node.parent.arguments, start, end);
}
case 232 /* VariableDeclarationList */:
- return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end);
case 246 /* NamedImports */:
case 250 /* NamedExports */:
- return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), node.getEnd());
+ return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end);
+ case 179 /* ObjectBindingPattern */:
+ case 180 /* ArrayBindingPattern */:
+ return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end);
}
}
return undefined;
@@ -97160,10 +98383,10 @@ var ts;
return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile);
}
function getAdjustedEndPosition(sourceFile, node, options) {
+ var end = node.end;
if (options.useNonAdjustedEndPosition || ts.isExpression(node)) {
- return node.getEnd();
+ return end;
}
- var end = node.getEnd();
var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))
? newEnd
@@ -97188,6 +98411,7 @@ var ts;
this.newLineCharacter = newLineCharacter;
this.formatContext = formatContext;
this.changes = [];
+ this.newFiles = [];
this.deletedNodesInLists = []; // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`.
this.classesWithNodesInsertedAtStart = ts.createMap(); // Set implemented as Map
}
@@ -97399,20 +98623,34 @@ var ts;
};
ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) {
var clsStart = cls.getStart(sourceFile);
- var prefix = "";
- var suffix = this.newLineCharacter;
- if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) {
- prefix = this.newLineCharacter;
- // For `class C {\n}`, don't add the trailing "\n"
- if (cls.members.length === 0 && !ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile]))) { // TODO: GH#4130 remove 'as any'
- suffix = "";
- }
- }
var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options)
+ this.formatContext.options.indentSize;
- this.insertNodeAt(sourceFile, cls.members.pos, newElement, { indentation: indentation, prefix: prefix, suffix: suffix });
+ this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls)));
+ };
+ ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) {
+ if (cls.members.length === 0) {
+ if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) {
+ // For `class C {\n}`, don't add the trailing "\n"
+ var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any'
+ return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" };
+ }
+ else {
+ return { prefix: "", suffix: this.newLineCharacter };
+ }
+ }
+ else {
+ return { prefix: this.newLineCharacter, suffix: "" };
+ }
};
ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) {
+ var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode);
+ this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
+ };
+ ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) {
+ var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes));
+ this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after));
+ };
+ ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) {
if (needSemicolonBetween(after, newNode)) {
// check if previous statement ends with semicolon
// if not - insert semicolon to preserve the code from changing the meaning due to ASI
@@ -97421,9 +98659,13 @@ var ts;
}
}
var endPosition = getAdjustedEndPosition(sourceFile, after, {});
- return this.replaceRange(sourceFile, ts.createTextRange(endPosition), newNode, this.getInsertNodeAfterOptions(after));
+ return endPosition;
};
- ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) {
+ ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) {
+ var options = this.getInsertNodeAfterOptionsWorker(after);
+ return __assign({}, options, { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix });
+ };
+ ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) {
if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) {
return { prefix: this.newLineCharacter, suffix: this.newLineCharacter };
}
@@ -97468,13 +98710,16 @@ var ts;
this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " });
}
};
+ ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) {
+ this.insertText(sourceFile, node.getStart(sourceFile), "export ");
+ };
/**
* This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range,
* i.e. arguments in arguments lists, parameters in parameter lists etc.
* Note that separators are part of the node in statements and class elements.
*/
- ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) {
- var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile);
+ ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) {
+ if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); }
if (!containingList) {
ts.Debug.fail("node is not a list element");
return this;
@@ -97600,7 +98845,15 @@ var ts;
*/
ChangeTracker.prototype.getChanges = function (validate) {
this.finishClassesWithNodesInsertedAtStart();
- return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
+ var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate);
+ for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) {
+ var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements;
+ changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter));
+ }
+ return changes;
+ };
+ ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) {
+ this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements });
};
return ChangeTracker;
}());
@@ -97614,15 +98867,16 @@ var ts;
return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) {
var sourceFile = changesInFile[0].sourceFile;
// order changes by start position
- var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; });
- var _loop_16 = function (i) {
+ // 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_17 = 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_16(i);
+ _loop_17(i);
}
var textChanges = normalized.map(function (c) {
return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate));
@@ -97631,6 +98885,11 @@ var ts;
});
}
changesToText.getTextChangesFromChanges = getTextChangesFromChanges;
+ function newFileChanges(oldFile, fileName, statements, newLineCharacter) {
+ var text = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter);
+ return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)] };
+ }
+ changesToText.newFileChanges = newFileChanges;
function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) {
if (change.kind === ChangeKind.Remove) {
return "";
@@ -97980,10 +99239,11 @@ var ts;
}
refactor_1.getEditsForRefactor = getEditsForRefactor;
})(refactor = ts.refactor || (ts.refactor = {}));
- function getRefactorContextLength(context) {
- return context.endPosition === undefined ? 0 : context.endPosition - context.startPosition;
+ function getRefactorContextSpan(_a) {
+ var startPosition = _a.startPosition, endPosition = _a.endPosition;
+ return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition);
}
- ts.getRefactorContextLength = getRefactorContextLength;
+ ts.getRefactorContextSpan = getRefactorContextSpan;
})(ts || (ts = {}));
/* @internal */
var ts;
@@ -98087,18 +99347,18 @@ var ts;
}
function transformJSDocType(node) {
switch (node.kind) {
- case 276 /* JSDocAllType */:
- case 277 /* JSDocUnknownType */:
+ case 278 /* JSDocAllType */:
+ case 279 /* JSDocUnknownType */:
return ts.createTypeReferenceNode("any", ts.emptyArray);
- case 280 /* JSDocOptionalType */:
+ case 282 /* JSDocOptionalType */:
return transformJSDocOptionalType(node);
- case 279 /* JSDocNonNullableType */:
+ case 281 /* JSDocNonNullableType */:
return transformJSDocType(node.type);
- case 278 /* JSDocNullableType */:
+ case 280 /* JSDocNullableType */:
return transformJSDocNullableType(node);
- case 282 /* JSDocVariadicType */:
+ case 284 /* JSDocVariadicType */:
return transformJSDocVariadicType(node);
- case 281 /* JSDocFunctionType */:
+ case 283 /* JSDocFunctionType */:
return transformJSDocFunctionType(node);
case 161 /* TypeReference */:
return transformJSDocTypeReference(node);
@@ -98122,7 +99382,7 @@ var ts;
}
function transformJSDocParameter(node) {
var index = node.parent.parameters.indexOf(node);
- var isRest = node.type.kind === 282 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
+ var isRest = node.type.kind === 284 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1;
var name = node.name || (isRest ? "rest" : "arg" + index);
var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken;
return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer);
@@ -98403,7 +99663,7 @@ var ts;
var importNode = ts.importFromModuleSpecifier(moduleSpecifier);
switch (importNode.kind) {
case 242 /* ImportEqualsDeclaration */:
- changes.replaceNode(importingFile, importNode, makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier));
+ changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier));
break;
case 186 /* CallExpression */:
if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) {
@@ -98467,7 +99727,7 @@ var ts;
case 186 /* CallExpression */: {
if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) {
// For side-effecting require() call, just make a side-effecting import.
- changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0]));
+ changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0]));
}
return false;
}
@@ -98540,27 +99800,30 @@ var ts;
changes.deleteNode(sourceFile, assignment.parent);
}
else {
- var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined;
- var changedToDefaultExport = false;
- if (!newNodes) {
- (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]);
+ var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right)
+ : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker)
+ : undefined;
+ if (replacement) {
+ changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]);
+ return replacement[1];
+ }
+ else {
+ changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default");
+ return true;
}
- changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes);
- return changedToDefaultExport;
}
}
else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) {
convertNamedExport(sourceFile, assignment, changes, exports);
}
return false;
- var _a;
}
/**
* Convert `module.exports = { ... }` to individual exports..
* We can't always do this if the module has interesting members -- then it will be a default export instead.
*/
function tryChangeModuleExportsObject(object) {
- return ts.mapAllOrFail(object.properties, function (prop) {
+ var statements = ts.mapAllOrFail(object.properties, function (prop) {
switch (prop.kind) {
case 155 /* GetAccessor */:
case 156 /* SetAccessor */:
@@ -98576,6 +99839,7 @@ var ts;
ts.Debug.assertNever(prop);
}
});
+ return statements && [statements, true];
}
function convertNamedExport(sourceFile, assignment, changes, exports) {
// If "originalKeywordKind" was set, this is e.g. `exports.
@@ -98596,30 +99860,6 @@ var ts;
convertExportsPropertyAssignment(assignment, sourceFile, changes);
}
}
- function convertModuleExportsToExportDefault(exported, checker) {
- var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)];
- switch (exported.kind) {
- case 191 /* FunctionExpression */:
- case 192 /* ArrowFunction */: {
- // `module.exports = function f() {}` --> `export default function f() {}`
- var fn = exported;
- return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true];
- }
- case 204 /* ClassExpression */: {
- // `module.exports = class C {}` --> `export default class C {}`
- var cls = exported;
- return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true];
- }
- case 186 /* CallExpression */:
- if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteralLike*/ true)) {
- return convertReExportAll(exported.arguments[0], checker);
- }
- // falls through
- default:
- // `module.exports = 0;` --> `export default 0;`
- return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true];
- }
- }
function convertReExportAll(reExported, checker) {
// `module.exports = require("x");` ==> `export * from "x"; export { default } from "x";`
var moduleSpecifier = reExported.text;
@@ -98695,7 +99935,7 @@ var ts;
: makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text);
});
if (importSpecifiers) {
- return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)];
+ return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)];
}
}
// falls through -- object destructuring has an interesting pattern and must be a variable declaration
@@ -98706,7 +99946,7 @@ var ts;
*/
var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers);
return [
- makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier),
+ ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier),
makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)),
];
}
@@ -98755,7 +99995,7 @@ var ts;
// If it was unused, ensure that we at least import *something*.
needDefaultImport = true;
}
- return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
+ return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)];
}
// Identifiers helpers
function makeUniqueName(name, identifiers) {
@@ -98797,17 +100037,9 @@ var ts;
}
function makeSingleImport(localName, propertyName, moduleSpecifier) {
return propertyName === "default"
- ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier)
- : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
+ ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier)
+ : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier);
}
- function makeImport(name, namedImports, moduleSpecifier) {
- return makeImportDeclaration(name, namedImports, moduleSpecifier);
- }
- function makeImportDeclaration(name, namedImports, moduleSpecifier) {
- var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports));
- return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifier);
- }
- codefix.makeImportDeclaration = makeImportDeclaration;
function makeImportSpecifier(propertyName, name) {
return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name));
}
@@ -99014,11 +100246,11 @@ var ts;
if (context.symbolToken && ts.isIdentifier(context.symbolToken)) {
for (var _i = 0, existingImports_1 = existingImports; _i < existingImports_1.length; _i++) {
var declaration = existingImports_1[_i].declaration;
- var namespace = getNamespaceImportName(declaration);
- if (namespace) {
- var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace));
+ var namespace_2 = getNamespaceImportName(declaration);
+ if (namespace_2) {
+ var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace_2));
if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) {
- useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken));
+ useExisting.push(getCodeActionForUseExistingNamespaceImport(namespace_2.text, context, context.symbolToken));
}
}
}
@@ -99119,7 +100351,7 @@ var ts;
if (global) {
return [global];
}
- var relativePath = removeExtensionAndIndexPostFix(ts.getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), moduleResolutionKind, addJsExtension);
+ var relativePath = removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension);
if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") {
return [relativePath];
}
@@ -99169,7 +100401,7 @@ var ts;
1 < 2 = true
In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a".
*/
- var pathFromSourceToBaseUrl = ts.getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName);
+ var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName));
var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl);
return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath];
});
@@ -99192,11 +100424,14 @@ var ts;
return symlinks.length === 0 ? [fileName] : symlinks;
}
function getRelativePathNParents(relativePath) {
- var count = 0;
- for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) {
- count++;
+ var components = ts.getPathComponents(relativePath);
+ if (components[0] || components.length === 1)
+ return 0;
+ for (var i = 1; i < components.length; i++) {
+ if (components[i] !== "..")
+ return i - 1;
}
- return count;
+ return components.length - 1;
}
function tryGetModuleNameFromAmbientModule(moduleSymbol) {
var decl = moduleSymbol.valueDeclaration;
@@ -99235,7 +100470,7 @@ var ts;
return undefined;
}
var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
- var relativePath = normalizedSourcePath !== undefined ? ts.getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath;
+ var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
return ts.removeFileExtension(relativePath);
}
function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) {
@@ -99295,7 +100530,7 @@ var ts;
return path.substring(parts.topLevelPackageNameIndex + 1);
}
else {
- return ts.getRelativePath(path, sourceDirectory, getCanonicalFileName);
+ return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, path, getCanonicalFileName));
}
}
}
@@ -99848,7 +101083,24 @@ var ts;
/*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName,
/*questionToken*/ undefined, typeNode,
/*initializer*/ undefined);
- changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property);
+ var lastProp = getNodeToInsertPropertyAfter(classDeclaration);
+ if (lastProp) {
+ changeTracker.insertNodeAfter(classDeclarationSourceFile, lastProp, property);
+ }
+ else {
+ changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property);
+ }
+ }
+ // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration.
+ function getNodeToInsertPropertyAfter(cls) {
+ var res;
+ for (var _i = 0, _a = cls.members; _i < _a.length; _i++) {
+ var member = _a[_i];
+ if (!ts.isPropertyDeclaration(member))
+ break;
+ res = member;
+ }
+ return res;
}
function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) {
// Index signatures cannot have the static modifier.
@@ -100160,6 +101412,7 @@ var ts;
ts.Diagnostics._0_is_declared_but_never_used.code,
ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code,
ts.Diagnostics.All_imports_in_import_declaration_are_unused.code,
+ ts.Diagnostics.All_destructured_elements_are_unused.code,
];
codefix.registerCodeFix({
errorCodes: errorCodes,
@@ -100170,6 +101423,10 @@ var ts;
var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); });
return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)];
}
+ var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullDestructure(t, sourceFile, context.span.start); });
+ if (delDestructure.length) {
+ return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)];
+ }
var token = getToken(sourceFile, ts.textSpanEnd(context.span));
var result = [];
var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token); });
@@ -100198,7 +101455,9 @@ var ts;
changes.deleteNode(sourceFile, importDecl);
}
else {
- tryDeleteDeclaration(changes, sourceFile, token);
+ if (!tryDeleteFullDestructure(changes, sourceFile, diag.start)) {
+ tryDeleteDeclaration(changes, sourceFile, token);
+ }
}
break;
default:
@@ -100211,6 +101470,26 @@ var ts;
var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined;
}
+ function tryDeleteFullDestructure(changes, sourceFile, pos) {
+ var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false);
+ if (startToken.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(startToken.parent))
+ return false;
+ var decl = startToken.parent.parent;
+ switch (decl.kind) {
+ case 231 /* VariableDeclaration */:
+ tryDeleteVariableDeclaration(changes, sourceFile, decl);
+ break;
+ case 148 /* Parameter */:
+ changes.deleteNodeInList(sourceFile, decl);
+ break;
+ case 181 /* BindingElement */:
+ changes.deleteNode(sourceFile, decl);
+ break;
+ default:
+ return ts.Debug.assertNever(decl);
+ }
+ return true;
+ }
function getToken(sourceFile, pos) {
var token = ts.findPrecedingToken(pos, sourceFile);
// this handles var ["computed"] = 12;
@@ -100299,6 +101578,20 @@ var ts;
changes.deleteNodeInList(sourceFile, parent);
}
break;
+ case 181 /* BindingElement */: {
+ var pattern = parent.parent;
+ switch (pattern.kind) {
+ case 180 /* ArrayBindingPattern */:
+ changes.deleteNode(sourceFile, parent); // Don't delete ','
+ break;
+ case 179 /* ObjectBindingPattern */:
+ changes.deleteNodeInList(sourceFile, parent);
+ break;
+ default:
+ return ts.Debug.assertNever(pattern);
+ }
+ break;
+ }
// handle case where 'import a = A;'
case 242 /* ImportEqualsDeclaration */:
var importEquals = ts.getAncestor(identifier, 242 /* ImportEqualsDeclaration */);
@@ -100413,7 +101706,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 === 278 /* JSDocNullableType */) {
+ if (typeNode.kind === 280 /* 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, 4096 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types));
@@ -100433,7 +101726,7 @@ var ts;
if (!info)
return;
var typeNode = info.typeNode, type = info.type;
- var fixedType = typeNode.kind === 278 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type;
+ var fixedType = typeNode.kind === 280 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type;
doChange(changes, sourceFile, typeNode, fixedType, checker);
});
}
@@ -101349,7 +102642,7 @@ var ts;
var opts = context.program.getCompilerOptions();
var variations = [];
// import Bluebird from "bluebird";
- variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier)));
+ variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier)));
if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) {
// import Bluebird = require("bluebird");
variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration(
@@ -101575,7 +102868,7 @@ var ts;
}
}
function doChange(changes, sourceFile, info) {
- changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier));
+ changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier));
}
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
@@ -101593,7 +102886,7 @@ var ts;
* Exported for tests.
*/
function getAvailableActions(context) {
- var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) });
+ var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
var targetRange = rangeToExtract.targetRange;
if (targetRange === undefined) {
return undefined;
@@ -101662,7 +102955,7 @@ var ts;
extractSymbol.getAvailableActions = getAvailableActions;
/* Exported for tests */
function getEditsForAction(context, actionName) {
- var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) });
+ var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context));
var targetRange = rangeToExtract.targetRange;
var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName);
if (parsedFunctionIndexMatch) {
@@ -102797,7 +104090,7 @@ var ts;
: ts.getEnclosingBlockScopeContainer(scopes[0]);
ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations);
}
- var _loop_17 = function (i) {
+ var _loop_18 = 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
@@ -102837,7 +104130,7 @@ var ts;
}
};
for (var i = 0; i < scopes.length; i++) {
- _loop_17(i);
+ _loop_18(i);
}
return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations };
function hasTypeParameters(node) {
@@ -103137,21 +104430,39 @@ var ts;
return undefined;
var isJS = ts.isSourceFileJavaScript(file);
var changeTracker = ts.textChanges.ChangeTracker.fromContext(context);
- var isStatic = fieldInfo.isStatic, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration;
+ var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration;
+ ts.suppressLeadingAndTrailingTrivia(fieldName);
+ ts.suppressLeadingAndTrailingTrivia(declaration);
+ ts.suppressLeadingAndTrailingTrivia(container);
var isInClassLike = ts.isClassLike(container);
+ // avoid Readonly modifier because it will convert to get accessor
+ var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */;
var accessorModifiers = isInClassLike
- ? !declaration.modifiers || ts.getModifierFlags(declaration) & 8 /* Private */ ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */) : declaration.modifiers
+ ? !modifierFlags || modifierFlags & 8 /* Private */
+ ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */)
+ : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags))
: undefined;
var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 112 /* PrivateKeyword */) : undefined;
- updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers, container);
+ updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers);
var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
- var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
+ ts.suppressLeadingAndTrailingTrivia(getAccessor);
insertAccessor(changeTracker, file, getAccessor, declaration, container);
- insertAccessor(changeTracker, file, setAccessor, declaration, container);
+ if (isReadonly) {
+ // readonly modifier only existed in classLikeDeclaration
+ var constructor = ts.getFirstConstructorWithBody(container);
+ if (constructor) {
+ updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName);
+ }
+ }
+ else {
+ var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container);
+ ts.suppressLeadingAndTrailingTrivia(setAccessor);
+ insertAccessor(changeTracker, file, setAccessor, declaration, container);
+ }
var edits = changeTracker.getChanges();
var renameFilename = file.fileName;
var renameLocationOffset = ts.isIdentifier(fieldName) ? 0 : -1;
- var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, fieldName.text, /*isDeclaredBeforeUse*/ false);
+ var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, fieldName.text, /*preferLastLocation*/ ts.isParameter(declaration));
return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits };
}
function isConvertableName(name) {
@@ -103174,18 +104485,18 @@ var ts;
function getConvertibleFieldAtPosition(file, startPosition) {
var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false);
var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration);
- // make sure propertyDeclaration have AccessibilityModifier or Static Modifier
- var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */;
+ // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier
+ var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */;
if (!declaration || !isConvertableName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning)
return undefined;
var fieldName = createPropertyName(ts.getUniqueName("_" + declaration.name.text, file.text), declaration.name);
var accessorName = createPropertyName(declaration.name.text, declaration.name);
- ts.suppressLeadingAndTrailingTrivia(fieldName);
- ts.suppressLeadingAndTrailingTrivia(declaration);
return {
isStatic: ts.hasStaticModifier(declaration),
+ isReadonly: ts.hasReadonlyModifier(declaration),
type: ts.getTypeAnnotationNode(declaration),
container: declaration.kind === 148 /* Parameter */ ? declaration.parent.parent : declaration.parent,
+ originalName: declaration.name,
declaration: declaration,
fieldName: fieldName,
accessorName: accessorName,
@@ -103212,16 +104523,11 @@ var ts;
var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer);
changeTracker.replaceNode(file, declaration, property);
}
- function updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, classLikeContainer) {
- var property = ts.createProperty(declaration.decorators, modifiers, fieldName, declaration.questionToken, declaration.type, declaration.initializer);
- changeTracker.insertNodeAtClassStart(file, classLikeContainer, property);
- changeTracker.deleteNodeInList(file, declaration);
- }
function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) {
var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer);
changeTracker.replacePropertyAssignment(file, declaration, assignment);
}
- function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers, container) {
+ function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) {
if (ts.isPropertyDeclaration(declaration)) {
updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers);
}
@@ -103229,7 +104535,7 @@ var ts;
updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName);
}
else {
- updateParameterPropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers, container);
+ changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer));
}
}
function insertAccessor(changeTracker, file, accessor, declaration, container) {
@@ -103237,11 +104543,592 @@ var ts;
? changeTracker.insertNodeAtClassStart(file, container, accessor)
: changeTracker.insertNodeAfter(file, declaration, accessor);
}
+ function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) {
+ if (!constructor.body)
+ return;
+ var file = context.file, program = context.program, cancellationToken = context.cancellationToken;
+ var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { return ((entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined); });
+ ts.forEach(referenceEntries, function (entry) {
+ var parent = entry.parent;
+ var accessorName = ts.createIdentifier(fieldName.text);
+ var node = ts.isBinaryExpression(parent)
+ ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken)
+ : ts.isPropertyAccessExpression(parent)
+ ? ts.updatePropertyAccess(parent, parent.expression, accessorName)
+ : ts.Debug.fail("Unexpected write access token");
+ changeTracker.replaceNode(file, parent, node);
+ });
+ }
})(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {}));
})(refactor = ts.refactor || (ts.refactor = {}));
})(ts || (ts = {}));
/* @internal */
var ts;
+(function (ts) {
+ var refactor;
+ (function (refactor) {
+ var refactorName = "Move to a new file";
+ refactor.registerRefactor(refactorName, {
+ getAvailableActions: function (context) {
+ if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined)
+ return undefined;
+ var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file);
+ return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }];
+ },
+ getEditsForAction: function (context, actionName) {
+ ts.Debug.assert(actionName === refactorName);
+ var statements = ts.Debug.assertDefined(getStatementsToMove(context));
+ var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host); });
+ return { edits: edits, renameFilename: undefined, renameLocation: undefined };
+ }
+ });
+ function getStatementsToMove(context) {
+ var file = context.file;
+ var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context));
+ var statements = file.statements;
+ var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; });
+ if (startNodeIndex === -1)
+ return undefined;
+ // Can't only partially include the start node or be partially into the next node
+ if (range.pos > statements[startNodeIndex].getStart(file))
+ return undefined;
+ var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex);
+ // Can't be partially into the next node
+ if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end))
+ return undefined;
+ return statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex);
+ }
+ function doChange(oldFile, program, toMove, changes, host) {
+ var checker = program.getTypeChecker();
+ var usage = getUsageInfo(oldFile, toMove, checker);
+ var currentDirectory = ts.getDirectoryPath(oldFile.fileName);
+ var extension = ts.extensionFromPath(oldFile.fileName);
+ var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host);
+ var newFileNameWithExtension = newModuleName + extension;
+ // If previous file was global, this is easy.
+ changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatements(oldFile, usage, changes, toMove, program, newModuleName));
+ addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host));
+ }
+ function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) {
+ var cfg = program.getCompilerOptions().configFile;
+ if (!cfg)
+ return;
+ var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension));
+ var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName);
+ var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression);
+ var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) {
+ return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files";
+ });
+ if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) {
+ changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements);
+ }
+ }
+ function getNewStatements(oldFile, usage, changes, toMove, program, newModuleName) {
+ var checker = program.getTypeChecker();
+ if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) {
+ changes.deleteNodeRange(oldFile, ts.first(toMove), ts.last(toMove));
+ return toMove;
+ }
+ var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator;
+ var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax);
+ if (importsFromNewFile) {
+ changes.insertNodeBefore(oldFile, oldFile.statements[0], importsFromNewFile, /*blankLineBetween*/ true);
+ }
+ deleteUnusedOldImports(oldFile, toMove, changes, usage.unusedImportsFromOldFile, checker);
+ changes.deleteNodeRange(oldFile, ts.first(toMove), ts.last(toMove));
+ updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName);
+ return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax).concat(addExports(oldFile, toMove, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax));
+ }
+ function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) {
+ for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
+ var statement = _a[_i];
+ if (ts.contains(toMove, statement))
+ continue;
+ forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); });
+ }
+ }
+ function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) {
+ var checker = program.getTypeChecker();
+ var _loop_19 = function (sourceFile) {
+ if (sourceFile === oldFile)
+ return "continue";
+ var _loop_20 = function (statement) {
+ forEachImportInStatement(statement, function (importNode) {
+ var shouldMove = function (name) {
+ var symbol = ts.isBindingElement(name.parent)
+ ? ts.getPropertySymbolFromBindingElement(checker, name.parent)
+ : ts.skipAlias(checker.getSymbolAtLocation(name), checker);
+ return !!symbol && movedSymbols.has(symbol);
+ };
+ deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file
+ var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName);
+ var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove);
+ if (newImportDeclaration)
+ changes.insertNodeAfter(sourceFile, statement, newImportDeclaration);
+ });
+ };
+ for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
+ var statement = _a[_i];
+ _loop_20(statement);
+ }
+ };
+ for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
+ var sourceFile = _a[_i];
+ _loop_19(sourceFile);
+ }
+ }
+ function moduleSpecifierFromImport(i) {
+ return (i.kind === 243 /* ImportDeclaration */ ? i.moduleSpecifier
+ : i.kind === 242 /* ImportEqualsDeclaration */ ? i.moduleReference.expression
+ : i.initializer.arguments[0]);
+ }
+ function forEachImportInStatement(statement, cb) {
+ if (ts.isImportDeclaration(statement)) {
+ if (ts.isStringLiteral(statement.moduleSpecifier))
+ cb(statement);
+ }
+ else if (ts.isImportEqualsDeclaration(statement)) {
+ if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) {
+ cb(statement);
+ }
+ }
+ else if (ts.isVariableStatement(statement)) {
+ for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) {
+ cb(decl);
+ }
+ }
+ }
+ }
+ function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports) {
+ var defaultImport;
+ var imports = [];
+ newFileNeedExport.forEach(function (symbol) {
+ if (symbol.escapedName === "default" /* Default */) {
+ defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol));
+ }
+ else {
+ imports.push(symbol.name);
+ }
+ });
+ return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports);
+ }
+ function makeImportOrRequire(defaultImport, imports, path, useEs6Imports) {
+ path = ts.ensurePathIsNonModuleName(path);
+ if (useEs6Imports) {
+ var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); });
+ return ts.makeImportIfNecessary(defaultImport, specifiers, path);
+ }
+ else {
+ ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module.
+ var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); });
+ return bindingElements.length
+ ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path)))
+ : undefined;
+ }
+ }
+ function makeVariableStatement(name, type, initializer, flags) {
+ if (flags === void 0) { flags = 2 /* Const */; }
+ return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags));
+ }
+ function createRequireCall(moduleSpecifier) {
+ return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]);
+ }
+ function addExports(sourceFile, toMove, needExport, useEs6Exports) {
+ return ts.flatMap(toMove, function (statement) {
+ 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;
+ }
+ return statement;
+ });
+ }
+ function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) {
+ switch (importDecl.kind) {
+ case 243 /* ImportDeclaration */:
+ deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused);
+ break;
+ case 242 /* ImportEqualsDeclaration */:
+ if (isUnused(importDecl.name)) {
+ changes.deleteNode(sourceFile, importDecl);
+ }
+ break;
+ case 231 /* VariableDeclaration */:
+ deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused);
+ break;
+ default:
+ ts.Debug.assertNever(importDecl);
+ }
+ }
+ function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) {
+ if (!importDecl.importClause)
+ return;
+ var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings;
+ var defaultUnused = !name || isUnused(name);
+ var namedBindingsUnused = !namedBindings ||
+ (namedBindings.kind === 245 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.every(function (e) { return isUnused(e.name); }));
+ if (defaultUnused && namedBindingsUnused) {
+ changes.deleteNode(sourceFile, importDecl);
+ }
+ else {
+ if (name && defaultUnused) {
+ changes.deleteNode(sourceFile, name);
+ }
+ if (namedBindings) {
+ if (namedBindingsUnused) {
+ changes.deleteNode(sourceFile, namedBindings);
+ }
+ else if (namedBindings.kind === 246 /* NamedImports */) {
+ for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) {
+ var element = _b[_i];
+ if (isUnused(element.name))
+ changes.deleteNodeInList(sourceFile, element);
+ }
+ }
+ }
+ }
+ }
+ function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) {
+ var name = varDecl.name;
+ switch (name.kind) {
+ case 71 /* Identifier */:
+ if (isUnused(name)) {
+ changes.deleteNode(sourceFile, name);
+ }
+ break;
+ case 180 /* ArrayBindingPattern */:
+ break;
+ case 179 /* ObjectBindingPattern */:
+ if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) {
+ changes.deleteNode(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl);
+ }
+ else {
+ for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
+ var element = _a[_i];
+ if (ts.isIdentifier(element.name) && isUnused(element.name)) {
+ changes.deleteNode(sourceFile, element.name);
+ }
+ }
+ }
+ break;
+ }
+ }
+ function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax) {
+ var copiedOldImports = [];
+ for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) {
+ var oldStatement = _a[_i];
+ forEachImportInStatement(oldStatement, function (i) {
+ ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); }));
+ });
+ }
+ // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file.
+ var oldFileDefault;
+ var oldFileNamedImports = [];
+ var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`.
+ newFileImportsFromOldFile.forEach(function (symbol) {
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (!isTopLevelDeclaration(decl))
+ continue;
+ var name = nameOfTopLevelDeclaration(decl);
+ if (!name)
+ continue;
+ var top = getTopLevelDeclarationStatement(decl);
+ if (markSeenTop(top)) {
+ addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax);
+ }
+ if (ts.hasModifier(decl, 512 /* Default */)) {
+ oldFileDefault = name;
+ }
+ else {
+ oldFileNamedImports.push(name.text);
+ }
+ }
+ });
+ ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax));
+ return copiedOldImports;
+ }
+ function makeUniqueModuleName(moduleName, extension, inDirectory, host) {
+ var newModuleName = moduleName;
+ for (var i = 1;; i++) {
+ var name = ts.combinePaths(inDirectory, newModuleName + extension);
+ if (!host.fileExists(name))
+ return newModuleName;
+ newModuleName = moduleName + "." + i;
+ }
+ }
+ function getNewModuleName(movedSymbols) {
+ return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile";
+ }
+ function getUsageInfo(oldFile, toMove, checker) {
+ var movedSymbols = new SymbolSet();
+ var oldImportsNeededByNewFile = new SymbolSet();
+ var newFileImportsFromOldFile = new SymbolSet();
+ for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) {
+ var statement = toMove_1[_i];
+ forEachTopLevelDeclaration(statement, function (decl) {
+ movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol));
+ });
+ }
+ for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) {
+ var statement = toMove_2[_a];
+ forEachReference(statement, checker, function (symbol) {
+ if (!symbol.declarations)
+ return;
+ for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
+ var decl = _a[_i];
+ if (isInImport(decl)) {
+ oldImportsNeededByNewFile.add(symbol);
+ }
+ else if (isTopLevelDeclaration(decl) && !movedSymbols.has(symbol)) {
+ newFileImportsFromOldFile.add(symbol);
+ }
+ }
+ });
+ }
+ var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone();
+ var oldFileImportsFromNewFile = new SymbolSet();
+ for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) {
+ var statement = _c[_b];
+ if (ts.contains(toMove, statement))
+ continue;
+ forEachReference(statement, checker, function (symbol) {
+ if (movedSymbols.has(symbol))
+ oldFileImportsFromNewFile.add(symbol);
+ unusedImportsFromOldFile.delete(symbol);
+ });
+ }
+ return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile };
+ }
+ // Below should all be utilities
+ function isInImport(decl) {
+ switch (decl.kind) {
+ case 242 /* ImportEqualsDeclaration */:
+ case 247 /* ImportSpecifier */:
+ case 244 /* ImportClause */:
+ return true;
+ case 231 /* VariableDeclaration */:
+ return isVariableDeclarationInImport(decl);
+ case 181 /* BindingElement */:
+ return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent);
+ default:
+ return false;
+ }
+ }
+ function isVariableDeclarationInImport(decl) {
+ return ts.isSourceFile(decl.parent.parent.parent) &&
+ ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true);
+ }
+ function filterImport(i, moduleSpecifier, keep) {
+ switch (i.kind) {
+ case 243 /* ImportDeclaration */: {
+ var clause = i.importClause;
+ var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined;
+ var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep);
+ return defaultImport || namedBindings
+ ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier)
+ : undefined;
+ }
+ case 242 /* ImportEqualsDeclaration */:
+ return keep(i.name) ? i : undefined;
+ case 231 /* VariableDeclaration */: {
+ var name = filterBindingName(i.name, keep);
+ return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined;
+ }
+ default:
+ return ts.Debug.assertNever(i);
+ }
+ }
+ function filterNamedBindings(namedBindings, keep) {
+ if (namedBindings.kind === 245 /* NamespaceImport */) {
+ return keep(namedBindings.name) ? namedBindings : undefined;
+ }
+ else {
+ var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); });
+ return newElements.length ? ts.createNamedImports(newElements) : undefined;
+ }
+ }
+ function filterBindingName(name, keep) {
+ switch (name.kind) {
+ case 71 /* Identifier */:
+ return keep(name) ? name : undefined;
+ case 180 /* ArrayBindingPattern */:
+ return name;
+ case 179 /* ObjectBindingPattern */: {
+ // We can't handle nested destructurings or property names well here, so just copy them all.
+ var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); });
+ return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined;
+ }
+ }
+ }
+ function forEachReference(node, checker, onReference) {
+ node.forEachChild(function cb(node) {
+ if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) {
+ var sym = checker.getSymbolAtLocation(node);
+ if (sym)
+ onReference(sym);
+ }
+ else {
+ node.forEachChild(cb);
+ }
+ });
+ }
+ var SymbolSet = /** @class */ (function () {
+ function SymbolSet() {
+ this.map = ts.createMap();
+ }
+ SymbolSet.prototype.add = function (symbol) {
+ this.map.set(String(ts.getSymbolId(symbol)), symbol);
+ };
+ SymbolSet.prototype.has = function (symbol) {
+ return this.map.has(String(ts.getSymbolId(symbol)));
+ };
+ SymbolSet.prototype.delete = function (symbol) {
+ this.map.delete(String(ts.getSymbolId(symbol)));
+ };
+ SymbolSet.prototype.forEach = function (cb) {
+ this.map.forEach(cb);
+ };
+ SymbolSet.prototype.forEachEntry = function (cb) {
+ return ts.forEachEntry(this.map, cb);
+ };
+ SymbolSet.prototype.clone = function () {
+ var clone = new SymbolSet();
+ ts.copyEntries(this.map, clone.map);
+ return clone;
+ };
+ return SymbolSet;
+ }());
+ function isTopLevelDeclaration(node) {
+ return isNonVariableTopLevelDeclaration(node) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent);
+ }
+ function isTopLevelDeclarationStatement(node) {
+ ts.Debug.assert(ts.isSourceFile(node.parent));
+ return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node);
+ }
+ function isNonVariableTopLevelDeclaration(node) {
+ switch (node.kind) {
+ case 233 /* FunctionDeclaration */:
+ case 234 /* ClassDeclaration */:
+ case 238 /* ModuleDeclaration */:
+ case 237 /* EnumDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 242 /* ImportEqualsDeclaration */:
+ return true;
+ default:
+ return false;
+ }
+ }
+ function forEachTopLevelDeclaration(statement, cb) {
+ switch (statement.kind) {
+ case 233 /* FunctionDeclaration */:
+ case 234 /* ClassDeclaration */:
+ case 238 /* ModuleDeclaration */:
+ case 237 /* EnumDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 242 /* ImportEqualsDeclaration */:
+ return cb(statement);
+ case 213 /* VariableStatement */:
+ return ts.forEach(statement.declarationList.declarations, cb);
+ case 215 /* ExpressionStatement */: {
+ var expression = statement.expression;
+ return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */
+ ? cb(statement)
+ : undefined;
+ }
+ }
+ }
+ function nameOfTopLevelDeclaration(d) {
+ return d.kind === 215 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier);
+ }
+ function getTopLevelDeclarationStatement(d) {
+ return ts.isVariableDeclaration(d) ? d.parent.parent : d;
+ }
+ function addExportToChanges(sourceFile, decl, changes, useEs6Exports) {
+ if (isExported(sourceFile, decl, useEs6Exports))
+ return;
+ if (useEs6Exports) {
+ if (!ts.isExpressionStatement(decl))
+ changes.insertExportModifier(sourceFile, decl);
+ }
+ else {
+ var names = getNamesToExportInCommonJS(decl);
+ if (names.length !== 0)
+ changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment));
+ }
+ }
+ function isExported(sourceFile, decl, useEs6Exports) {
+ if (useEs6Exports) {
+ return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */);
+ }
+ else {
+ return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); });
+ }
+ }
+ function addExport(decl, useEs6Exports) {
+ return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl);
+ }
+ function addEs6Export(d) {
+ var modifiers = ts.concatenate([ts.createModifier(84 /* ExportKeyword */)], d.modifiers);
+ switch (d.kind) {
+ case 233 /* FunctionDeclaration */:
+ return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body);
+ case 234 /* ClassDeclaration */:
+ return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
+ case 213 /* VariableStatement */:
+ return ts.updateVariableStatement(d, modifiers, d.declarationList);
+ case 238 /* ModuleDeclaration */:
+ return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body);
+ case 237 /* EnumDeclaration */:
+ return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members);
+ case 236 /* TypeAliasDeclaration */:
+ return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type);
+ case 235 /* InterfaceDeclaration */:
+ return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members);
+ case 242 /* ImportEqualsDeclaration */:
+ return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference);
+ case 215 /* ExpressionStatement */:
+ return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
+ default:
+ return ts.Debug.assertNever(d);
+ }
+ }
+ function addCommonjsExport(decl) {
+ return [decl].concat(getNamesToExportInCommonJS(decl).map(createExportAssignment));
+ }
+ function getNamesToExportInCommonJS(decl) {
+ switch (decl.kind) {
+ case 233 /* FunctionDeclaration */:
+ case 234 /* ClassDeclaration */:
+ return [decl.name.text];
+ case 213 /* VariableStatement */:
+ return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; });
+ case 238 /* ModuleDeclaration */:
+ case 237 /* EnumDeclaration */:
+ case 236 /* TypeAliasDeclaration */:
+ case 235 /* InterfaceDeclaration */:
+ case 242 /* ImportEqualsDeclaration */:
+ return undefined;
+ case 215 /* ExpressionStatement */:
+ return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...`
+ default:
+ ts.Debug.assertNever(decl);
+ }
+ }
+ /** Creates `exports.x = x;` */
+ function createExportAssignment(name) {
+ return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 58 /* EqualsToken */, ts.createIdentifier(name)));
+ }
+ })(refactor = ts.refactor || (ts.refactor = {}));
+})(ts || (ts = {}));
+/* @internal */
+var ts;
(function (ts) {
var sourcemaps;
(function (sourcemaps) {
@@ -103563,7 +105450,7 @@ var ts;
if (!children.length) {
return undefined;
}
- var child = ts.find(children, function (kid) { return kid.kind < 275 /* FirstJSDocNode */ || kid.kind > 293 /* LastJSDocNode */; });
+ var child = ts.find(children, function (kid) { return kid.kind < 277 /* FirstJSDocNode */ || kid.kind > 295 /* LastJSDocNode */; });
return child.kind < 145 /* FirstNode */ ?
child :
child.getFirstToken(sourceFile);
@@ -103633,7 +105520,7 @@ var ts;
}
}
function createSyntaxList(nodes, parent) {
- var list = createNode(294 /* SyntaxList */, nodes.pos, nodes.end, parent);
+ var list = createNode(296 /* SyntaxList */, nodes.pos, nodes.end, parent);
list._children = [];
var pos = nodes.pos;
for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) {
@@ -104156,6 +106043,9 @@ var ts;
HostCache.prototype.compilationSettings = function () {
return this._compilationSettings;
};
+ HostCache.prototype.getProjectReferences = function () {
+ return this.host.getProjectReferences && this.host.getProjectReferences();
+ };
HostCache.prototype.createEntry = function (fileName, path) {
var entry;
var scriptSnapshot = this.host.getScriptSnapshot(fileName);
@@ -104185,9 +106075,18 @@ var ts;
return ts.isString(info) ? undefined : info;
};
HostCache.prototype.getRootFileNames = function () {
- return ts.arrayFrom(this.fileNameToEntry.values(), function (entry) {
- return ts.isString(entry) ? entry : entry.hostFileName;
+ var names = [];
+ this.fileNameToEntry.forEach(function (entry) {
+ if (ts.isString(entry)) {
+ names.push(entry);
+ }
+ else {
+ if (entry.scriptKind !== 6 /* JSON */) {
+ names.push(entry.hostFileName);
+ }
+ }
});
+ return names;
};
HostCache.prototype.getVersion = function (path) {
var file = this.getHostFileInformation(path);
@@ -104363,6 +106262,7 @@ var ts;
}
ts.createSourceFileLikeCache = createSourceFileLikeCache;
function createLanguageService(host, documentRegistry, syntaxOnly) {
+ var _a;
if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); }
if (syntaxOnly === void 0) { syntaxOnly = false; }
var syntaxTreeCache = new SyntaxTreeCache(host);
@@ -104466,7 +106366,14 @@ var ts;
};
}
var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings);
- program = ts.createProgram(rootFileNames, newSettings, compilerHost, program);
+ var options = {
+ rootNames: rootFileNames,
+ options: newSettings,
+ host: compilerHost,
+ oldProgram: program,
+ projectReferences: hostCache.getProjectReferences()
+ };
+ program = ts.createProgram(options);
// hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point.
// It needs to be cleared to allow all collected snapshots to be released
hostCache = undefined;
@@ -104670,6 +106577,11 @@ var ts;
}
return checker.getSymbolAtLocation(node);
}
+ function toLineColumnOffset(fileName, position) {
+ var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
+ var file = program.getSourceFile(path) || sourcemappedFileCache.get(path);
+ return file.getLineAndCharacterOfPosition(position);
+ }
// Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M])
var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)$/gm;
var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/;
@@ -104744,15 +106656,15 @@ var ts;
function getTargetOfMappedPosition(input) {
var info = extract(input);
if (ts.endsWith(info.fileName, ".d.ts" /* Dts */)) {
- var file = program.getSourceFile(info.fileName);
- if (!file) {
+ var file_17 = program.getSourceFile(info.fileName);
+ if (!file_17) {
var path = ts.toPath(info.fileName, currentDirectory, getCanonicalFileName);
- file = sourcemappedFileCache.get(path);
+ file_17 = sourcemappedFileCache.get(path);
}
- if (!file) {
+ if (!file_17) {
return input;
}
- var mapper = getSourceMapper(info.fileName, file);
+ var mapper = getSourceMapper(info.fileName, file_17);
var newLoc = mapper.getOriginalPosition(info);
if (newLoc === info)
return input;
@@ -105317,8 +107229,8 @@ var ts;
getProgram: getProgram,
getApplicableRefactors: getApplicableRefactors,
getEditsForRefactor: getEditsForRefactor,
+ toLineColumnOffset: toLineColumnOffset
};
- var _a;
}
ts.createLanguageService = createLanguageService;
/* @internal */
@@ -105389,20 +107301,20 @@ var ts;
function getPropertySymbolsFromType(type, propName) {
var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName));
if (name && type) {
- var result_6 = [];
+ var result_7 = [];
var symbol = type.getProperty(name);
if (type.flags & 131072 /* Union */) {
ts.forEach(type.types, function (t) {
var symbol = t.getProperty(name);
if (symbol) {
- result_6.push(symbol);
+ result_7.push(symbol);
}
});
- return result_6;
+ return result_7;
}
if (symbol) {
- result_6.push(symbol);
- return result_6;
+ result_7.push(symbol);
+ return result_7;
}
}
return undefined;
@@ -105469,7 +107381,7 @@ var ts;
return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd());
}
function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) {
- return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent));
+ return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile));
}
function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) {
if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) {
@@ -105484,7 +107396,7 @@ var ts;
return spanInNode(ts.findPrecedingToken(node.pos, sourceFile));
}
function spanInNextNode(node) {
- return spanInNode(ts.findNextToken(node, node.parent));
+ return spanInNode(ts.findNextToken(node, node.parent, sourceFile));
}
function spanInNode(node) {
if (node) {
@@ -106823,5 +108735,3 @@ var TypeScript;
// TODO: it should be moved into a namespace though.
/* @internal */
var toolsVersion = ts.versionMajorMinor;
-
-//# sourceMappingURL=typescriptServices.js.map
diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js
index a273ff745f7..b0edb96170f 100644
--- a/lib/typingsInstaller.js
+++ b/lib/typingsInstaller.js
@@ -34,564 +34,18 @@ var __extends = (this && this.__extends) || (function () {
})();
var ts;
(function (ts) {
- var Comparison;
- (function (Comparison) {
- Comparison[Comparison["LessThan"] = -1] = "LessThan";
- Comparison[Comparison["EqualTo"] = 0] = "EqualTo";
- Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan";
- })(Comparison = ts.Comparison || (ts.Comparison = {}));
- var SyntaxKind;
- (function (SyntaxKind) {
- SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown";
- SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken";
- SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia";
- SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia";
- SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia";
- SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia";
- SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia";
- SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia";
- SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral";
- SyntaxKind[SyntaxKind["StringLiteral"] = 9] = "StringLiteral";
- SyntaxKind[SyntaxKind["JsxText"] = 10] = "JsxText";
- SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 11] = "JsxTextAllWhiteSpaces";
- SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 12] = "RegularExpressionLiteral";
- SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 13] = "NoSubstitutionTemplateLiteral";
- SyntaxKind[SyntaxKind["TemplateHead"] = 14] = "TemplateHead";
- SyntaxKind[SyntaxKind["TemplateMiddle"] = 15] = "TemplateMiddle";
- SyntaxKind[SyntaxKind["TemplateTail"] = 16] = "TemplateTail";
- SyntaxKind[SyntaxKind["OpenBraceToken"] = 17] = "OpenBraceToken";
- SyntaxKind[SyntaxKind["CloseBraceToken"] = 18] = "CloseBraceToken";
- SyntaxKind[SyntaxKind["OpenParenToken"] = 19] = "OpenParenToken";
- SyntaxKind[SyntaxKind["CloseParenToken"] = 20] = "CloseParenToken";
- SyntaxKind[SyntaxKind["OpenBracketToken"] = 21] = "OpenBracketToken";
- SyntaxKind[SyntaxKind["CloseBracketToken"] = 22] = "CloseBracketToken";
- SyntaxKind[SyntaxKind["DotToken"] = 23] = "DotToken";
- SyntaxKind[SyntaxKind["DotDotDotToken"] = 24] = "DotDotDotToken";
- SyntaxKind[SyntaxKind["SemicolonToken"] = 25] = "SemicolonToken";
- SyntaxKind[SyntaxKind["CommaToken"] = 26] = "CommaToken";
- SyntaxKind[SyntaxKind["LessThanToken"] = 27] = "LessThanToken";
- SyntaxKind[SyntaxKind["LessThanSlashToken"] = 28] = "LessThanSlashToken";
- SyntaxKind[SyntaxKind["GreaterThanToken"] = 29] = "GreaterThanToken";
- SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 30] = "LessThanEqualsToken";
- SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 31] = "GreaterThanEqualsToken";
- SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 32] = "EqualsEqualsToken";
- SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 33] = "ExclamationEqualsToken";
- SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 34] = "EqualsEqualsEqualsToken";
- SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 35] = "ExclamationEqualsEqualsToken";
- SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 36] = "EqualsGreaterThanToken";
- SyntaxKind[SyntaxKind["PlusToken"] = 37] = "PlusToken";
- SyntaxKind[SyntaxKind["MinusToken"] = 38] = "MinusToken";
- SyntaxKind[SyntaxKind["AsteriskToken"] = 39] = "AsteriskToken";
- SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 40] = "AsteriskAsteriskToken";
- SyntaxKind[SyntaxKind["SlashToken"] = 41] = "SlashToken";
- SyntaxKind[SyntaxKind["PercentToken"] = 42] = "PercentToken";
- SyntaxKind[SyntaxKind["PlusPlusToken"] = 43] = "PlusPlusToken";
- SyntaxKind[SyntaxKind["MinusMinusToken"] = 44] = "MinusMinusToken";
- SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 45] = "LessThanLessThanToken";
- SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 46] = "GreaterThanGreaterThanToken";
- SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 47] = "GreaterThanGreaterThanGreaterThanToken";
- SyntaxKind[SyntaxKind["AmpersandToken"] = 48] = "AmpersandToken";
- SyntaxKind[SyntaxKind["BarToken"] = 49] = "BarToken";
- SyntaxKind[SyntaxKind["CaretToken"] = 50] = "CaretToken";
- SyntaxKind[SyntaxKind["ExclamationToken"] = 51] = "ExclamationToken";
- SyntaxKind[SyntaxKind["TildeToken"] = 52] = "TildeToken";
- SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 53] = "AmpersandAmpersandToken";
- SyntaxKind[SyntaxKind["BarBarToken"] = 54] = "BarBarToken";
- SyntaxKind[SyntaxKind["QuestionToken"] = 55] = "QuestionToken";
- SyntaxKind[SyntaxKind["ColonToken"] = 56] = "ColonToken";
- SyntaxKind[SyntaxKind["AtToken"] = 57] = "AtToken";
- SyntaxKind[SyntaxKind["EqualsToken"] = 58] = "EqualsToken";
- SyntaxKind[SyntaxKind["PlusEqualsToken"] = 59] = "PlusEqualsToken";
- SyntaxKind[SyntaxKind["MinusEqualsToken"] = 60] = "MinusEqualsToken";
- SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 61] = "AsteriskEqualsToken";
- SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 62] = "AsteriskAsteriskEqualsToken";
- SyntaxKind[SyntaxKind["SlashEqualsToken"] = 63] = "SlashEqualsToken";
- SyntaxKind[SyntaxKind["PercentEqualsToken"] = 64] = "PercentEqualsToken";
- SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 65] = "LessThanLessThanEqualsToken";
- SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 66] = "GreaterThanGreaterThanEqualsToken";
- SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 67] = "GreaterThanGreaterThanGreaterThanEqualsToken";
- SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 68] = "AmpersandEqualsToken";
- SyntaxKind[SyntaxKind["BarEqualsToken"] = 69] = "BarEqualsToken";
- SyntaxKind[SyntaxKind["CaretEqualsToken"] = 70] = "CaretEqualsToken";
- SyntaxKind[SyntaxKind["Identifier"] = 71] = "Identifier";
- SyntaxKind[SyntaxKind["BreakKeyword"] = 72] = "BreakKeyword";
- SyntaxKind[SyntaxKind["CaseKeyword"] = 73] = "CaseKeyword";
- SyntaxKind[SyntaxKind["CatchKeyword"] = 74] = "CatchKeyword";
- SyntaxKind[SyntaxKind["ClassKeyword"] = 75] = "ClassKeyword";
- SyntaxKind[SyntaxKind["ConstKeyword"] = 76] = "ConstKeyword";
- SyntaxKind[SyntaxKind["ContinueKeyword"] = 77] = "ContinueKeyword";
- SyntaxKind[SyntaxKind["DebuggerKeyword"] = 78] = "DebuggerKeyword";
- SyntaxKind[SyntaxKind["DefaultKeyword"] = 79] = "DefaultKeyword";
- SyntaxKind[SyntaxKind["DeleteKeyword"] = 80] = "DeleteKeyword";
- SyntaxKind[SyntaxKind["DoKeyword"] = 81] = "DoKeyword";
- SyntaxKind[SyntaxKind["ElseKeyword"] = 82] = "ElseKeyword";
- SyntaxKind[SyntaxKind["EnumKeyword"] = 83] = "EnumKeyword";
- SyntaxKind[SyntaxKind["ExportKeyword"] = 84] = "ExportKeyword";
- SyntaxKind[SyntaxKind["ExtendsKeyword"] = 85] = "ExtendsKeyword";
- SyntaxKind[SyntaxKind["FalseKeyword"] = 86] = "FalseKeyword";
- SyntaxKind[SyntaxKind["FinallyKeyword"] = 87] = "FinallyKeyword";
- SyntaxKind[SyntaxKind["ForKeyword"] = 88] = "ForKeyword";
- SyntaxKind[SyntaxKind["FunctionKeyword"] = 89] = "FunctionKeyword";
- SyntaxKind[SyntaxKind["IfKeyword"] = 90] = "IfKeyword";
- SyntaxKind[SyntaxKind["ImportKeyword"] = 91] = "ImportKeyword";
- SyntaxKind[SyntaxKind["InKeyword"] = 92] = "InKeyword";
- SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 93] = "InstanceOfKeyword";
- SyntaxKind[SyntaxKind["NewKeyword"] = 94] = "NewKeyword";
- SyntaxKind[SyntaxKind["NullKeyword"] = 95] = "NullKeyword";
- SyntaxKind[SyntaxKind["ReturnKeyword"] = 96] = "ReturnKeyword";
- SyntaxKind[SyntaxKind["SuperKeyword"] = 97] = "SuperKeyword";
- SyntaxKind[SyntaxKind["SwitchKeyword"] = 98] = "SwitchKeyword";
- SyntaxKind[SyntaxKind["ThisKeyword"] = 99] = "ThisKeyword";
- SyntaxKind[SyntaxKind["ThrowKeyword"] = 100] = "ThrowKeyword";
- SyntaxKind[SyntaxKind["TrueKeyword"] = 101] = "TrueKeyword";
- SyntaxKind[SyntaxKind["TryKeyword"] = 102] = "TryKeyword";
- SyntaxKind[SyntaxKind["TypeOfKeyword"] = 103] = "TypeOfKeyword";
- SyntaxKind[SyntaxKind["VarKeyword"] = 104] = "VarKeyword";
- SyntaxKind[SyntaxKind["VoidKeyword"] = 105] = "VoidKeyword";
- SyntaxKind[SyntaxKind["WhileKeyword"] = 106] = "WhileKeyword";
- SyntaxKind[SyntaxKind["WithKeyword"] = 107] = "WithKeyword";
- SyntaxKind[SyntaxKind["ImplementsKeyword"] = 108] = "ImplementsKeyword";
- SyntaxKind[SyntaxKind["InterfaceKeyword"] = 109] = "InterfaceKeyword";
- SyntaxKind[SyntaxKind["LetKeyword"] = 110] = "LetKeyword";
- SyntaxKind[SyntaxKind["PackageKeyword"] = 111] = "PackageKeyword";
- SyntaxKind[SyntaxKind["PrivateKeyword"] = 112] = "PrivateKeyword";
- SyntaxKind[SyntaxKind["ProtectedKeyword"] = 113] = "ProtectedKeyword";
- SyntaxKind[SyntaxKind["PublicKeyword"] = 114] = "PublicKeyword";
- SyntaxKind[SyntaxKind["StaticKeyword"] = 115] = "StaticKeyword";
- SyntaxKind[SyntaxKind["YieldKeyword"] = 116] = "YieldKeyword";
- SyntaxKind[SyntaxKind["AbstractKeyword"] = 117] = "AbstractKeyword";
- SyntaxKind[SyntaxKind["AsKeyword"] = 118] = "AsKeyword";
- SyntaxKind[SyntaxKind["AnyKeyword"] = 119] = "AnyKeyword";
- SyntaxKind[SyntaxKind["AsyncKeyword"] = 120] = "AsyncKeyword";
- SyntaxKind[SyntaxKind["AwaitKeyword"] = 121] = "AwaitKeyword";
- SyntaxKind[SyntaxKind["BooleanKeyword"] = 122] = "BooleanKeyword";
- SyntaxKind[SyntaxKind["ConstructorKeyword"] = 123] = "ConstructorKeyword";
- SyntaxKind[SyntaxKind["DeclareKeyword"] = 124] = "DeclareKeyword";
- SyntaxKind[SyntaxKind["GetKeyword"] = 125] = "GetKeyword";
- SyntaxKind[SyntaxKind["InferKeyword"] = 126] = "InferKeyword";
- SyntaxKind[SyntaxKind["IsKeyword"] = 127] = "IsKeyword";
- SyntaxKind[SyntaxKind["KeyOfKeyword"] = 128] = "KeyOfKeyword";
- SyntaxKind[SyntaxKind["ModuleKeyword"] = 129] = "ModuleKeyword";
- SyntaxKind[SyntaxKind["NamespaceKeyword"] = 130] = "NamespaceKeyword";
- SyntaxKind[SyntaxKind["NeverKeyword"] = 131] = "NeverKeyword";
- SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 132] = "ReadonlyKeyword";
- SyntaxKind[SyntaxKind["RequireKeyword"] = 133] = "RequireKeyword";
- SyntaxKind[SyntaxKind["NumberKeyword"] = 134] = "NumberKeyword";
- SyntaxKind[SyntaxKind["ObjectKeyword"] = 135] = "ObjectKeyword";
- SyntaxKind[SyntaxKind["SetKeyword"] = 136] = "SetKeyword";
- SyntaxKind[SyntaxKind["StringKeyword"] = 137] = "StringKeyword";
- SyntaxKind[SyntaxKind["SymbolKeyword"] = 138] = "SymbolKeyword";
- SyntaxKind[SyntaxKind["TypeKeyword"] = 139] = "TypeKeyword";
- SyntaxKind[SyntaxKind["UndefinedKeyword"] = 140] = "UndefinedKeyword";
- SyntaxKind[SyntaxKind["UniqueKeyword"] = 141] = "UniqueKeyword";
- SyntaxKind[SyntaxKind["FromKeyword"] = 142] = "FromKeyword";
- SyntaxKind[SyntaxKind["GlobalKeyword"] = 143] = "GlobalKeyword";
- SyntaxKind[SyntaxKind["OfKeyword"] = 144] = "OfKeyword";
- SyntaxKind[SyntaxKind["QualifiedName"] = 145] = "QualifiedName";
- SyntaxKind[SyntaxKind["ComputedPropertyName"] = 146] = "ComputedPropertyName";
- SyntaxKind[SyntaxKind["TypeParameter"] = 147] = "TypeParameter";
- SyntaxKind[SyntaxKind["Parameter"] = 148] = "Parameter";
- SyntaxKind[SyntaxKind["Decorator"] = 149] = "Decorator";
- SyntaxKind[SyntaxKind["PropertySignature"] = 150] = "PropertySignature";
- SyntaxKind[SyntaxKind["PropertyDeclaration"] = 151] = "PropertyDeclaration";
- SyntaxKind[SyntaxKind["MethodSignature"] = 152] = "MethodSignature";
- SyntaxKind[SyntaxKind["MethodDeclaration"] = 153] = "MethodDeclaration";
- SyntaxKind[SyntaxKind["Constructor"] = 154] = "Constructor";
- SyntaxKind[SyntaxKind["GetAccessor"] = 155] = "GetAccessor";
- SyntaxKind[SyntaxKind["SetAccessor"] = 156] = "SetAccessor";
- SyntaxKind[SyntaxKind["CallSignature"] = 157] = "CallSignature";
- SyntaxKind[SyntaxKind["ConstructSignature"] = 158] = "ConstructSignature";
- SyntaxKind[SyntaxKind["IndexSignature"] = 159] = "IndexSignature";
- SyntaxKind[SyntaxKind["TypePredicate"] = 160] = "TypePredicate";
- SyntaxKind[SyntaxKind["TypeReference"] = 161] = "TypeReference";
- SyntaxKind[SyntaxKind["FunctionType"] = 162] = "FunctionType";
- SyntaxKind[SyntaxKind["ConstructorType"] = 163] = "ConstructorType";
- SyntaxKind[SyntaxKind["TypeQuery"] = 164] = "TypeQuery";
- SyntaxKind[SyntaxKind["TypeLiteral"] = 165] = "TypeLiteral";
- SyntaxKind[SyntaxKind["ArrayType"] = 166] = "ArrayType";
- SyntaxKind[SyntaxKind["TupleType"] = 167] = "TupleType";
- SyntaxKind[SyntaxKind["UnionType"] = 168] = "UnionType";
- SyntaxKind[SyntaxKind["IntersectionType"] = 169] = "IntersectionType";
- SyntaxKind[SyntaxKind["ConditionalType"] = 170] = "ConditionalType";
- SyntaxKind[SyntaxKind["InferType"] = 171] = "InferType";
- SyntaxKind[SyntaxKind["ParenthesizedType"] = 172] = "ParenthesizedType";
- SyntaxKind[SyntaxKind["ThisType"] = 173] = "ThisType";
- SyntaxKind[SyntaxKind["TypeOperator"] = 174] = "TypeOperator";
- SyntaxKind[SyntaxKind["IndexedAccessType"] = 175] = "IndexedAccessType";
- SyntaxKind[SyntaxKind["MappedType"] = 176] = "MappedType";
- SyntaxKind[SyntaxKind["LiteralType"] = 177] = "LiteralType";
- SyntaxKind[SyntaxKind["ImportType"] = 178] = "ImportType";
- SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 179] = "ObjectBindingPattern";
- SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 180] = "ArrayBindingPattern";
- SyntaxKind[SyntaxKind["BindingElement"] = 181] = "BindingElement";
- SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 182] = "ArrayLiteralExpression";
- SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 183] = "ObjectLiteralExpression";
- SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 184] = "PropertyAccessExpression";
- SyntaxKind[SyntaxKind["ElementAccessExpression"] = 185] = "ElementAccessExpression";
- SyntaxKind[SyntaxKind["CallExpression"] = 186] = "CallExpression";
- SyntaxKind[SyntaxKind["NewExpression"] = 187] = "NewExpression";
- SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 188] = "TaggedTemplateExpression";
- SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 189] = "TypeAssertionExpression";
- SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 190] = "ParenthesizedExpression";
- SyntaxKind[SyntaxKind["FunctionExpression"] = 191] = "FunctionExpression";
- SyntaxKind[SyntaxKind["ArrowFunction"] = 192] = "ArrowFunction";
- SyntaxKind[SyntaxKind["DeleteExpression"] = 193] = "DeleteExpression";
- SyntaxKind[SyntaxKind["TypeOfExpression"] = 194] = "TypeOfExpression";
- SyntaxKind[SyntaxKind["VoidExpression"] = 195] = "VoidExpression";
- SyntaxKind[SyntaxKind["AwaitExpression"] = 196] = "AwaitExpression";
- SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 197] = "PrefixUnaryExpression";
- SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 198] = "PostfixUnaryExpression";
- SyntaxKind[SyntaxKind["BinaryExpression"] = 199] = "BinaryExpression";
- SyntaxKind[SyntaxKind["ConditionalExpression"] = 200] = "ConditionalExpression";
- SyntaxKind[SyntaxKind["TemplateExpression"] = 201] = "TemplateExpression";
- SyntaxKind[SyntaxKind["YieldExpression"] = 202] = "YieldExpression";
- SyntaxKind[SyntaxKind["SpreadElement"] = 203] = "SpreadElement";
- SyntaxKind[SyntaxKind["ClassExpression"] = 204] = "ClassExpression";
- SyntaxKind[SyntaxKind["OmittedExpression"] = 205] = "OmittedExpression";
- SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 206] = "ExpressionWithTypeArguments";
- SyntaxKind[SyntaxKind["AsExpression"] = 207] = "AsExpression";
- SyntaxKind[SyntaxKind["NonNullExpression"] = 208] = "NonNullExpression";
- SyntaxKind[SyntaxKind["MetaProperty"] = 209] = "MetaProperty";
- SyntaxKind[SyntaxKind["TemplateSpan"] = 210] = "TemplateSpan";
- SyntaxKind[SyntaxKind["SemicolonClassElement"] = 211] = "SemicolonClassElement";
- SyntaxKind[SyntaxKind["Block"] = 212] = "Block";
- SyntaxKind[SyntaxKind["VariableStatement"] = 213] = "VariableStatement";
- SyntaxKind[SyntaxKind["EmptyStatement"] = 214] = "EmptyStatement";
- SyntaxKind[SyntaxKind["ExpressionStatement"] = 215] = "ExpressionStatement";
- SyntaxKind[SyntaxKind["IfStatement"] = 216] = "IfStatement";
- SyntaxKind[SyntaxKind["DoStatement"] = 217] = "DoStatement";
- SyntaxKind[SyntaxKind["WhileStatement"] = 218] = "WhileStatement";
- SyntaxKind[SyntaxKind["ForStatement"] = 219] = "ForStatement";
- SyntaxKind[SyntaxKind["ForInStatement"] = 220] = "ForInStatement";
- SyntaxKind[SyntaxKind["ForOfStatement"] = 221] = "ForOfStatement";
- SyntaxKind[SyntaxKind["ContinueStatement"] = 222] = "ContinueStatement";
- SyntaxKind[SyntaxKind["BreakStatement"] = 223] = "BreakStatement";
- SyntaxKind[SyntaxKind["ReturnStatement"] = 224] = "ReturnStatement";
- SyntaxKind[SyntaxKind["WithStatement"] = 225] = "WithStatement";
- SyntaxKind[SyntaxKind["SwitchStatement"] = 226] = "SwitchStatement";
- SyntaxKind[SyntaxKind["LabeledStatement"] = 227] = "LabeledStatement";
- SyntaxKind[SyntaxKind["ThrowStatement"] = 228] = "ThrowStatement";
- SyntaxKind[SyntaxKind["TryStatement"] = 229] = "TryStatement";
- SyntaxKind[SyntaxKind["DebuggerStatement"] = 230] = "DebuggerStatement";
- SyntaxKind[SyntaxKind["VariableDeclaration"] = 231] = "VariableDeclaration";
- SyntaxKind[SyntaxKind["VariableDeclarationList"] = 232] = "VariableDeclarationList";
- SyntaxKind[SyntaxKind["FunctionDeclaration"] = 233] = "FunctionDeclaration";
- SyntaxKind[SyntaxKind["ClassDeclaration"] = 234] = "ClassDeclaration";
- SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 235] = "InterfaceDeclaration";
- SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 236] = "TypeAliasDeclaration";
- SyntaxKind[SyntaxKind["EnumDeclaration"] = 237] = "EnumDeclaration";
- SyntaxKind[SyntaxKind["ModuleDeclaration"] = 238] = "ModuleDeclaration";
- SyntaxKind[SyntaxKind["ModuleBlock"] = 239] = "ModuleBlock";
- SyntaxKind[SyntaxKind["CaseBlock"] = 240] = "CaseBlock";
- SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 241] = "NamespaceExportDeclaration";
- SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 242] = "ImportEqualsDeclaration";
- SyntaxKind[SyntaxKind["ImportDeclaration"] = 243] = "ImportDeclaration";
- SyntaxKind[SyntaxKind["ImportClause"] = 244] = "ImportClause";
- SyntaxKind[SyntaxKind["NamespaceImport"] = 245] = "NamespaceImport";
- SyntaxKind[SyntaxKind["NamedImports"] = 246] = "NamedImports";
- SyntaxKind[SyntaxKind["ImportSpecifier"] = 247] = "ImportSpecifier";
- SyntaxKind[SyntaxKind["ExportAssignment"] = 248] = "ExportAssignment";
- SyntaxKind[SyntaxKind["ExportDeclaration"] = 249] = "ExportDeclaration";
- SyntaxKind[SyntaxKind["NamedExports"] = 250] = "NamedExports";
- SyntaxKind[SyntaxKind["ExportSpecifier"] = 251] = "ExportSpecifier";
- SyntaxKind[SyntaxKind["MissingDeclaration"] = 252] = "MissingDeclaration";
- SyntaxKind[SyntaxKind["ExternalModuleReference"] = 253] = "ExternalModuleReference";
- SyntaxKind[SyntaxKind["JsxElement"] = 254] = "JsxElement";
- SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 255] = "JsxSelfClosingElement";
- SyntaxKind[SyntaxKind["JsxOpeningElement"] = 256] = "JsxOpeningElement";
- SyntaxKind[SyntaxKind["JsxClosingElement"] = 257] = "JsxClosingElement";
- SyntaxKind[SyntaxKind["JsxFragment"] = 258] = "JsxFragment";
- SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 259] = "JsxOpeningFragment";
- SyntaxKind[SyntaxKind["JsxClosingFragment"] = 260] = "JsxClosingFragment";
- SyntaxKind[SyntaxKind["JsxAttribute"] = 261] = "JsxAttribute";
- SyntaxKind[SyntaxKind["JsxAttributes"] = 262] = "JsxAttributes";
- SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 263] = "JsxSpreadAttribute";
- SyntaxKind[SyntaxKind["JsxExpression"] = 264] = "JsxExpression";
- SyntaxKind[SyntaxKind["CaseClause"] = 265] = "CaseClause";
- SyntaxKind[SyntaxKind["DefaultClause"] = 266] = "DefaultClause";
- SyntaxKind[SyntaxKind["HeritageClause"] = 267] = "HeritageClause";
- SyntaxKind[SyntaxKind["CatchClause"] = 268] = "CatchClause";
- SyntaxKind[SyntaxKind["PropertyAssignment"] = 269] = "PropertyAssignment";
- SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 270] = "ShorthandPropertyAssignment";
- SyntaxKind[SyntaxKind["SpreadAssignment"] = 271] = "SpreadAssignment";
- SyntaxKind[SyntaxKind["EnumMember"] = 272] = "EnumMember";
- SyntaxKind[SyntaxKind["SourceFile"] = 273] = "SourceFile";
- SyntaxKind[SyntaxKind["Bundle"] = 274] = "Bundle";
- SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 275] = "JSDocTypeExpression";
- SyntaxKind[SyntaxKind["JSDocAllType"] = 276] = "JSDocAllType";
- SyntaxKind[SyntaxKind["JSDocUnknownType"] = 277] = "JSDocUnknownType";
- SyntaxKind[SyntaxKind["JSDocNullableType"] = 278] = "JSDocNullableType";
- SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 279] = "JSDocNonNullableType";
- SyntaxKind[SyntaxKind["JSDocOptionalType"] = 280] = "JSDocOptionalType";
- SyntaxKind[SyntaxKind["JSDocFunctionType"] = 281] = "JSDocFunctionType";
- SyntaxKind[SyntaxKind["JSDocVariadicType"] = 282] = "JSDocVariadicType";
- SyntaxKind[SyntaxKind["JSDocComment"] = 283] = "JSDocComment";
- SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 284] = "JSDocTypeLiteral";
- SyntaxKind[SyntaxKind["JSDocTag"] = 285] = "JSDocTag";
- SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 286] = "JSDocAugmentsTag";
- SyntaxKind[SyntaxKind["JSDocClassTag"] = 287] = "JSDocClassTag";
- SyntaxKind[SyntaxKind["JSDocParameterTag"] = 288] = "JSDocParameterTag";
- SyntaxKind[SyntaxKind["JSDocReturnTag"] = 289] = "JSDocReturnTag";
- SyntaxKind[SyntaxKind["JSDocTypeTag"] = 290] = "JSDocTypeTag";
- SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 291] = "JSDocTemplateTag";
- SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 292] = "JSDocTypedefTag";
- SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 293] = "JSDocPropertyTag";
- SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList";
- SyntaxKind[SyntaxKind["NotEmittedStatement"] = 295] = "NotEmittedStatement";
- SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 296] = "PartiallyEmittedExpression";
- SyntaxKind[SyntaxKind["CommaListExpression"] = 297] = "CommaListExpression";
- SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 298] = "MergeDeclarationMarker";
- SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 299] = "EndOfDeclarationMarker";
- SyntaxKind[SyntaxKind["Count"] = 300] = "Count";
- SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment";
- SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment";
- SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment";
- SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 70] = "LastCompoundAssignment";
- SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord";
- SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord";
- SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword";
- SyntaxKind[SyntaxKind["LastKeyword"] = 144] = "LastKeyword";
- SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord";
- SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord";
- SyntaxKind[SyntaxKind["FirstTypeNode"] = 160] = "FirstTypeNode";
- SyntaxKind[SyntaxKind["LastTypeNode"] = 178] = "LastTypeNode";
- SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation";
- SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation";
- SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken";
- SyntaxKind[SyntaxKind["LastToken"] = 144] = "LastToken";
- SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken";
- SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken";
- SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken";
- SyntaxKind[SyntaxKind["LastLiteralToken"] = 13] = "LastLiteralToken";
- SyntaxKind[SyntaxKind["FirstTemplateToken"] = 13] = "FirstTemplateToken";
- SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken";
- SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator";
- SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator";
- SyntaxKind[SyntaxKind["FirstNode"] = 145] = "FirstNode";
- SyntaxKind[SyntaxKind["FirstJSDocNode"] = 275] = "FirstJSDocNode";
- SyntaxKind[SyntaxKind["LastJSDocNode"] = 293] = "LastJSDocNode";
- SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 285] = "FirstJSDocTagNode";
- SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 293] = "LastJSDocTagNode";
- SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword";
- SyntaxKind[SyntaxKind["LastContextualKeyword"] = 144] = "LastContextualKeyword";
- })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
- var NodeFlags;
- (function (NodeFlags) {
- NodeFlags[NodeFlags["None"] = 0] = "None";
- NodeFlags[NodeFlags["Let"] = 1] = "Let";
- NodeFlags[NodeFlags["Const"] = 2] = "Const";
- NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace";
- NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized";
- NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace";
- NodeFlags[NodeFlags["ExportContext"] = 32] = "ExportContext";
- NodeFlags[NodeFlags["ContainsThis"] = 64] = "ContainsThis";
- NodeFlags[NodeFlags["HasImplicitReturn"] = 128] = "HasImplicitReturn";
- NodeFlags[NodeFlags["HasExplicitReturn"] = 256] = "HasExplicitReturn";
- NodeFlags[NodeFlags["GlobalAugmentation"] = 512] = "GlobalAugmentation";
- NodeFlags[NodeFlags["HasAsyncFunctions"] = 1024] = "HasAsyncFunctions";
- NodeFlags[NodeFlags["DisallowInContext"] = 2048] = "DisallowInContext";
- NodeFlags[NodeFlags["YieldContext"] = 4096] = "YieldContext";
- NodeFlags[NodeFlags["DecoratorContext"] = 8192] = "DecoratorContext";
- NodeFlags[NodeFlags["AwaitContext"] = 16384] = "AwaitContext";
- NodeFlags[NodeFlags["ThisNodeHasError"] = 32768] = "ThisNodeHasError";
- NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile";
- NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError";
- NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData";
- NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport";
- NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 1048576] = "PossiblyContainsImportMeta";
- NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc";
- NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient";
- NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement";
- NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
- NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags";
- NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags";
- NodeFlags[NodeFlags["ContextFlags"] = 12679168] = "ContextFlags";
- NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags";
- NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 1572864] = "PermanentlySetIncrementalFlags";
- })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {}));
- var ModifierFlags;
- (function (ModifierFlags) {
- ModifierFlags[ModifierFlags["None"] = 0] = "None";
- ModifierFlags[ModifierFlags["Export"] = 1] = "Export";
- ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient";
- ModifierFlags[ModifierFlags["Public"] = 4] = "Public";
- ModifierFlags[ModifierFlags["Private"] = 8] = "Private";
- ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected";
- ModifierFlags[ModifierFlags["Static"] = 32] = "Static";
- ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly";
- ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract";
- ModifierFlags[ModifierFlags["Async"] = 256] = "Async";
- ModifierFlags[ModifierFlags["Default"] = 512] = "Default";
- ModifierFlags[ModifierFlags["Const"] = 2048] = "Const";
- ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
- ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier";
- ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier";
- ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier";
- ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier";
- ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault";
- ModifierFlags[ModifierFlags["All"] = 3071] = "All";
- })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {}));
- var JsxFlags;
- (function (JsxFlags) {
- JsxFlags[JsxFlags["None"] = 0] = "None";
- JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement";
- JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement";
- JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement";
- })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {}));
- var RelationComparisonResult;
- (function (RelationComparisonResult) {
- RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded";
- RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed";
- RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported";
- })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {}));
- var GeneratedIdentifierFlags;
- (function (GeneratedIdentifierFlags) {
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 32] = "Optimistic";
- GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 64] = "FileLevel";
- })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
- var TokenFlags;
- (function (TokenFlags) {
- TokenFlags[TokenFlags["None"] = 0] = "None";
- TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
- TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
- TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
- TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
- TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
- TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
- TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
- TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
- TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
- TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
- TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
- TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
- })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
- var FlowFlags;
- (function (FlowFlags) {
- FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable";
- FlowFlags[FlowFlags["Start"] = 2] = "Start";
- FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel";
- FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel";
- FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment";
- FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition";
- FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition";
- FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause";
- FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation";
- FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced";
- FlowFlags[FlowFlags["Shared"] = 1024] = "Shared";
- FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally";
- FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally";
- FlowFlags[FlowFlags["Label"] = 12] = "Label";
- FlowFlags[FlowFlags["Condition"] = 96] = "Condition";
- })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {}));
var OperationCanceledException = (function () {
function OperationCanceledException() {
}
return OperationCanceledException;
}());
ts.OperationCanceledException = OperationCanceledException;
- var StructureIsReused;
- (function (StructureIsReused) {
- StructureIsReused[StructureIsReused["Not"] = 0] = "Not";
- StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules";
- StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely";
- })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {}));
var ExitStatus;
(function (ExitStatus) {
ExitStatus[ExitStatus["Success"] = 0] = "Success";
ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped";
ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated";
})(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {}));
- var UnionReduction;
- (function (UnionReduction) {
- UnionReduction[UnionReduction["None"] = 0] = "None";
- UnionReduction[UnionReduction["Literal"] = 1] = "Literal";
- UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype";
- })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {}));
- var NodeBuilderFlags;
- (function (NodeBuilderFlags) {
- NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None";
- NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
- NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
- NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
- NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
- NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
- NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing";
- NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
- NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName";
- NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
- NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
- NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
- NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
- NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
- NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral";
- NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier";
- NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier";
- NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection";
- NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
- NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
- NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
- NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 3112960] = "IgnoreErrors";
- NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
- NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
- NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
- NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
- })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
- var TypeFormatFlags;
- (function (TypeFormatFlags) {
- TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None";
- TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation";
- TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
- TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
- TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
- TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
- TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
- TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
- TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
- TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
- TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
- TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
- TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
- TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined";
- TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature";
- TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType";
- TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType";
- TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument";
- TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
- TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike";
- TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469291] = "NodeBuilderFlagsMask";
- })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
- var SymbolFormatFlags;
- (function (SymbolFormatFlags) {
- SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None";
- SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments";
- SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing";
- SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind";
- SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope";
- })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {}));
- var SymbolAccessibility;
- (function (SymbolAccessibility) {
- SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible";
- SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible";
- SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed";
- })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {}));
- var SyntheticSymbolKind;
- (function (SyntheticSymbolKind) {
- SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection";
- SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread";
- })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {}));
- var TypePredicateKind;
- (function (TypePredicateKind) {
- TypePredicateKind[TypePredicateKind["This"] = 0] = "This";
- TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier";
- })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {}));
var TypeReferenceSerializationKind;
(function (TypeReferenceSerializationKind) {
TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown";
@@ -606,269 +60,6 @@ var ts;
TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 9] = "TypeWithCallSignature";
TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 10] = "ObjectType";
})(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {}));
- var SymbolFlags;
- (function (SymbolFlags) {
- SymbolFlags[SymbolFlags["None"] = 0] = "None";
- SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable";
- SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable";
- SymbolFlags[SymbolFlags["Property"] = 4] = "Property";
- SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember";
- SymbolFlags[SymbolFlags["Function"] = 16] = "Function";
- SymbolFlags[SymbolFlags["Class"] = 32] = "Class";
- SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface";
- SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum";
- SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum";
- SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule";
- SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule";
- SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral";
- SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral";
- SymbolFlags[SymbolFlags["Method"] = 8192] = "Method";
- SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor";
- SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor";
- SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor";
- SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature";
- SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter";
- SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias";
- SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue";
- SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias";
- SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype";
- SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar";
- SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional";
- SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient";
- SymbolFlags[SymbolFlags["JSContainer"] = 67108864] = "JSContainer";
- SymbolFlags[SymbolFlags["All"] = 67108863] = "All";
- SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum";
- SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable";
- SymbolFlags[SymbolFlags["Value"] = 67216319] = "Value";
- SymbolFlags[SymbolFlags["Type"] = 67901928] = "Type";
- SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace";
- SymbolFlags[SymbolFlags["Module"] = 1536] = "Module";
- SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor";
- SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 67216318] = "FunctionScopedVariableExcludes";
- SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 67216319] = "BlockScopedVariableExcludes";
- SymbolFlags[SymbolFlags["ParameterExcludes"] = 67216319] = "ParameterExcludes";
- SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes";
- SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 68008959] = "EnumMemberExcludes";
- SymbolFlags[SymbolFlags["FunctionExcludes"] = 67215791] = "FunctionExcludes";
- SymbolFlags[SymbolFlags["ClassExcludes"] = 68008383] = "ClassExcludes";
- SymbolFlags[SymbolFlags["InterfaceExcludes"] = 67901832] = "InterfaceExcludes";
- SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 68008191] = "RegularEnumExcludes";
- SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 68008831] = "ConstEnumExcludes";
- SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 67215503] = "ValueModuleExcludes";
- SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes";
- SymbolFlags[SymbolFlags["MethodExcludes"] = 67208127] = "MethodExcludes";
- SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 67150783] = "GetAccessorExcludes";
- SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 67183551] = "SetAccessorExcludes";
- SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 67639784] = "TypeParameterExcludes";
- SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 67901928] = "TypeAliasExcludes";
- SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes";
- SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember";
- SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal";
- SymbolFlags[SymbolFlags["HasExports"] = 1952] = "HasExports";
- SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers";
- SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped";
- SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor";
- SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember";
- SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable";
- SymbolFlags[SymbolFlags["LateBindingContainer"] = 6240] = "LateBindingContainer";
- })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {}));
- var EnumKind;
- (function (EnumKind) {
- EnumKind[EnumKind["Numeric"] = 0] = "Numeric";
- EnumKind[EnumKind["Literal"] = 1] = "Literal";
- })(EnumKind = ts.EnumKind || (ts.EnumKind = {}));
- var CheckFlags;
- (function (CheckFlags) {
- CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated";
- CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty";
- CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod";
- CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly";
- CheckFlags[CheckFlags["Partial"] = 16] = "Partial";
- CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType";
- CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic";
- CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected";
- CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate";
- CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic";
- CheckFlags[CheckFlags["Late"] = 1024] = "Late";
- CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped";
- CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic";
- })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {}));
- var InternalSymbolName;
- (function (InternalSymbolName) {
- InternalSymbolName["Call"] = "__call";
- InternalSymbolName["Constructor"] = "__constructor";
- InternalSymbolName["New"] = "__new";
- InternalSymbolName["Index"] = "__index";
- InternalSymbolName["ExportStar"] = "__export";
- InternalSymbolName["Global"] = "__global";
- InternalSymbolName["Missing"] = "__missing";
- InternalSymbolName["Type"] = "__type";
- InternalSymbolName["Object"] = "__object";
- InternalSymbolName["JSXAttributes"] = "__jsxAttributes";
- InternalSymbolName["Class"] = "__class";
- InternalSymbolName["Function"] = "__function";
- InternalSymbolName["Computed"] = "__computed";
- InternalSymbolName["Resolving"] = "__resolving__";
- InternalSymbolName["ExportEquals"] = "export=";
- InternalSymbolName["Default"] = "default";
- })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {}));
- var NodeCheckFlags;
- (function (NodeCheckFlags) {
- NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked";
- NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis";
- NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis";
- NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget";
- NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance";
- NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic";
- NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked";
- NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper";
- NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding";
- NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments";
- NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed";
- NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass";
- NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding";
- NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 131072] = "CapturedBlockScopedBinding";
- NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 262144] = "BlockScopedBindingInLoop";
- NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 524288] = "ClassWithBodyScopedClassBinding";
- NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 1048576] = "BodyScopedClassBinding";
- NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 2097152] = "NeedsLoopOutParameter";
- NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 4194304] = "AssignmentsMarked";
- NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 8388608] = "ClassWithConstructorReference";
- NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 16777216] = "ConstructorReferenceInClass";
- })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {}));
- var TypeFlags;
- (function (TypeFlags) {
- TypeFlags[TypeFlags["Any"] = 1] = "Any";
- TypeFlags[TypeFlags["String"] = 2] = "String";
- TypeFlags[TypeFlags["Number"] = 4] = "Number";
- TypeFlags[TypeFlags["Boolean"] = 8] = "Boolean";
- TypeFlags[TypeFlags["Enum"] = 16] = "Enum";
- TypeFlags[TypeFlags["StringLiteral"] = 32] = "StringLiteral";
- TypeFlags[TypeFlags["NumberLiteral"] = 64] = "NumberLiteral";
- TypeFlags[TypeFlags["BooleanLiteral"] = 128] = "BooleanLiteral";
- TypeFlags[TypeFlags["EnumLiteral"] = 256] = "EnumLiteral";
- TypeFlags[TypeFlags["ESSymbol"] = 512] = "ESSymbol";
- TypeFlags[TypeFlags["UniqueESSymbol"] = 1024] = "UniqueESSymbol";
- TypeFlags[TypeFlags["Void"] = 2048] = "Void";
- TypeFlags[TypeFlags["Undefined"] = 4096] = "Undefined";
- TypeFlags[TypeFlags["Null"] = 8192] = "Null";
- TypeFlags[TypeFlags["Never"] = 16384] = "Never";
- TypeFlags[TypeFlags["TypeParameter"] = 32768] = "TypeParameter";
- TypeFlags[TypeFlags["Object"] = 65536] = "Object";
- TypeFlags[TypeFlags["Union"] = 131072] = "Union";
- TypeFlags[TypeFlags["Intersection"] = 262144] = "Intersection";
- TypeFlags[TypeFlags["Index"] = 524288] = "Index";
- TypeFlags[TypeFlags["IndexedAccess"] = 1048576] = "IndexedAccess";
- TypeFlags[TypeFlags["Conditional"] = 2097152] = "Conditional";
- TypeFlags[TypeFlags["Substitution"] = 4194304] = "Substitution";
- TypeFlags[TypeFlags["FreshLiteral"] = 8388608] = "FreshLiteral";
- TypeFlags[TypeFlags["ContainsWideningType"] = 16777216] = "ContainsWideningType";
- TypeFlags[TypeFlags["ContainsObjectLiteral"] = 33554432] = "ContainsObjectLiteral";
- TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 67108864] = "ContainsAnyFunctionType";
- TypeFlags[TypeFlags["NonPrimitive"] = 134217728] = "NonPrimitive";
- TypeFlags[TypeFlags["GenericMappedType"] = 536870912] = "GenericMappedType";
- TypeFlags[TypeFlags["Nullable"] = 12288] = "Nullable";
- TypeFlags[TypeFlags["Literal"] = 224] = "Literal";
- TypeFlags[TypeFlags["Unit"] = 13536] = "Unit";
- TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral";
- TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 1120] = "StringOrNumberLiteralOrUnique";
- TypeFlags[TypeFlags["DefinitelyFalsy"] = 14560] = "DefinitelyFalsy";
- TypeFlags[TypeFlags["PossiblyFalsy"] = 14574] = "PossiblyFalsy";
- TypeFlags[TypeFlags["Intrinsic"] = 134249103] = "Intrinsic";
- TypeFlags[TypeFlags["Primitive"] = 16382] = "Primitive";
- TypeFlags[TypeFlags["StringLike"] = 34] = "StringLike";
- TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike";
- TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike";
- TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike";
- TypeFlags[TypeFlags["ESSymbolLike"] = 1536] = "ESSymbolLike";
- TypeFlags[TypeFlags["VoidLike"] = 6144] = "VoidLike";
- TypeFlags[TypeFlags["DisjointDomains"] = 134233854] = "DisjointDomains";
- TypeFlags[TypeFlags["UnionOrIntersection"] = 393216] = "UnionOrIntersection";
- TypeFlags[TypeFlags["StructuredType"] = 458752] = "StructuredType";
- TypeFlags[TypeFlags["TypeVariable"] = 1081344] = "TypeVariable";
- TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 7372800] = "InstantiableNonPrimitive";
- TypeFlags[TypeFlags["InstantiablePrimitive"] = 524288] = "InstantiablePrimitive";
- TypeFlags[TypeFlags["Instantiable"] = 7897088] = "Instantiable";
- TypeFlags[TypeFlags["StructuredOrInstantiable"] = 8355840] = "StructuredOrInstantiable";
- TypeFlags[TypeFlags["Narrowable"] = 142575359] = "Narrowable";
- TypeFlags[TypeFlags["NotUnionOrUnit"] = 134283777] = "NotUnionOrUnit";
- TypeFlags[TypeFlags["RequiresWidening"] = 50331648] = "RequiresWidening";
- TypeFlags[TypeFlags["PropagatingFlags"] = 117440512] = "PropagatingFlags";
- TypeFlags[TypeFlags["NonWideningType"] = 16777216] = "NonWideningType";
- TypeFlags[TypeFlags["Wildcard"] = 33554432] = "Wildcard";
- TypeFlags[TypeFlags["EmptyObject"] = 67108864] = "EmptyObject";
- TypeFlags[TypeFlags["ConstructionFlags"] = 117440512] = "ConstructionFlags";
- })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
- var ObjectFlags;
- (function (ObjectFlags) {
- ObjectFlags[ObjectFlags["Class"] = 1] = "Class";
- ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface";
- ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference";
- ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple";
- ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous";
- ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped";
- ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated";
- ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral";
- ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray";
- ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties";
- ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread";
- ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped";
- ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes";
- ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
- ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
- })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
- var Variance;
- (function (Variance) {
- Variance[Variance["Invariant"] = 0] = "Invariant";
- Variance[Variance["Covariant"] = 1] = "Covariant";
- Variance[Variance["Contravariant"] = 2] = "Contravariant";
- Variance[Variance["Bivariant"] = 3] = "Bivariant";
- Variance[Variance["Independent"] = 4] = "Independent";
- })(Variance = ts.Variance || (ts.Variance = {}));
- var SignatureKind;
- (function (SignatureKind) {
- SignatureKind[SignatureKind["Call"] = 0] = "Call";
- SignatureKind[SignatureKind["Construct"] = 1] = "Construct";
- })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {}));
- var IndexKind;
- (function (IndexKind) {
- IndexKind[IndexKind["String"] = 0] = "String";
- IndexKind[IndexKind["Number"] = 1] = "Number";
- })(IndexKind = ts.IndexKind || (ts.IndexKind = {}));
- var InferencePriority;
- (function (InferencePriority) {
- InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
- InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType";
- InferencePriority[InferencePriority["MappedTypeConstraint"] = 4] = "MappedTypeConstraint";
- InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType";
- InferencePriority[InferencePriority["LiteralKeyof"] = 16] = "LiteralKeyof";
- InferencePriority[InferencePriority["NoConstraints"] = 32] = "NoConstraints";
- InferencePriority[InferencePriority["AlwaysStrict"] = 64] = "AlwaysStrict";
- InferencePriority[InferencePriority["PriorityImpliesCombination"] = 28] = "PriorityImpliesCombination";
- })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
- var InferenceFlags;
- (function (InferenceFlags) {
- InferenceFlags[InferenceFlags["None"] = 0] = "None";
- InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes";
- InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault";
- InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault";
- })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
- var Ternary;
- (function (Ternary) {
- Ternary[Ternary["False"] = 0] = "False";
- Ternary[Ternary["Maybe"] = 1] = "Maybe";
- Ternary[Ternary["True"] = -1] = "True";
- })(Ternary = ts.Ternary || (ts.Ternary = {}));
- var SpecialPropertyAssignmentKind;
- (function (SpecialPropertyAssignmentKind) {
- SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None";
- SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ExportsProperty"] = 1] = "ExportsProperty";
- SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ModuleExports"] = 2] = "ModuleExports";
- SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["PrototypeProperty"] = 3] = "PrototypeProperty";
- SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["ThisProperty"] = 4] = "ThisProperty";
- SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Property"] = 5] = "Property";
- SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["Prototype"] = 6] = "Prototype";
- })(SpecialPropertyAssignmentKind = ts.SpecialPropertyAssignmentKind || (ts.SpecialPropertyAssignmentKind = {}));
var DiagnosticCategory;
(function (DiagnosticCategory) {
DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
@@ -897,390 +88,6 @@ var ts;
ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext";
})(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {}));
- var JsxEmit;
- (function (JsxEmit) {
- JsxEmit[JsxEmit["None"] = 0] = "None";
- JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
- JsxEmit[JsxEmit["React"] = 2] = "React";
- JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative";
- })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {}));
- var NewLineKind;
- (function (NewLineKind) {
- NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed";
- NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed";
- })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {}));
- var ScriptKind;
- (function (ScriptKind) {
- ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown";
- ScriptKind[ScriptKind["JS"] = 1] = "JS";
- ScriptKind[ScriptKind["JSX"] = 2] = "JSX";
- ScriptKind[ScriptKind["TS"] = 3] = "TS";
- ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
- ScriptKind[ScriptKind["External"] = 5] = "External";
- ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
- })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
- var ScriptTarget;
- (function (ScriptTarget) {
- ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3";
- ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5";
- ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015";
- ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
- ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
- ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
- ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext";
- ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest";
- })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
- var LanguageVariant;
- (function (LanguageVariant) {
- LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard";
- LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX";
- })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {}));
- var WatchDirectoryFlags;
- (function (WatchDirectoryFlags) {
- WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None";
- WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive";
- })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {}));
- var CharacterCodes;
- (function (CharacterCodes) {
- CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
- CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
- CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
- CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
- CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
- CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
- CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
- CharacterCodes[CharacterCodes["space"] = 32] = "space";
- CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
- CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
- CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
- CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
- CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
- CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
- CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
- CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
- CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
- CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
- CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
- CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
- CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
- CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
- CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
- CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
- CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
- CharacterCodes[CharacterCodes["_"] = 95] = "_";
- CharacterCodes[CharacterCodes["$"] = 36] = "$";
- CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
- CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
- CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
- CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
- CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
- CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
- CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
- CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
- CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
- CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
- CharacterCodes[CharacterCodes["a"] = 97] = "a";
- CharacterCodes[CharacterCodes["b"] = 98] = "b";
- CharacterCodes[CharacterCodes["c"] = 99] = "c";
- CharacterCodes[CharacterCodes["d"] = 100] = "d";
- CharacterCodes[CharacterCodes["e"] = 101] = "e";
- CharacterCodes[CharacterCodes["f"] = 102] = "f";
- CharacterCodes[CharacterCodes["g"] = 103] = "g";
- CharacterCodes[CharacterCodes["h"] = 104] = "h";
- CharacterCodes[CharacterCodes["i"] = 105] = "i";
- CharacterCodes[CharacterCodes["j"] = 106] = "j";
- CharacterCodes[CharacterCodes["k"] = 107] = "k";
- CharacterCodes[CharacterCodes["l"] = 108] = "l";
- CharacterCodes[CharacterCodes["m"] = 109] = "m";
- CharacterCodes[CharacterCodes["n"] = 110] = "n";
- CharacterCodes[CharacterCodes["o"] = 111] = "o";
- CharacterCodes[CharacterCodes["p"] = 112] = "p";
- CharacterCodes[CharacterCodes["q"] = 113] = "q";
- CharacterCodes[CharacterCodes["r"] = 114] = "r";
- CharacterCodes[CharacterCodes["s"] = 115] = "s";
- CharacterCodes[CharacterCodes["t"] = 116] = "t";
- CharacterCodes[CharacterCodes["u"] = 117] = "u";
- CharacterCodes[CharacterCodes["v"] = 118] = "v";
- CharacterCodes[CharacterCodes["w"] = 119] = "w";
- CharacterCodes[CharacterCodes["x"] = 120] = "x";
- CharacterCodes[CharacterCodes["y"] = 121] = "y";
- CharacterCodes[CharacterCodes["z"] = 122] = "z";
- CharacterCodes[CharacterCodes["A"] = 65] = "A";
- CharacterCodes[CharacterCodes["B"] = 66] = "B";
- CharacterCodes[CharacterCodes["C"] = 67] = "C";
- CharacterCodes[CharacterCodes["D"] = 68] = "D";
- CharacterCodes[CharacterCodes["E"] = 69] = "E";
- CharacterCodes[CharacterCodes["F"] = 70] = "F";
- CharacterCodes[CharacterCodes["G"] = 71] = "G";
- CharacterCodes[CharacterCodes["H"] = 72] = "H";
- CharacterCodes[CharacterCodes["I"] = 73] = "I";
- CharacterCodes[CharacterCodes["J"] = 74] = "J";
- CharacterCodes[CharacterCodes["K"] = 75] = "K";
- CharacterCodes[CharacterCodes["L"] = 76] = "L";
- CharacterCodes[CharacterCodes["M"] = 77] = "M";
- CharacterCodes[CharacterCodes["N"] = 78] = "N";
- CharacterCodes[CharacterCodes["O"] = 79] = "O";
- CharacterCodes[CharacterCodes["P"] = 80] = "P";
- CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
- CharacterCodes[CharacterCodes["R"] = 82] = "R";
- CharacterCodes[CharacterCodes["S"] = 83] = "S";
- CharacterCodes[CharacterCodes["T"] = 84] = "T";
- CharacterCodes[CharacterCodes["U"] = 85] = "U";
- CharacterCodes[CharacterCodes["V"] = 86] = "V";
- CharacterCodes[CharacterCodes["W"] = 87] = "W";
- CharacterCodes[CharacterCodes["X"] = 88] = "X";
- CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
- CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
- CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
- CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
- CharacterCodes[CharacterCodes["at"] = 64] = "at";
- CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
- CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick";
- CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
- CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
- CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
- CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
- CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
- CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
- CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
- CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
- CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
- CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
- CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
- CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
- CharacterCodes[CharacterCodes["hash"] = 35] = "hash";
- CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
- CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
- CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
- CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
- CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
- CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
- CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
- CharacterCodes[CharacterCodes["question"] = 63] = "question";
- CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
- CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
- CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
- CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
- CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
- CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
- CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
- CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
- CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
- })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {}));
- var Extension;
- (function (Extension) {
- Extension["Ts"] = ".ts";
- Extension["Tsx"] = ".tsx";
- Extension["Dts"] = ".d.ts";
- Extension["Js"] = ".js";
- Extension["Jsx"] = ".jsx";
- Extension["Json"] = ".json";
- })(Extension = ts.Extension || (ts.Extension = {}));
- var TransformFlags;
- (function (TransformFlags) {
- TransformFlags[TransformFlags["None"] = 0] = "None";
- TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript";
- TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript";
- TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx";
- TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext";
- TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017";
- TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016";
- TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015";
- TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015";
- TransformFlags[TransformFlags["Generator"] = 256] = "Generator";
- TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
- TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment";
- TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment";
- TransformFlags[TransformFlags["ContainsDecorators"] = 4096] = "ContainsDecorators";
- TransformFlags[TransformFlags["ContainsPropertyInitializer"] = 8192] = "ContainsPropertyInitializer";
- TransformFlags[TransformFlags["ContainsLexicalThis"] = 16384] = "ContainsLexicalThis";
- TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 32768] = "ContainsCapturedLexicalThis";
- TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 65536] = "ContainsLexicalThisInComputedPropertyName";
- TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 131072] = "ContainsDefaultValueAssignments";
- TransformFlags[TransformFlags["ContainsParameterPropertyAssignments"] = 262144] = "ContainsParameterPropertyAssignments";
- TransformFlags[TransformFlags["ContainsSpread"] = 524288] = "ContainsSpread";
- TransformFlags[TransformFlags["ContainsObjectSpread"] = 1048576] = "ContainsObjectSpread";
- TransformFlags[TransformFlags["ContainsRest"] = 524288] = "ContainsRest";
- TransformFlags[TransformFlags["ContainsObjectRest"] = 1048576] = "ContainsObjectRest";
- TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 2097152] = "ContainsComputedPropertyName";
- TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 4194304] = "ContainsBlockScopedBinding";
- TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern";
- TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield";
- TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion";
- TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport";
- TransformFlags[TransformFlags["Super"] = 134217728] = "Super";
- TransformFlags[TransformFlags["ContainsSuper"] = 268435456] = "ContainsSuper";
- TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
- TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript";
- TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx";
- TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext";
- TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017";
- TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016";
- TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015";
- TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator";
- TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment";
- TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes";
- TransformFlags[TransformFlags["PropertyAccessExcludes"] = 671089985] = "PropertyAccessExcludes";
- TransformFlags[TransformFlags["NodeExcludes"] = 939525441] = "NodeExcludes";
- TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 1003902273] = "ArrowFunctionExcludes";
- TransformFlags[TransformFlags["FunctionExcludes"] = 1003935041] = "FunctionExcludes";
- TransformFlags[TransformFlags["ConstructorExcludes"] = 1003668801] = "ConstructorExcludes";
- TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 1003668801] = "MethodOrAccessorExcludes";
- TransformFlags[TransformFlags["ClassExcludes"] = 942011713] = "ClassExcludes";
- TransformFlags[TransformFlags["ModuleExcludes"] = 977327425] = "ModuleExcludes";
- TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes";
- TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 942740801] = "ObjectLiteralExcludes";
- TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 940049729] = "ArrayLiteralOrCallOrNewExcludes";
- TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 948962625] = "VariableDeclarationListExcludes";
- TransformFlags[TransformFlags["ParameterExcludes"] = 939525441] = "ParameterExcludes";
- TransformFlags[TransformFlags["CatchClauseExcludes"] = 940574017] = "CatchClauseExcludes";
- TransformFlags[TransformFlags["BindingPatternExcludes"] = 940049729] = "BindingPatternExcludes";
- TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask";
- TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 163840] = "ES2015FunctionSyntaxMask";
- })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
- var EmitFlags;
- (function (EmitFlags) {
- EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine";
- EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode";
- EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution";
- EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis";
- EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap";
- EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap";
- EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap";
- EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps";
- EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps";
- EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps";
- EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps";
- EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments";
- EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments";
- EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments";
- EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments";
- EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName";
- EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName";
- EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName";
- EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName";
- EmitFlags[EmitFlags["Indented"] = 65536] = "Indented";
- EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation";
- EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody";
- EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope";
- EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue";
- EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting";
- EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker";
- EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator";
- EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping";
- EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper";
- EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper";
- })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {}));
- var ExternalEmitHelpers;
- (function (ExternalEmitHelpers) {
- ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends";
- ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign";
- ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest";
- ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate";
- ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata";
- ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param";
- ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter";
- ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator";
- ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values";
- ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read";
- ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread";
- ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await";
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator";
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator";
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues";
- ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar";
- ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 65536] = "MakeTemplateObject";
- ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
- ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 65536] = "LastEmitHelper";
- ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
- ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes";
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes";
- ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes";
- ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
- })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
- var EmitHint;
- (function (EmitHint) {
- EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile";
- EmitHint[EmitHint["Expression"] = 1] = "Expression";
- EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName";
- EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter";
- EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
- })(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
- var ListFormat;
- (function (ListFormat) {
- ListFormat[ListFormat["None"] = 0] = "None";
- ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine";
- ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine";
- ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines";
- ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask";
- ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited";
- ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited";
- ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited";
- ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited";
- ListFormat[ListFormat["DelimitersMask"] = 28] = "DelimitersMask";
- ListFormat[ListFormat["AllowTrailingComma"] = 32] = "AllowTrailingComma";
- ListFormat[ListFormat["Indented"] = 64] = "Indented";
- ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces";
- ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings";
- ListFormat[ListFormat["Braces"] = 512] = "Braces";
- ListFormat[ListFormat["Parenthesis"] = 1024] = "Parenthesis";
- ListFormat[ListFormat["AngleBrackets"] = 2048] = "AngleBrackets";
- ListFormat[ListFormat["SquareBrackets"] = 4096] = "SquareBrackets";
- ListFormat[ListFormat["BracketsMask"] = 7680] = "BracketsMask";
- ListFormat[ListFormat["OptionalIfUndefined"] = 8192] = "OptionalIfUndefined";
- ListFormat[ListFormat["OptionalIfEmpty"] = 16384] = "OptionalIfEmpty";
- ListFormat[ListFormat["Optional"] = 24576] = "Optional";
- ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine";
- ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine";
- ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments";
- ListFormat[ListFormat["NoSpaceIfEmpty"] = 262144] = "NoSpaceIfEmpty";
- ListFormat[ListFormat["SingleElement"] = 524288] = "SingleElement";
- ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers";
- ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses";
- ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 384] = "SingleLineTypeLiteralMembers";
- ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 16449] = "MultiLineTypeLiteralMembers";
- ListFormat[ListFormat["TupleTypeElements"] = 272] = "TupleTypeElements";
- ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents";
- ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents";
- ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements";
- ListFormat[ListFormat["ArrayBindingPatternElements"] = 262448] = "ArrayBindingPatternElements";
- ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 263122] = "ObjectLiteralExpressionProperties";
- ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements";
- ListFormat[ListFormat["CommaListElements"] = 272] = "CommaListElements";
- ListFormat[ListFormat["CallExpressionArguments"] = 1296] = "CallExpressionArguments";
- ListFormat[ListFormat["NewExpressionArguments"] = 9488] = "NewExpressionArguments";
- ListFormat[ListFormat["TemplateExpressionSpans"] = 131072] = "TemplateExpressionSpans";
- ListFormat[ListFormat["SingleLineBlockStatements"] = 384] = "SingleLineBlockStatements";
- ListFormat[ListFormat["MultiLineBlockStatements"] = 65] = "MultiLineBlockStatements";
- ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList";
- ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements";
- ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements";
- ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses";
- ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers";
- ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers";
- ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers";
- ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses";
- ListFormat[ListFormat["NamedImportsOrExportsElements"] = 262576] = "NamedImportsOrExportsElements";
- ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren";
- ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes";
- ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements";
- ListFormat[ListFormat["HeritageClauseTypes"] = 272] = "HeritageClauseTypes";
- ListFormat[ListFormat["SourceFileStatements"] = 65537] = "SourceFileStatements";
- ListFormat[ListFormat["Decorators"] = 24577] = "Decorators";
- ListFormat[ListFormat["TypeArguments"] = 26896] = "TypeArguments";
- ListFormat[ListFormat["TypeParameters"] = 26896] = "TypeParameters";
- ListFormat[ListFormat["Parameters"] = 1296] = "Parameters";
- ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters";
- })(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
- var PragmaKindFlags;
- (function (PragmaKindFlags) {
- PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
- PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
- PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
- PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
- PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
- PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
- })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
function _contextuallyTypePragmas(args) {
return args;
}
@@ -1618,8 +425,8 @@ var ts;
return undefined;
}
ts.findLast = findLast;
- function findIndex(array, predicate) {
- for (var i = 0; i < array.length; i++) {
+ function findIndex(array, predicate, startIndex) {
+ for (var i = startIndex || 0; i < array.length; i++) {
if (predicate(array[i], i)) {
return i;
}
@@ -2147,6 +954,15 @@ var ts;
return to;
}
ts.addRange = addRange;
+ function prependRange(to, from) {
+ if (from === undefined || from.length === 0)
+ return to;
+ if (to === undefined)
+ return from.slice();
+ to.unshift.apply(to, from);
+ return to;
+ }
+ ts.prependRange = prependRange;
function pushIfUnique(array, toAdd, equalityComparer) {
if (contains(array, toAdd, equalityComparer)) {
return false;
@@ -2344,17 +1160,18 @@ var ts;
}
ts.getOwnValues = getOwnValues;
function arrayFrom(iterator, map) {
+ var _a;
var result = [];
- for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) {
result.push(map ? map(value) : value);
}
return result;
- var _b;
}
ts.arrayFrom = arrayFrom;
function forEachEntry(map, callback) {
+ var _a;
var iterator = map.entries();
- for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) {
var key = pair[0], value = pair[1];
var result = callback(value, key);
if (result) {
@@ -2362,19 +1179,18 @@ var ts;
}
}
return undefined;
- var _b;
}
ts.forEachEntry = forEachEntry;
function forEachKey(map, callback) {
+ var _a;
var iterator = map.keys();
- for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done, _b) {
+ for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) {
var result = callback(key);
if (result) {
return result;
}
}
return undefined;
- var _b;
}
ts.forEachKey = forEachKey;
function copyEntries(source, target) {
@@ -2843,11 +1659,11 @@ var ts;
comparer(a[key], b[key]);
}
ts.compareProperties = compareProperties;
- function getDiagnosticFileName(diagnostic) {
- return diagnostic.file ? diagnostic.file.fileName : undefined;
+ function getDiagnosticFilePath(diagnostic) {
+ return diagnostic.file ? diagnostic.file.path : undefined;
}
function compareDiagnostics(d1, d2) {
- return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) ||
+ return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
compareValues(d1.start, d2.start) ||
compareValues(d1.length, d2.length) ||
compareValues(d1.code, d2.code) ||
@@ -2875,90 +1691,6 @@ var ts;
}
return text1 ? 1 : -1;
}
- function normalizeSlashes(path) {
- return path.replace(/\\/g, "/");
- }
- ts.normalizeSlashes = normalizeSlashes;
- function getRootLength(path) {
- if (path.charCodeAt(0) === 47) {
- if (path.charCodeAt(1) !== 47)
- return 1;
- var p1 = path.indexOf("/", 2);
- if (p1 < 0)
- return 2;
- var p2 = path.indexOf("/", p1 + 1);
- if (p2 < 0)
- return p1 + 1;
- return p2 + 1;
- }
- if (path.charCodeAt(1) === 58) {
- if (path.charCodeAt(2) === 47 || path.charCodeAt(2) === 92)
- return 3;
- }
- if (path.lastIndexOf("file:///", 0) === 0) {
- return "file:///".length;
- }
- var idx = path.indexOf("://");
- if (idx !== -1) {
- return idx + "://".length;
- }
- return 0;
- }
- ts.getRootLength = getRootLength;
- ts.directorySeparator = "/";
- var directorySeparatorCharCode = 47;
- function getNormalizedParts(normalizedSlashedPath, rootLength) {
- var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator);
- var normalized = [];
- for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
- var part = parts_1[_i];
- if (part !== ".") {
- if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") {
- normalized.pop();
- }
- else {
- if (part) {
- normalized.push(part);
- }
- }
- }
- }
- return normalized;
- }
- function normalizePath(path) {
- return normalizePathAndParts(path).path;
- }
- ts.normalizePath = normalizePath;
- function normalizePathAndParts(path) {
- path = normalizeSlashes(path);
- var rootLength = getRootLength(path);
- var root = path.substr(0, rootLength);
- var parts = getNormalizedParts(path, rootLength);
- if (parts.length) {
- var joinedParts = root + parts.join(ts.directorySeparator);
- return { path: pathEndsWithDirectorySeparator(path) ? joinedParts + ts.directorySeparator : joinedParts, parts: parts };
- }
- else {
- return { path: root, parts: parts };
- }
- }
- ts.normalizePathAndParts = normalizePathAndParts;
- function pathEndsWithDirectorySeparator(path) {
- return path.charCodeAt(path.length - 1) === directorySeparatorCharCode;
- }
- ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator;
- function getDirectoryPath(path) {
- return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator)));
- }
- ts.getDirectoryPath = getDirectoryPath;
- function isUrl(path) {
- return path && !isRootedDiskPath(path) && stringContains(path, "://");
- }
- ts.isUrl = isUrl;
- function pathIsRelative(path) {
- return /^\.\.?($|[\\/])/.test(path);
- }
- ts.pathIsRelative = pathIsRelative;
function getEmitScriptTarget(compilerOptions) {
return compilerOptions.target || 0;
}
@@ -2990,6 +1722,10 @@ var ts;
: moduleKind === ts.ModuleKind.System;
}
ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
+ function getEmitDeclarations(compilerOptions) {
+ return !!(compilerOptions.declaration || compilerOptions.composite);
+ }
+ ts.getEmitDeclarations = getEmitDeclarations;
function getStrictOptionValue(compilerOptions, flag) {
return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag];
}
@@ -3009,181 +1745,351 @@ var ts;
return true;
}
ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
+ ts.directorySeparator = "/";
+ var altDirectorySeparator = "\\";
+ var urlSchemeSeparator = "://";
+ var backslashRegExp = /\\/g;
+ function normalizeSlashes(path) {
+ return path.replace(backslashRegExp, ts.directorySeparator);
+ }
+ ts.normalizeSlashes = normalizeSlashes;
+ function isVolumeCharacter(charCode) {
+ return (charCode >= 97 && charCode <= 122) ||
+ (charCode >= 65 && charCode <= 90);
+ }
+ function getFileUrlVolumeSeparatorEnd(url, start) {
+ var ch0 = url.charCodeAt(start);
+ if (ch0 === 58)
+ return start + 1;
+ if (ch0 === 37 && url.charCodeAt(start + 1) === 51) {
+ var ch2 = url.charCodeAt(start + 2);
+ if (ch2 === 97 || ch2 === 65)
+ return start + 3;
+ }
+ return -1;
+ }
+ function getEncodedRootLength(path) {
+ if (!path)
+ return 0;
+ var ch0 = path.charCodeAt(0);
+ if (ch0 === 47 || ch0 === 92) {
+ if (path.charCodeAt(1) !== ch0)
+ return 1;
+ var p1 = path.indexOf(ch0 === 47 ? ts.directorySeparator : altDirectorySeparator, 2);
+ if (p1 < 0)
+ return path.length;
+ return p1 + 1;
+ }
+ if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58) {
+ var ch2 = path.charCodeAt(2);
+ if (ch2 === 47 || ch2 === 92)
+ return 3;
+ if (path.length === 2)
+ return 2;
+ }
+ var schemeEnd = path.indexOf(urlSchemeSeparator);
+ if (schemeEnd !== -1) {
+ var authorityStart = schemeEnd + urlSchemeSeparator.length;
+ var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
+ if (authorityEnd !== -1) {
+ var scheme = path.slice(0, schemeEnd);
+ var authority = path.slice(authorityStart, authorityEnd);
+ if (scheme === "file" && (authority === "" || authority === "localhost") &&
+ isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
+ var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
+ if (volumeSeparatorEnd !== -1) {
+ if (path.charCodeAt(volumeSeparatorEnd) === 47) {
+ return ~(volumeSeparatorEnd + 1);
+ }
+ if (volumeSeparatorEnd === path.length) {
+ return ~volumeSeparatorEnd;
+ }
+ }
+ }
+ return ~(authorityEnd + 1);
+ }
+ return ~path.length;
+ }
+ return 0;
+ }
+ function getRootLength(path) {
+ var rootLength = getEncodedRootLength(path);
+ return rootLength < 0 ? ~rootLength : rootLength;
+ }
+ ts.getRootLength = getRootLength;
+ function normalizePath(path) {
+ return resolvePath(path);
+ }
+ ts.normalizePath = normalizePath;
+ function normalizePathAndParts(path) {
+ path = normalizeSlashes(path);
+ var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
+ if (parts.length) {
+ var joinedParts = root + parts.join(ts.directorySeparator);
+ return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
+ }
+ else {
+ return { path: root, parts: parts };
+ }
+ }
+ ts.normalizePathAndParts = normalizePathAndParts;
+ function getDirectoryPath(path) {
+ path = normalizeSlashes(path);
+ var rootLength = getRootLength(path);
+ if (rootLength === path.length)
+ return path;
+ path = removeTrailingDirectorySeparator(path);
+ return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
+ }
+ ts.getDirectoryPath = getDirectoryPath;
+ function isUrl(path) {
+ return getEncodedRootLength(path) < 0;
+ }
+ ts.isUrl = isUrl;
+ function pathIsRelative(path) {
+ return /^\.\.?($|[\\/])/.test(path);
+ }
+ ts.pathIsRelative = pathIsRelative;
function isRootedDiskPath(path) {
- return path && getRootLength(path) !== 0;
+ return getEncodedRootLength(path) > 0;
}
ts.isRootedDiskPath = isRootedDiskPath;
+ function isDiskPathRoot(path) {
+ var rootLength = getEncodedRootLength(path);
+ return rootLength > 0 && rootLength === path.length;
+ }
+ ts.isDiskPathRoot = isDiskPathRoot;
function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
return !isRootedDiskPath(absoluteOrRelativePath)
? absoluteOrRelativePath
: getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false);
}
ts.convertToRelativePath = convertToRelativePath;
- function normalizedPathComponents(path, rootLength) {
- var normalizedParts = getNormalizedParts(path, rootLength);
- return [path.substr(0, rootLength)].concat(normalizedParts);
+ function pathComponents(path, rootLength) {
+ var root = path.substring(0, rootLength);
+ var rest = path.substring(rootLength).split(ts.directorySeparator);
+ if (rest.length && !lastOrUndefined(rest))
+ rest.pop();
+ return [root].concat(rest);
}
- function getNormalizedPathComponents(path, currentDirectory) {
- path = normalizeSlashes(path);
+ function getPathComponents(path, currentDirectory) {
+ if (currentDirectory === void 0) { currentDirectory = ""; }
+ path = combinePaths(currentDirectory, path);
var rootLength = getRootLength(path);
- if (rootLength === 0) {
- path = combinePaths(normalizeSlashes(currentDirectory), path);
- rootLength = getRootLength(path);
+ return pathComponents(path, rootLength);
+ }
+ ts.getPathComponents = getPathComponents;
+ function reducePathComponents(components) {
+ if (!some(components))
+ return [];
+ var reduced = [components[0]];
+ for (var i = 1; i < components.length; i++) {
+ var component = components[i];
+ if (!component)
+ continue;
+ if (component === ".")
+ continue;
+ if (component === "..") {
+ if (reduced.length > 1) {
+ if (reduced[reduced.length - 1] !== "..") {
+ reduced.pop();
+ continue;
+ }
+ }
+ else if (reduced[0])
+ continue;
+ }
+ reduced.push(component);
}
- return normalizedPathComponents(path, rootLength);
+ return reduced;
+ }
+ ts.reducePathComponents = reducePathComponents;
+ function getNormalizedPathComponents(path, currentDirectory) {
+ return reducePathComponents(getPathComponents(path, currentDirectory));
}
ts.getNormalizedPathComponents = getNormalizedPathComponents;
function getNormalizedAbsolutePath(fileName, currentDirectory) {
- return getNormalizedPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
+ return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
}
ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
- function getNormalizedPathFromPathComponents(pathComponents) {
- if (pathComponents && pathComponents.length) {
- return pathComponents[0] + pathComponents.slice(1).join(ts.directorySeparator);
- }
+ function getPathFromPathComponents(pathComponents) {
+ if (pathComponents.length === 0)
+ return "";
+ var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
+ if (pathComponents.length === 1)
+ return root;
+ return root + pathComponents.slice(1).join(ts.directorySeparator);
}
- ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents;
- function getNormalizedPathComponentsOfUrl(url) {
- var urlLength = url.length;
- var rootLength = url.indexOf("://") + "://".length;
- while (rootLength < urlLength) {
- if (url.charCodeAt(rootLength) === 47) {
- rootLength++;
- }
- else {
+ ts.getPathFromPathComponents = getPathFromPathComponents;
+ function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
+ var fromComponents = reducePathComponents(getPathComponents(from));
+ var toComponents = reducePathComponents(getPathComponents(to));
+ var start;
+ for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
+ var fromComponent = getCanonicalFileName(fromComponents[start]);
+ var toComponent = getCanonicalFileName(toComponents[start]);
+ var comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer;
+ if (!comparer(fromComponent, toComponent))
break;
- }
}
- if (rootLength === urlLength) {
- return [url];
+ if (start === 0) {
+ return toComponents;
}
- var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength);
- if (indexOfNextSlash !== -1) {
- rootLength = indexOfNextSlash + 1;
- return normalizedPathComponents(url, rootLength);
- }
- else {
- return [url + ts.directorySeparator];
+ var components = toComponents.slice(start);
+ var relative = [];
+ for (; start < fromComponents.length; start++) {
+ relative.push("..");
}
+ return [""].concat(relative, components);
}
- function getNormalizedPathOrUrlComponents(pathOrUrl, currentDirectory) {
- if (isUrl(pathOrUrl)) {
- return getNormalizedPathComponentsOfUrl(pathOrUrl);
- }
- else {
- return getNormalizedPathComponents(pathOrUrl, currentDirectory);
- }
+ function getRelativePathFromFile(from, to, getCanonicalFileName) {
+ return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
}
+ ts.getRelativePathFromFile = getRelativePathFromFile;
+ function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
+ Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
+ var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : identity;
+ var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
+ var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive, getCanonicalFileName);
+ return getPathFromPathComponents(pathComponents);
+ }
+ ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
- var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory);
- var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory);
- if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") {
- directoryComponents.pop();
+ var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), equateStringsCaseSensitive, getCanonicalFileName);
+ var firstComponent = pathComponents[0];
+ if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
+ var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
+ pathComponents[0] = prefix + firstComponent;
}
- var joinStartIndex;
- for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) {
- if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) {
- break;
- }
- }
- if (joinStartIndex) {
- var relativePath = "";
- var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length);
- for (; joinStartIndex < directoryComponents.length; joinStartIndex++) {
- if (directoryComponents[joinStartIndex] !== "") {
- relativePath = relativePath + ".." + ts.directorySeparator;
- }
- }
- return relativePath + relativePathComponents.join(ts.directorySeparator);
- }
- var absolutePath = getNormalizedPathFromPathComponents(pathComponents);
- if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) {
- absolutePath = "file:///" + absolutePath;
- }
- return absolutePath;
+ return getPathFromPathComponents(pathComponents);
}
ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
- function getRelativePath(path, directoryPath, getCanonicalFileName) {
- var relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false);
- return ensurePathIsRelative(relativePath);
+ function ensurePathIsNonModuleName(path) {
+ return getRootLength(path) === 0 && !pathIsRelative(path) ? "./" + path : path;
}
- ts.getRelativePath = getRelativePath;
- function ensurePathIsRelative(path) {
- return !pathIsRelative(path) ? "./" + path : path;
- }
- ts.ensurePathIsRelative = ensurePathIsRelative;
- function getBaseFileName(path) {
- if (path === undefined) {
- return undefined;
- }
- var i = path.lastIndexOf(ts.directorySeparator);
- return i < 0 ? path : path.substring(i + 1);
+ ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
+ function getBaseFileName(path, extensions, ignoreCase) {
+ path = normalizeSlashes(path);
+ var rootLength = getRootLength(path);
+ if (rootLength === path.length)
+ return "";
+ path = removeTrailingDirectorySeparator(path);
+ var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
+ var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
+ return extension ? name.slice(0, name.length - extension.length) : name;
}
ts.getBaseFileName = getBaseFileName;
- function combinePaths(path1, path2) {
- if (!(path1 && path1.length))
- return path2;
- if (!(path2 && path2.length))
- return path1;
- if (getRootLength(path2) !== 0)
- return path2;
- if (path1.charAt(path1.length - 1) === ts.directorySeparator)
- return path1 + path2;
- return path1 + ts.directorySeparator + path2;
+ function combinePaths(path) {
+ var paths = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ paths[_i - 1] = arguments[_i];
+ }
+ if (path)
+ path = normalizeSlashes(path);
+ for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
+ var relativePath = paths_1[_a];
+ if (!relativePath)
+ continue;
+ relativePath = normalizeSlashes(relativePath);
+ if (!path || getRootLength(relativePath) !== 0) {
+ path = relativePath;
+ }
+ else {
+ path = ensureTrailingDirectorySeparator(path) + relativePath;
+ }
+ }
+ return path;
}
ts.combinePaths = combinePaths;
+ function resolvePath(path) {
+ var paths = [];
+ for (var _i = 1; _i < arguments.length; _i++) {
+ paths[_i - 1] = arguments[_i];
+ }
+ var combined = some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : normalizeSlashes(path);
+ var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(combined)));
+ return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized;
+ }
+ ts.resolvePath = resolvePath;
+ function hasTrailingDirectorySeparator(path) {
+ if (path.length === 0)
+ return false;
+ var ch = path.charCodeAt(path.length - 1);
+ return ch === 47 || ch === 92;
+ }
+ ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
function removeTrailingDirectorySeparator(path) {
- if (path.charAt(path.length - 1) === ts.directorySeparator) {
+ if (hasTrailingDirectorySeparator(path)) {
return path.substr(0, path.length - 1);
}
return path;
}
ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
function ensureTrailingDirectorySeparator(path) {
- if (path.charAt(path.length - 1) !== ts.directorySeparator) {
+ if (!hasTrailingDirectorySeparator(path)) {
return path + ts.directorySeparator;
}
return path;
}
ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
- function comparePaths(a, b, currentDirectory, ignoreCase) {
+ function comparePathsWorker(a, b, componentComparer) {
if (a === b)
return 0;
if (a === undefined)
return -1;
if (b === undefined)
return 1;
- a = removeTrailingDirectorySeparator(a);
- b = removeTrailingDirectorySeparator(b);
- var aComponents = getNormalizedPathComponents(a, currentDirectory);
- var bComponents = getNormalizedPathComponents(b, currentDirectory);
+ var aComponents = reducePathComponents(getPathComponents(a));
+ var bComponents = reducePathComponents(getPathComponents(b));
var sharedLength = Math.min(aComponents.length, bComponents.length);
- var comparer = getStringComparer(ignoreCase);
for (var i = 0; i < sharedLength; i++) {
- var result = comparer(aComponents[i], bComponents[i]);
+ var stringComparer = i === 0 ? compareStringsCaseInsensitive : componentComparer;
+ var result = stringComparer(aComponents[i], bComponents[i]);
if (result !== 0) {
return result;
}
}
return compareValues(aComponents.length, bComponents.length);
}
+ function comparePathsCaseSensitive(a, b) {
+ return comparePathsWorker(a, b, compareStringsCaseSensitive);
+ }
+ ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
+ function comparePathsCaseInsensitive(a, b) {
+ return comparePathsWorker(a, b, compareStringsCaseInsensitive);
+ }
+ ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
+ function comparePaths(a, b, currentDirectory, ignoreCase) {
+ if (typeof currentDirectory === "string") {
+ a = combinePaths(currentDirectory, a);
+ b = combinePaths(currentDirectory, b);
+ }
+ else if (typeof currentDirectory === "boolean") {
+ ignoreCase = currentDirectory;
+ }
+ return comparePathsWorker(a, b, getStringComparer(ignoreCase));
+ }
ts.comparePaths = comparePaths;
function containsPath(parent, child, currentDirectory, ignoreCase) {
+ if (typeof currentDirectory === "string") {
+ parent = combinePaths(currentDirectory, parent);
+ child = combinePaths(currentDirectory, child);
+ }
+ else if (typeof currentDirectory === "boolean") {
+ ignoreCase = currentDirectory;
+ }
if (parent === undefined || child === undefined)
return false;
if (parent === child)
return true;
- parent = removeTrailingDirectorySeparator(parent);
- child = removeTrailingDirectorySeparator(child);
- if (parent === child)
- return true;
- var parentComponents = getNormalizedPathComponents(parent, currentDirectory);
- var childComponents = getNormalizedPathComponents(child, currentDirectory);
+ var parentComponents = reducePathComponents(getPathComponents(parent));
+ var childComponents = reducePathComponents(getPathComponents(child));
if (childComponents.length < parentComponents.length) {
return false;
}
- var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive;
+ var componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive;
for (var i = 0; i < parentComponents.length; i++) {
+ var equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer;
if (!equalityComparer(parentComponents[i], childComponents[i])) {
return false;
}
@@ -3460,13 +2366,17 @@ var ts;
ts.supportedJavascriptExtensions = [".js", ".jsx"];
var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions);
function getSupportedExtensions(options, extraFileExtensions) {
- var needAllExtensions = options && options.allowJs;
- if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) {
- return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
+ var needJsExtensions = options && options.allowJs;
+ if (!extraFileExtensions || extraFileExtensions.length === 0) {
+ return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions;
}
- return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive);
+ var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; }));
+ return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive);
}
ts.getSupportedExtensions = getSupportedExtensions;
+ function isJavaScriptLike(scriptKind) {
+ return scriptKind === 1 || scriptKind === 2;
+ }
function hasJavaScriptFileExtension(fileName) {
return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); });
}
@@ -3488,13 +2398,6 @@ var ts;
return false;
}
ts.isSupportedSourceFileName = isSupportedSourceFileName;
- var ExtensionPriority;
- (function (ExtensionPriority) {
- ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles";
- ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles";
- ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest";
- ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest";
- })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {}));
function getExtensionPriority(path, supportedExtensions) {
for (var i = supportedExtensions.length - 1; i >= 0; i--) {
if (fileExtensionIs(path, supportedExtensions[i])) {
@@ -3525,7 +2428,7 @@ var ts;
}
}
ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
- var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"];
+ var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx", ".json"];
function removeFileExtension(path) {
for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
var ext = extensionsToRemove_1[_i];
@@ -3546,9 +2449,14 @@ var ts;
}
ts.removeExtension = removeExtension;
function changeExtension(path, newExtension) {
- return (removeFileExtension(path) + newExtension);
+ return changeAnyExtension(path, newExtension, extensionsToRemove, false);
}
ts.changeExtension = changeExtension;
+ function changeAnyExtension(path, ext, extensions, ignoreCase) {
+ var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
+ return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path;
+ }
+ ts.changeAnyExtension = changeAnyExtension;
function removeMinAndVersionNumbers(fileName) {
var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/;
return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, "");
@@ -3596,13 +2504,6 @@ var ts;
getSignatureConstructor: function () { return Signature; },
getSourceMapSourceConstructor: function () { return SourceMapSource; },
};
- var AssertionLevel;
- (function (AssertionLevel) {
- AssertionLevel[AssertionLevel["None"] = 0] = "None";
- AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal";
- AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive";
- AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive";
- })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {}));
var Debug;
(function (Debug) {
Debug.currentAssertionLevel = 0;
@@ -3807,6 +2708,10 @@ var ts;
return ext === ".ts" || ext === ".tsx" || ext === ".d.ts";
}
ts.extensionIsTypeScript = extensionIsTypeScript;
+ function resolutionExtensionIsTypeScriptOrJson(ext) {
+ return extensionIsTypeScript(ext) || ext === ".json";
+ }
+ ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson;
function extensionFromPath(path) {
var ext = tryGetExtensionFromPath(path);
if (ext !== undefined) {
@@ -3823,12 +2728,32 @@ var ts;
return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); });
}
ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
- function getAnyExtensionFromPath(path) {
+ function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
+ if (typeof extensions === "string")
+ extensions = [extensions];
+ for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
+ var extension = extensions_2[_i];
+ if (!startsWith(extension, "."))
+ extension = "." + extension;
+ if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") {
+ var pathExtension = path.slice(path.length - extension.length);
+ if (stringEqualityComparer(pathExtension, extension)) {
+ return pathExtension;
+ }
+ }
+ }
+ return "";
+ }
+ function getAnyExtensionFromPath(path, extensions, ignoreCase) {
+ if (extensions) {
+ return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive);
+ }
var baseFileName = getBaseFileName(path);
var extensionIndex = baseFileName.lastIndexOf(".");
if (extensionIndex >= 0) {
return baseFileName.substring(extensionIndex);
}
+ return "";
}
ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
@@ -3921,12 +2846,12 @@ var ts;
ts.watchFileUsingPriorityPollingInterval = watchFileUsingPriorityPollingInterval;
ts.missingFileModifiedTime = new Date(0);
function createPollingIntervalBasedLevels(levels) {
+ var _a;
return _a = {},
_a[PollingInterval.Low] = levels.Low,
_a[PollingInterval.Medium] = levels.Medium,
_a[PollingInterval.High] = levels.High,
_a;
- var _a;
}
var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
@@ -4199,11 +3124,6 @@ var ts;
var isNode4OrLater = nodeVersion >= 4;
var platform = _os.platform();
var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
- var FileSystemEntryKind;
- (function (FileSystemEntryKind) {
- FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File";
- FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory";
- })(FileSystemEntryKind || (FileSystemEntryKind = {}));
var useNonPollingWatchers = process.env.TSC_NONPOLLING_WATCHER;
var tscWatchFile = process.env.TSC_WATCHFILE;
var tscWatchDirectory = process.env.TSC_WATCHDIRECTORY;
@@ -4917,7 +3837,7 @@ var ts;
Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."),
Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."),
Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."),
- Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."),
+ Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."),
Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."),
Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."),
Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"),
@@ -5394,6 +4314,7 @@ var ts;
Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."),
Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."),
Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."),
+ Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."),
Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."),
Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."),
Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
@@ -5577,6 +4498,17 @@ var ts;
Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."),
Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."),
_0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", true),
+ Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
+ All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", true),
+ Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
+ Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
+ Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"),
+ Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."),
+ Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."),
+ Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."),
+ File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."),
+ Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"),
+ Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"),
Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."),
Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."),
Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."),
@@ -5675,6 +4607,7 @@ var ts;
Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
+ Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"),
Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""),
@@ -5738,6 +4671,7 @@ var ts;
Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
+ Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
};
})(ts || (ts = {}));
var ts;
@@ -5971,7 +4905,7 @@ var ts;
if (includeJsDoc && ts.hasJSDocNodes(node)) {
return getTokenPosOfNode(node.jsDoc[0]);
}
- if (node.kind === 294 && node._children.length > 0) {
+ if (node.kind === 296 && node._children.length > 0) {
return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
}
return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
@@ -6146,12 +5080,12 @@ var ts;
case 159:
case 162:
case 163:
- case 281:
+ case 283:
case 234:
case 204:
case 235:
case 236:
- case 291:
+ case 293:
case 233:
case 153:
case 154:
@@ -6181,6 +5115,12 @@ var ts;
case 243:
case 242:
case 213:
+ case 234:
+ case 233:
+ case 238:
+ case 236:
+ case 235:
+ case 237:
return true;
default:
return false;
@@ -6308,6 +5248,8 @@ var ts;
case 155:
case 156:
case 236:
+ case 151:
+ case 150:
errorNode = node.name;
break;
case 192:
@@ -6335,6 +5277,10 @@ var ts;
return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
}
ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
+ function isJsonSourceFile(file) {
+ return file.scriptKind === 6;
+ }
+ ts.isJsonSourceFile = isJsonSourceFile;
function isConstEnumDeclaration(node) {
return node.kind === 237 && isConst(node);
}
@@ -6646,6 +5592,23 @@ var ts;
});
}
ts.getPropertyAssignment = getPropertyAssignment;
+ function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
+ if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
+ var expression = tsConfigSourceFile.statements[0].expression;
+ return ts.isObjectLiteralExpression(expression) && expression;
+ }
+ }
+ ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
+ function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
+ var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
+ return jsonObjectLiteral &&
+ ts.firstDefined(getPropertyAssignment(jsonObjectLiteral, propKey), function (property) {
+ return ts.isArrayLiteralExpression(property.initializer) ?
+ ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
+ undefined;
+ });
+ }
+ ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
function getContainingFunction(node) {
return ts.findAncestor(node.parent, ts.isFunctionLike);
}
@@ -6983,6 +5946,10 @@ var ts;
return node && !!(node.flags & 65536);
}
ts.isInJavaScriptFile = isInJavaScriptFile;
+ function isInJsonFile(node) {
+ return node && !!(node.flags & 16777216);
+ }
+ ts.isInJsonFile = isInJsonFile;
function isInJSDoc(node) {
return node && !!(node.flags & 2097152);
}
@@ -7223,7 +6190,7 @@ var ts;
}
ts.hasQuestionToken = hasQuestionToken;
function isJSDocConstructSignature(node) {
- return node.kind === 281 &&
+ return node.kind === 283 &&
node.parameters.length > 0 &&
node.parameters[0].name &&
node.parameters[0].name.escapedText === "new";
@@ -7329,15 +6296,15 @@ var ts;
}
ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
function getJSDocHost(node) {
- while (node.parent.kind === 284) {
- if (node.parent.parent.kind === 292) {
+ while (node.parent.kind === 286) {
+ if (node.parent.parent.kind === 294) {
node = node.parent.parent;
}
else {
node = node.parent.parent.parent;
}
}
- ts.Debug.assert(node.parent.kind === 283);
+ ts.Debug.assert(node.parent.kind === 285);
return node.parent.parent;
}
ts.getJSDocHost = getJSDocHost;
@@ -7353,15 +6320,9 @@ var ts;
}
ts.hasRestParameter = hasRestParameter;
function isRestParameter(node) {
- return node.dotDotDotToken !== undefined || node.type && node.type.kind === 282;
+ return node.dotDotDotToken !== undefined || node.type && node.type.kind === 284;
}
ts.isRestParameter = isRestParameter;
- var AssignmentKind;
- (function (AssignmentKind) {
- AssignmentKind[AssignmentKind["None"] = 0] = "None";
- AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite";
- AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound";
- })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {}));
function getAssignmentTargetKind(node) {
var parent = node.parent;
while (true) {
@@ -7484,8 +6445,14 @@ var ts;
if (ts.isDeclaration(name.parent)) {
return name.parent.name === name;
}
- var binExp = name.parent.parent;
- return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name;
+ else if (ts.isQualifiedName(name.parent)) {
+ var tag = name.parent.parent;
+ return ts.isJSDocParameterTag(tag) && tag.name === name.parent;
+ }
+ else {
+ var binExp = name.parent.parent;
+ return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name;
+ }
default:
return false;
}
@@ -7615,14 +6582,6 @@ var ts;
return 2 <= token && token <= 7;
}
ts.isTrivia = isTrivia;
- var FunctionFlags;
- (function (FunctionFlags) {
- FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
- FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
- FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
- FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
- FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator";
- })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
function getFunctionFlags(node) {
if (!node) {
return 4;
@@ -7770,11 +6729,6 @@ var ts;
return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile;
}
ts.getOriginalSourceFile = getOriginalSourceFile;
- var Associativity;
- (function (Associativity) {
- Associativity[Associativity["Left"] = 0] = "Left";
- Associativity[Associativity["Right"] = 1] = "Right";
- })(Associativity = ts.Associativity || (ts.Associativity = {}));
function getExpressionAssociativity(expression) {
var operator = getOperator(expression);
var hasArguments = expression.kind === 187 && expression.arguments !== undefined;
@@ -7835,7 +6789,7 @@ var ts;
ts.getOperator = getOperator;
function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
switch (nodeKind) {
- case 297:
+ case 299:
return 0;
case 203:
return 1;
@@ -8956,12 +7910,6 @@ var ts;
return accessKind(node) !== 0;
}
ts.isWriteAccess = isWriteAccess;
- var AccessKind;
- (function (AccessKind) {
- AccessKind[AccessKind["Read"] = 0] = "Read";
- AccessKind[AccessKind["Write"] = 1] = "Write";
- AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite";
- })(AccessKind || (AccessKind = {}));
function accessKind(node) {
var parent = node.parent;
if (!parent)
@@ -9456,8 +8404,8 @@ var ts;
break;
case 71:
return declaration;
- case 293:
- case 288: {
+ case 295:
+ case 290: {
var name = declaration.name;
if (name.kind === 145) {
return name.right;
@@ -9476,7 +8424,7 @@ var ts;
return undefined;
}
}
- case 292:
+ case 294:
return getNameOfJSDocTypedef(declaration);
case 248: {
var expression = declaration.expression;
@@ -9674,6 +8622,10 @@ var ts;
return node.kind === 159;
}
ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
+ function isGetOrSetAccessorDeclaration(node) {
+ return node.kind === 156 || node.kind === 155;
+ }
+ ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
function isTypePredicateNode(node) {
return node.kind === 160;
}
@@ -9799,7 +8751,7 @@ var ts;
}
ts.isParenthesizedExpression = isParenthesizedExpression;
function skipPartiallyEmittedExpressions(node) {
- while (node.kind === 296) {
+ while (node.kind === 298) {
node = node.expression;
}
return node;
@@ -10146,85 +9098,85 @@ var ts;
}
ts.isBundle = isBundle;
function isJSDocTypeExpression(node) {
- return node.kind === 275;
+ return node.kind === 277;
}
ts.isJSDocTypeExpression = isJSDocTypeExpression;
function isJSDocAllType(node) {
- return node.kind === 276;
+ return node.kind === 278;
}
ts.isJSDocAllType = isJSDocAllType;
function isJSDocUnknownType(node) {
- return node.kind === 277;
+ return node.kind === 279;
}
ts.isJSDocUnknownType = isJSDocUnknownType;
function isJSDocNullableType(node) {
- return node.kind === 278;
+ return node.kind === 280;
}
ts.isJSDocNullableType = isJSDocNullableType;
function isJSDocNonNullableType(node) {
- return node.kind === 279;
+ return node.kind === 281;
}
ts.isJSDocNonNullableType = isJSDocNonNullableType;
function isJSDocOptionalType(node) {
- return node.kind === 280;
+ return node.kind === 282;
}
ts.isJSDocOptionalType = isJSDocOptionalType;
function isJSDocFunctionType(node) {
- return node.kind === 281;
+ return node.kind === 283;
}
ts.isJSDocFunctionType = isJSDocFunctionType;
function isJSDocVariadicType(node) {
- return node.kind === 282;
+ return node.kind === 284;
}
ts.isJSDocVariadicType = isJSDocVariadicType;
function isJSDoc(node) {
- return node.kind === 283;
+ return node.kind === 285;
}
ts.isJSDoc = isJSDoc;
function isJSDocAugmentsTag(node) {
- return node.kind === 286;
+ return node.kind === 288;
}
ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
function isJSDocClassTag(node) {
- return node.kind === 287;
+ return node.kind === 289;
}
ts.isJSDocClassTag = isJSDocClassTag;
function isJSDocParameterTag(node) {
- return node.kind === 288;
+ return node.kind === 290;
}
ts.isJSDocParameterTag = isJSDocParameterTag;
function isJSDocReturnTag(node) {
- return node.kind === 289;
+ return node.kind === 291;
}
ts.isJSDocReturnTag = isJSDocReturnTag;
function isJSDocTypeTag(node) {
- return node.kind === 290;
+ return node.kind === 292;
}
ts.isJSDocTypeTag = isJSDocTypeTag;
function isJSDocTemplateTag(node) {
- return node.kind === 291;
+ return node.kind === 293;
}
ts.isJSDocTemplateTag = isJSDocTemplateTag;
function isJSDocTypedefTag(node) {
- return node.kind === 292;
+ return node.kind === 294;
}
ts.isJSDocTypedefTag = isJSDocTypedefTag;
function isJSDocPropertyTag(node) {
- return node.kind === 293;
+ return node.kind === 295;
}
ts.isJSDocPropertyTag = isJSDocPropertyTag;
function isJSDocPropertyLikeTag(node) {
- return node.kind === 293 || node.kind === 288;
+ return node.kind === 295 || node.kind === 290;
}
ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
function isJSDocTypeLiteral(node) {
- return node.kind === 284;
+ return node.kind === 286;
}
ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
})(ts || (ts = {}));
(function (ts) {
function isSyntaxList(n) {
- return n.kind === 294;
+ return n.kind === 296;
}
ts.isSyntaxList = isSyntaxList;
function isNode(node) {
@@ -10349,7 +9301,7 @@ var ts;
case 158:
case 159:
case 162:
- case 281:
+ case 283:
case 163:
return true;
default:
@@ -10428,13 +9380,13 @@ var ts;
|| kind === 95
|| kind === 131
|| kind === 206
- || kind === 276
- || kind === 277
|| kind === 278
|| kind === 279
|| kind === 280
|| kind === 281
- || kind === 282;
+ || kind === 282
+ || kind === 283
+ || kind === 284;
}
function isTypeNode(node) {
return isTypeNodeKind(node.kind);
@@ -10621,8 +9573,8 @@ var ts;
case 203:
case 207:
case 205:
- case 297:
- case 296:
+ case 299:
+ case 298:
return true;
default:
return isUnaryExpressionKind(kind);
@@ -10635,11 +9587,11 @@ var ts;
}
ts.isAssertionExpression = isAssertionExpression;
function isPartiallyEmittedExpression(node) {
- return node.kind === 296;
+ return node.kind === 298;
}
ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
function isNotEmittedStatement(node) {
- return node.kind === 295;
+ return node.kind === 297;
}
ts.isNotEmittedStatement = isNotEmittedStatement;
function isNotEmittedOrPartiallyEmittedNode(node) {
@@ -10739,7 +9691,8 @@ var ts;
|| kind === 236
|| kind === 147
|| kind === 231
- || kind === 292;
+ || kind === 294
+ || kind === 295;
}
function isDeclarationStatementKind(kind) {
return kind === 233
@@ -10774,13 +9727,13 @@ var ts;
|| kind === 213
|| kind === 218
|| kind === 225
- || kind === 295
- || kind === 299
- || kind === 298;
+ || kind === 297
+ || kind === 301
+ || kind === 300;
}
function isDeclaration(node) {
if (node.kind === 147) {
- return node.parent.kind !== 291 || ts.isInJavaScriptFile(node);
+ return node.parent.kind !== 293 || ts.isInJavaScriptFile(node);
}
return isDeclarationKind(node.kind);
}
@@ -10858,15 +9811,15 @@ var ts;
}
ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
function isJSDocNode(node) {
- return node.kind >= 275 && node.kind <= 293;
+ return node.kind >= 277 && node.kind <= 295;
}
ts.isJSDocNode = isJSDocNode;
function isJSDocCommentContainingNode(node) {
- return node.kind === 283 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node);
+ return node.kind === 285 || isJSDocTag(node) || ts.isJSDocTypeLiteral(node);
}
ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
function isJSDocTag(node) {
- return node.kind >= 285 && node.kind <= 293;
+ return node.kind >= 287 && node.kind <= 295;
}
ts.isJSDocTag = isJSDocTag;
function isSetAccessor(node) {
@@ -10911,12 +9864,12 @@ var ts;
case 231:
case 233:
case 236:
- case 275:
- case 278:
- case 279:
+ case 277:
case 280:
case 281:
case 282:
+ case 283:
+ case 284:
return true;
}
return false;
@@ -12678,16 +11631,6 @@ var ts;
})(ts || (ts = {}));
var ts;
(function (ts) {
- var SignatureFlags;
- (function (SignatureFlags) {
- SignatureFlags[SignatureFlags["None"] = 0] = "None";
- SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield";
- SignatureFlags[SignatureFlags["Await"] = 2] = "Await";
- SignatureFlags[SignatureFlags["Type"] = 4] = "Type";
- SignatureFlags[SignatureFlags["RequireCompleteParameterList"] = 8] = "RequireCompleteParameterList";
- SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
- SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
- })(SignatureFlags || (SignatureFlags = {}));
var NodeConstructor;
var TokenConstructor;
var IdentifierConstructor;
@@ -13077,7 +12020,7 @@ var ts;
return visitNode(cbNode, node.expression);
case 252:
return visitNodes(cbNode, cbNodes, node.decorators);
- case 297:
+ case 299:
return visitNodes(cbNode, cbNodes, node.elements);
case 254:
return visitNode(cbNode, node.openingElement) ||
@@ -13104,23 +12047,23 @@ var ts;
visitNode(cbNode, node.expression);
case 257:
return visitNode(cbNode, node.tagName);
- case 275:
+ case 277:
return visitNode(cbNode, node.type);
- case 279:
- return visitNode(cbNode, node.type);
- case 278:
+ case 281:
return visitNode(cbNode, node.type);
case 280:
return visitNode(cbNode, node.type);
- case 281:
- return visitNodes(cbNode, cbNodes, node.parameters) ||
- visitNode(cbNode, node.type);
case 282:
return visitNode(cbNode, node.type);
case 283:
+ return visitNodes(cbNode, cbNodes, node.parameters) ||
+ visitNode(cbNode, node.type);
+ case 284:
+ return visitNode(cbNode, node.type);
+ case 285:
return visitNodes(cbNode, cbNodes, node.tags);
- case 288:
- case 293:
+ case 290:
+ case 295:
if (node.isNameFirst) {
return visitNode(cbNode, node.name) ||
visitNode(cbNode, node.typeExpression);
@@ -13129,17 +12072,17 @@ var ts;
return visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.name);
}
- case 289:
- return visitNode(cbNode, node.typeExpression);
- case 290:
- return visitNode(cbNode, node.typeExpression);
- case 286:
- return visitNode(cbNode, node.class);
case 291:
- return visitNodes(cbNode, cbNodes, node.typeParameters);
+ return visitNode(cbNode, node.typeExpression);
case 292:
+ return visitNode(cbNode, node.typeExpression);
+ case 288:
+ return visitNode(cbNode, node.class);
+ case 293:
+ return visitNodes(cbNode, cbNodes, node.typeParameters);
+ case 294:
if (node.typeExpression &&
- node.typeExpression.kind === 275) {
+ node.typeExpression.kind === 277) {
return visitNode(cbNode, node.typeExpression) ||
visitNode(cbNode, node.fullName);
}
@@ -13147,7 +12090,7 @@ var ts;
return visitNode(cbNode, node.fullName) ||
visitNode(cbNode, node.typeExpression);
}
- case 284:
+ case 286:
if (node.jsDocPropertyTags) {
for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) {
var tag = _a[_i];
@@ -13155,7 +12098,7 @@ var ts;
}
}
return;
- case 296:
+ case 298:
return visitNode(cbNode, node.expression);
}
}
@@ -13163,7 +12106,13 @@ var ts;
function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
if (setParentNodes === void 0) { setParentNodes = false; }
ts.performance.mark("beforeParse");
- var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind);
+ var result;
+ if (languageVersion === 100) {
+ result = Parser.parseJsonText(fileName, sourceText, languageVersion, undefined, setParentNodes);
+ }
+ else {
+ result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind);
+ }
ts.performance.mark("afterParse");
ts.performance.measure("Parse", "beforeParse", "afterParse");
return result;
@@ -13220,6 +12169,13 @@ var ts;
var parseErrorBeforeNextFinishedNode = false;
function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
scriptKind = ts.ensureScriptKind(fileName, scriptKind);
+ if (scriptKind === 6) {
+ var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
+ ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, false, undefined, undefined);
+ result_1.typeReferenceDirectives = ts.emptyArray;
+ result_1.amdDependencies = ts.emptyArray;
+ return result_1;
+ }
initializeState(sourceText, languageVersion, syntaxCursor, scriptKind);
var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind);
clearState();
@@ -13235,23 +12191,54 @@ var ts;
return isInvalid ? entityName : undefined;
}
Parser.parseIsolatedEntityName = parseIsolatedEntityName;
- function parseJsonText(fileName, sourceText) {
- initializeState(sourceText, 2, undefined, 6);
+ function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
+ if (languageVersion === void 0) { languageVersion = 2; }
+ initializeState(sourceText, languageVersion, syntaxCursor, 6);
sourceFile = createSourceFile(fileName, 2, 6, false);
- var result = sourceFile;
nextToken();
+ var pos = getNodePos();
if (token() === 1) {
+ sourceFile.statements = createNodeArray([], pos, pos);
sourceFile.endOfFileToken = parseTokenNode();
}
- else if (token() === 17 ||
- lookAhead(function () { return token() === 9; })) {
- result.jsonObject = parseObjectLiteralExpression();
+ else {
+ var statement = createNode(215);
+ switch (token()) {
+ case 21:
+ statement.expression = parseArrayLiteralExpression();
+ break;
+ case 101:
+ case 86:
+ case 95:
+ statement.expression = parseTokenNode();
+ break;
+ case 38:
+ if (lookAhead(function () { return nextToken() === 8 && nextToken() !== 56; })) {
+ statement.expression = parsePrefixUnaryExpression();
+ }
+ else {
+ statement.expression = parseObjectLiteralExpression();
+ }
+ break;
+ case 8:
+ case 9:
+ if (lookAhead(function () { return nextToken() !== 56; })) {
+ statement.expression = parseLiteralNode();
+ break;
+ }
+ default:
+ statement.expression = parseObjectLiteralExpression();
+ break;
+ }
+ finishNode(statement);
+ sourceFile.statements = createNodeArray([statement], pos);
sourceFile.endOfFileToken = parseExpectedToken(1, ts.Diagnostics.Unexpected_token);
}
- else {
- parseExpected(17);
+ if (setParentNodes) {
+ fixupParentReferences(sourceFile);
}
sourceFile.parseDiagnostics = parseDiagnostics;
+ var result = sourceFile;
clearState();
return result;
}
@@ -13274,9 +12261,11 @@ var ts;
switch (scriptKind) {
case 1:
case 2:
- case 6:
contextFlags = 65536;
break;
+ case 6:
+ contextFlags = 65536 | 16777216;
+ break;
default:
contextFlags = 0;
break;
@@ -14266,9 +13255,9 @@ var ts;
return finishNode(node);
}
function parseJSDocAllType(postFixEquals) {
- var result = createNode(276);
+ var result = createNode(278);
if (postFixEquals) {
- return createJSDocPostfixType(280, result);
+ return createJSDocPostfixType(282, result);
}
else {
nextToken();
@@ -14276,7 +13265,7 @@ var ts;
return finishNode(result);
}
function parseJSDocNonNullableType() {
- var result = createNode(279);
+ var result = createNode(281);
nextToken();
result.type = parseNonArrayType();
return finishNode(result);
@@ -14290,18 +13279,18 @@ var ts;
token() === 29 ||
token() === 58 ||
token() === 49) {
- var result = createNode(277, pos);
+ var result = createNode(279, pos);
return finishNode(result);
}
else {
- var result = createNode(278, pos);
+ var result = createNode(280, pos);
result.type = parseType();
return finishNode(result);
}
}
function parseJSDocFunctionType() {
if (lookAhead(nextTokenIsOpenParen)) {
- var result = createNodeWithJSDoc(281);
+ var result = createNodeWithJSDoc(283);
nextToken();
fillSignature(56, 4 | 32, result);
return finishNode(result);
@@ -14323,12 +13312,12 @@ var ts;
var dotdotdot = parseOptionalToken(24);
var type = parseType();
if (dotdotdot) {
- var variadic = createNode(282, dotdotdot.pos);
+ var variadic = createNode(284, dotdotdot.pos);
variadic.type = type;
type = finishNode(variadic);
}
if (token() === 58) {
- return createJSDocPostfixType(280, type);
+ return createJSDocPostfixType(282, type);
}
return type;
}
@@ -14782,13 +13771,13 @@ var ts;
while (!scanner.hasPrecedingLineBreak()) {
switch (token()) {
case 51:
- type = createJSDocPostfixType(279, type);
+ type = createJSDocPostfixType(281, type);
break;
case 55:
if (!(contextFlags & 2097152) && lookAhead(nextTokenIsStartOfType)) {
return type;
}
- type = createJSDocPostfixType(278, type);
+ type = createJSDocPostfixType(280, type);
break;
case 21:
parseExpected(21);
@@ -17115,39 +16104,6 @@ var ts;
function isImportMeta(node) {
return ts.isMetaProperty(node) && node.keywordToken === 91 && node.name.escapedText === "meta";
}
- var ParsingContext;
- (function (ParsingContext) {
- ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
- ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
- ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
- ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
- ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
- ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
- ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
- ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
- ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
- ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
- ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
- ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
- ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
- ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
- ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
- ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
- ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
- ParsingContext[ParsingContext["RestProperties"] = 17] = "RestProperties";
- ParsingContext[ParsingContext["TypeParameters"] = 18] = "TypeParameters";
- ParsingContext[ParsingContext["TypeArguments"] = 19] = "TypeArguments";
- ParsingContext[ParsingContext["TupleElementTypes"] = 20] = "TupleElementTypes";
- ParsingContext[ParsingContext["HeritageClauses"] = 21] = "HeritageClauses";
- ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 22] = "ImportOrExportSpecifiers";
- ParsingContext[ParsingContext["Count"] = 23] = "Count";
- })(ParsingContext || (ParsingContext = {}));
- var Tristate;
- (function (Tristate) {
- Tristate[Tristate["False"] = 0] = "False";
- Tristate[Tristate["True"] = 1] = "True";
- Tristate[Tristate["Unknown"] = 2] = "Unknown";
- })(Tristate || (Tristate = {}));
var JSDocParser;
(function (JSDocParser) {
function parseJSDocTypeExpressionForTests(content, start, length) {
@@ -17162,7 +16118,7 @@ var ts;
}
JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
function parseJSDocTypeExpression(mayOmitBraces) {
- var result = createNode(275, scanner.getTokenPos());
+ var result = createNode(277, scanner.getTokenPos());
var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17);
result.type = doInsideOfContext(2097152, parseJSDocType);
if (!mayOmitBraces || hasBrace) {
@@ -17182,6 +16138,7 @@ var ts;
}
JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
function parseJSDocComment(parent, start, length) {
+ var _a;
var saveToken = currentToken;
var saveParseDiagnosticsLength = parseDiagnostics.length;
var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
@@ -17199,20 +16156,8 @@ var ts;
parseDiagnostics.length = saveParseDiagnosticsLength;
parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
return comment;
- var _a;
}
JSDocParser.parseJSDocComment = parseJSDocComment;
- var JSDocState;
- (function (JSDocState) {
- JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
- JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
- JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
- })(JSDocState || (JSDocState = {}));
- var PropertyLikeParse;
- (function (PropertyLikeParse) {
- PropertyLikeParse[PropertyLikeParse["Property"] = 0] = "Property";
- PropertyLikeParse[PropertyLikeParse["Parameter"] = 1] = "Parameter";
- })(PropertyLikeParse || (PropertyLikeParse = {}));
function parseJSDocCommentWorker(start, length) {
var content = sourceText;
start = start || 0;
@@ -17318,7 +16263,7 @@ var ts;
}
}
function createJSDocComment() {
- var result = createNode(283, start);
+ var result = createNode(285, start);
result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
result.comment = comments.length ? comments.join("") : undefined;
return finishNode(result, end);
@@ -17436,7 +16381,7 @@ var ts;
return comments.length === 0 ? undefined : comments.join("");
}
function parseUnknownTag(atToken, tagName) {
- var result = createNode(285, atToken.pos);
+ var result = createNode(287, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
return finishNode(result);
@@ -17490,8 +16435,8 @@ var ts;
typeExpression = tryParseTypeExpression();
}
var result = target === 1 ?
- createNode(288, atToken.pos) :
- createNode(293, atToken.pos);
+ createNode(290, atToken.pos) :
+ createNode(295, atToken.pos);
var comment;
if (indent !== undefined)
comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos);
@@ -17511,18 +16456,18 @@ var ts;
}
function parseNestedTypeLiteral(typeExpression, name, target) {
if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
- var typeLiteralExpression = createNode(275, scanner.getTokenPos());
+ var typeLiteralExpression = createNode(277, 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, name); })) {
- if (child.kind === 288 || child.kind === 293) {
+ if (child.kind === 290 || child.kind === 295) {
children = ts.append(children, child);
}
}
if (children) {
- jsdocTypeLiteral = createNode(284, start_2);
+ jsdocTypeLiteral = createNode(286, start_2);
jsdocTypeLiteral.jsDocPropertyTags = children;
if (typeExpression.type.kind === 166) {
jsdocTypeLiteral.isArrayType = true;
@@ -17533,27 +16478,27 @@ var ts;
}
}
function parseReturnTag(atToken, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 289; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 291; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(289, atToken.pos);
+ var result = createNode(291, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeExpression = tryParseTypeExpression();
return finishNode(result);
}
function parseTypeTag(atToken, tagName) {
- if (ts.forEach(tags, function (t) { return t.kind === 290; })) {
+ if (ts.forEach(tags, function (t) { return t.kind === 292; })) {
parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
}
- var result = createNode(290, atToken.pos);
+ var result = createNode(292, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeExpression = parseJSDocTypeExpression(true);
return finishNode(result);
}
function parseAugmentsTag(atToken, tagName) {
- var result = createNode(286, atToken.pos);
+ var result = createNode(288, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.class = parseExpressionWithTypeArgumentsForAugments();
@@ -17581,7 +16526,7 @@ var ts;
return node;
}
function parseClassTag(atToken, tagName) {
- var tag = createNode(287, atToken.pos);
+ var tag = createNode(289, atToken.pos);
tag.atToken = atToken;
tag.tagName = tagName;
return finishNode(tag);
@@ -17589,7 +16534,7 @@ var ts;
function parseTypedefTag(atToken, tagName) {
var typeExpression = tryParseTypeExpression();
skipWhitespace();
- var typedefTag = createNode(292, atToken.pos);
+ var typedefTag = createNode(294, atToken.pos);
typedefTag.atToken = atToken;
typedefTag.tagName = tagName;
typedefTag.fullName = parseJSDocTypeNameWithNamespace(0);
@@ -17612,9 +16557,9 @@ var ts;
var start_3 = scanner.getStartPos();
while (child = tryParse(function () { return parseChildPropertyTag(); })) {
if (!jsdocTypeLiteral) {
- jsdocTypeLiteral = createNode(284, start_3);
+ jsdocTypeLiteral = createNode(286, start_3);
}
- if (child.kind === 290) {
+ if (child.kind === 292) {
if (childTypeTag) {
break;
}
@@ -17675,7 +16620,7 @@ var ts;
case 57:
if (canParseTag) {
var child = tryParseChildTag(target);
- if (child && child.kind === 288 &&
+ if (child && child.kind === 290 &&
(ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
return false;
}
@@ -17759,7 +16704,7 @@ var ts;
break;
}
}
- var result = createNode(291, atToken.pos);
+ var result = createNode(293, atToken.pos);
result.atToken = atToken;
result.tagName = tagName;
result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
@@ -18101,10 +17046,6 @@ var ts;
}
}
}
- var InvalidPosition;
- (function (InvalidPosition) {
- InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
- })(InvalidPosition || (InvalidPosition = {}));
})(IncrementalParser || (IncrementalParser = {}));
function isDeclarationFileName(fileName) {
return ts.fileExtensionIs(fileName, ".d.ts");
@@ -18536,6 +17477,13 @@ var ts;
category: ts.Diagnostics.Basic_Options,
description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
},
+ {
+ name: "composite",
+ type: "boolean",
+ isTSConfigOnly: true,
+ category: ts.Diagnostics.Basic_Options,
+ description: ts.Diagnostics.Enable_project_compilation,
+ },
{
name: "removeComments",
type: "boolean",
@@ -18786,6 +17734,12 @@ var ts;
category: ts.Diagnostics.Advanced_Options,
description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
},
+ {
+ name: "resolveJsonModule",
+ type: "boolean",
+ category: ts.Diagnostics.Advanced_Options,
+ description: ts.Diagnostics.Include_modules_imported_with_json_extension
+ },
{
name: "listFiles",
type: "boolean",
@@ -19067,11 +18021,13 @@ var ts;
function parseCommandLine(commandLine, readFile) {
var options = {};
var fileNames = [];
+ var projectReferences = undefined;
var errors = [];
parseStrings(commandLine);
return {
options: options,
fileNames: fileNames,
+ projectReferences: projectReferences,
errors: errors
};
function parseStrings(args) {
@@ -19179,6 +18135,26 @@ var ts;
}
return optionNameMap.get(optionName);
}
+ function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) {
+ var configFileText;
+ try {
+ configFileText = host.readFile(configFileName);
+ }
+ catch (e) {
+ var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message);
+ host.onUnRecoverableConfigFileDiagnostic(error);
+ return undefined;
+ }
+ if (!configFileText) {
+ var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
+ host.onUnRecoverableConfigFileDiagnostic(error);
+ return undefined;
+ }
+ var result = ts.parseJsonText(configFileName, configFileText);
+ var cwd = host.getCurrentDirectory();
+ return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd));
+ }
+ ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
function readConfigFile(fileName, readFile) {
var textOrDiagnostic = tryReadFile(fileName, readFile);
return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
@@ -19213,69 +18189,84 @@ var ts;
var _tsconfigRootOptions;
function getTsconfigRootOptionsMap() {
if (_tsconfigRootOptions === undefined) {
- _tsconfigRootOptions = commandLineOptionsToMap([
- {
- name: "compilerOptions",
- type: "object",
- elementOptions: commandLineOptionsToMap(ts.optionDeclarations),
- extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0
- },
- {
- name: "typingOptions",
- type: "object",
- elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
- extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
- },
- {
- name: "typeAcquisition",
- type: "object",
- elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
- extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
- },
- {
- name: "extends",
- type: "string"
- },
- {
- name: "files",
- type: "list",
- element: {
+ _tsconfigRootOptions = {
+ name: undefined,
+ type: "object",
+ elementOptions: commandLineOptionsToMap([
+ {
+ name: "compilerOptions",
+ type: "object",
+ elementOptions: commandLineOptionsToMap(ts.optionDeclarations),
+ extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0
+ },
+ {
+ name: "typingOptions",
+ type: "object",
+ elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
+ extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
+ },
+ {
+ name: "typeAcquisition",
+ type: "object",
+ elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations),
+ extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0
+ },
+ {
+ name: "extends",
+ type: "string"
+ },
+ {
+ name: "references",
+ type: "list",
+ element: {
+ name: "references",
+ type: "object"
+ }
+ },
+ {
name: "files",
- type: "string"
- }
- },
- {
- name: "include",
- type: "list",
- element: {
+ type: "list",
+ element: {
+ name: "files",
+ type: "string"
+ }
+ },
+ {
name: "include",
- type: "string"
- }
- },
- {
- name: "exclude",
- type: "list",
- element: {
+ type: "list",
+ element: {
+ name: "include",
+ type: "string"
+ }
+ },
+ {
name: "exclude",
- type: "string"
- }
- },
- ts.compileOnSaveCommandLineOption
- ]);
+ type: "list",
+ element: {
+ name: "exclude",
+ type: "string"
+ }
+ },
+ ts.compileOnSaveCommandLineOption
+ ])
+ };
}
return _tsconfigRootOptions;
}
function convertToObject(sourceFile, errors) {
- return convertToObjectWorker(sourceFile, errors, undefined, undefined);
+ return convertToObjectWorker(sourceFile, errors, true, undefined, undefined);
}
ts.convertToObject = convertToObject;
- function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) {
- if (!sourceFile.jsonObject) {
- return {};
+ function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
+ if (!sourceFile.statements.length) {
+ return returnValue ? {} : undefined;
+ }
+ return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
+ function isRootOptionMap(knownOptions) {
+ return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
}
- return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions, undefined, undefined);
function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) {
- var result = {};
+ var result = returnValue ? {} : undefined;
for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
var element = _a[_i];
if (element.kind !== 269) {
@@ -19295,16 +18286,18 @@ var ts;
}
var value = convertPropertyValueToJson(element.initializer, option);
if (typeof keyText !== "undefined") {
- result[keyText] = value;
+ if (returnValue) {
+ result[keyText] = value;
+ }
if (jsonConversionNotifier &&
- (parentOption || knownOptions === knownRootOptions)) {
+ (parentOption || isRootOptionMap(knownOptions))) {
var isValidOptionValue = isCompilerOptionsValue(option, value);
if (parentOption) {
if (isValidOptionValue) {
jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
}
}
- else if (knownOptions === knownRootOptions) {
+ else if (isRootOptionMap(knownOptions)) {
if (isValidOptionValue) {
jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
}
@@ -19318,7 +18311,7 @@ var ts;
return result;
}
function convertArrayLiteralExpressionToJson(elements, elementOption) {
- return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); });
+ return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); });
}
function convertPropertyValueToJson(valueExpression, option) {
switch (valueExpression.kind) {
@@ -19384,6 +18377,7 @@ var ts;
return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
}
}
+ ts.convertToObjectWorker = convertToObjectWorker;
function getCompilerOptionValueTypeString(option) {
return option.type === "list" ?
"Array" :
@@ -19566,12 +18560,13 @@ var ts;
var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors);
var raw = parsedConfig.raw;
var options = ts.extend(existingOptions, parsedConfig.options || {});
- options.configFilePath = configFileName;
+ options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
setConfigFileInOptions(options, sourceFile);
- var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
+ var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences;
return {
options: options,
fileNames: fileNames,
+ projectReferences: projectReferences,
typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
raw: raw,
errors: errors,
@@ -19620,9 +18615,32 @@ var ts;
includeSpecs = ["**/*"];
}
var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
- if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) {
+ if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) {
errors.push(getErrorForNoInputFiles(result.spec, configFileName));
}
+ if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) {
+ if (ts.isArray(raw.references)) {
+ var references = [];
+ for (var _i = 0, _a = raw.references; _i < _a.length; _i++) {
+ var ref = _a[_i];
+ if (typeof ref.path !== "string") {
+ createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
+ }
+ else {
+ references.push({
+ path: ts.getNormalizedAbsolutePath(ref.path, basePath),
+ originalPath: ref.path,
+ prepend: ref.prepend,
+ circular: ref.circular
+ });
+ }
+ }
+ result.projectReferences = references;
+ }
+ else {
+ createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array");
+ }
+ }
return result;
}
function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
@@ -19730,7 +18748,7 @@ var ts;
}
}
};
- var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator);
+ var json = convertToObjectWorker(sourceFile, errors, true, getTsconfigRootOptionsMap(), optionsIterator);
if (!typeAcquisition) {
if (typingOptionstypeAcquisition) {
typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
@@ -19764,6 +18782,7 @@ var ts;
return extendedConfigPath;
}
function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) {
+ var _a;
var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
if (sourceFile) {
(sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName);
@@ -19791,7 +18810,6 @@ var ts;
mapPropertiesInRawIfNotUndefined("files");
}
return extendedConfig;
- var _a;
}
function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
@@ -19816,7 +18834,7 @@ var ts;
}
ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
function getDefaultCompilerOptions(configFileName) {
- var options = ts.getBaseFileName(configFileName) === "jsconfig.json"
+ var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
: {};
return options;
@@ -19824,10 +18842,13 @@ var ts;
function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
var options = getDefaultCompilerOptions(configFileName);
convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors);
+ if (configFileName) {
+ options.configFilePath = ts.normalizeSlashes(configFileName);
+ }
return options;
}
function getDefaultTypeAcquisition(configFileName) {
- return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
+ return { enable: configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
}
function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
var options = getDefaultTypeAcquisition(configFileName);
@@ -19921,7 +18942,7 @@ var ts;
validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, true, jsonSourceFile, "exclude");
}
var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
- var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
+ var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
}
function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) {
@@ -19954,8 +18975,12 @@ var ts;
}
var literalFiles = ts.arrayFrom(literalFileMap.values());
var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
+ var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) {
+ return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) });
+ });
return {
fileNames: literalFiles.concat(wildcardFiles),
+ projectReferences: projectReferences,
wildcardDirectories: wildcardDirectories,
spec: spec
};
@@ -19970,20 +18995,10 @@ var ts;
return diag === undefined;
});
function createDiagnostic(message, spec) {
- if (jsonSourceFile && jsonSourceFile.jsonObject) {
- for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) {
- var property = _a[_i];
- if (ts.isArrayLiteralExpression(property.initializer)) {
- for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) {
- var element = _c[_b];
- if (ts.isStringLiteral(element) && element.text === spec) {
- return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec);
- }
- }
- }
- }
- }
- return ts.createCompilerDiagnostic(message, spec);
+ var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
+ return element ?
+ ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
+ ts.createCompilerDiagnostic(message, spec);
}
}
function specToDiagnostic(spec, allowTrailingRecursion) {
@@ -20120,7 +19135,8 @@ var ts;
(function (Extensions) {
Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
- Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly";
+ Extensions[Extensions["Json"] = 2] = "Json";
+ Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly";
})(Extensions || (Extensions = {}));
function resolvedTypeScriptOnly(resolved) {
if (!resolved) {
@@ -20161,7 +19177,13 @@ var ts;
function readJson(path, host) {
try {
var jsonText = host.readFile(path);
- return jsonText ? JSON.parse(jsonText) : {};
+ if (!jsonText)
+ return {};
+ var result = ts.parseConfigFileTextToJson(path, jsonText);
+ if (result.error) {
+ return {};
+ }
+ return result.config;
}
catch (e) {
return {};
@@ -20571,7 +19593,11 @@ var ts;
var traceEnabled = isTraceEnabled(compilerOptions, host);
var failedLookupLocations = [];
var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled };
- var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript));
+ var result = jsOnly ?
+ tryResolve(Extensions.JavaScript) :
+ (tryResolve(Extensions.TypeScript) ||
+ tryResolve(Extensions.JavaScript) ||
+ (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined));
if (result && result.value) {
var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport;
return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations);
@@ -20624,7 +19650,7 @@ var ts;
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
}
- if (!ts.pathEndsWithDirectorySeparator(candidate)) {
+ if (!ts.hasTrailingDirectorySeparator(candidate)) {
if (!onlyRecordFailures) {
var parentOfCandidate = ts.getDirectoryPath(candidate);
if (!directoryProbablyExists(parentOfCandidate, state.host)) {
@@ -20692,6 +19718,10 @@ var ts;
return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state));
}
function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) {
+ if (extensions === Extensions.Json) {
+ var extensionLess = ts.tryRemoveExtension(candidate, ".json");
+ return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state);
+ }
var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state);
if (resolvedByAddingExtension) {
return resolvedByAddingExtension;
@@ -20719,6 +19749,8 @@ var ts;
return tryExtension(".ts") || tryExtension(".tsx") || tryExtension(".d.ts");
case Extensions.JavaScript:
return tryExtension(".js") || tryExtension(".jsx");
+ case Extensions.Json:
+ return tryExtension(".json");
}
function tryExtension(ext) {
var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state);
@@ -20803,7 +19835,7 @@ var ts;
}
}
function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) {
- var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state);
+ var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state);
if (!file) {
return undefined;
}
@@ -20833,6 +19865,8 @@ var ts;
switch (extensions) {
case Extensions.JavaScript:
return extension === ".js" || extension === ".jsx";
+ case Extensions.Json:
+ return extension === ".json";
case Extensions.TypeScript:
return extension === ".ts" || extension === ".tsx" || extension === ".d.ts";
case Extensions.DtsOnly:
@@ -20898,7 +19932,7 @@ var ts;
if (packageResult) {
return packageResult;
}
- if (extensions !== Extensions.JavaScript) {
+ if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) {
var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
var nodeModulesAtTypesExists = nodeModulesFolderExists;
if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
@@ -21204,8 +20238,8 @@ var ts;
if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
continue;
}
- var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
- var packageJson = result_1.config;
+ var result_2 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
+ var packageJson = result_2.config;
if (baseFileName === "package.json" && packageJson._requiredBy &&
ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
continue;
@@ -21228,16 +20262,6 @@ var ts;
}
}
JsTyping.discoverTypings = discoverTypings;
- var PackageNameValidationResult;
- (function (PackageNameValidationResult) {
- PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok";
- PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported";
- PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName";
- PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong";
- PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot";
- PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore";
- PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters";
- })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {}));
var maxPackageNameLength = 214;
function validatePackageName(packageName) {
if (!packageName) {
@@ -21804,11 +20828,12 @@ var ts;
}());
function getDefaultNPMLocation(processName) {
if (path.basename(processName).indexOf("node") === 0) {
- return "\"" + path.join(path.dirname(process.argv[0]), "npm") + "\"";
- }
- else {
- return "npm";
+ var npmPath = "\"" + path.join(path.dirname(process.argv[0]), "npm") + "\"";
+ if (fs.existsSync(npmPath)) {
+ return npmPath;
+ }
}
+ return "npm";
}
function loadTypesRegistryFile(typesRegistryFilePath, host, log) {
if (!host.fileExists(typesRegistryFilePath)) {
@@ -21984,5 +21009,3 @@ var ts;
})(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
})(server = ts.server || (ts.server = {}));
})(ts || (ts = {}));
-
-//# sourceMappingURL=typingsInstaller.js.map
diff --git a/lib/watchGuard.js b/lib/watchGuard.js
new file mode 100644
index 00000000000..4048f128878
--- /dev/null
+++ b/lib/watchGuard.js
@@ -0,0 +1,27 @@
+/*! *****************************************************************************
+Copyright (c) Microsoft Corporation. All rights reserved.
+Licensed under the Apache License, Version 2.0 (the "License"); you may not use
+this file except in compliance with the License. You may obtain a copy of the
+License at http://www.apache.org/licenses/LICENSE-2.0
+
+THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+MERCHANTABLITY OR NON-INFRINGEMENT.
+
+See the Apache Version 2.0 License for specific language governing permissions
+and limitations under the License.
+***************************************************************************** */
+
+"use strict";
+if (process.argv.length < 3) {
+ process.exit(1);
+}
+var directoryName = process.argv[2];
+var fs = require("fs");
+try {
+ var watcher = fs.watch(directoryName, { recursive: true }, function () { return ({}); });
+ watcher.close();
+}
+catch (_a) { }
+process.exit(0);
diff --git a/lib/zh-cn/diagnosticMessages.generated.json b/lib/zh-cn/diagnosticMessages.generated.json
index 67b76930ca9..aefab2ea816 100644
--- a/lib/zh-cn/diagnosticMessages.generated.json
+++ b/lib/zh-cn/diagnosticMessages.generated.json
@@ -117,6 +117,7 @@
"All_declarations_of_0_must_have_identical_modifiers_2687": "“{0}”的所有声明必须具有相同的修饰符。",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "“{0}”的所有声明都必须具有相同的类型参数。",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有声明必须是连续的。",
+ "All_destructured_elements_are_unused_6198": "未取消使用任何解构元素。",
"All_imports_in_import_declaration_are_unused_6192": "未使用导入声明中的所有导入。",
"Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "允许从不带默认输出的模块中默认输入。这不会影响代码发出,只是类型检查。",
"Allow_javascript_files_to_be_compiled_6102": "允许编译 JavaScript 文件。",
@@ -220,6 +221,7 @@
"Cannot_invoke_an_object_which_is_possibly_null_2721": "不能调用可能是 \"null\" 的对象。",
"Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "不能调用可能是 \"null\" 或“未定义”的对象。",
"Cannot_invoke_an_object_which_is_possibly_undefined_2722": "不能调用可能是“未定义”的对象。",
+ "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "无法为项目“{0}”添加前缀,因为它未设置 \"outFile\"",
"Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "提供 \"--isolatedModules\" 标记时无法重新导出类型。",
"Cannot_read_file_0_Colon_1_5012": "无法读取文件“{0}”: {1}。",
"Cannot_redeclare_block_scoped_variable_0_2451": "无法重新声明块范围变量“{0}”。",
@@ -260,6 +262,7 @@
"Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "编译给定了其配置文件路径或带 \"tsconfig.json\" 的文件夹路径的项目。",
"Compiler_option_0_expects_an_argument_6044": "编译器选项“{0}”需要参数。",
"Compiler_option_0_requires_a_value_of_type_1_5024": "编译器选项“{0}”需要类型 {1} 的值。",
+ "Composite_projects_may_not_disable_declaration_emit_6304": "复合项目可能不会禁用声明发出。",
"Computed_property_names_are_not_allowed_in_enums_1164": "枚举中不允许计算属性名。",
"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "含字符串值成员的枚举中不允许使用计算值。",
"Concatenate_and_emit_output_to_single_file_6001": "连接输出并将其发出到单个文件。",
@@ -271,9 +274,11 @@
"Constructors_for_derived_classes_must_contain_a_super_call_2377": "派生类的构造函数必须包含 \"super\" 调用。",
"Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "未指定包含文件,并且无法确定根目录,正在跳过在 \"node_modules\" 文件夹中查找。",
"Convert_all_constructor_functions_to_classes_95045": "将所有构造函数都转换为类",
+ "Convert_all_require_to_import_95048": "将所有 \"require\" 转换为 \"import\"",
"Convert_all_to_default_imports_95035": "全部转换为默认导入",
"Convert_function_0_to_class_95002": "将函数“{0}”转换为类",
"Convert_function_to_an_ES2015_class_95001": "将函数转换为 ES2015 类",
+ "Convert_require_to_import_95047": "将 \"require\" 转换为 \"import\"",
"Convert_to_ES6_module_95017": "转换为 ES6 模块",
"Convert_to_default_import_95013": "转换为默认导入",
"Corrupted_locale_file_0_6051": "区域设置文件 {0} 已损坏。",
@@ -326,8 +331,8 @@
"Duplicate_label_0_1114": "标签“{0}”重复。",
"Duplicate_number_index_signature_2375": "数字索引签名重复。",
"Duplicate_string_index_signature_2374": "字符串索引签名重复。",
- "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "面向 ECMAScript 2015 模块时,不能使用动态导入。",
"Dynamic_import_cannot_have_type_arguments_1326": "动态导入不能含有类型参数",
+ "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'.",
"Dynamic_import_must_have_one_specifier_as_an_argument_1324": "动态导入必须具有一个说明符作为参数。",
"Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "动态导入的说明符类型必须是 \"string\",但此处类型是 \"{0}\"。",
"Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "元素隐式具有 \"any\" 类型,因为索引表达式的类型不为 \"number\"。",
@@ -336,6 +341,7 @@
"Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "发出包含源映射而非包含单独文件的单个文件。",
"Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "在单个文件内发出源以及源映射;需要设置 \"--inlineSourceMap\" 或 \"--sourceMap\"。",
"Enable_all_strict_type_checking_options_6180": "启用所有严格类型检查选项。",
+ "Enable_project_compilation_6302": "启用项目编译",
"Enable_strict_checking_of_function_types_6186": "对函数类型启用严格检查。",
"Enable_strict_checking_of_property_initialization_in_classes_6187": "启用类中属性初始化的严格检查。",
"Enable_strict_null_checks_6113": "启用严格的 NULL 检查。",
@@ -397,6 +403,7 @@
"File_0_has_an_unsupported_extension_so_skipping_it_6081": "文件“{0}”的扩展名不受支持,正在跳过。",
"File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "不支持文件“{0}”的扩展名。唯一支持的扩展名为 {1}。",
"File_0_is_not_a_module_2306": "文件“{0}”不是模块。",
+ "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "文件“{0}”不在项目文件列表中。项目必须列出的所有文件,或使用“包含”模式。",
"File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "文件“{0}”不在 \"rootDir\"“{1}”下。\"rootDir\" 应包含所有源文件。",
"File_0_not_found_6053": "找不到文件“{0}”。",
"File_change_detected_Starting_incremental_compilation_6032": "检测到文件更改。正在启动增量编译...",
@@ -461,6 +468,7 @@
"In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "在环境枚举声明中,成员初始化表达式必须是常数表达式。",
"In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "在包含多个声明的枚举中,只有一个声明可以省略其第一个枚举元素的初始化表达式。",
"In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "在 \"const\" 枚举声明中,成员初始化表达式必须是常数表达式。",
+ "Include_modules_imported_with_json_extension_6197": "包括通过 \".json\" 扩展导入的模块",
"Index_signature_in_type_0_only_permits_reading_2542": "类型“{0}”中的索引签名仅允许读取。",
"Index_signature_is_missing_in_type_0_2329": "类型“{0}”中缺少索引签名。",
"Index_signatures_are_incompatible_2330": "索引签名不兼容。",
@@ -600,8 +608,11 @@
"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "选项 \"isolatedModules\" 只可在提供了选项 \"--module\" 或者选项 \"target\" 是 \"ES2015\" 或更高版本时使用。",
"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "在未指定 \"--baseUrl\" 选项的情况下,无法使用选项 \"paths\"。",
"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "选项 \"project\" 在命令行上不能与源文件混合使用。",
+ "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "没有 \"node\" 模块解析策略的情况下,无法指定选项 \"-resolveJsonModule\"。",
"Options_Colon_6027": "选项:",
"Output_directory_for_generated_declaration_files_6166": "已生成声明文件的输出目录。",
+ "Output_file_0_from_project_1_does_not_exist_6309": "来自项目“{1}”的输出文件“{0}”不存在",
+ "Output_file_0_has_not_been_built_from_source_file_1_6305": "未从源文件“{1}”生成输出文件“{0}”。",
"Overload_signature_is_not_compatible_with_function_implementation_2394": "重载签名与函数实现不兼容。",
"Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "重载签名必须都是抽象的或都是非抽象的。",
"Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "重载签名必须全部为环境签名或非环境签名。",
@@ -645,6 +656,8 @@
"Print_names_of_generated_files_part_of_the_compilation_6154": "属于编译一部分的已生成文件的打印名称。",
"Print_the_compiler_s_version_6019": "打印编译器的版本。",
"Print_this_message_6017": "打印此消息。",
+ "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "项目引用不能形成环形图。检测到循环: {0}",
+ "Projects_to_reference_6300": "要引用的项目",
"Property_0_does_not_exist_on_const_enum_1_2479": "\"const\" 枚举“{1}”上不存在属性“{0}”。",
"Property_0_does_not_exist_on_type_1_2339": "类型“{1}”上不存在属性“{0}”。",
"Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "类型“{1}”上不存在属性“{0}”。是否忘记使用 \"await\"?",
@@ -692,7 +705,9 @@
"Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "对具有隐式 \"any\" 类型的表达式和声明引发错误。",
"Raise_error_on_this_expressions_with_an_implied_any_type_6115": "在带隐式“any\" 类型的 \"this\" 表达式上引发错误。",
"Redirect_output_structure_to_the_directory_6006": "将输出结构重定向到目录。",
+ "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "引用的项目“{0}”必须拥有设置 \"composite\": true。",
"Remove_declaration_for_Colon_0_90004": "删除“{0}”的声明",
+ "Remove_destructuring_90009": "删除解构",
"Remove_import_from_0_90005": "从“{0}”删除导入",
"Replace_import_with_0_95015": "用“{0}”替换导入。",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "在函数中的所有代码路径并非都返回值时报告错误。",
@@ -801,6 +816,7 @@
"The_files_list_in_config_file_0_is_empty_18002": "配置文件“{0}”中的 \"files\" 列表为空。",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "承诺的 \"then\" 方法的第一个参数必须是回调。",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "全局类型 \"JSX.{0}\" 不可具有多个属性。",
+ "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "\"import.meta\" 元属性仅允许对 \"target\" 和 \"module\" 编译器选项使用 \"ESNext\"。",
"The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "“{0}”的推断类型引用不可访问的“{1}”类型。需要类型批注。",
"The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "\"for...in\" 语句的左侧不能为析构模式。",
"The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "\"for...in\" 语句的左侧不能使用类型批注。",
@@ -1013,6 +1029,7 @@
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "\"parameter modifiers\" 只能在 .ts 文件中使用。",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "指定了 \"paths“ 选项,正在查找模式以匹配模块名“{0}”。",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "\"readonly\" 修饰符仅可出现在属性声明或索引签名中。",
+ "require_call_may_be_converted_to_an_import_80005": "可将“要求”调用转换为导入。",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "设置了 \"rootDirs\" 选项,可将其用于解析相对模块名称“{0}”。",
"super_can_only_be_referenced_in_a_derived_class_2335": "只能在派生类中引用 \"super\"。",
"super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "仅可在派生类或对象文字表达式的成员中引用 \"super\"。",
diff --git a/lib/zh-tw/diagnosticMessages.generated.json b/lib/zh-tw/diagnosticMessages.generated.json
index aa2d1eac0eb..3583d0e11ef 100644
--- a/lib/zh-tw/diagnosticMessages.generated.json
+++ b/lib/zh-tw/diagnosticMessages.generated.json
@@ -117,6 +117,7 @@
"All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' 的所有宣告都必須有相同修飾詞。",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}' 的所有宣告都必須具有相同的類型參數。",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有宣告必須連續。",
+ "All_destructured_elements_are_unused_6198": "不會使用所有未經結構化的項目。",
"All_imports_in_import_declaration_are_unused_6192": "匯入宣告中的所有匯入皆未使用。",
"Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011": "允許從沒有預設匯出的模組進行預設匯入。這不會影響程式碼發出,僅為類型檢查。",
"Allow_javascript_files_to_be_compiled_6102": "允許編譯 JavaScript 檔案。",
@@ -220,6 +221,7 @@
"Cannot_invoke_an_object_which_is_possibly_null_2721": "無法叫用可能為 'null' 的物件。",
"Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723": "無法叫用可能為 'null' 或 'undefined' 的物件。",
"Cannot_invoke_an_object_which_is_possibly_undefined_2722": "無法叫用可能為 'undefined' 的物件。",
+ "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308": "因為專案 '{0}' 未設定 'outFile',所以無法於其前面加上任何內容",
"Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205": "如有提供 '--isolatedModules' 旗標,即無法重新匯出類型。",
"Cannot_read_file_0_Colon_1_5012": "無法讀取檔案 '{0}': {1}。",
"Cannot_redeclare_block_scoped_variable_0_2451": "無法重新宣告區塊範圍變數 '{0}'。",
@@ -260,6 +262,7 @@
"Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020": "當路徑為專案組態檔或為 'tsconfig.json' 所在的資料夾時編譯專案。",
"Compiler_option_0_expects_an_argument_6044": "編譯器選項 '{0}' 必須要有一個引數。",
"Compiler_option_0_requires_a_value_of_type_1_5024": "編譯器選項 '{0}' 需要類型 {1} 的值。",
+ "Composite_projects_may_not_disable_declaration_emit_6304": "複合式專案可能未停用宣告發出。",
"Computed_property_names_are_not_allowed_in_enums_1164": "列舉中不能有計算的屬性名稱。",
"Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553": "具有字串值成員的列舉中不允許計算值。",
"Concatenate_and_emit_output_to_single_file_6001": "串連並發出輸出至單一檔案。",
@@ -271,11 +274,11 @@
"Constructors_for_derived_classes_must_contain_a_super_call_2377": "衍生類別的建構函式必須包含 'super' 呼叫。",
"Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "未指定包含檔案,因此無法決定根目錄,而將略過 'node_modules' 中的查閱。",
"Convert_all_constructor_functions_to_classes_95045": "將所有建構函式轉換為類別",
- "Convert_all_require_to_import_95048": "Convert all 'require' to 'import'",
+ "Convert_all_require_to_import_95048": "將所有 'require' 轉換至 'import'",
"Convert_all_to_default_imports_95035": "全部轉換為預設匯入",
"Convert_function_0_to_class_95002": "將函式 '{0}' 轉換為類別",
"Convert_function_to_an_ES2015_class_95001": "將函式轉換為 ES2015 類別",
- "Convert_require_to_import_95047": "Convert 'require' to 'import'",
+ "Convert_require_to_import_95047": "將 'require' 轉換至 'import'",
"Convert_to_ES6_module_95017": "轉換為 ES6 模組",
"Convert_to_default_import_95013": "轉換為預設匯入",
"Corrupted_locale_file_0_6051": "地區設定檔 {0} 已損毀。",
@@ -328,8 +331,8 @@
"Duplicate_label_0_1114": "標籤 '{0}' 重複。",
"Duplicate_number_index_signature_2375": "數字索引簽章重複。",
"Duplicate_string_index_signature_2374": "字串索引簽章重複。",
- "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323": "以 ECMAScript 2015 模組為目標時,無法使用動態匯入。",
"Dynamic_import_cannot_have_type_arguments_1326": "動態匯入不能有型別引數",
+ "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323": "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'.",
"Dynamic_import_must_have_one_specifier_as_an_argument_1324": "動態匯入必須有一個指定名稱作為引數。",
"Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036": "動態匯入的指定名稱必須屬於類型 'string',但這裡的類型為 '{0}'。",
"Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015": "因為索引運算式不屬於類型 'number',所以元素具有隱含 'any' 類型。",
@@ -338,6 +341,7 @@
"Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151": "發出單一檔案包含來源對應,而不要使用個別的檔案。",
"Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152": "使用單一檔案發出來源與來源對應。必須設定 '--inlineSourceMap' 或 '--sourceMap'。",
"Enable_all_strict_type_checking_options_6180": "啟用所有 Strict 類型檢查選項。",
+ "Enable_project_compilation_6302": "啟用專案編譯",
"Enable_strict_checking_of_function_types_6186": "啟用嚴格檢查函式類型。",
"Enable_strict_checking_of_property_initialization_in_classes_6187": "啟用類別中屬性初始化的 strict 檢查。",
"Enable_strict_null_checks_6113": "啟用嚴格 null 檢查。",
@@ -399,6 +403,7 @@
"File_0_has_an_unsupported_extension_so_skipping_it_6081": "因為不支援檔案 '{0}' 的副檔名,所以將其跳過。",
"File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054": "檔案 '{0}' 的附檔名不受支援。僅支援副檔名 {1}。",
"File_0_is_not_a_module_2306": "檔案 '{0}' 不是模組。",
+ "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307": "檔案 '{0}' 不在專案檔案清單內。專案必須列出所有檔案,或使用 'include' 模式。",
"File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059": "檔案 '{0}' 不在 'rootDir' '{1}' 之下。'rootDir' 必須包含所有原始程式檔。",
"File_0_not_found_6053": "找不到檔案 '{0}'。",
"File_change_detected_Starting_incremental_compilation_6032": "偵測到檔案變更。正在啟動累加編譯...",
@@ -463,6 +468,7 @@
"In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066": "在環境列舉宣告中,成員初始設定式必須是常數運算式。",
"In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432": "在具有多個宣告的列舉中,只有一個宣告可以在其第一個列舉項目中省略初始設定式。",
"In_const_enum_declarations_member_initializer_must_be_constant_expression_2474": "在 'const' 列舉宣告中,成員初始設定式必須是常數運算式。",
+ "Include_modules_imported_with_json_extension_6197": "包含匯入有 '.json' 延伸模組的模組",
"Index_signature_in_type_0_only_permits_reading_2542": "類型 '{0}' 中的索引簽章只允許讀取。",
"Index_signature_is_missing_in_type_0_2329": "類型 '{0}' 中遺漏索引簽章。",
"Index_signatures_are_incompatible_2330": "索引簽章不相容。",
@@ -602,8 +608,11 @@
"Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047": "只有在提供選項 '--module' 或是 'target' 為 'ES2015' 或更高項目時,才可使用選項 'isolatedModules'。",
"Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060": "必須指定 '--baseUrl' 選項才能使用選項 'paths'。",
"Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042": "在命令列上,'project' 選項不得與原始程式檔並用。",
+ "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070": "指定選項 '-resolveJsonModule' 時,不可沒有 'node' 模組解析策略。",
"Options_Colon_6027": "選項:",
"Output_directory_for_generated_declaration_files_6166": "所產生之宣告檔案的輸出目錄。",
+ "Output_file_0_from_project_1_does_not_exist_6309": "沒有來自專案 '{1}' 的輸出檔 '{0}'",
+ "Output_file_0_has_not_been_built_from_source_file_1_6305": "輸出檔 '{0}' 並非從原始程式檔 '{1}' 建置。",
"Overload_signature_is_not_compatible_with_function_implementation_2394": "多載簽章與函式實作不相容。",
"Overload_signatures_must_all_be_abstract_or_non_abstract_2512": "多載簽章必須全為抽象或非抽象。",
"Overload_signatures_must_all_be_ambient_or_non_ambient_2384": "多載簽章都必須是環境或非環境簽章。",
@@ -647,6 +656,8 @@
"Print_names_of_generated_files_part_of_the_compilation_6154": "列印編譯時所產生之檔案部分的名稱。",
"Print_the_compiler_s_version_6019": "列印編譯器的版本。",
"Print_this_message_6017": "列印這則訊息。",
+ "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202": "專案參考不會形成循環圖。但偵測到循環: {0}",
+ "Projects_to_reference_6300": "專案至參考",
"Property_0_does_not_exist_on_const_enum_1_2479": "'const' 列舉 '{1}' 上並沒有屬性 '{0}'。",
"Property_0_does_not_exist_on_type_1_2339": "類型 '{1}' 沒有屬性 '{0}'。",
"Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570": "類型 '{1}' 不存在屬性 '{0}'。是否忘記要使用 'await'?",
@@ -694,7 +705,9 @@
"Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052": "當運算式及宣告包含隱含的 'any' 類型時顯示錯誤。",
"Raise_error_on_this_expressions_with_an_implied_any_type_6115": "對具有隱含 'any' 類型的 'this' 運算式引發錯誤。",
"Redirect_output_structure_to_the_directory_6006": "將輸出結構重新導向至目錄。",
+ "Referenced_project_0_must_have_setting_composite_Colon_true_6306": "參考的專案 '{0}' 之設定 \"composite\" 必須為 true。",
"Remove_declaration_for_Colon_0_90004": "移除 '{0}' 的宣告",
+ "Remove_destructuring_90009": "移除解構",
"Remove_import_from_0_90005": "從 '{0}' 移除匯入",
"Replace_import_with_0_95015": "以 '{0}' 取代匯入。",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "當函式中的部分程式碼路徑並未傳回值時回報錯誤。",
@@ -803,7 +816,7 @@
"The_files_list_in_config_file_0_is_empty_18002": "設定檔 '{0}' 中的 'files' 清單是空的。",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise 的 'then' 方法第一個參數必須為回撥。",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "全域類型 'JSX.{0}' 的屬性不得超過一個。",
- "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options.",
+ "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343": "只有在為 'target' 及 'module' 編譯器選項使用 'ESNext' 時,才允許 'import.meta' 中繼屬性。",
"The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527": "'{0}' 的推斷型別參考了無法存取的 '{1}' 型別。必須有型別註解。",
"The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491": "'for...in' 陳述式的左側不得為解構模式。",
"The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404": "'for...in' 陳述式左側不得使用類型註釋。",
@@ -1016,7 +1029,7 @@
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' 只可用於 .ts 檔案中。",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' 選項已指定,將尋找符合模組名稱 '{0}' 的模式。",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 修飾詞只能出現在屬性宣告或索引簽章。",
- "require_call_may_be_converted_to_an_import_80005": "'require' call may be converted to an import.",
+ "require_call_may_be_converted_to_an_import_80005": "'require' 呼叫可能會轉換為匯入。",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' 選項已設定。該選項將用於解析相對的模組名稱 '{0}'。",
"super_can_only_be_referenced_in_a_derived_class_2335": "只有衍生類別中才可參考 'super'。",
"super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660": "只有在衍生類別或物件常值運算式的成員中才可參考 'super'。",