From b6b00ebc98a47b10b35f1ee57c6a3a953f413088 Mon Sep 17 00:00:00 2001 From: Filipe Silva Date: Fri, 12 Apr 2019 11:18:51 +0100 Subject: [PATCH] build: update typescript to version 3.4.3 --- package.json | 2 +- .../angular/cli/models/schematic-command.ts | 2 +- .../angular_devkit/build_angular/package.json | 2 +- .../build_optimizer/package.json | 2 +- packages/ngtools/webpack/package.json | 4 +- .../Microsoft/TypeScript/lib/typescript.d.ts | 180 +- .../Microsoft/TypeScript/lib/typescript.js | 8084 +++++++++++------ .../blank/project-files/package.json.template | 2 +- .../schematics/schematic/files/package.json | 2 +- yarn.lock | 5 + 10 files changed, 5406 insertions(+), 2879 deletions(-) diff --git a/package.json b/package.json index ee3d2e61ca5b..727c6054b311 100644 --- a/package.json +++ b/package.json @@ -74,7 +74,7 @@ "quicktype-core": "^6.0.15", "temp": "^0.9.0", "tslint": "^5.13.1", - "typescript": "3.3.4000" + "typescript": "3.4.3" }, "devDependencies": { "@angular/compiler": "^8.0.0-beta.11", diff --git a/packages/angular/cli/models/schematic-command.ts b/packages/angular/cli/models/schematic-command.ts index 90b133dc6dba..94aa069423d9 100644 --- a/packages/angular/cli/models/schematic-command.ts +++ b/packages/angular/cli/models/schematic-command.ts @@ -492,7 +492,7 @@ export abstract class SchematicCommand< } const pathOptions = o ? this.setPathOptions(o, workingDir) : {}; - let input = Object.assign(pathOptions, args); + let input = { ...pathOptions, ...args }; // Read the default values from the workspace. const projectName = input.project !== undefined ? '' + input.project : null; diff --git a/packages/angular_devkit/build_angular/package.json b/packages/angular_devkit/build_angular/package.json index 5ebd46a68865..da04648ec3ca 100644 --- a/packages/angular_devkit/build_angular/package.json +++ b/packages/angular_devkit/build_angular/package.json @@ -87,6 +87,6 @@ "zone.js": "^0.9.0" }, "peerDependencies": { - "typescript": ">=2.7 < 3.4" + "typescript": ">=2.7 < 3.5" } } diff --git a/packages/angular_devkit/build_optimizer/package.json b/packages/angular_devkit/build_optimizer/package.json index 3b7abb4a37bf..131ed5ec97a6 100644 --- a/packages/angular_devkit/build_optimizer/package.json +++ b/packages/angular_devkit/build_optimizer/package.json @@ -11,7 +11,7 @@ "dependencies": { "loader-utils": "1.2.3", "source-map": "0.5.6", - "typescript": "3.3.4000", + "typescript": "3.4.3", "webpack-sources": "1.3.0" } } diff --git a/packages/ngtools/webpack/package.json b/packages/ngtools/webpack/package.json index 1c3161d396df..1af7a691b3d0 100644 --- a/packages/ngtools/webpack/package.json +++ b/packages/ngtools/webpack/package.json @@ -29,13 +29,13 @@ }, "peerDependencies": { "@angular/compiler-cli": ">=6.0.0 <9.0.0 || ^8.0.0-beta.0", - "typescript": ">=2.7 < 3.4", + "typescript": ">=2.7 < 3.5", "webpack": "^4.0.0" }, "devDependencies": { "@angular/compiler": "^8.0.0-beta.11", "@angular/compiler-cli": "^8.0.0-beta.11", - "typescript": "3.3.4000", + "typescript": "3.4.3", "webpack": "4.29.6" } } diff --git a/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.d.ts b/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.d.ts index 83e72bf28000..314ccf298cf2 100644 --- a/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.d.ts +++ b/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.3"; + const versionMajorMinor = "3.4"; /** The version of the TypeScript compiler release */ const version: string; } @@ -355,40 +355,45 @@ declare namespace ts { ShorthandPropertyAssignment = 276, SpreadAssignment = 277, EnumMember = 278, - SourceFile = 279, - Bundle = 280, - UnparsedSource = 281, - InputFiles = 282, - JSDocTypeExpression = 283, - JSDocAllType = 284, - JSDocUnknownType = 285, - JSDocNullableType = 286, - JSDocNonNullableType = 287, - JSDocOptionalType = 288, - JSDocFunctionType = 289, - JSDocVariadicType = 290, - JSDocComment = 291, - JSDocTypeLiteral = 292, - JSDocSignature = 293, - JSDocTag = 294, - JSDocAugmentsTag = 295, - JSDocClassTag = 296, - JSDocCallbackTag = 297, - JSDocEnumTag = 298, - JSDocParameterTag = 299, - JSDocReturnTag = 300, - JSDocThisTag = 301, - JSDocTypeTag = 302, - JSDocTemplateTag = 303, - JSDocTypedefTag = 304, - JSDocPropertyTag = 305, - SyntaxList = 306, - NotEmittedStatement = 307, - PartiallyEmittedExpression = 308, - CommaListExpression = 309, - MergeDeclarationMarker = 310, - EndOfDeclarationMarker = 311, - Count = 312, + UnparsedPrologue = 279, + UnparsedPrepend = 280, + UnparsedText = 281, + UnparsedInternalText = 282, + UnparsedSyntheticReference = 283, + SourceFile = 284, + Bundle = 285, + UnparsedSource = 286, + InputFiles = 287, + JSDocTypeExpression = 288, + JSDocAllType = 289, + JSDocUnknownType = 290, + JSDocNullableType = 291, + JSDocNonNullableType = 292, + JSDocOptionalType = 293, + JSDocFunctionType = 294, + JSDocVariadicType = 295, + JSDocComment = 296, + JSDocTypeLiteral = 297, + JSDocSignature = 298, + JSDocTag = 299, + JSDocAugmentsTag = 300, + JSDocClassTag = 301, + JSDocCallbackTag = 302, + JSDocEnumTag = 303, + JSDocParameterTag = 304, + JSDocReturnTag = 305, + JSDocThisTag = 306, + JSDocTypeTag = 307, + JSDocTemplateTag = 308, + JSDocTypedefTag = 309, + JSDocPropertyTag = 310, + SyntaxList = 311, + NotEmittedStatement = 312, + PartiallyEmittedExpression = 313, + CommaListExpression = 314, + MergeDeclarationMarker = 315, + EndOfDeclarationMarker = 316, + Count = 317, FirstAssignment = 59, LastAssignment = 71, FirstCompoundAssignment = 60, @@ -414,10 +419,10 @@ declare namespace ts { FirstBinaryOperator = 28, LastBinaryOperator = 71, FirstNode = 148, - FirstJSDocNode = 283, - LastJSDocNode = 305, - FirstJSDocTagNode = 294, - LastJSDocTagNode = 305 + FirstJSDocNode = 288, + LastJSDocNode = 310, + FirstJSDocTagNode = 299, + LastJSDocTagNode = 310, } enum NodeFlags { None = 0, @@ -446,7 +451,7 @@ declare namespace ts { ReachabilityCheckFlags = 384, ReachabilityAndEmitFlags = 1408, ContextFlags = 12679168, - TypeExcludesFlags = 20480 + TypeExcludesFlags = 20480, } enum ModifierFlags { None = 0, @@ -814,7 +819,7 @@ declare namespace ts { } interface TypeOperatorNode extends TypeNode { kind: SyntaxKind.TypeOperator; - operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword; + operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword; type: TypeNode; } interface IndexedAccessTypeNode extends TypeNode { @@ -997,6 +1002,14 @@ declare namespace ts { interface NoSubstitutionTemplateLiteral extends LiteralExpression { kind: SyntaxKind.NoSubstitutionTemplateLiteral; } + enum TokenFlags { + None = 0, + Scientific = 16, + Octal = 32, + HexSpecifier = 64, + BinarySpecifier = 128, + OctalSpecifier = 256, + } interface NumericLiteral extends LiteralExpression { kind: SyntaxKind.NumericLiteral; } @@ -1190,9 +1203,9 @@ declare namespace ts { dotDotDotToken?: Token; expression?: Expression; } - interface JsxText extends Node { + interface JsxText extends LiteralLikeNode { kind: SyntaxKind.JsxText; - containsOnlyWhiteSpaces: boolean; + containsOnlyTriviaWhiteSpaces: boolean; parent: JsxElement; } type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; @@ -1737,10 +1750,44 @@ declare namespace ts { } interface UnparsedSource extends Node { kind: SyntaxKind.UnparsedSource; - fileName?: string; + fileName: string; text: string; + prologues: ReadonlyArray; + helpers: ReadonlyArray | undefined; + referencedFiles: ReadonlyArray; + typeReferenceDirectives: ReadonlyArray | undefined; + libReferenceDirectives: ReadonlyArray; + hasNoDefaultLib?: boolean; sourceMapPath?: string; sourceMapText?: string; + syntheticReferences?: ReadonlyArray; + texts: ReadonlyArray; + } + type UnparsedSourceText = UnparsedPrepend | UnparsedTextLike; + type UnparsedNode = UnparsedPrologue | UnparsedSourceText | UnparsedSyntheticReference; + interface UnparsedSection extends Node { + kind: SyntaxKind; + data?: string; + parent: UnparsedSource; + } + interface UnparsedPrologue extends UnparsedSection { + kind: SyntaxKind.UnparsedPrologue; + data: string; + parent: UnparsedSource; + } + interface UnparsedPrepend extends UnparsedSection { + kind: SyntaxKind.UnparsedPrepend; + data: string; + parent: UnparsedSource; + texts: ReadonlyArray; + } + interface UnparsedTextLike extends UnparsedSection { + kind: SyntaxKind.UnparsedText | SyntaxKind.UnparsedInternalText; + parent: UnparsedSource; + } + interface UnparsedSyntheticReference extends UnparsedSection { + kind: SyntaxKind.UnparsedSyntheticReference; + parent: UnparsedSource; } interface JsonSourceFile extends SourceFile { statements: NodeArray; @@ -2014,7 +2061,7 @@ declare namespace ts { WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, AllowAnyNodeKind = 4, - UseAliasDefinedOutsideCurrentScope = 8 + UseAliasDefinedOutsideCurrentScope = 8, } enum TypePredicateKind { This = 0, @@ -2092,7 +2139,7 @@ declare namespace ts { ExportHasLocal = 944, BlockScoped = 418, PropertyOrAccessor = 98308, - ClassMember = 106500 + ClassMember = 106500, } interface Symbol { flags: SymbolFlags; @@ -2200,7 +2247,7 @@ declare namespace ts { Instantiable = 63176704, StructuredOrInstantiable = 66846720, Narrowable = 133970943, - NotUnionOrUnit = 67637251 + NotUnionOrUnit = 67637251, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -2247,7 +2294,7 @@ declare namespace ts { MarkerType = 8192, JSLiteral = 16384, FreshLiteral = 32768, - ClassOrInterface = 3 + ClassOrInterface = 3, } interface ObjectType extends Type { objectFlags: ObjectFlags; @@ -2286,6 +2333,7 @@ declare namespace ts { interface TupleType extends GenericType { minLength: number; hasRestElement: boolean; + readonly: boolean; associatedNames?: __String[]; } interface TupleTypeReference extends TypeReference { @@ -2334,8 +2382,8 @@ declare namespace ts { root: ConditionalRoot; checkType: Type; extendsType: Type; - resolvedTrueType?: Type; - resolvedFalseType?: Type; + trueType: Type; + falseType: Type; } interface SubstitutionType extends InstantiableType { typeVariable: TypeVariable; @@ -2494,6 +2542,8 @@ declare namespace ts { reactNamespace?: string; jsxFactory?: string; composite?: boolean; + incremental?: boolean; + tsBuildInfoFile?: string; removeComments?: boolean; rootDir?: string; rootDirs?: string[]; @@ -2570,9 +2620,10 @@ declare namespace ts { ES2016 = 3, ES2017 = 4, ES2018 = 5, - ESNext = 6, + ES2019 = 6, + ESNext = 7, JSON = 100, - Latest = 6 + Latest = 7 } enum LanguageVariant { Standard = 0, @@ -2669,7 +2720,8 @@ declare namespace ts { Dts = ".d.ts", Js = ".js", Jsx = ".jsx", - Json = ".json" + Json = ".json", + TsBuildInfo = ".tsbuildinfo" } interface ResolvedModuleWithFailedLookupLocations { readonly resolvedModule: ResolvedModuleFull | undefined; @@ -2742,7 +2794,7 @@ declare namespace ts { NoHoisting = 2097152, HasEndOfDeclarationMarker = 4194304, Iterator = 8388608, - NoAsciiEscaping = 16777216 + NoAsciiEscaping = 16777216, } interface EmitHelper { readonly name: string; @@ -2750,6 +2802,10 @@ declare namespace ts { readonly text: string | ((node: EmitHelperUniqueNameCallback) => string); readonly priority?: number; } + interface UnscopedEmitHelper extends EmitHelper { + readonly scoped: false; + readonly text: string; + } type EmitHelperUniqueNameCallback = (name: string) => string; enum EmitHint { SourceFile = 0, @@ -3359,6 +3415,7 @@ declare namespace ts { function isNewExpression(node: Node): node is NewExpression; function isTaggedTemplateExpression(node: Node): node is TaggedTemplateExpression; function isTypeAssertion(node: Node): node is TypeAssertion; + function isConstTypeReference(node: Node): boolean; function isParenthesizedExpression(node: Node): node is ParenthesizedExpression; function skipPartiallyEmittedExpressions(node: Expression): Expression; function skipPartiallyEmittedExpressions(node: Node): Node; @@ -3448,6 +3505,9 @@ declare namespace ts { function isSourceFile(node: Node): node is SourceFile; function isBundle(node: Node): node is Bundle; function isUnparsedSource(node: Node): node is UnparsedSource; + function isUnparsedPrepend(node: Node): node is UnparsedPrepend; + function isUnparsedTextLike(node: Node): node is UnparsedTextLike; + function isUnparsedNode(node: Node): node is UnparsedNode; function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression; function isJSDocAllType(node: JSDocAllType): node is JSDocAllType; function isJSDocUnknownType(node: Node): node is JSDocUnknownType; @@ -3667,7 +3727,7 @@ declare namespace ts { function createLiteral(value: number | PseudoBigInt): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; function createLiteral(value: string | number | PseudoBigInt | boolean): PrimaryExpression; - function createNumericLiteral(value: string): NumericLiteral; + function createNumericLiteral(value: string, numericLiteralFlags?: TokenFlags): NumericLiteral; function createBigIntLiteral(value: string): BigIntLiteral; function createStringLiteral(text: string): StringLiteral; function createRegularExpressionLiteral(text: string): RegularExpressionLiteral; @@ -3759,7 +3819,7 @@ declare namespace ts { function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; function createThisTypeNode(): ThisTypeNode; function createTypeOperatorNode(type: TypeNode): TypeOperatorNode; - function createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword, type: TypeNode): TypeOperatorNode; + function createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword, type: TypeNode): TypeOperatorNode; function updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; @@ -3932,6 +3992,10 @@ declare namespace ts { function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; function createJsxFragment(openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment): JsxFragment; + function createJsxText(text: string, containsOnlyTriviaWhiteSpaces?: boolean): JsxText; + function updateJsxText(node: JsxText, text: string, containsOnlyTriviaWhiteSpaces?: boolean): JsxText; + function createJsxOpeningFragment(): JsxOpeningFragment; + function createJsxJsxClosingFragment(): JsxClosingFragment; function updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment): JsxFragment; function createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; function updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression): JsxAttribute; @@ -3983,10 +4047,10 @@ declare namespace ts { function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression; function createBundle(sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle; function createUnparsedSourceFile(text: string): UnparsedSource; - function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts"): UnparsedSource; + function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts", stripInternal?: boolean): UnparsedSource; function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource; function createInputFiles(javascriptText: string, declarationText: string): InputFiles; - function createInputFiles(readFileText: (path: string) => string | undefined, javascriptPath: string, javascriptMapPath: string | undefined, declarationPath: string, declarationMapPath: string | undefined): InputFiles; + function createInputFiles(readFileText: (path: string) => string | undefined, javascriptPath: string, javascriptMapPath: string | undefined, declarationPath: string, declarationMapPath: string | undefined, buildInfoPath: string | undefined): InputFiles; function createInputFiles(javascriptText: string, declarationText: string, javascriptMapPath: string | undefined, javascriptMapText: string | undefined, declarationMapPath: string | undefined, declarationMapText: string | undefined): InputFiles; function updateBundle(node: Bundle, sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle; function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray): CallExpression; diff --git a/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.js b/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.js index d2e2e7ecb403..da4767072f7c 100644 --- a/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.js +++ b/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.js @@ -73,9 +73,9 @@ var ts; (function (ts) { // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.3"; + ts.versionMajorMinor = "3.4"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".3333"; + ts.version = ts.versionMajorMinor + ".3"; })(ts || (ts = {})); (function (ts) { /* @internal */ @@ -131,19 +131,25 @@ var ts; // Keep the class inside a function so it doesn't get compiled if it's not used. function shimMap() { var MapIterator = /** @class */ (function () { - function MapIterator(data, selector) { - this.index = 0; - this.data = data; + function MapIterator(currentEntry, selector) { + this.currentEntry = currentEntry; this.selector = selector; - this.keys = Object.keys(data); } MapIterator.prototype.next = function () { - var index = this.index; - if (index < this.keys.length) { - this.index++; - return { value: this.selector(this.data, this.keys[index]), done: false }; + // Navigate to the next entry. + while (this.currentEntry) { + var skipNext = !!this.currentEntry.skipNext; + this.currentEntry = this.currentEntry.nextEntry; + if (!skipNext) { + break; + } + } + if (this.currentEntry) { + return { value: this.selector(this.currentEntry.key, this.currentEntry.value), done: false }; + } + else { + return { value: undefined, done: true }; } - return { value: undefined, done: true }; }; return MapIterator; }()); @@ -151,15 +157,36 @@ var ts; function class_1() { this.data = createDictionaryObject(); this.size = 0; + // Create a first (stub) map entry that will not contain a key + // and value but serves as starting point for iterators. + this.firstEntry = {}; + // When the map is empty, the last entry is the same as the + // first one. + this.lastEntry = this.firstEntry; } class_1.prototype.get = function (key) { - return this.data[key]; + var entry = this.data[key]; + return entry && entry.value; }; class_1.prototype.set = function (key, value) { if (!this.has(key)) { this.size++; + // Create a new entry that will be appended at the + // end of the linked list. + var newEntry = { + key: key, + value: value + }; + this.data[key] = newEntry; + // Adjust the references. + var previousLastEntry = this.lastEntry; + previousLastEntry.nextEntry = newEntry; + newEntry.previousEntry = previousLastEntry; + this.lastEntry = newEntry; + } + else { + this.data[key].value = value; } - this.data[key] = value; return this; }; class_1.prototype.has = function (key) { @@ -169,7 +196,28 @@ var ts; class_1.prototype.delete = function (key) { if (this.has(key)) { this.size--; + var entry = this.data[key]; delete this.data[key]; + // Adjust the linked list references of the neighbor entries. + var previousEntry = entry.previousEntry; + previousEntry.nextEntry = entry.nextEntry; + if (entry.nextEntry) { + entry.nextEntry.previousEntry = previousEntry; + } + // When the deleted entry was the last one, we need to + // adust the lastEntry reference. + if (this.lastEntry === entry) { + this.lastEntry = previousEntry; + } + // Adjust the forward reference of the deleted entry + // in case an iterator still references it. This allows us + // to throw away the entry, but when an active iterator + // (which points to the current entry) continues, it will + // navigate to the entry that originally came before the + // current one and skip it. + entry.previousEntry = undefined; + entry.nextEntry = previousEntry; + entry.skipNext = true; return true; } return false; @@ -177,24 +225,46 @@ var ts; class_1.prototype.clear = function () { this.data = createDictionaryObject(); this.size = 0; + // Reset the linked list. Note that we must adjust the forward + // references of the deleted entries to ensure iterators stuck + // in the middle of the list don't continue with deleted entries, + // but can continue with new entries added after the clear() + // operation. + var firstEntry = this.firstEntry; + var currentEntry = firstEntry.nextEntry; + while (currentEntry) { + var nextEntry = currentEntry.nextEntry; + currentEntry.previousEntry = undefined; + currentEntry.nextEntry = firstEntry; + currentEntry.skipNext = true; + currentEntry = nextEntry; + } + firstEntry.nextEntry = undefined; + this.lastEntry = firstEntry; }; class_1.prototype.keys = function () { - return new MapIterator(this.data, function (_data, key) { return key; }); + return new MapIterator(this.firstEntry, function (key) { return key; }); }; class_1.prototype.values = function () { - return new MapIterator(this.data, function (data, key) { return data[key]; }); + return new MapIterator(this.firstEntry, function (_key, value) { return value; }); }; class_1.prototype.entries = function () { - return new MapIterator(this.data, function (data, key) { return [key, data[key]]; }); + return new MapIterator(this.firstEntry, function (key, value) { return [key, value]; }); }; class_1.prototype.forEach = function (action) { - for (var key in this.data) { - action(this.data[key], key); + var iterator = this.entries(); + while (true) { + var _a = iterator.next(), entry = _a.value, done = _a.done; + if (done) { + break; + } + action(entry[1], entry[0]); } }; return class_1; }()); } + ts.shimMap = shimMap; function length(array) { return array ? array.length : 0; } @@ -742,7 +812,7 @@ var ts; } /** * Deduplicates an unsorted array. - * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates. * @param comparer An optional `Comparer` used to sort entries before comparison, though the * result will remain in the original order in `array`. */ @@ -958,6 +1028,21 @@ var ts; } }; } ts.arrayIterator = arrayIterator; + function arrayReverseIterator(array) { + var i = array.length; + return { + next: function () { + if (i === 0) { + return { value: undefined, done: true }; + } + else { + i--; + return { value: array[i], done: false }; + } + } + }; + } + ts.arrayReverseIterator = arrayReverseIterator; /** * Stable sort of an array. Elements equal to each other maintain their relative position in the array. */ @@ -1168,9 +1253,11 @@ var ts; } for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { var arg = args_1[_a]; + if (arg === undefined) + continue; for (var p in arg) { if (hasProperty(arg, p)) { - t[p] = arg[p]; // TODO: GH#23368 + t[p] = arg[p]; } } } @@ -1346,6 +1433,9 @@ var ts; /** Do nothing and return true */ function returnTrue() { return true; } ts.returnTrue = returnTrue; + /** Do nothing and return undefined */ + function returnUndefined() { return undefined; } + ts.returnUndefined = returnUndefined; /** Returns its argument. */ function identity(x) { return x; } ts.identity = identity; @@ -1492,7 +1582,7 @@ var ts; Debug.assertEachDefined = assertEachDefined; function assertNever(member, message, stackCrawlMark) { if (message === void 0) { message = "Illegal value:"; } - var detail = "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); + var detail = typeof member === "object" && "kind" in member && "pos" in member ? "SyntaxKind: " + Debug.showSyntaxKind(member) : JSON.stringify(member); return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; @@ -2795,47 +2885,53 @@ var ts; SyntaxKind[SyntaxKind["SpreadAssignment"] = 277] = "SpreadAssignment"; // Enum SyntaxKind[SyntaxKind["EnumMember"] = 278] = "EnumMember"; + // Unparsed + SyntaxKind[SyntaxKind["UnparsedPrologue"] = 279] = "UnparsedPrologue"; + SyntaxKind[SyntaxKind["UnparsedPrepend"] = 280] = "UnparsedPrepend"; + SyntaxKind[SyntaxKind["UnparsedText"] = 281] = "UnparsedText"; + SyntaxKind[SyntaxKind["UnparsedInternalText"] = 282] = "UnparsedInternalText"; + SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 283] = "UnparsedSyntheticReference"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 279] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 280] = "Bundle"; - SyntaxKind[SyntaxKind["UnparsedSource"] = 281] = "UnparsedSource"; - SyntaxKind[SyntaxKind["InputFiles"] = 282] = "InputFiles"; + SyntaxKind[SyntaxKind["SourceFile"] = 284] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 285] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 286] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 287] = "InputFiles"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 283] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 288] = "JSDocTypeExpression"; // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 284] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 289] = "JSDocAllType"; // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 285] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 286] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 287] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 288] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 289] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 290] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 291] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 292] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocSignature"] = 293] = "JSDocSignature"; - SyntaxKind[SyntaxKind["JSDocTag"] = 294] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 295] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 296] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 297] = "JSDocCallbackTag"; - SyntaxKind[SyntaxKind["JSDocEnumTag"] = 298] = "JSDocEnumTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 299] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 300] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocThisTag"] = 301] = "JSDocThisTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 302] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 303] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 304] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 305] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 290] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 291] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 292] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 293] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 294] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 295] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 296] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 297] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 298] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocTag"] = 299] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 300] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 301] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 302] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 303] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 304] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 305] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 306] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 307] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 308] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 309] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 310] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 306] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 311] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 307] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 308] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 309] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 310] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 311] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 312] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 313] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 314] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 315] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 316] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 312] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 317] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 59] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 71] = "LastAssignment"; @@ -2862,10 +2958,10 @@ var ts; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 28] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 71] = "LastBinaryOperator"; SyntaxKind[SyntaxKind["FirstNode"] = 148] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 283] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 305] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 294] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 305] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 288] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 310] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 299] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 310] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 118] = "FirstContextualKeyword"; /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 147] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); @@ -2972,21 +3068,27 @@ var ts; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel"; })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); - /* @internal */ var TokenFlags; (function (TokenFlags) { TokenFlags[TokenFlags["None"] = 0] = "None"; + /* @internal */ TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak"; + /* @internal */ TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment"; + /* @internal */ TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated"; + /* @internal */ 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"; + /* @internal */ TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator"; + /* @internal */ TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; + /* @internal */ TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); var FlowFlags; @@ -3346,12 +3448,6 @@ var ts; TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution"; TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive"; /* @internal */ - TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType"; - /* @internal */ - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 268435456] = "ContainsObjectLiteral"; - /* @internal */ - TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 536870912] = "ContainsAnyFunctionType"; - /* @internal */ TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable"; @@ -3383,28 +3479,29 @@ var ts; TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive"; TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable"; TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable"; + /* @internal */ + TypeFlags[TypeFlags["ObjectFlagsType"] = 3768320] = "ObjectFlagsType"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable"; TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit"; /* @internal */ TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion"; + // The following flags are aggregated during union and intersection type construction /* @internal */ - TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening"; - /* @internal */ - TypeFlags[TypeFlags["PropagatingFlags"] = 939524096] = "PropagatingFlags"; + TypeFlags[TypeFlags["IncludesMask"] = 1835007] = "IncludesMask"; // The following flags are used for different purposes during union and intersection type construction /* @internal */ - TypeFlags[TypeFlags["NonWideningType"] = 134217728] = "NonWideningType"; + TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable"; /* @internal */ - TypeFlags[TypeFlags["Wildcard"] = 268435456] = "Wildcard"; + TypeFlags[TypeFlags["IncludesNonWideningType"] = 2097152] = "IncludesNonWideningType"; /* @internal */ - TypeFlags[TypeFlags["EmptyObject"] = 536870912] = "EmptyObject"; + TypeFlags[TypeFlags["IncludesWildcard"] = 4194304] = "IncludesWildcard"; /* @internal */ - TypeFlags[TypeFlags["ConstructionFlags"] = 939524096] = "ConstructionFlags"; + TypeFlags[TypeFlags["IncludesEmptyObject"] = 8388608] = "IncludesEmptyObject"; // The following flag is used for different purposes by maybeTypeOfKind /* @internal */ - TypeFlags[TypeFlags["GenericMappedType"] = 134217728] = "GenericMappedType"; + TypeFlags[TypeFlags["GenericMappedType"] = 131072] = "GenericMappedType"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); var ObjectFlags; (function (ObjectFlags) { @@ -3424,7 +3521,19 @@ var ts; ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType"; ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral"; ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral"; + /* @internal */ + ObjectFlags[ObjectFlags["PrimitiveUnion"] = 65536] = "PrimitiveUnion"; + /* @internal */ + ObjectFlags[ObjectFlags["ContainsWideningType"] = 131072] = "ContainsWideningType"; + /* @internal */ + ObjectFlags[ObjectFlags["ContainsObjectLiteral"] = 262144] = "ContainsObjectLiteral"; + /* @internal */ + ObjectFlags[ObjectFlags["ContainsAnyFunctionType"] = 524288] = "ContainsAnyFunctionType"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; + /* @internal */ + ObjectFlags[ObjectFlags["RequiresWidening"] = 393216] = "RequiresWidening"; + /* @internal */ + ObjectFlags[ObjectFlags["PropagatingFlags"] = 917504] = "PropagatingFlags"; })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {})); /* @internal */ var Variance; @@ -3469,6 +3578,7 @@ var ts; InferenceFlags[InferenceFlags["None"] = 0] = "None"; InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault"; InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault"; + InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction"; })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /** * Ternary values are defined such that @@ -3576,9 +3686,10 @@ var ts; ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016"; ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; - ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext"; + ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019"; + ScriptTarget[ScriptTarget["ESNext"] = 7] = "ESNext"; ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; - ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest"; + ScriptTarget[ScriptTarget["Latest"] = 7] = "Latest"; })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); var LanguageVariant; (function (LanguageVariant) { @@ -3727,6 +3838,7 @@ var ts; Extension["Js"] = ".js"; Extension["Jsx"] = ".jsx"; Extension["Json"] = ".json"; + Extension["TsBuildInfo"] = ".tsbuildinfo"; })(Extension = ts.Extension || (ts.Extension = {})); /* @internal */ var TransformFlags; @@ -3734,71 +3846,69 @@ var ts; TransformFlags[TransformFlags["None"] = 0] = "None"; // Facts // - Flags used to indicate that a node or subtree contains syntax that requires transformation. - 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["ContainsTypeScript"] = 1] = "ContainsTypeScript"; + TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2019"] = 8] = "ContainsES2019"; + TransformFlags[TransformFlags["ContainsES2018"] = 16] = "ContainsES2018"; + TransformFlags[TransformFlags["ContainsES2017"] = 32] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 64] = "ContainsES2016"; 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["ContainsGenerator"] = 256] = "ContainsGenerator"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 512] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; - TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 1024] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 2048] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 4096] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 8192] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 16384] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 32768] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 65536] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 131072] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 262144] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 524288] = "ContainsDynamicImport"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; // Assertions // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. - 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["AssertTypeScript"] = 1] = "AssertTypeScript"; + TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx"; + TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext"; + TransformFlags[TransformFlags["AssertES2019"] = 8] = "AssertES2019"; + TransformFlags[TransformFlags["AssertES2018"] = 16] = "AssertES2018"; + TransformFlags[TransformFlags["AssertES2017"] = 32] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 64] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 128] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 256] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 512] = "AssertDestructuringAssignment"; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; - TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 537371648] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 537373696] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 537372672] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 537372672] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["PropertyExcludes"] = 536872960] = "PropertyExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 536888320] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 537168896] = "ModuleExcludes"; + TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536896512] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536875008] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 536944640] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 536879104] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 536875008] = "BindingPatternExcludes"; + // Propagating flags + // - Bitmasks for flags that should propagate from a child + TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 2048] = "PropertyNamePropagatingFlags"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -3880,6 +3990,20 @@ var ts; EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + /*@internal*/ + var BundleFileSectionKind; + (function (BundleFileSectionKind) { + BundleFileSectionKind["Prologue"] = "prologue"; + BundleFileSectionKind["EmitHelpers"] = "emitHelpers"; + BundleFileSectionKind["NoDefaultLib"] = "no-default-lib"; + BundleFileSectionKind["Reference"] = "reference"; + BundleFileSectionKind["Type"] = "type"; + BundleFileSectionKind["Lib"] = "lib"; + BundleFileSectionKind["Prepend"] = "prepend"; + BundleFileSectionKind["Text"] = "text"; + BundleFileSectionKind["Internal"] = "internal"; + // comments? + })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {})); var ListFormat; (function (ListFormat) { ListFormat[ListFormat["None"] = 0] = "None"; @@ -4026,8 +4150,11 @@ var ts; */ /* @internal */ function generateDjb2Hash(data) { - var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); - return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + var acc = 5381; + for (var i = 0; i < data.length; i++) { + acc = ((acc << 5) + acc) + data.charCodeAt(i); + } + return acc.toString(); } ts.generateDjb2Hash = generateDjb2Hash; /** @@ -4287,6 +4414,8 @@ var ts; : FileWatcherEventKind.Changed; } ts.getFileWatcherEventKind = getFileWatcherEventKind; + /*@internal*/ + ts.ignoredPaths = ["/node_modules/.", "/.git"]; /** * Watch the directory recursively using host provided method to watch child directories * that means if this is recursive watcher, watch the children directories as well @@ -4311,6 +4440,8 @@ var ts; else { directoryWatcher = { watcher: host.watchDirectory(dirName, function (fileName) { + if (isIgnoredPath(fileName)) + return; // Call the actual callback callbackCache.forEach(function (callbacks, rootDirName) { if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) { @@ -4360,7 +4491,7 @@ var ts; var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); // Filter our the symbolic link directories since those arent included in recursive watch // which is same behaviour when recursive: true is passed to fs.watch - return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined; + return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined; }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); return newChildWatches || ts.emptyArray; /** @@ -4377,6 +4508,16 @@ var ts; (newChildWatches || (newChildWatches = [])).push(childWatcher); } } + function isIgnoredPath(path) { + return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); }); + } + function isInPath(path, searchPath) { + if (ts.stringContains(path, searchPath)) + return true; + if (host.useCaseSensitiveFileNames) + return false; + return ts.stringContains(toCanonicalFilePath(path), searchPath); + } } ts.createRecursiveDirectoryWatcher = createRecursiveDirectoryWatcher; function getNodeMajorVersion() { @@ -4445,7 +4586,17 @@ var ts; directoryExists: directoryExists, createDirectory: function (directoryName) { if (!nodeSystem.directoryExists(directoryName)) { - _fs.mkdirSync(directoryName); + // Wrapped in a try-catch to prevent crashing if we are in a race + // with another copy of ourselves to create the same directory + try { + _fs.mkdirSync(directoryName); + } + catch (e) { + if (e.code !== "EEXIST") { + // Failed for some other reason (access denied?); still throw + throw e; + } + } } }, getExecutingFilePath: function () { @@ -4462,7 +4613,7 @@ var ts; getModifiedTime: getModifiedTime, setModifiedTime: setModifiedTime, deleteFile: deleteFile, - createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + createHash: _crypto ? createSHA256Hash : generateDjb2Hash, createSHA256Hash: _crypto ? createSHA256Hash : undefined, getMemoryUsage: function () { if (global.gc) { @@ -4850,7 +5001,7 @@ var ts; } } function readDirectory(path, extensions, excludes, includes, depth) { - return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries); + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); } function fileSystemEntryExists(path, entryKind) { try { @@ -4906,11 +5057,6 @@ var ts; return; } } - function createMD5HashUsingNativeCrypto(data) { - var hash = _crypto.createHash("md5"); - hash.update(data); - return hash.digest("hex"); - } function createSHA256Hash(data) { var hash = _crypto.createHash("sha256"); hash.update(data); @@ -5171,7 +5317,6 @@ var ts; Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."), - Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."), Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."), A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), @@ -5262,6 +5407,8 @@ var ts; An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."), A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."), A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."), + readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types: diag(1354, ts.DiagnosticCategory.Error, "readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types_1354", "'readonly' type modifier is only permitted on array and tuple literal types."), + A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal: diag(1355, ts.DiagnosticCategory.Error, "A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal_1355", "A 'const' assertion can only be applied to a string, number, boolean, array, or object literal."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5356,7 +5503,7 @@ var ts; Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."), Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."), Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."), - Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."), + This_overload_signature_is_not_compatible_with_its_implementation_signature: diag(2394, ts.DiagnosticCategory.Error, "This_overload_signature_is_not_compatible_with_its_implementation_signature_2394", "This overload signature is not compatible with its implementation signature."), Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."), Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."), Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."), @@ -5529,15 +5676,20 @@ var ts; No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"), Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), - Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."), Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom: diag(2584, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2584", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'."), _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2585, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_2585", "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."), Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."), JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."), Cannot_assign_to_0_because_it_is_a_constant: diag(2588, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_2588", "Cannot assign to '{0}' because it is a constant."), + Type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2589, ts.DiagnosticCategory.Error, "Type_instantiation_is_excessively_deep_and_possibly_infinite_2589", "Type instantiation is excessively deep and possibly infinite."), + Expression_produces_a_union_type_that_is_too_complex_to_represent: diag(2590, ts.DiagnosticCategory.Error, "Expression_produces_a_union_type_that_is_too_complex_to_represent_2590", "Expression produces a union type that is too complex to represent."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."), + Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5644,6 +5796,12 @@ var ts; This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."), This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."), _0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."), + Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided: diag(2748, ts.DiagnosticCategory.Error, "Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided_2748", "Cannot access ambient const enums when the '--isolatedModules' flag is provided."), + _0_refers_to_a_value_but_is_being_used_as_a_type_here: diag(2749, ts.DiagnosticCategory.Error, "_0_refers_to_a_value_but_is_being_used_as_a_type_here_2749", "'{0}' refers to a value, but is being used as a type here."), + The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."), + Circularity_originates_in_type_at_this_location: diag(2751, ts.DiagnosticCategory.Error, "Circularity_originates_in_type_at_this_location_2751", "Circularity originates in type at this location."), + The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."), + Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5727,6 +5885,7 @@ var ts; Public_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4100, ts.DiagnosticCategory.Error, "Public_method_0_of_exported_class_has_or_is_using_private_name_1_4100", "Public method '{0}' of exported class has or is using private name '{1}'."), Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4101, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101", "Method '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), Method_0_of_exported_interface_has_or_is_using_private_name_1: diag(4102, ts.DiagnosticCategory.Error, "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102", "Method '{0}' of exported interface has or is using private name '{1}'."), + Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1: diag(4103, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1_4103", "Type parameter '{0}' of exported mapped object type is using private name '{1}'."), The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), @@ -5775,7 +5934,7 @@ var ts; Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), Do_not_resolve_the_real_path_of_symlinks: diag(6013, ts.DiagnosticCategory.Message, "Do_not_resolve_the_real_path_of_symlinks_6013", "Do not resolve the real path of symlinks."), Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."), - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'."), Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), @@ -5994,6 +6153,16 @@ var ts; Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."), + Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed: diag(6372, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed_6372", "Project '{0}' is out of date because output of its dependency '{1}' has changed"), + Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."), + A_non_dry_build_would_update_timestamps_for_output_of_project_0: diag(6374, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_timestamps_for_output_of_project_0_6374", "A non-dry build would update timestamps for output of project '{0}'"), + A_non_dry_build_would_update_output_of_project_0: diag(6375, ts.DiagnosticCategory.Message, "A_non_dry_build_would_update_output_of_project_0_6375", "A non-dry build would update output of project '{0}'"), + Cannot_update_output_of_project_0_because_there_was_error_reading_file_1: diag(6376, ts.DiagnosticCategory.Message, "Cannot_update_output_of_project_0_because_there_was_error_reading_file_1_6376", "Cannot update output of project '{0}' because there was error reading file '{1}'"), + Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1: diag(6377, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1_6377", "Cannot write file '{0}' because it will overwrite '.tsbuildinfo' file generated by referenced project '{1}'"), + Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"), + Composite_projects_may_not_disable_incremental_compilation: diag(6379, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_incremental_compilation_6379", "Composite projects may not disable incremental compilation."), + Specify_file_to_store_incremental_compilation_information: diag(6380, ts.DiagnosticCategory.Message, "Specify_file_to_store_incremental_compilation_information_6380", "Specify file to store incremental compilation information"), + Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2: diag(6381, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_curren_6381", "Project '{0}' is out of date because output for it was generated with version '{1}' that differs with current version '{2}'"), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -6030,7 +6199,7 @@ var ts; Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{1}`"), - The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any_7041", "The containing arrow function captures the global value of 'this' which implicitly has type 'any'."), + The_containing_arrow_function_captures_the_global_value_of_this: diag(7041, ts.DiagnosticCategory.Error, "The_containing_arrow_function_captures_the_global_value_of_this_7041", "The containing arrow function captures the global value of 'this'."), Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used: diag(7042, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used_7042", "Module '{0}' was resolved to '{1}', but '--resolveJsonModule' is not used."), Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7043, ts.DiagnosticCategory.Suggestion, "Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7043", "Variable '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage: diag(7044, ts.DiagnosticCategory.Suggestion, "Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage_7044", "Parameter '{0}' implicitly has an '{1}' type, but a better type may be inferred from usage."), @@ -6210,6 +6379,7 @@ var ts; Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"), + Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"), }; })(ts || (ts = {})); var ts; @@ -6697,16 +6867,20 @@ var ts; return pos; } var shebangTriviaRegex = /^#!.*/; + /*@internal*/ function isShebangTrivia(text, pos) { // Shebangs check must only be done at the start of the file ts.Debug.assert(pos === 0); return shebangTriviaRegex.test(text); } + ts.isShebangTrivia = isShebangTrivia; + /*@internal*/ function scanShebangTrivia(text, pos) { var shebang = shebangTriviaRegex.exec(text)[0]; pos = pos + shebang.length; return pos; } + ts.scanShebangTrivia = scanShebangTrivia; /** * Invokes a callback for each comment range following the provided position. * @@ -6733,8 +6907,15 @@ var ts; var pendingKind; var pendingHasTrailingNewLine; var hasPendingCommentRange = false; - var collecting = trailing || pos === 0; + var collecting = trailing; var accumulator = initial; + if (pos === 0) { + collecting = true; + var shebang = getShebang(text); + if (shebang) { + pos = shebang.length; + } + } scan: while (pos >= 0 && pos < text.length) { var ch = text.charCodeAt(pos); switch (ch) { @@ -7969,6 +8150,7 @@ var ts; } pos++; } + tokenValue = text.substring(startPos, pos); return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */; } // Scans a JSX identifier; these differ from normal identifiers in that @@ -8050,8 +8232,8 @@ var ts; pos++; return token = 14 /* NoSubstitutionTemplateLiteral */; } - if (isIdentifierStart(ch, 6 /* Latest */)) { - while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { + if (isIdentifierStart(ch, 7 /* Latest */)) { + while (isIdentifierPart(text.charCodeAt(pos), 7 /* Latest */) && pos < end) { pos++; } tokenValue = text.substring(tokenPos, pos); @@ -8409,7 +8591,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 279 /* SourceFile */) { + while (node && node.kind !== 284 /* SourceFile */) { node = node.parent; } return node; @@ -8496,10 +8678,7 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; - /** - * Prepends statements to an array while taking care of prologue directives. - */ - function addStatementsAfterPrologue(to, from) { + function insertStatementsAfterPrologue(to, from, isPrologueDirective) { if (from === undefined || from.length === 0) return to; var statementIndex = 0; @@ -8512,7 +8691,44 @@ var ts; to.splice.apply(to, [statementIndex, 0].concat(from)); return to; } - ts.addStatementsAfterPrologue = addStatementsAfterPrologue; + function insertStatementAfterPrologue(to, statement, isPrologueDirective) { + if (statement === undefined) + return to; + var statementIndex = 0; + // skip all prologue directives to insert at the correct position + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } + } + to.splice(statementIndex, 0, statement); + return to; + } + function isAnyPrologueDirective(node) { + return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */); + } + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function insertStatementsAfterStandardPrologue(to, from) { + return insertStatementsAfterPrologue(to, from, isPrologueDirective); + } + ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue; + function insertStatementsAfterCustomPrologue(to, from) { + return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective); + } + ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue; + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function insertStatementAfterStandardPrologue(to, statement) { + return insertStatementAfterPrologue(to, statement, isPrologueDirective); + } + ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue; + function insertStatementAfterCustomPrologue(to, statement) { + return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective); + } + ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue; /** * Determine if the given comment is a triple-slash * @@ -8555,7 +8771,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 306 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 311 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -8574,7 +8790,7 @@ var ts; } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; function isJSDocTypeExpressionOrChild(node) { - return node.kind === 283 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); + return node.kind === 288 /* JSDocTypeExpression */ || (node.parent && isJSDocTypeExpressionOrChild(node.parent)); } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) { if (includeTrivia === void 0) { includeTrivia = false; } @@ -8701,7 +8917,7 @@ var ts; return node && node.kind === 244 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 279 /* SourceFile */ || + return node.kind === 284 /* SourceFile */ || node.kind === 244 /* ModuleDeclaration */ || ts.isFunctionLike(node); } @@ -8719,7 +8935,7 @@ var ts; // - defined in the top level scope and source file is an external module // - defined inside ambient module declaration located in the top level scope and source file not an external module switch (node.parent.kind) { - case 279 /* SourceFile */: + case 284 /* SourceFile */: return ts.isExternalModule(node.parent); case 245 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); @@ -8737,7 +8953,7 @@ var ts; ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { - case 279 /* SourceFile */: + case 284 /* SourceFile */: case 246 /* CaseBlock */: case 274 /* CatchClause */: case 244 /* ModuleDeclaration */: @@ -8762,9 +8978,9 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 297 /* JSDocCallbackTag */: - case 304 /* JSDocTypedefTag */: - case 293 /* JSDocSignature */: + case 302 /* JSDocCallbackTag */: + case 309 /* JSDocTypedefTag */: + case 298 /* JSDocSignature */: return true; default: ts.assertType(node); @@ -8780,12 +8996,12 @@ var ts; case 162 /* IndexSignature */: case 165 /* FunctionType */: case 166 /* ConstructorType */: - case 289 /* JSDocFunctionType */: + case 294 /* JSDocFunctionType */: case 240 /* ClassDeclaration */: case 209 /* ClassExpression */: case 241 /* InterfaceDeclaration */: case 242 /* TypeAliasDeclaration */: - case 303 /* JSDocTemplateTag */: + case 308 /* JSDocTemplateTag */: case 239 /* FunctionDeclaration */: case 156 /* MethodDeclaration */: case 157 /* Constructor */: @@ -8930,7 +9146,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 279 /* SourceFile */: + case 284 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -9105,7 +9321,7 @@ var ts; return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); case 150 /* TypeParameter */: return node === parent.constraint; - case 303 /* JSDocTemplateTag */: + case 308 /* JSDocTemplateTag */: return node === parent.constraint; case 154 /* PropertyDeclaration */: case 153 /* PropertySignature */: @@ -9365,7 +9581,7 @@ var ts; } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { - ts.Debug.assert(node.kind !== 279 /* SourceFile */); + ts.Debug.assert(node.kind !== 284 /* SourceFile */); while (true) { node = node.parent; if (!node) { @@ -9419,7 +9635,7 @@ var ts; case 161 /* ConstructSignature */: case 162 /* IndexSignature */: case 243 /* EnumDeclaration */: - case 279 /* SourceFile */: + case 284 /* SourceFile */: return node; } } @@ -9502,6 +9718,11 @@ var ts; } } ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; + function isSuperOrSuperProperty(node) { + return node.kind === 98 /* SuperKeyword */ + || isSuperProperty(node); + } + ts.isSuperOrSuperProperty = isSuperOrSuperProperty; /** * Determines whether a node is a property or element access expression for `super`. */ @@ -10127,7 +10348,7 @@ var ts; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 304 /* JSDocTypedefTag */ || node.kind === 297 /* JSDocCallbackTag */; + return node.kind === 309 /* JSDocTypedefTag */ || node.kind === 302 /* JSDocCallbackTag */; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -10271,7 +10492,7 @@ var ts; ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return node.dotDotDotToken !== undefined || !!type && type.kind === 290 /* JSDocVariadicType */; + return node.dotDotDotToken !== undefined || !!type && type.kind === 295 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -10509,14 +10730,15 @@ var ts; } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; function getEffectiveBaseTypeNode(node) { - if (isInJSFile(node)) { + var baseType = getClassExtendsHeritageElement(node); + if (baseType && isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. var tag = ts.getJSDocAugmentsTag(node); if (tag) { return tag.class; } } - return getClassExtendsHeritageElement(node); + return baseType; } ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode; function getClassExtendsHeritageElement(node) { @@ -10755,7 +10977,7 @@ var ts; || kind === 158 /* GetAccessor */ || kind === 159 /* SetAccessor */ || kind === 244 /* ModuleDeclaration */ - || kind === 279 /* SourceFile */; + || kind === 284 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -10832,7 +11054,7 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 309 /* CommaListExpression */: + case 314 /* CommaListExpression */: return 0; case 208 /* SpreadElement */: return 1; @@ -11150,6 +11372,9 @@ var ts; lineStart = true; } } + function getTextPosWithWriteLine() { + return lineStart ? output.length : (output.length + newLine.length); + } reset(); return { write: write, @@ -11178,7 +11403,8 @@ var ts; writeStringLiteral: write, writeSymbol: function (s, _) { return write(s); }, writeTrailingSemicolon: write, - writeComment: write + writeComment: write, + getTextPosWithWriteLine: getTextPosWithWriteLine }; } ts.createTextWriter = createTextWriter; @@ -11307,23 +11533,27 @@ var ts; function getSourceFilesToEmit(host, targetSourceFile) { var options = host.getCompilerOptions(); var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; + var getResolvedProjectReferenceToRedirect = function (fileName) { return host.getResolvedProjectReferenceToRedirect(fileName); }; if (options.outFile || options.out) { var moduleKind = ts.getEmitModuleKind(options); var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified return ts.filter(host.getSourceFiles(), function (sourceFile) { - return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); + return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); }); } else { var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; - return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); }); + return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); }); } } ts.getSourceFilesToEmit = getSourceFilesToEmit; /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ - function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect) { + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && + !sourceFile.isDeclarationFile && + !isSourceFileFromExternalLibrary(sourceFile) && + !(isJsonSourceFile(sourceFile) && getResolvedProjectReferenceToRedirect(sourceFile.fileName)); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; function getSourceFilePathInNewDir(fileName, host, newDirPath) { @@ -11469,7 +11699,7 @@ var ts; ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; /** template tags are only available when a typedef isn't already using them */ function isNonTypeAliasTemplate(tag) { - return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 291 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 296 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); } /** * Gets the effective type annotation of the value parameter of a set accessor. If the node @@ -12374,7 +12604,7 @@ var ts; } ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; function getObjectFlags(type) { - return type.flags & 524288 /* Object */ ? type.objectFlags : 0; + return type.flags & 3768320 /* ObjectFlagsType */ ? type.objectFlags : 0; } ts.getObjectFlags = getObjectFlags; function typeHasCallOrConstructSignatures(type, checker) { @@ -12441,25 +12671,37 @@ var ts; || kind === 96 /* NullKeyword */ || kind === 132 /* NeverKeyword */ || kind === 211 /* ExpressionWithTypeArguments */ - || kind === 284 /* JSDocAllType */ - || kind === 285 /* JSDocUnknownType */ - || kind === 286 /* JSDocNullableType */ - || kind === 287 /* JSDocNonNullableType */ - || kind === 288 /* JSDocOptionalType */ - || kind === 289 /* JSDocFunctionType */ - || kind === 290 /* JSDocVariadicType */; + || kind === 289 /* JSDocAllType */ + || kind === 290 /* JSDocUnknownType */ + || kind === 291 /* JSDocNullableType */ + || kind === 292 /* JSDocNonNullableType */ + || kind === 293 /* JSDocOptionalType */ + || kind === 294 /* JSDocFunctionType */ + || kind === 295 /* JSDocVariadicType */; } ts.isTypeNodeKind = isTypeNodeKind; function isAccessExpression(node) { return node.kind === 189 /* PropertyAccessExpression */ || node.kind === 190 /* ElementAccessExpression */; } ts.isAccessExpression = isAccessExpression; + function isBundleFileTextLike(section) { + switch (section.kind) { + case "text" /* Text */: + case "internal" /* Internal */: + return true; + default: + return false; + } + } + ts.isBundleFileTextLike = isBundleFileTextLike; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { switch (options.target) { - case 6 /* ESNext */: + case 7 /* ESNext */: return "lib.esnext.full.d.ts"; + case 6 /* ES2019 */: + return "lib.es2019.full.d.ts"; case 5 /* ES2018 */: return "lib.es2018.full.d.ts"; case 4 /* ES2017 */: @@ -12913,8 +13155,8 @@ var ts; switch (declaration.kind) { case 72 /* Identifier */: return declaration; - case 305 /* JSDocPropertyTag */: - case 299 /* JSDocParameterTag */: { + case 310 /* JSDocPropertyTag */: + case 304 /* JSDocParameterTag */: { var name = declaration.name; if (name.kind === 148 /* QualifiedName */) { return name.right; @@ -12938,7 +13180,7 @@ var ts; return undefined; } } - case 304 /* JSDocTypedefTag */: + case 309 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); case 254 /* ExportAssignment */: { var expression = declaration.expression; @@ -13142,7 +13384,7 @@ var ts; return ts.emptyArray; } if (ts.isJSDocTypeAlias(node)) { - ts.Debug.assert(node.parent.kind === 291 /* JSDocComment */); + ts.Debug.assert(node.parent.kind === 296 /* JSDocComment */); return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); } if (node.typeParameters) { @@ -13404,12 +13646,17 @@ var ts; return node.kind === 194 /* TypeAssertionExpression */; } ts.isTypeAssertion = isTypeAssertion; + function isConstTypeReference(node) { + return isTypeReferenceNode(node) && isIdentifier(node.typeName) && + node.typeName.escapedText === "const" && !node.typeArguments; + } + ts.isConstTypeReference = isConstTypeReference; function isParenthesizedExpression(node) { return node.kind === 195 /* ParenthesizedExpression */; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 308 /* PartiallyEmittedExpression */) { + while (node.kind === 313 /* PartiallyEmittedExpression */) { node = node.expression; } return node; @@ -13756,108 +14003,128 @@ var ts; ts.isEnumMember = isEnumMember; // Top-level nodes function isSourceFile(node) { - return node.kind === 279 /* SourceFile */; + return node.kind === 284 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 280 /* Bundle */; + return node.kind === 285 /* Bundle */; } ts.isBundle = isBundle; function isUnparsedSource(node) { - return node.kind === 281 /* UnparsedSource */; + return node.kind === 286 /* UnparsedSource */; } ts.isUnparsedSource = isUnparsedSource; + function isUnparsedPrepend(node) { + return node.kind === 280 /* UnparsedPrepend */; + } + ts.isUnparsedPrepend = isUnparsedPrepend; + function isUnparsedTextLike(node) { + switch (node.kind) { + case 281 /* UnparsedText */: + case 282 /* UnparsedInternalText */: + return true; + default: + return false; + } + } + ts.isUnparsedTextLike = isUnparsedTextLike; + function isUnparsedNode(node) { + return isUnparsedTextLike(node) || + node.kind === 279 /* UnparsedPrologue */ || + node.kind === 283 /* UnparsedSyntheticReference */; + } + ts.isUnparsedNode = isUnparsedNode; // JSDoc function isJSDocTypeExpression(node) { - return node.kind === 283 /* JSDocTypeExpression */; + return node.kind === 288 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 284 /* JSDocAllType */; + return node.kind === 289 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 285 /* JSDocUnknownType */; + return node.kind === 290 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 286 /* JSDocNullableType */; + return node.kind === 291 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 287 /* JSDocNonNullableType */; + return node.kind === 292 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 288 /* JSDocOptionalType */; + return node.kind === 293 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 289 /* JSDocFunctionType */; + return node.kind === 294 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 290 /* JSDocVariadicType */; + return node.kind === 295 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 291 /* JSDocComment */; + return node.kind === 296 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 295 /* JSDocAugmentsTag */; + return node.kind === 300 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; function isJSDocClassTag(node) { - return node.kind === 296 /* JSDocClassTag */; + return node.kind === 301 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocEnumTag(node) { - return node.kind === 298 /* JSDocEnumTag */; + return node.kind === 303 /* JSDocEnumTag */; } ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocThisTag(node) { - return node.kind === 301 /* JSDocThisTag */; + return node.kind === 306 /* JSDocThisTag */; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocParameterTag(node) { - return node.kind === 299 /* JSDocParameterTag */; + return node.kind === 304 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 300 /* JSDocReturnTag */; + return node.kind === 305 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 302 /* JSDocTypeTag */; + return node.kind === 307 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 303 /* JSDocTemplateTag */; + return node.kind === 308 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 304 /* JSDocTypedefTag */; + return node.kind === 309 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 305 /* JSDocPropertyTag */; + return node.kind === 310 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 305 /* JSDocPropertyTag */ || node.kind === 299 /* JSDocParameterTag */; + return node.kind === 310 /* JSDocPropertyTag */ || node.kind === 304 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 292 /* JSDocTypeLiteral */; + return node.kind === 297 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; function isJSDocCallbackTag(node) { - return node.kind === 297 /* JSDocCallbackTag */; + return node.kind === 302 /* JSDocCallbackTag */; } ts.isJSDocCallbackTag = isJSDocCallbackTag; function isJSDocSignature(node) { - return node.kind === 293 /* JSDocSignature */; + return node.kind === 298 /* JSDocSignature */; } ts.isJSDocSignature = isJSDocSignature; })(ts || (ts = {})); @@ -13868,7 +14135,7 @@ var ts; (function (ts) { /* @internal */ function isSyntaxList(n) { - return n.kind === 306 /* SyntaxList */; + return n.kind === 311 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -14020,11 +14287,11 @@ var ts; switch (kind) { case 155 /* MethodSignature */: case 160 /* CallSignature */: - case 293 /* JSDocSignature */: + case 298 /* JSDocSignature */: case 161 /* ConstructSignature */: case 162 /* IndexSignature */: case 165 /* FunctionType */: - case 289 /* JSDocFunctionType */: + case 294 /* JSDocFunctionType */: case 166 /* ConstructorType */: return true; default: @@ -14315,8 +14582,8 @@ var ts; case 208 /* SpreadElement */: case 212 /* AsExpression */: case 210 /* OmittedExpression */: - case 309 /* CommaListExpression */: - case 308 /* PartiallyEmittedExpression */: + case 314 /* CommaListExpression */: + case 313 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -14330,12 +14597,12 @@ var ts; ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 308 /* PartiallyEmittedExpression */; + return node.kind === 313 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 307 /* NotEmittedStatement */; + return node.kind === 312 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ @@ -14446,9 +14713,9 @@ var ts; || kind === 242 /* TypeAliasDeclaration */ || kind === 150 /* TypeParameter */ || kind === 237 /* VariableDeclaration */ - || kind === 304 /* JSDocTypedefTag */ - || kind === 297 /* JSDocCallbackTag */ - || kind === 305 /* JSDocPropertyTag */; + || kind === 309 /* JSDocTypedefTag */ + || kind === 302 /* JSDocCallbackTag */ + || kind === 310 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { return kind === 239 /* FunctionDeclaration */ @@ -14483,14 +14750,14 @@ var ts; || kind === 219 /* VariableStatement */ || kind === 224 /* WhileStatement */ || kind === 231 /* WithStatement */ - || kind === 307 /* NotEmittedStatement */ - || kind === 311 /* EndOfDeclarationMarker */ - || kind === 310 /* MergeDeclarationMarker */; + || kind === 312 /* NotEmittedStatement */ + || kind === 316 /* EndOfDeclarationMarker */ + || kind === 315 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { if (node.kind === 150 /* TypeParameter */) { - return node.parent.kind !== 303 /* JSDocTemplateTag */ || ts.isInJSFile(node); + return (node.parent && node.parent.kind !== 308 /* JSDocTemplateTag */) || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -14585,18 +14852,18 @@ var ts; /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 283 /* FirstJSDocNode */ && node.kind <= 305 /* LastJSDocNode */; + return node.kind >= 288 /* FirstJSDocNode */ && node.kind <= 310 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 291 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); + return node.kind === 296 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 294 /* FirstJSDocTagNode */ && node.kind <= 305 /* LastJSDocTagNode */; + return node.kind >= 299 /* FirstJSDocTagNode */ && node.kind <= 310 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { @@ -14913,6 +15180,10 @@ var ts; return !!(compilerOptions.declaration || compilerOptions.composite); } ts.getEmitDeclarations = getEmitDeclarations; + function isIncrementalCompilation(options) { + return !!(options.incremental || options.composite); + } + ts.isIncrementalCompilation = isIncrementalCompilation; function getStrictOptionValue(compilerOptions, flag) { return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; } @@ -15600,7 +15871,7 @@ var ts; } ts.getRegexFromPattern = getRegexFromPattern; /** @param path directory of the tsconfig.json */ - function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); @@ -15610,12 +15881,18 @@ var ts; // Associate an array of results with each include regex. This keeps results in order of the "include" order. // If there are no "includes", then just put everything in results[0]. var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; + var visited = ts.createMap(); + var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { + var canonicalPath = toCanonical(realpath(absolutePath)); + if (visited.has(canonicalPath)) + return; + visited.set(canonicalPath, true); var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; var _loop_1 = function (current) { var name = combinePaths(path, current); @@ -15998,6 +16275,19 @@ var ts; return arr.slice(index); } ts.sliceAfter = sliceAfter; + function addRelatedInfo(diagnostic) { + var _a; + var relatedInformation = []; + for (var _i = 1; _i < arguments.length; _i++) { + relatedInformation[_i - 1] = arguments[_i]; + } + if (!diagnostic.relatedInformation) { + diagnostic.relatedInformation = []; + } + (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation); + return diagnostic; + } + ts.addRelatedInfo = addRelatedInfo; function minAndMax(arr, getValue) { Debug.assert(arr.length !== 0); var min = getValue(arr[0]); @@ -16197,7 +16487,7 @@ var ts; var SourceFileConstructor; // tslint:enable variable-name function createNode(kind, pos, end) { - if (kind === 279 /* SourceFile */) { + if (kind === 284 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } else if (kind === 72 /* Identifier */) { @@ -16448,7 +16738,7 @@ var ts; case 218 /* Block */: case 245 /* ModuleBlock */: return visitNodes(cbNode, cbNodes, node.statements); - case 279 /* SourceFile */: + case 284 /* SourceFile */: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); case 219 /* VariableStatement */: @@ -16597,7 +16887,7 @@ var ts; return visitNode(cbNode, node.expression); case 258 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 309 /* CommaListExpression */: + case 314 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); case 260 /* JsxElement */: return visitNode(cbNode, node.openingElement) || @@ -16626,60 +16916,60 @@ var ts; return visitNode(cbNode, node.tagName); case 171 /* OptionalType */: case 172 /* RestType */: - case 283 /* JSDocTypeExpression */: - case 287 /* JSDocNonNullableType */: - case 286 /* JSDocNullableType */: - case 288 /* JSDocOptionalType */: - case 290 /* JSDocVariadicType */: + case 288 /* JSDocTypeExpression */: + case 292 /* JSDocNonNullableType */: + case 291 /* JSDocNullableType */: + case 293 /* JSDocOptionalType */: + case 295 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 289 /* JSDocFunctionType */: + case 294 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 291 /* JSDocComment */: + case 296 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 299 /* JSDocParameterTag */: - case 305 /* JSDocPropertyTag */: + case 304 /* JSDocParameterTag */: + case 310 /* JSDocPropertyTag */: return visitNode(cbNode, node.tagName) || (node.isNameFirst ? visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression) : visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name)); - case 295 /* JSDocAugmentsTag */: + case 300 /* JSDocAugmentsTag */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.class); - case 303 /* JSDocTemplateTag */: + case 308 /* JSDocTemplateTag */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); - case 304 /* JSDocTypedefTag */: + case 309 /* JSDocTypedefTag */: return visitNode(cbNode, node.tagName) || (node.typeExpression && - node.typeExpression.kind === 283 /* JSDocTypeExpression */ + node.typeExpression.kind === 288 /* JSDocTypeExpression */ ? visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName) : visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression)); - case 297 /* JSDocCallbackTag */: + case 302 /* JSDocCallbackTag */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 300 /* JSDocReturnTag */: - case 302 /* JSDocTypeTag */: - case 301 /* JSDocThisTag */: - case 298 /* JSDocEnumTag */: + case 305 /* JSDocReturnTag */: + case 307 /* JSDocTypeTag */: + case 306 /* JSDocThisTag */: + case 303 /* JSDocEnumTag */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.typeExpression); - case 293 /* JSDocSignature */: + case 298 /* JSDocSignature */: return ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 292 /* JSDocTypeLiteral */: + case 297 /* JSDocTypeLiteral */: return ts.forEach(node.jsDocPropertyTags, cbNode); - case 294 /* JSDocTag */: - case 296 /* JSDocClassTag */: + case 299 /* JSDocTag */: + case 301 /* JSDocClassTag */: return visitNode(cbNode, node.tagName); - case 308 /* PartiallyEmittedExpression */: + case 313 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -16759,7 +17049,7 @@ var ts; (function (Parser) { // Share a single scanner across all calls to parse a source file. This helps speed things // up by avoiding the cost of creating/compiling scanners over and over again. - var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true); + var scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ true); var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */; // capture constructors in 'initializeState' to avoid null checks // tslint:disable variable-name @@ -17053,7 +17343,7 @@ var ts; function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { // code from createNode is inlined here so createNode won't have to deal with special case of creating source files // this is quite rare comparing to other nodes and createNode should be as fast as possible - var sourceFile = new SourceFileConstructor(279 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + var sourceFile = new SourceFileConstructor(284 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; @@ -18253,9 +18543,9 @@ var ts; return finishNode(node); } function parseJSDocAllType(postFixEquals) { - var result = createNode(284 /* JSDocAllType */); + var result = createNode(289 /* JSDocAllType */); if (postFixEquals) { - return createPostfixType(288 /* JSDocOptionalType */, result); + return createPostfixType(293 /* JSDocOptionalType */, result); } else { nextToken(); @@ -18263,7 +18553,7 @@ var ts; return finishNode(result); } function parseJSDocNonNullableType() { - var result = createNode(287 /* JSDocNonNullableType */); + var result = createNode(292 /* JSDocNonNullableType */); nextToken(); result.type = parseNonArrayType(); return finishNode(result); @@ -18287,18 +18577,18 @@ var ts; token() === 30 /* GreaterThanToken */ || token() === 59 /* EqualsToken */ || token() === 50 /* BarToken */) { - var result = createNode(285 /* JSDocUnknownType */, pos); + var result = createNode(290 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(286 /* JSDocNullableType */, pos); + var result = createNode(291 /* JSDocNullableType */, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNodeWithJSDoc(289 /* JSDocFunctionType */); + var result = createNodeWithJSDoc(294 /* JSDocFunctionType */); nextToken(); fillSignature(57 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); return finishNode(result); @@ -18322,12 +18612,12 @@ var ts; var type = parseTypeOrTypePredicate(); scanner.setInJSDocType(false); if (dotdotdot) { - var variadic = createNode(290 /* JSDocVariadicType */, dotdotdot.pos); + var variadic = createNode(295 /* JSDocVariadicType */, dotdotdot.pos); variadic.type = type; type = finishNode(variadic); } if (token() === 59 /* EqualsToken */) { - return createPostfixType(288 /* JSDocOptionalType */, type); + return createPostfixType(293 /* JSDocOptionalType */, type); } return type; } @@ -18699,7 +18989,7 @@ var ts; return finishNode(node); } var type = parseType(); - if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 286 /* JSDocNullableType */ && type.pos === type.type.pos) { + if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 291 /* JSDocNullableType */ && type.pos === type.type.pos) { type.kind = 171 /* OptionalType */; } return type; @@ -18837,6 +19127,7 @@ var ts; case 135 /* NumberKeyword */: case 146 /* BigIntKeyword */: case 123 /* BooleanKeyword */: + case 133 /* ReadonlyKeyword */: case 139 /* SymbolKeyword */: case 142 /* UniqueKeyword */: case 106 /* VoidKeyword */: @@ -18885,14 +19176,14 @@ var ts; while (!scanner.hasPrecedingLineBreak()) { switch (token()) { case 52 /* ExclamationToken */: - type = createPostfixType(287 /* JSDocNonNullableType */, type); + type = createPostfixType(292 /* JSDocNonNullableType */, type); break; case 56 /* QuestionToken */: // If not in JSDoc and next token is start of a type we have a conditional type if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { return type; } - type = createPostfixType(286 /* JSDocNullableType */, type); + type = createPostfixType(291 /* JSDocNullableType */, type); break; case 22 /* OpenBracketToken */: parseExpected(22 /* OpenBracketToken */); @@ -18942,6 +19233,7 @@ var ts; switch (operator) { case 129 /* KeyOfKeyword */: case 142 /* UniqueKeyword */: + case 133 /* ReadonlyKeyword */: return parseTypeOperator(operator); case 127 /* InferKeyword */: return parseInferType(); @@ -20001,7 +20293,8 @@ var ts; } function parseJsxText() { var node = createNode(11 /* JsxText */); - node.containsOnlyWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */; + node.text = scanner.getTokenValue(); + node.containsOnlyTriviaWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */; currentToken = scanner.scanJsxToken(); return finishNode(node); } @@ -21816,8 +22109,8 @@ var ts; var JSDocParser; (function (JSDocParser) { function parseJSDocTypeExpressionForTests(content, start, length) { - initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); - sourceFile = createSourceFile("file.js", 6 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false); + initializeState(content, 7 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + sourceFile = createSourceFile("file.js", 7 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false); scanner.setText(content, start, length); currentToken = scanner.scan(); var jsDocTypeExpression = parseJSDocTypeExpression(); @@ -21828,7 +22121,7 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(283 /* JSDocTypeExpression */); + var result = createNode(288 /* JSDocTypeExpression */); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */); result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { @@ -21839,7 +22132,7 @@ var ts; } JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression; function parseIsolatedJSDocComment(content, start, length) { - initializeState(content, 6 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); + initializeState(content, 7 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); sourceFile = { languageVariant: 0 /* Standard */, text: content }; // tslint:disable-line no-object-literal-type-assertion var jsDoc = parseJSDocCommentWorker(start, length); var diagnostics = parseDiagnostics; @@ -21991,7 +22284,7 @@ var ts; } } function createJSDocComment() { - var result = createNode(291 /* JSDocComment */, start); + var result = createNode(296 /* JSDocComment */, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); @@ -22158,7 +22451,7 @@ var ts; return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(start, tagName) { - var result = createNode(294 /* JSDocTag */, start); + var result = createNode(299 /* JSDocTag */, start); result.tagName = tagName; return finishNode(result); } @@ -22217,8 +22510,8 @@ var ts; typeExpression = tryParseTypeExpression(); } var result = target === 1 /* Property */ ? - createNode(305 /* JSDocPropertyTag */, start) : - createNode(299 /* JSDocParameterTag */, start); + createNode(310 /* JSDocPropertyTag */, start) : + createNode(304 /* JSDocParameterTag */, start); var comment = parseTagComments(indent + scanner.getStartPos() - start); var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { @@ -22235,18 +22528,18 @@ var ts; } function parseNestedTypeLiteral(typeExpression, name, target, indent) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(283 /* JSDocTypeExpression */, scanner.getTokenPos()); + var typeLiteralExpression = createNode(288 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { - if (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) { + if (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) { children = ts.append(children, child); } } if (children) { - jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; if (typeExpression.type.kind === 169 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; @@ -22257,25 +22550,25 @@ var ts; } } function parseReturnTag(start, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 300 /* JSDocReturnTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 305 /* JSDocReturnTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(300 /* JSDocReturnTag */, start); + var result = createNode(305 /* JSDocReturnTag */, start); result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(start, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 302 /* JSDocTypeTag */; })) { + if (ts.forEach(tags, function (t) { return t.kind === 307 /* JSDocTypeTag */; })) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(302 /* JSDocTypeTag */, start); + var result = createNode(307 /* JSDocTypeTag */, start); result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); return finishNode(result); } function parseAugmentsTag(start, tagName) { - var result = createNode(295 /* JSDocAugmentsTag */, start); + var result = createNode(300 /* JSDocAugmentsTag */, start); result.tagName = tagName; result.class = parseExpressionWithTypeArgumentsForAugments(); return finishNode(result); @@ -22302,19 +22595,19 @@ var ts; return node; } function parseClassTag(start, tagName) { - var tag = createNode(296 /* JSDocClassTag */, start); + var tag = createNode(301 /* JSDocClassTag */, start); tag.tagName = tagName; return finishNode(tag); } function parseThisTag(start, tagName) { - var tag = createNode(301 /* JSDocThisTag */, start); + var tag = createNode(306 /* JSDocThisTag */, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); return finishNode(tag); } function parseEnumTag(start, tagName) { - var tag = createNode(298 /* JSDocEnumTag */, start); + var tag = createNode(303 /* JSDocEnumTag */, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); @@ -22323,7 +22616,7 @@ var ts; function parseTypedefTag(start, tagName, indent) { var typeExpression = tryParseTypeExpression(); skipWhitespaceOrAsterisk(); - var typedefTag = createNode(304 /* JSDocTypedefTag */, start); + var typedefTag = createNode(309 /* JSDocTypedefTag */, start); typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(); typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); @@ -22337,9 +22630,9 @@ var ts; var childTypeTag = void 0; while (child = tryParse(function () { return parseChildPropertyTag(indent); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, start); + jsdocTypeLiteral = createNode(297 /* JSDocTypeLiteral */, start); } - if (child.kind === 302 /* JSDocTypeTag */) { + if (child.kind === 307 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -22385,14 +22678,14 @@ var ts; return typeNameOrNamespaceName; } function parseCallbackTag(start, tagName, indent) { - var callbackTag = createNode(297 /* JSDocCallbackTag */, start); + var callbackTag = createNode(302 /* JSDocCallbackTag */, start); callbackTag.tagName = tagName; callbackTag.fullName = parseJSDocTypeNameWithNamespace(); callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); skipWhitespace(); callbackTag.comment = parseTagComments(indent); var child; - var jsdocSignature = createNode(293 /* JSDocSignature */, start); + var jsdocSignature = createNode(298 /* JSDocSignature */, start); jsdocSignature.parameters = []; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) { jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); @@ -22400,7 +22693,7 @@ var ts; var returnTag = tryParse(function () { if (parseOptionalJsdoc(58 /* AtToken */)) { var tag = parseTag(indent); - if (tag && tag.kind === 300 /* JSDocReturnTag */) { + if (tag && tag.kind === 305 /* JSDocReturnTag */) { return tag; } } @@ -22445,7 +22738,7 @@ var ts; case 58 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target, indent); - if (child && (child.kind === 299 /* JSDocParameterTag */ || child.kind === 305 /* JSDocPropertyTag */) && + if (child && (child.kind === 304 /* JSDocParameterTag */ || child.kind === 310 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -22515,7 +22808,7 @@ var ts; skipWhitespace(); typeParameters.push(typeParameter); } while (parseOptionalJsdoc(27 /* CommaToken */)); - var result = createNode(303 /* JSDocTemplateTag */, start); + var result = createNode(308 /* JSDocTemplateTag */, start); result.tagName = tagName; result.constraint = constraint; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -23293,6 +23586,7 @@ var ts; ["es2016", "lib.es2016.d.ts"], ["es2017", "lib.es2017.d.ts"], ["es2018", "lib.es2018.d.ts"], + ["es2019", "lib.es2019.d.ts"], ["esnext", "lib.esnext.d.ts"], // Host only ["dom", "lib.dom.d.ts"], @@ -23316,12 +23610,16 @@ var ts; ["es2017.string", "lib.es2017.string.d.ts"], ["es2017.intl", "lib.es2017.intl.d.ts"], ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"], + ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"], ["es2018.intl", "lib.es2018.intl.d.ts"], ["es2018.promise", "lib.es2018.promise.d.ts"], ["es2018.regexp", "lib.es2018.regexp.d.ts"], - ["esnext.array", "lib.esnext.array.d.ts"], - ["esnext.symbol", "lib.esnext.symbol.d.ts"], - ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], + ["es2019.array", "lib.es2019.array.d.ts"], + ["es2019.string", "lib.es2019.string.d.ts"], + ["es2019.symbol", "lib.es2019.symbol.d.ts"], + ["esnext.array", "lib.es2019.array.d.ts"], + ["esnext.symbol", "lib.es2019.symbol.d.ts"], + ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"], ["esnext.intl", "lib.esnext.intl.d.ts"], ["esnext.bigint", "lib.esnext.bigint.d.ts"] ]; @@ -23467,14 +23765,15 @@ var ts; es2016: 3 /* ES2016 */, es2017: 4 /* ES2017 */, es2018: 5 /* ES2018 */, - esnext: 6 /* ESNext */, + es2019: 6 /* ES2019 */, + esnext: 7 /* ESNext */, }), affectsSourceFile: true, affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT, }, { name: "module", @@ -23595,6 +23894,22 @@ var ts; category: ts.Diagnostics.Basic_Options, description: ts.Diagnostics.Enable_project_compilation, }, + { + name: "incremental", + type: "boolean", + isTSConfigOnly: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Enable_incremental_compilation, + }, + { + name: "tsBuildInfoFile", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.FILE, + isTSConfigOnly: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information, + }, { name: "removeComments", type: "boolean", @@ -25021,7 +25336,7 @@ var ts; } function directoryOfCombinedPath(fileName, basePath) { // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical - // until consistient casing errors are reported + // until consistent casing errors are reported return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); } /** @@ -27313,7 +27628,7 @@ var ts; return "__constructor" /* Constructor */; case 165 /* FunctionType */: case 160 /* CallSignature */: - case 293 /* JSDocSignature */: + case 298 /* JSDocSignature */: return "__call" /* Call */; case 166 /* ConstructorType */: case 161 /* ConstructSignature */: @@ -27322,7 +27637,7 @@ var ts; return "__index" /* Index */; case 255 /* ExportDeclaration */: return "__export" /* ExportStar */; - case 279 /* SourceFile */: + case 284 /* SourceFile */: // json file should behave as // module.exports = ... return "export=" /* ExportEquals */; @@ -27333,12 +27648,12 @@ var ts; } ts.Debug.fail("Unknown binary declaration kind"); break; - case 289 /* JSDocFunctionType */: + case 294 /* JSDocFunctionType */: return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); case 151 /* Parameter */: // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 289 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + ts.Debug.assert(node.parent.kind === 294 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); var functionType = node.parent; var index = functionType.parameters.indexOf(node); return "arg" + index; @@ -27422,13 +27737,15 @@ var ts; message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations; messageNeedsName_1 = false; } - if (symbol.declarations && symbol.declarations.length) { + var multipleDefaultExports_1 = false; + if (ts.length(symbol.declarations)) { // If the current node is a default export of some sort, then check if // there are any other default exports that we need to error on. // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName_1 = false; + multipleDefaultExports_1 = true; } else { // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. @@ -27439,14 +27756,22 @@ var ts; (node.kind === 254 /* ExportAssignment */ && !node.isExportEquals)) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName_1 = false; + multipleDefaultExports_1 = true; } } } - var addError = function (decl) { - file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(decl) || decl, message_1, messageNeedsName_1 ? getDisplayName(decl) : undefined)); - }; - ts.forEach(symbol.declarations, addError); - addError(node); + var declarationName_1 = ts.getNameOfDeclaration(node) || node; + var relatedInformation_1 = []; + ts.forEach(symbol.declarations, function (declaration, index) { + var decl = ts.getNameOfDeclaration(declaration) || declaration; + var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined); + file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo(diag, createDiagnosticForNode(declarationName_1, index === 0 ? ts.Diagnostics.Another_export_default_is_here : ts.Diagnostics.and_here)) : diag); + if (multipleDefaultExports_1) { + relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here)); + } + }); + var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined); + file.bindDiagnostics.push(multipleDefaultExports_1 ? ts.addRelatedInfo.apply(void 0, [diag].concat(relatedInformation_1)) : diag); symbol = createSymbol(0 /* None */, name); } } @@ -27562,7 +27887,7 @@ var ts; } } // We create a return control flow graph for IIFEs and constructors. For constructors - // we use the return control flow graph in strict property intialization checks. + // we use the return control flow graph in strict property initialization checks. currentReturnTarget = isIIFE || node.kind === 157 /* Constructor */ ? createBranchLabel() : undefined; currentBreakTarget = undefined; currentContinueTarget = undefined; @@ -27577,7 +27902,7 @@ var ts; if (hasExplicitReturn) node.flags |= 256 /* HasExplicitReturn */; } - if (node.kind === 279 /* SourceFile */) { + if (node.kind === 284 /* SourceFile */) { node.flags |= emitFlags; } if (currentReturnTarget) { @@ -27721,12 +28046,12 @@ var ts; case 191 /* CallExpression */: bindCallExpressionFlow(node); break; - case 304 /* JSDocTypedefTag */: - case 297 /* JSDocCallbackTag */: + case 309 /* JSDocTypedefTag */: + case 302 /* JSDocCallbackTag */: bindJSDocTypeAlias(node); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime - case 279 /* SourceFile */: { + case 284 /* SourceFile */: { bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); break; @@ -28413,7 +28738,7 @@ var ts; case 243 /* EnumDeclaration */: case 188 /* ObjectLiteralExpression */: case 168 /* TypeLiteral */: - case 292 /* JSDocTypeLiteral */: + case 297 /* JSDocTypeLiteral */: case 268 /* JsxAttributes */: return 1 /* IsContainer */; case 241 /* InterfaceDeclaration */: @@ -28422,7 +28747,7 @@ var ts; case 242 /* TypeAliasDeclaration */: case 181 /* MappedType */: return 1 /* IsContainer */ | 32 /* HasLocals */; - case 279 /* SourceFile */: + case 284 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; case 156 /* MethodDeclaration */: if (ts.isObjectLiteralOrClassExpressionMethod(node)) { @@ -28435,8 +28760,8 @@ var ts; case 158 /* GetAccessor */: case 159 /* SetAccessor */: case 160 /* CallSignature */: - case 293 /* JSDocSignature */: - case 289 /* JSDocFunctionType */: + case 298 /* JSDocSignature */: + case 294 /* JSDocFunctionType */: case 165 /* FunctionType */: case 161 /* ConstructSignature */: case 162 /* IndexSignature */: @@ -28490,7 +28815,7 @@ var ts; // handlers to take care of declaring these child members. case 244 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); - case 279 /* SourceFile */: + case 284 /* SourceFile */: return declareSourceFileMember(node, symbolFlags, symbolExcludes); case 209 /* ClassExpression */: case 240 /* ClassDeclaration */: @@ -28498,7 +28823,7 @@ var ts; case 243 /* EnumDeclaration */: return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); case 168 /* TypeLiteral */: - case 292 /* JSDocTypeLiteral */: + case 297 /* JSDocTypeLiteral */: case 188 /* ObjectLiteralExpression */: case 241 /* InterfaceDeclaration */: case 268 /* JsxAttributes */: @@ -28512,7 +28837,7 @@ var ts; case 166 /* ConstructorType */: case 160 /* CallSignature */: case 161 /* ConstructSignature */: - case 293 /* JSDocSignature */: + case 298 /* JSDocSignature */: case 162 /* IndexSignature */: case 156 /* MethodDeclaration */: case 155 /* MethodSignature */: @@ -28522,9 +28847,9 @@ var ts; case 239 /* FunctionDeclaration */: case 196 /* FunctionExpression */: case 197 /* ArrowFunction */: - case 289 /* JSDocFunctionType */: - case 304 /* JSDocTypedefTag */: - case 297 /* JSDocCallbackTag */: + case 294 /* JSDocFunctionType */: + case 309 /* JSDocTypedefTag */: + case 302 /* JSDocCallbackTag */: case 242 /* TypeAliasDeclaration */: case 181 /* MappedType */: // All the children of these container types are never visible through another @@ -28547,8 +28872,8 @@ var ts; : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } function hasExportDeclarations(node) { - var body = node.kind === 279 /* SourceFile */ ? node : node.body; - if (body && (body.kind === 279 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) { + var body = node.kind === 284 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 284 /* SourceFile */ || body.kind === 245 /* ModuleBlock */)) { for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { var stat = _a[_i]; if (stat.kind === 255 /* ExportDeclaration */ || stat.kind === 254 /* ExportAssignment */) { @@ -28682,7 +29007,7 @@ var ts; case 244 /* ModuleDeclaration */: declareModuleMember(node, symbolFlags, symbolExcludes); break; - case 279 /* SourceFile */: + case 284 /* SourceFile */: if (ts.isExternalOrCommonJsModule(container)) { declareModuleMember(node, symbolFlags, symbolExcludes); break; @@ -28820,7 +29145,7 @@ var ts; function checkStrictModeFunctionDeclaration(node) { if (languageVersion < 2 /* ES2015 */) { // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 279 /* SourceFile */ && + if (blockScopeContainer.kind !== 284 /* SourceFile */ && blockScopeContainer.kind !== 244 /* ModuleDeclaration */ && !ts.isFunctionLike(blockScopeContainer)) { // We check first if the name is inside class declaration or class expression; if so give explicit message @@ -29095,12 +29420,12 @@ var ts; case 159 /* SetAccessor */: return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67187647 /* SetAccessorExcludes */); case 165 /* FunctionType */: - case 289 /* JSDocFunctionType */: - case 293 /* JSDocSignature */: + case 294 /* JSDocFunctionType */: + case 298 /* JSDocSignature */: case 166 /* ConstructorType */: return bindFunctionOrConstructorType(node); case 168 /* TypeLiteral */: - case 292 /* JSDocTypeLiteral */: + case 297 /* JSDocTypeLiteral */: case 181 /* MappedType */: return bindAnonymousTypeWorker(node); case 188 /* ObjectLiteralExpression */: @@ -29159,7 +29484,7 @@ var ts; return bindExportDeclaration(node); case 254 /* ExportAssignment */: return bindExportAssignment(node); - case 279 /* SourceFile */: + case 284 /* SourceFile */: updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); case 218 /* Block */: @@ -29169,22 +29494,22 @@ var ts; // falls through case 245 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 299 /* JSDocParameterTag */: - if (node.parent.kind === 293 /* JSDocSignature */) { + case 304 /* JSDocParameterTag */: + if (node.parent.kind === 298 /* JSDocSignature */) { return bindParameter(node); } - if (node.parent.kind !== 292 /* JSDocTypeLiteral */) { + if (node.parent.kind !== 297 /* JSDocTypeLiteral */) { break; } // falls through - case 305 /* JSDocPropertyTag */: + case 310 /* JSDocPropertyTag */: var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 288 /* JSDocOptionalType */ ? + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 293 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 304 /* JSDocTypedefTag */: - case 297 /* JSDocCallbackTag */: + case 309 /* JSDocTypedefTag */: + case 302 /* JSDocCallbackTag */: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } @@ -29356,9 +29681,14 @@ var ts; var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); break; - case 279 /* SourceFile */: - // this.foo assignment in a source file - // Do not bind. It would be nice to support this someday though. + case 284 /* SourceFile */: + // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script + if (thisContainer.commonJsModuleIndicator) { + declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67220414 /* FunctionScopedVariableExcludes */); + } break; default: ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer)); @@ -29368,7 +29698,7 @@ var ts; if (node.expression.kind === 100 /* ThisKeyword */) { bindThisPropertyAssignment(node); } - else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 279 /* SourceFile */) { + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 284 /* SourceFile */) { if (ts.isPrototypeAccess(node.expression)) { bindPrototypePropertyAssignment(node, node.parent); } @@ -29405,7 +29735,7 @@ var ts; } function bindObjectDefinePropertyAssignment(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]); - var isToplevel = node.parent.parent.kind === 279 /* SourceFile */; + var isToplevel = node.parent.parent.kind === 284 /* SourceFile */; namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false); bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false); } @@ -29472,8 +29802,8 @@ var ts; function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { var namespaceSymbol = lookupSymbolForPropertyAccess(name); var isToplevel = ts.isBinaryExpression(propertyAccess.parent) - ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 279 /* SourceFile */ - : propertyAccess.parent.parent.kind === 279 /* SourceFile */; + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 284 /* SourceFile */ + : propertyAccess.parent.parent.kind === 284 /* SourceFile */; namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty); bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty); } @@ -29611,7 +29941,7 @@ var ts; } } function bindParameter(node) { - if (node.kind === 299 /* JSDocParameterTag */ && container.kind !== 293 /* JSDocSignature */) { + if (node.kind === 304 /* JSDocParameterTag */ && container.kind !== 298 /* JSDocSignature */) { return; } if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { @@ -29869,44 +30199,37 @@ var ts; ts.computeTransformFlagsForNode = computeTransformFlagsForNode; function computeCallExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; + var callee = ts.skipOuterExpressions(node.expression); var expression = node.expression; if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } - if (subtreeFlags & 131072 /* ContainsRestOrSpread */ - || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { + if (subtreeFlags & 4096 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. - transformFlags |= 192 /* AssertES2015 */; - // super property or element accesses could be inside lambdas, etc, and need a captured `this`, - // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 67108864 /* ContainsSuper */) { - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 128 /* AssertES2015 */; + if (ts.isSuperProperty(callee)) { + transformFlags |= 2048 /* ContainsLexicalThis */; } } if (expression.kind === 92 /* ImportKeyword */) { - transformFlags |= 16777216 /* ContainsDynamicImport */; - // A dynamic 'import()' call that contains a lexical 'this' will - // require a captured 'this' when emitting down-level. - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - transformFlags |= 16384 /* ContainsCapturedLexicalThis */; - } + transformFlags |= 524288 /* ContainsDynamicImport */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } - if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + if (subtreeFlags & 4096 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -29914,20 +30237,20 @@ var ts; var leftKind = node.left.kind; if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) { // Destructuring object assignments with are ES2015 syntax - // and possibly ESNext if they contain rest - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + // and possibly ES2018 if they contain rest + transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */; } else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) { // Destructuring assignments are ES2015 syntax. - transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + transformFlags |= 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */; } else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */ || operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) { // Exponentiation is ES2016 syntax. - transformFlags |= 32 /* AssertES2016 */; + transformFlags |= 64 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -29938,147 +30261,131 @@ var ts; // syntax. if (node.questionToken || node.type - || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) + || (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */; } - // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 8 /* AssertESNext */; + // parameters with object rest destructuring are ES2018 syntax + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 65536 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* ParameterExcludes */; + return transformFlags & ~536870912 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; - var expressionTransformFlags = expression.transformFlags; // If the node is synthesized, it means the emitter put the parentheses there, // not the user. If we didn't want them, the emitter would not have put them // there. if (expressionKind === 212 /* AsExpression */ || expressionKind === 194 /* TypeAssertionExpression */) { - transformFlags |= 3 /* AssertTypeScript */; - } - // If the expression of a ParenthesizedExpression is a destructuring assignment, - // then the ParenthesizedExpression is a destructuring assignment. - if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 1024 /* DestructuringAssignment */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* OuterExpressionExcludes */; + return transformFlags & ~536870912 /* OuterExpressionExcludes */; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; if (ts.hasModifier(node, 2 /* Ambient */)) { // An ambient declaration is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; + transformFlags = 1 /* AssertTypeScript */; } else { // A ClassDeclaration is ES6 syntax. - transformFlags = subtreeFlags | 192 /* AssertES2015 */; + transformFlags = subtreeFlags | 128 /* AssertES2015 */; // 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. - if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) + if ((subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 1 /* AssertTypeScript */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~638121281 /* ClassExcludes */; + return transformFlags & ~536888320 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ + if (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~638121281 /* ClassExcludes */; + return transformFlags & ~536888320 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { case 86 /* ExtendsKeyword */: // An `extends` HeritageClause is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; break; case 109 /* ImplementsKeyword */: // An `implements` HeritageClause is TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; break; default: ts.Debug.fail("Unexpected token for heritage clause"); break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; if (!node.variableDeclaration) { - transformFlags |= 8 /* AssertESNext */; + transformFlags |= 8 /* AssertES2019 */; } else if (ts.isBindingPattern(node.variableDeclaration.name)) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637797697 /* CatchClauseExcludes */; + return transformFlags & ~536879104 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the // extends clause of a class. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // If an ExpressionWithTypeArguments contains type arguments, then it // is TypeScript syntax. if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; // TypeScript-specific modifiers and overloads are TypeScript syntax if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 8 /* AssertESNext */; + // function declarations with object rest destructuring are ES2018 syntax + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653616449 /* ConstructorExcludes */; + return transformFlags & ~537372672 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and // overloads are TypeScript syntax. if (node.decorators @@ -30087,21 +30394,21 @@ var ts; || node.type || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 8 /* AssertESNext */; + // function declarations with object rest destructuring are ES2018 syntax + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // An async method declaration is ES2017 syntax. if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */; } if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; + transformFlags |= 256 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */); } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30112,25 +30419,25 @@ var ts; || node.type || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 8 /* AssertESNext */; + // function declarations with object rest destructuring are ES2018 syntax + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */); } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. - var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; + var transformFlags = subtreeFlags | 1 /* AssertTypeScript */; // 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 || ts.isComputedPropertyName(node.name)) { - transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; + transformFlags |= 1024 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return propagatePropertyNameFlags(node.name, transformFlags & ~536872960 /* PropertyExcludes */); } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -30139,42 +30446,36 @@ var ts; if (!body || (modifierFlags & 2 /* Ambient */)) { // An ambient declaration is TypeScript syntax. // A FunctionDeclaration without a body is an overload and is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; + transformFlags = 1 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ || node.typeParameters || node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // An async function declaration is ES2017 syntax. if (modifierFlags & 256 /* Async */) { - transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; - } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 8 /* AssertESNext */; + transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */; } - // If a FunctionDeclaration's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; + // function declarations with object rest destructuring are ES2018 syntax + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // If a FunctionDeclaration is generator function and is the body of a // transformed async function, then this node can be transformed to a // down-level generator. - // Currently we do not support transforming any other generator fucntions + // Currently we do not support transforming any other generator functions // down level. if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; + transformFlags |= 256 /* AssertGenerator */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653620545 /* FunctionExcludes */; + return transformFlags & ~537373696 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30183,181 +30484,161 @@ var ts; if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // An async function expression is ES2017 syntax. if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */; } - // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 8 /* AssertESNext */; - } - // If a FunctionExpression's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; + // function expressions with object rest destructuring are ES2018 syntax + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // If a FunctionExpression is generator function and is the body of a // transformed async function, then this node can be transformed to a // down-level generator. if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; + transformFlags |= 256 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653620545 /* FunctionExcludes */; + return transformFlags & ~537373696 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // An async arrow function is ES2017 syntax. if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= 16 /* AssertES2017 */; - } - // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 8 /* AssertESNext */; + transformFlags |= 32 /* AssertES2017 */; } - // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + // arrow functions with object rest destructuring are ES2018 syntax + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653604161 /* ArrowFunctionExcludes */; + return transformFlags & ~537371648 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 33554432 /* Super */) { - transformFlags ^= 33554432 /* Super */; + if (node.expression.kind === 98 /* SuperKeyword */) { // super inside of an async function requires hoisting the super access (ES2017). - // same for super inside of an async generator, which is ESNext. - transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; + // same for super inside of an async generator, which is ES2018. + transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~570426689 /* PropertyAccessExcludes */; + return transformFlags & ~536870912 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 33554432 /* Super */) { - transformFlags &= ~33554432 /* Super */; + if (node.expression.kind === 98 /* SuperKeyword */) { // super inside of an async function requires hoisting the super access (ES2017). - // same for super inside of an async generator, which is ESNext. - transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 8 /* ContainsESNext */; + // same for super inside of an async generator, which is ES2018. + transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~570426689 /* PropertyAccessExcludes */; + return transformFlags & ~536870912 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; - // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 8 /* AssertESNext */; + transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally? + // A VariableDeclaration containing ObjectRest is ES2018 syntax + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // Type annotations are TypeScript syntax. if (node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; var declarationListTransformFlags = node.declarationList.transformFlags; // An ambient declaration is TypeScript syntax. if (ts.hasModifier(node, 2 /* Ambient */)) { - transformFlags = 3 /* AssertTypeScript */; + transformFlags = 1 /* AssertTypeScript */; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; + if (declarationListTransformFlags & 65536 /* ContainsBindingPattern */) { + transformFlags |= 128 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; // An ImportEqualsDeclaration with a namespace reference is TypeScript. if (!ts.isExternalModuleImportEqualsDeclaration(node)) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - // If the expression of an expression statement is a destructuring assignment, - // then we treat the statement as ES6 so that we can indicate that we do not - // need to hold on to the right-hand side. - if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 192 /* AssertES2015 */; - } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { - var transformFlags = 3 /* AssertTypeScript */; + var transformFlags = 1 /* AssertTypeScript */; var modifierFlags = ts.getModifierFlags(node); if ((modifierFlags & 2 /* Ambient */) === 0) { transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~647001409 /* ModuleExcludes */; + return transformFlags & ~537168896 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 65536 /* ContainsBindingPattern */) { + transformFlags |= 128 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; + transformFlags |= 128 /* AssertES2015 */ | 32768 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; + return transformFlags & ~536944640 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 637535553 /* NodeExcludes */; + var excludeFlags = 536870912 /* NodeExcludes */; switch (kind) { case 121 /* AsyncKeyword */: case 201 /* AwaitExpression */: - // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) - transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; + // async/await is ES2017 syntax, but may be ES2018 syntax (for async generators) + transformFlags |= 16 /* AssertES2018 */ | 32 /* AssertES2017 */; break; case 194 /* TypeAssertionExpression */: case 212 /* AsExpression */: - case 308 /* PartiallyEmittedExpression */: + case 313 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; - excludeFlags = 536872257 /* OuterExpressionExcludes */; + transformFlags |= 1 /* AssertTypeScript */; + excludeFlags = 536870912 /* OuterExpressionExcludes */; break; case 115 /* PublicKeyword */: case 113 /* PrivateKeyword */: @@ -30370,7 +30651,7 @@ var ts; case 213 /* NonNullExpression */: case 133 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; break; case 260 /* JsxElement */: case 261 /* JsxSelfClosingElement */: @@ -30385,7 +30666,7 @@ var ts; case 269 /* JsxSpreadAttribute */: case 270 /* JsxExpression */: // These nodes are Jsx syntax. - transformFlags |= 4 /* AssertJsx */; + transformFlags |= 2 /* AssertJsx */; break; case 14 /* NoSubstitutionTemplateLiteral */: case 15 /* TemplateHead */: @@ -30397,32 +30678,32 @@ var ts; case 116 /* StaticKeyword */: case 214 /* MetaProperty */: // These nodes are ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; break; case 10 /* StringLiteral */: if (node.hasExtendedUnicodeEscape) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } break; case 8 /* NumericLiteral */: if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } break; case 9 /* BigIntLiteral */: - transformFlags |= 8 /* AssertESNext */; + transformFlags |= 4 /* AssertESNext */; break; case 227 /* ForOfStatement */: // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). if (node.awaitModifier) { - transformFlags |= 8 /* AssertESNext */; + transformFlags |= 16 /* AssertES2018 */; } - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; break; case 207 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; + transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 131072 /* ContainsYield */; break; case 120 /* AnyKeyword */: case 135 /* NumberKeyword */: @@ -30463,115 +30744,93 @@ var ts; case 182 /* LiteralType */: case 247 /* NamespaceExportDeclaration */: // Types and signatures are TypeScript syntax, and exclude all other facts. - transformFlags = 3 /* AssertTypeScript */; - excludeFlags = -3 /* TypeExcludes */; + transformFlags = 1 /* AssertTypeScript */; + excludeFlags = -2 /* TypeExcludes */; break; case 149 /* ComputedPropertyName */: // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 524288 /* ContainsComputedPropertyName */; - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - // A computed method name like `[this.getName()](x: string) { ... }` needs to - // distinguish itself from the normal case of a method body containing `this`: - // `this` inside a method doesn't need to be rewritten (the method provides `this`), - // whereas `this` inside a computed name *might* need to be rewritten if the class/object - // is inside an arrow function: - // `_this = this; () => class K { [_this.getName()]() { ... } }` - // To make this distinction, use ContainsLexicalThisInComputedPropertyName - // instead of ContainsLexicalThis for computed property names - transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; - } + transformFlags |= 16384 /* ContainsComputedPropertyName */; break; case 208 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; + transformFlags |= 128 /* AssertES2015 */ | 4096 /* ContainsRestOrSpread */; break; case 277 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; + transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */; break; case 98 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; - excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` + transformFlags |= 128 /* AssertES2015 */; + excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 100 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 2048 /* ContainsLexicalThis */; break; case 184 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; - if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { - transformFlags |= 8 /* AssertESNext */ | 262144 /* ContainsObjectRestOrSpread */; + transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; + if (subtreeFlags & 4096 /* ContainsRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */; } - excludeFlags = 637666625 /* BindingPatternExcludes */; + excludeFlags = 536875008 /* BindingPatternExcludes */; break; case 185 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; - excludeFlags = 637666625 /* BindingPatternExcludes */; + transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; + excludeFlags = 536875008 /* BindingPatternExcludes */; break; case 186 /* BindingElement */: - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 131072 /* ContainsRestOrSpread */; + transformFlags |= 4096 /* ContainsRestOrSpread */; } break; case 152 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */; break; case 188 /* ObjectLiteralExpression */: - excludeFlags = 638358849 /* ObjectLiteralExcludes */; - if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { + excludeFlags = 536896512 /* ObjectLiteralExcludes */; + if (subtreeFlags & 16384 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; - } - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it - // is an ES next node. - transformFlags |= 8 /* AssertESNext */; + // is an ES2018 node. + transformFlags |= 16 /* AssertES2018 */; } break; case 187 /* ArrayLiteralExpression */: - case 192 /* NewExpression */: - excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { - // If the this node contains a SpreadExpression, then it is an ES6 - // node. - transformFlags |= 192 /* AssertES2015 */; - } + excludeFlags = 536875008 /* ArrayLiteralOrCallOrNewExcludes */; break; case 223 /* DoStatement */: case 224 /* WhileStatement */: case 225 /* ForStatement */: case 226 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { - transformFlags |= 192 /* AssertES2015 */; + if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */) { + transformFlags |= 128 /* AssertES2015 */; } break; - case 279 /* SourceFile */: - if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { - transformFlags |= 192 /* AssertES2015 */; - } + case 284 /* SourceFile */: break; case 230 /* ReturnStatement */: - // Return statements may require an `await` in ESNext. - transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + // Return statements may require an `await` in ES2018. + transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */ | 16 /* AssertES2018 */; break; case 228 /* ContinueStatement */: case 229 /* BreakStatement */: - transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~excludeFlags; } + function propagatePropertyNameFlags(node, transformFlags) { + return transformFlags | (node.transformFlags & 2048 /* PropertyNamePropagatingFlags */); + } /** * Gets the transform flags to exclude when unioning the transform flags of a subtree. * @@ -30581,33 +30840,33 @@ var ts; */ function getTransformFlagsSubtreeExclusions(kind) { if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) { - return -3 /* TypeExcludes */; + return -2 /* TypeExcludes */; } switch (kind) { case 191 /* CallExpression */: case 192 /* NewExpression */: case 187 /* ArrayLiteralExpression */: - return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + return 536875008 /* ArrayLiteralOrCallOrNewExcludes */; case 244 /* ModuleDeclaration */: - return 647001409 /* ModuleExcludes */; + return 537168896 /* ModuleExcludes */; case 151 /* Parameter */: - return 637535553 /* ParameterExcludes */; + return 536870912 /* ParameterExcludes */; case 197 /* ArrowFunction */: - return 653604161 /* ArrowFunctionExcludes */; + return 537371648 /* ArrowFunctionExcludes */; case 196 /* FunctionExpression */: case 239 /* FunctionDeclaration */: - return 653620545 /* FunctionExcludes */; + return 537373696 /* FunctionExcludes */; case 238 /* VariableDeclarationList */: - return 639894849 /* VariableDeclarationListExcludes */; + return 536944640 /* VariableDeclarationListExcludes */; case 240 /* ClassDeclaration */: case 209 /* ClassExpression */: - return 638121281 /* ClassExcludes */; + return 536888320 /* ClassExcludes */; case 157 /* Constructor */: - return 653616449 /* ConstructorExcludes */; + return 537372672 /* ConstructorExcludes */; case 156 /* MethodDeclaration */: case 158 /* GetAccessor */: case 159 /* SetAccessor */: - return 653616449 /* MethodOrAccessorExcludes */; + return 537372672 /* MethodOrAccessorExcludes */; case 120 /* AnyKeyword */: case 135 /* NumberKeyword */: case 146 /* BigIntKeyword */: @@ -30625,25 +30884,25 @@ var ts; case 162 /* IndexSignature */: case 241 /* InterfaceDeclaration */: case 242 /* TypeAliasDeclaration */: - return -3 /* TypeExcludes */; + return -2 /* TypeExcludes */; case 188 /* ObjectLiteralExpression */: - return 638358849 /* ObjectLiteralExcludes */; + return 536896512 /* ObjectLiteralExcludes */; case 274 /* CatchClause */: - return 637797697 /* CatchClauseExcludes */; + return 536879104 /* CatchClauseExcludes */; case 184 /* ObjectBindingPattern */: case 185 /* ArrayBindingPattern */: - return 637666625 /* BindingPatternExcludes */; + return 536875008 /* BindingPatternExcludes */; case 194 /* TypeAssertionExpression */: case 212 /* AsExpression */: - case 308 /* PartiallyEmittedExpression */: + case 313 /* PartiallyEmittedExpression */: case 195 /* ParenthesizedExpression */: case 98 /* SuperKeyword */: - return 536872257 /* OuterExpressionExcludes */; + return 536870912 /* OuterExpressionExcludes */; case 189 /* PropertyAccessExpression */: case 190 /* ElementAccessExpression */: - return 570426689 /* PropertyAccessExcludes */; + return 536870912 /* PropertyAccessExcludes */; default: - return 637535553 /* NodeExcludes */; + return 536870912 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -30892,6 +31151,7 @@ var ts; var enumCount = 0; var instantiationDepth = 0; var constraintDepth = 0; + var currentNode; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); @@ -30908,8 +31168,14 @@ var ts; var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */; var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); + var globals = ts.createSymbolTable(); var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); undefinedSymbol.declarations = []; + var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */); + globalThisSymbol.exports = globals; + globalThisSymbol.valueDeclaration = ts.createNode(72 /* Identifier */); + globalThisSymbol.valueDeclaration.escapedText = "globalThis"; + globals.set(globalThisSymbol.escapedName, globalThisSymbol); var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); var requireSymbol = createSymbol(4 /* Property */, "require"); /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ @@ -31039,11 +31305,13 @@ var ts; isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, getResolvedSignature: function (node, candidatesOutArray, agumentCount) { - return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ false); + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 0 /* Normal */); }, getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, agumentCount) { - return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, /*isForSignatureHelp*/ true); + return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16 /* IsForSignatureHelp */); }, + getExpandedParameters: getExpandedParameters, + hasEffectiveRestParameter: hasEffectiveRestParameter, getConstantValue: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; @@ -31105,6 +31373,8 @@ var ts; getNeverType: function () { return neverType; }, isSymbolAccessible: isSymbolAccessible, getObjectFlags: ts.getObjectFlags, + isArrayType: isArrayType, + isTupleType: isTupleType, isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, @@ -31120,9 +31390,9 @@ var ts; getAccessibleSymbolChain: getAccessibleSymbolChain, getTypePredicateOfSignature: getTypePredicateOfSignature, resolveExternalModuleSymbol: resolveExternalModuleSymbol, - tryGetThisTypeAt: function (node) { + tryGetThisTypeAt: function (node, includeGlobalThis) { node = ts.getParseTreeNode(node); - return node && tryGetThisTypeAt(node); + return node && tryGetThisTypeAt(node, includeGlobalThis); }, getTypeArgumentConstraint: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); @@ -31169,10 +31439,10 @@ var ts; }, getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; - function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { + function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); apparentArgumentCount = argumentCount; - var res = node ? getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) : undefined; + var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined; apparentArgumentCount = undefined; return res; } @@ -31181,6 +31451,7 @@ var ts; var intersectionTypes = ts.createMap(); var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); + var conditionalTypes = ts.createMap(); var evolvingArrayTypes = []; var undefinedProperties = ts.createMap(); var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -31190,10 +31461,10 @@ var ts; var wildcardType = createIntrinsicType(1 /* Any */, "any"); var errorType = createIntrinsicType(1 /* Any */, "error"); var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); - var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined"); - var nullType = createIntrinsicType(65536 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */ | 134217728 /* ContainsWideningType */, "null"); + var undefinedType = createNullableType(32768 /* Undefined */, "undefined", 0); + var undefinedWideningType = strictNullChecks ? undefinedType : createNullableType(32768 /* Undefined */, "undefined", 131072 /* ContainsWideningType */); + var nullType = createNullableType(65536 /* Null */, "null", 0); + var nullWideningType = strictNullChecks ? nullType : createNullableType(65536 /* Null */, "null", 131072 /* ContainsWideningType */); var stringType = createIntrinsicType(4 /* String */, "string"); var numberType = createIntrinsicType(8 /* Number */, "number"); var bigintType = createIntrinsicType(64 /* BigInt */, "bigint"); @@ -31235,7 +31506,7 @@ var ts; var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.flags |= 536870912 /* ContainsAnyFunctionType */; + anyFunctionType.objectFlags |= 524288 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); @@ -31249,7 +31520,6 @@ var ts; var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); - var globals = ts.createSymbolTable(); /** Key is "/path/to/a.ts|/path/to/b.ts". */ var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); @@ -31448,9 +31718,11 @@ var ts; var CheckMode; (function (CheckMode) { CheckMode[CheckMode["Normal"] = 0] = "Normal"; - CheckMode[CheckMode["SkipContextSensitive"] = 1] = "SkipContextSensitive"; + CheckMode[CheckMode["Contextual"] = 1] = "Contextual"; CheckMode[CheckMode["Inferential"] = 2] = "Inferential"; - CheckMode[CheckMode["Contextual"] = 3] = "Contextual"; + CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive"; + CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions"; + CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp"; })(CheckMode || (CheckMode = {})); var CallbackCheck; (function (CallbackCheck) { @@ -31537,18 +31809,6 @@ var ts; return diagnostic; } } - function addRelatedInfo(diagnostic) { - var relatedInformation = []; - for (var _i = 1; _i < arguments.length; _i++) { - relatedInformation[_i - 1] = arguments[_i]; - } - var _a; - if (!diagnostic.relatedInformation) { - diagnostic.relatedInformation = []; - } - (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation); - return diagnostic; - } function error(location, message, arg0, arg1, arg2, arg3) { var diagnostic = location ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) @@ -31728,7 +31988,7 @@ var ts; err.relatedInformation = err.relatedInformation || []; if (ts.length(err.relatedInformation) >= 5) continue; - addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); + ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } function combineSymbolTables(first, second) { @@ -31806,7 +32066,7 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } function isGlobalSourceFile(node) { - return node.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -31980,7 +32240,7 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 291 /* JSDocComment */) { + if (meaning & result.flags & 67897832 /* Type */ && lastLocation.kind !== 296 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || @@ -32022,14 +32282,14 @@ var ts; } } switch (location.kind) { - case 279 /* SourceFile */: + case 284 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; // falls through case 244 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location)) { + if (location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location)) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports.get("default" /* Default */)) { @@ -32197,12 +32457,18 @@ var ts; // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method. // } // - if (location.parent && ts.isClassElement(location.parent)) { + // class Decorators are resolved outside of the class to avoid referencing type parameters of that class. + // + // type T = number; + // declare function y(x: T): any; + // @param(1 as T) // <-- T should resolve to the type alias outside of class C + // class C {} + if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 240 /* ClassDeclaration */)) { location = location.parent; } break; - case 304 /* JSDocTypedefTag */: - case 297 /* JSDocCallbackTag */: + case 309 /* JSDocTypedefTag */: + case 302 /* JSDocCallbackTag */: // js type aliases do not resolve names from their host, so skip past it location = ts.getJSDocHost(location); break; @@ -32221,7 +32487,7 @@ var ts; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 279 /* SourceFile */); + ts.Debug.assert(lastLocation.kind === 284 /* SourceFile */); if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) { return lastLocation.symbol; } @@ -32244,7 +32510,8 @@ var ts; !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { + !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && + !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); @@ -32252,7 +32519,7 @@ var ts; var suggestionName = symbolToString(suggestion); var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); if (suggestion.valueDeclaration) { - addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); } } } @@ -32409,6 +32676,16 @@ var ts; } return false; } + function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) { + if (meaning & (67897832 /* Type */ & ~1920 /* Namespace */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, ~67897832 /* Type */ & 67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (symbol && !(symbol.flags & 1920 /* Namespace */)) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) { if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { @@ -32417,7 +32694,7 @@ var ts; } var symbol = resolveSymbol(resolveName(errorLocation, name, 67897832 /* Type */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) { - var message = (name === "Promise" || name === "Symbol") + var message = isES2015OrLaterConstructorName(name) ? ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; error(errorLocation, message, ts.unescapeLeadingUnderscores(name)); @@ -32426,6 +32703,18 @@ var ts; } return false; } + function isES2015OrLaterConstructorName(n) { + switch (n) { + case "Promise": + case "Symbol": + case "Map": + case "WeakMap": + case "Set": + case "WeakSet": + return true; + } + return false; + } function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { if (meaning & (67220415 /* Value */ & ~1024 /* NamespaceModule */ & ~67897832 /* Type */)) { var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~67220415 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)); @@ -32468,7 +32757,7 @@ var ts; } } if (diagnosticMessage) { - addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); + ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); } } } @@ -32652,7 +32941,7 @@ var ts; var suggestionName = symbolToString(suggestion); var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName); if (suggestion.valueDeclaration) { - addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); } } else { @@ -32972,20 +33261,12 @@ var ts; return undefined; } if (moduleNotFoundError) { - // 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; - } - } + // See if this was possibly a projectReference redirect + if (resolvedModule) { + var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName); + if (redirect) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName); + return undefined; } } if (resolutionDiagnostic) { @@ -33054,7 +33335,7 @@ var ts; function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { - if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) { + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 284 /* SourceFile */)) { var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop"; @@ -33332,6 +33613,11 @@ var ts; type.intrinsicName = intrinsicName; return type; } + function createNullableType(kind, intrinsicName, objectFlags) { + var type = createIntrinsicType(kind, intrinsicName); + type.objectFlags = objectFlags; + return type; + } function createBooleanType(trueFalseTypes) { var type = getUnionType(trueFalseTypes); type.flags |= 16 /* Boolean */; @@ -33400,7 +33686,7 @@ var ts; } } switch (location.kind) { - case 279 /* SourceFile */: + case 284 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } @@ -33640,10 +33926,10 @@ var ts; return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { - return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; @@ -34012,8 +34298,8 @@ var ts; context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context); context.inferTypeParameters = saveInferTypeParameters; - var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); - var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + var trueTypeNode = typeToTypeNodeHelper(type.trueType, context); + var falseTypeNode = typeToTypeNodeHelper(type.falseType, context); context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } @@ -34100,7 +34386,7 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 279 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */; + return declaration.parent.kind === 284 /* SourceFile */ || declaration.parent.kind === 245 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions @@ -34140,13 +34426,14 @@ var ts; } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || ts.emptyArray; - if (type.target === globalArrayType) { + if (type.target === globalArrayType || type.target === globalReadonlyArrayType) { if (context.flags & 2 /* WriteArrayAsGenericType */) { var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); - return ts.createTypeReferenceNode("Array", [typeArgumentNode]); + return ts.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]); } var elementType = typeToTypeNodeHelper(typeArguments[0], context); - return ts.createArrayTypeNode(elementType); + var arrayType = ts.createArrayTypeNode(elementType); + return type.target === globalArrayType ? arrayType : ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, arrayType); } else if (type.target.objectFlags & 8 /* Tuple */) { if (typeArguments.length > 0) { @@ -34159,11 +34446,13 @@ var ts; ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : ts.createOptionalTypeNode(tupleConstituentNodes[i]); } - return ts.createTupleTypeNode(tupleConstituentNodes); + var tupleTypeNode = ts.createTupleTypeNode(tupleConstituentNodes); + return type.target.readonly ? ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode; } } if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) { - return ts.createTupleTypeNode([]); + var tupleTypeNode = ts.createTupleTypeNode([]); + return type.target.readonly ? ts.createTypeOperatorNode(133 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode; } context.encounteredError = true; return undefined; // TODO: GH#18217 @@ -34327,7 +34616,7 @@ var ts; context.approximateLength += (ts.symbolName(propertySymbol).length + 1); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(56 /* QuestionToken */) : undefined; - if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { + if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) { var signatures = getSignaturesOfType(propertyType, 0 /* Call */); for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { var signature = signatures_1[_i]; @@ -34463,7 +34752,7 @@ var ts; var savedContextFlags = context.flags; context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && - type.symbol.declarations[0] && + type.symbol.declarations && type.symbol.declarations[0] && ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && typeParameterShadowsNameInScope(type, context); var name = shouldUseGeneratedName @@ -34482,7 +34771,7 @@ var ts; function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 151 /* Parameter */); if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 299 /* JSDocParameterTag */); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 304 /* JSDocParameterTag */); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { @@ -34640,7 +34929,7 @@ var ts; return top; } function getSpecifierForModuleSymbol(symbol, context) { - var file = ts.getDeclarationOfKind(symbol, 279 /* SourceFile */); + var file = ts.getDeclarationOfKind(symbol, 284 /* SourceFile */); if (file && file.moduleName !== undefined) { // Use the amd name if it is available return file.moduleName; @@ -34893,7 +35182,7 @@ var ts; ts.isExternalModuleAugmentation(node.parent.parent); } function isDefaultBindingContext(location) { - return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location); + return location.kind === 284 /* SourceFile */ || ts.isAmbientModule(location); } function getNameOfSymbolFromNameType(symbol, context) { var nameType = symbol.nameType; @@ -34970,8 +35259,8 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 297 /* JSDocCallbackTag */: - case 304 /* JSDocTypedefTag */: + case 302 /* JSDocCallbackTag */: + case 309 /* JSDocTypedefTag */: // Top-level jsdoc type aliases are considered exported // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); @@ -34998,7 +35287,7 @@ var ts; var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 279 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { + !(node.kind !== 248 /* ImportEqualsDeclaration */ && parent.kind !== 284 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible @@ -35040,7 +35329,7 @@ var ts; // Type parameters are always visible case 150 /* TypeParameter */: // Source file and namespace export are always visible - case 279 /* SourceFile */: + case 284 /* SourceFile */: case 247 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module @@ -35219,7 +35508,7 @@ var ts; if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType) && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) && isSpreadableProperty(prop)) { - members.set(prop.escapedName, getSpreadSymbol(prop)); + members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false)); } } var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); @@ -35288,17 +35577,8 @@ var ts; function getTypeForBindingElement(declaration) { var pattern = declaration.parent; var parentType = getTypeForBindingElementParent(pattern.parent); - // If parent has the unknown (error) type, then so does this binding element - if (parentType === errorType) { - return errorType; - } - // If no type was specified or inferred for parent, - // infer from the initializer of the binding element if one is present. - // Otherwise, go with the undefined type of the parent. - if (!parentType) { - return declaration.initializer ? checkDeclarationInitializer(declaration) : parentType; - } - if (isTypeAny(parentType)) { + // If no type or an any type was inferred for parent, infer that for the binding element + if (!parentType || isTypeAny(parentType)) { return parentType; } // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation @@ -35380,6 +35660,11 @@ var ts; if (optional === void 0) { optional = true; } return strictNullChecks && optional ? getOptionalType(type) : type; } + function isParameterOfContextuallyTypedFunction(node) { + return node.kind === 151 /* Parameter */ && + (node.parent.kind === 196 /* FunctionExpression */ || node.parent.kind === 197 /* ArrowFunction */) && + !!getContextualType(node.parent); + } // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the @@ -35455,8 +35740,9 @@ var ts; return containerObjectType; } } - // Use the type of the initializer expression if one is present - if (declaration.initializer) { + // Use the type of the initializer expression if one is present and the declaration is + // not a parameter of a contextually typed function + if (declaration.initializer && !isParameterOfContextuallyTypedFunction(declaration)) { var type = checkDeclarationInitializer(declaration); return addOptionality(type, isOptional); } @@ -35465,8 +35751,9 @@ var ts; // I.e is sugar for return trueType; } - // If the declaration specifies a binding pattern, use the type implied by the binding pattern - if (ts.isBindingPattern(declaration.name)) { + // If the declaration specifies a binding pattern and is not a parameter of a contextually + // typed function, use the type implied by the binding pattern + if (ts.isBindingPattern(declaration.name) && !isParameterOfContextuallyTypedFunction(declaration)) { return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); } // No type specified and nothing can be inferred @@ -35522,7 +35809,7 @@ var ts; definedInConstructor = true; } } - var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(98304 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217 type = getUnionType(sourceTypes, 2 /* Subtype */); } var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); @@ -35673,7 +35960,7 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var objectFlags = 128 /* ObjectLiteral */; + var objectFlags = 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -35694,7 +35981,6 @@ var ts; members.set(symbol.escapedName, symbol); }); var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */; result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; @@ -35778,7 +36064,16 @@ var ts; } function getTypeOfVariableOrParameterOrProperty(symbol) { var links = getSymbolLinks(symbol); - return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol)); + if (!links.type) { + var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol); + // For a contextually typed parameter it is possible that a type has already + // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want + // to preserve this type. + if (!links.type) { + links.type = type; + } + } + return links.type; } function getTypeOfVariableOrParameterOrPropertyWorker(symbol) { // Handle prototype property @@ -35811,19 +36106,19 @@ var ts; } return type_1; } - if (declaration.kind === 254 /* ExportAssignment */) { - return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); - } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` if (symbol.flags & 512 /* ValueModule */) { return getTypeOfFuncClassEnumModule(symbol); } - return errorType; + return reportCircularityError(symbol); } var type; - if (ts.isInJSFile(declaration) && + if (declaration.kind === 254 /* ExportAssignment */) { + type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); + } + else if (ts.isInJSFile(declaration) && (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { type = getWidenedTypeFromAssignmentDeclaration(symbol); } @@ -35878,7 +36173,7 @@ var ts; if (symbol.flags & 512 /* ValueModule */) { return getTypeOfFuncClassEnumModule(symbol); } - type = reportCircularityError(symbol); + return reportCircularityError(symbol); } return type; } @@ -36056,15 +36351,19 @@ var ts; return links.type; } function reportCircularityError(symbol) { + var declaration = symbol.valueDeclaration; // Check if variable has type annotation that circularly references the variable itself - if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) { + if (ts.getEffectiveTypeAnnotationNode(declaration)) { error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); return errorType; } - // Otherwise variable has initializer that circularly references the variable itself - if (noImplicitAny) { + // Check if variable has initializer that circularly references the variable itself + if (noImplicitAny && (declaration.kind !== 151 /* Parameter */ || declaration.initializer)) { error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); } + // Circularities could also result from parameters in function expressions that end up + // having themselves as contextual types following type argument inference. In those cases + // we have already reported an implicit any error so we don't report anything here. return anyType; } function getTypeOfSymbol(symbol) { @@ -36140,15 +36439,15 @@ var ts; case 155 /* MethodSignature */: case 165 /* FunctionType */: case 166 /* ConstructorType */: - case 289 /* JSDocFunctionType */: + case 294 /* JSDocFunctionType */: case 239 /* FunctionDeclaration */: case 156 /* MethodDeclaration */: case 196 /* FunctionExpression */: case 197 /* ArrowFunction */: case 242 /* TypeAliasDeclaration */: - case 303 /* JSDocTemplateTag */: - case 304 /* JSDocTypedefTag */: - case 297 /* JSDocCallbackTag */: + case 308 /* JSDocTemplateTag */: + case 309 /* JSDocTypedefTag */: + case 302 /* JSDocCallbackTag */: case 181 /* MappedType */: case 175 /* ConditionalType */: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); @@ -36269,7 +36568,7 @@ var ts; ctorReturn = getReturnTypeOfSignature(ctorSig[0]); } } - addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); + ts.addRelatedInfo(err, ts.createDiagnosticForNode(baseConstructorType.symbol.declarations[0], ts.Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); } return type.resolvedBaseConstructorType = errorType; } @@ -36280,7 +36579,7 @@ var ts; function getBaseTypes(type) { if (!type.resolvedBaseTypes) { if (type.objectFlags & 8 /* Tuple */) { - type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray))]; + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray), type.readonly)]; } else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { if (type.symbol.flags & 32 /* Class */) { @@ -36645,7 +36944,7 @@ var ts; } return false; } - /** A type parameter is thisless if its contraint is thisless, or if it has no constraint. */ + /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */ function isThislessTypeParameter(node) { var constraint = ts.getEffectiveConstraintOfTypeParameter(node); return !constraint || isThislessType(constraint); @@ -36688,6 +36987,8 @@ var ts; case 156 /* MethodDeclaration */: case 155 /* MethodSignature */: case 157 /* Constructor */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: return isThislessFunctionLikeDeclaration(declaration); } } @@ -37019,8 +37320,18 @@ var ts; return sig; } function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, + var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + result.target = sig.target; + result.mapper = sig.mapper; + return result; + } + function createUnionSignature(signature, unionSignatures) { + var result = cloneSignature(signature); + result.unionSignatures = unionSignatures; + result.target = undefined; + result.mapper = undefined; + return result; } function getExpandedParameters(sig) { if (sig.hasRestParameter) { @@ -37129,9 +37440,8 @@ var ts; var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */); thisParameter = createSymbolWithType(signature.thisParameter, thisType); } - s = cloneSignature(signature); + s = createUnionSignature(signature, unionSignatures); s.thisParameter = thisParameter; - s.unionSignatures = unionSignatures; } (result || (result = [])).push(s); } @@ -37246,13 +37556,22 @@ var ts; function unionSpreadIndexInfos(info1, info2) { return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); } - function includeMixinType(type, types, index) { + function findMixins(types) { + var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; }); + var mixinFlags = ts.map(types, isMixinConstructorType); + if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) { + var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true); + mixinFlags[firstMixinIndex] = false; + } + return mixinFlags; + } + function includeMixinType(type, types, mixinFlags, index) { var mixedTypes = []; for (var i = 0; i < types.length; i++) { if (i === index) { mixedTypes.push(type); } - else if (isMixinConstructorType(types[i])) { + else if (mixinFlags[i]) { mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0])); } } @@ -37266,7 +37585,8 @@ var ts; var stringIndexInfo; var numberIndexInfo; var types = type.types; - var mixinCount = ts.countWhere(types, isMixinConstructorType); + var mixinFlags = findMixins(types); + var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; }); var _loop_6 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from @@ -37274,12 +37594,12 @@ var ts; // other construct signatures in the intersection type. For example, the intersection type // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature // 'new(s: string) => A & B'. - if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { + if (!mixinFlags[i]) { var signatures = getSignaturesOfType(t, 1 /* Construct */); if (signatures.length && mixinCount > 0) { signatures = ts.map(signatures, function (s) { var clone = cloneSignature(s); - clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i); + clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i); return clone; }); } @@ -37323,6 +37643,15 @@ var ts; var stringIndexInfo = void 0; if (symbol.exports) { members = getExportsOfSymbol(symbol); + if (symbol === globalThisSymbol) { + var varsOnly_1 = ts.createMap(); + members.forEach(function (p) { + if (!(p.flags & 418 /* BlockScoped */)) { + varsOnly_1.set(p.escapedName, p); + } + }); + members = varsOnly_1; + } } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); if (symbol.flags & 32 /* Class */) { @@ -37622,7 +37951,7 @@ var ts; var nameType = property.name && getLiteralTypeFromPropertyName(property.name); var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined; var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); - return !!expected && isLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); + return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected); }); } function getAllPossiblePropertiesOfTypes(types) { @@ -37655,6 +37984,9 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { + return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined; + } + function getConstraintFromIndexedAccess(type) { var objectType = getConstraintOfType(type.objectType) || type.objectType; if (objectType !== type.objectType) { var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); @@ -37667,13 +37999,13 @@ var ts; } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { - var rootTrueType = type.root.trueType; - var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) - ? rootTrueType - : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */ - ? rootTrueType.typeVariable - : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); - type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); + // An `any` branch of a conditional type would normally be viral - specifically, without special handling here, + // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to + // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type, + // in effect treating `any` like `never` rather than `unknown` in this location. + var trueConstraint = getInferredTrueTypeFromConditionalType(type); + var falseConstraint = type.falseType; + type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]); } return type.resolvedDefaultConstraint; } @@ -37683,7 +38015,13 @@ var ts; // with its constraint. We do this because if the constraint is a union type it will be distributed // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. - if (type.root.isDistributive) { + // We skip returning a distributive constraint for a restrictive instantiation of a conditional type + // as the constraint for all type params (check type included) have been replace with `unknown`, which + // is going to produce even more false positive/negative results than the distribute constraint already does. + // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter + // a union - once negated types exist and are applied to the conditional false branch, this "constraint" + // likely doesn't need to exist. + if (type.root.isDistributive && type.restrictiveInstantiation !== type) { var simplified = getSimplifiedType(type.checkType); var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint && constraint !== type.checkType) { @@ -37696,9 +38034,12 @@ var ts; } return undefined; } - function getConstraintOfConditionalType(type) { + function getConstraintFromConditionalType(type) { return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); } + function getConstraintOfConditionalType(type) { + return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined; + } function getUnionConstraintOfIntersection(type, targetIsUnion) { var constraints; var hasDisjointDomainType = false; @@ -37772,18 +38113,31 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } - if (constraintDepth === 50) { + if (constraintDepth >= 50) { // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a // very high likelyhood we're dealing with an infinite generic type that perpetually generates // new type identities as we descend into it. We stop the recursion here and mark this type // and the outer types as having circular constraints. + error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); nonTerminating = true; return t.immediateBaseConstraint = noConstraintType; } constraintDepth++; var result = computeBaseConstraint(getSimplifiedType(t)); constraintDepth--; - if (!popTypeResolution() || nonTerminating) { + if (!popTypeResolution()) { + if (t.flags & 262144 /* TypeParameter */) { + var errorNode = getConstraintDeclaration(t); + if (errorNode) { + var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t)); + if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location)); + } + } + } + result = circularConstraintType; + } + if (nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -37825,8 +38179,11 @@ var ts; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 16777216 /* Conditional */) { - var constraint = getConstraintOfConditionalType(t); - return constraint && getBaseConstraint(constraint); + var constraint = getConstraintFromConditionalType(t); + constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward) + var result = constraint && getBaseConstraint(constraint); + constraintDepth--; + return result; } if (t.flags & 33554432 /* Substitution */) { return getBaseConstraint(t.substitute); @@ -37887,7 +38244,7 @@ var ts; var typeVariable = getHomomorphicTypeVariable(type); if (typeVariable) { var constraint = getConstraintOfTypeParameter(typeVariable); - if (constraint && (isArrayType(constraint) || isReadonlyArrayType(constraint) || isTupleType(constraint))) { + if (constraint && (isArrayType(constraint) || isTupleType(constraint))) { var mapper = makeUnaryTypeMapper(typeVariable, constraint); return instantiateType(type, combineTypeMappers(mapper, type.mapper)); } @@ -37905,7 +38262,7 @@ var ts; t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : t.flags & 132 /* StringLike */ ? globalStringType : t.flags & 296 /* NumberLike */ ? globalNumberType : - t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 6 /* ESNext */) : + t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ESNext */) : t.flags & 528 /* BooleanLike */ ? globalBooleanType : t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : @@ -37913,7 +38270,7 @@ var ts; t; } function createUnionOrIntersectionProperty(containingType, name) { - var props; + var propSet = ts.createMap(); var indexTypes; var isUnion = containingType.flags & 1048576 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; @@ -37929,7 +38286,10 @@ var ts; var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; - props = ts.appendIfUnique(props, prop); + var id = "" + getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 128 /* ContainsPublic */ : 0) | (modifiers & 16 /* Protected */ ? 256 /* ContainsProtected */ : 0) | @@ -37951,9 +38311,10 @@ var ts; } } } - if (!props) { + if (!propSet.size) { return undefined; } + var props = ts.arrayFrom(propSet.values()); if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) { return props[0]; } @@ -38125,10 +38486,10 @@ var ts; function isJSDocOptionalParameter(node) { return ts.isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType - node.type && node.type.kind === 288 /* JSDocOptionalType */ + node.type && node.type.kind === 293 /* JSDocOptionalType */ || ts.getJSDocParameterTags(node).some(function (_a) { var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */; })); } function tryFindAmbientModule(moduleName, withAugmentations) { @@ -38162,7 +38523,7 @@ var ts; return false; } var isBracketed = node.isBracketed, typeExpression = node.typeExpression; - return isBracketed || !!typeExpression && typeExpression.type.kind === 288 /* JSDocOptionalType */; + return isBracketed || !!typeExpression && typeExpression.type.kind === 293 /* JSDocOptionalType */; } function createIdentifierTypePredicate(parameterName, parameterIndex, type) { return { kind: 1 /* Identifier */, parameterName: parameterName, parameterIndex: parameterIndex, type: type }; @@ -38396,32 +38757,23 @@ var ts; } } signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? - createTypePredicateFromTypePredicateNode(type, signature.declaration) : + createTypePredicateFromTypePredicateNode(type, signature) : jsdocPredicate || noTypePredicate; } ts.Debug.assert(!!signature.resolvedTypePredicate); } return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; } - function createTypePredicateFromTypePredicateNode(node, func) { + function createTypePredicateFromTypePredicateNode(node, signature) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); if (parameterName.kind === 72 /* Identifier */) { - return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + return createIdentifierTypePredicate(parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type); } else { return createThisTypePredicate(type); } } - function getTypePredicateParameterIndex(parameterList, parameter) { - for (var i = 0; i < parameterList.length; i++) { - var param = parameterList[i]; - if (param.name.kind === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) { - return i; - } - } - return -1; - } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { @@ -38493,8 +38845,19 @@ var ts; } return undefined; } - function getSignatureInstantiation(signature, typeArguments, isJavascript) { - return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); + function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) { + var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); + if (inferredTypeParameters) { + var returnSignature = getSingleCallSignature(getReturnTypeOfSignature(instantiatedSignature)); + if (returnSignature) { + var newReturnSignature = cloneSignature(returnSignature); + newReturnSignature.typeParameters = inferredTypeParameters; + var newInstantiatedSignature = cloneSignature(instantiatedSignature); + newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature); + return newInstantiatedSignature; + } + } + return instantiatedSignature; } function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) { var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); @@ -38689,10 +39052,10 @@ var ts; for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { var type = types_5[_i]; if (!(type.flags & excludeKinds)) { - result |= type.flags; + result |= ts.getObjectFlags(type); } } - return result & 939524096 /* PropagatingFlags */; + return result & 917504 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -38700,7 +39063,7 @@ var ts; if (!type) { type = createObjectType(4 /* Reference */, target.symbol); target.instantiations.set(id, type); - type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; + type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; type.target = target; type.typeArguments = typeArguments; } @@ -38866,7 +39229,7 @@ var ts; } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { - if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) { + if (symbol.valueDeclaration && symbol.valueDeclaration.parent && ts.isBinaryExpression(symbol.valueDeclaration.parent)) { var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); if (jsdocType) { return jsdocType; @@ -38887,6 +39250,9 @@ var ts; } } function getSubstitutionType(typeVariable, substitute) { + if (substitute.flags & 3 /* AnyOrUnknown */) { + return typeVariable; + } var result = createType(33554432 /* Substitution */); result.typeVariable = typeVariable; result.substitute = substitute; @@ -38902,7 +39268,7 @@ var ts; } function getConstrainedTypeVariable(typeVariable, node) { var constraints; - while (node && !ts.isStatement(node) && node.kind !== 291 /* JSDocComment */) { + while (node && !ts.isStatement(node) && node.kind !== 296 /* JSDocComment */) { var parent = node.parent; if (parent.kind === 175 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); @@ -39134,19 +39500,19 @@ var ts; function createIterableIteratorType(iteratedType) { return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]); } - function createArrayType(elementType) { - return createTypeFromGenericGlobalType(globalArrayType, [elementType]); - } - function createReadonlyArrayType(elementType) { - return createTypeFromGenericGlobalType(globalReadonlyArrayType, [elementType]); + function createArrayType(elementType, readonly) { + return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]); } function getTypeFromArrayTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); + links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType), isReadonlyTypeOperator(node.parent)); } return links.resolvedType; } + function isReadonlyTypeOperator(node) { + return ts.isTypeOperatorNode(node) && node.operator === 133 /* ReadonlyKeyword */; + } // We represent tuple types as type references to synthesized generic interface types created by // this function. The types are of the form: // @@ -39154,7 +39520,7 @@ var ts; // // Note that the generic type created by this function has no symbol associated with it. The same // is true for each of the synthesized type parameters. - function createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + function createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) { var typeParameters; var properties = []; var maxLength = hasRestElement ? arity - 1 : arity; @@ -39163,7 +39529,7 @@ var ts; for (var i = 0; i < arity; i++) { var typeParameter = typeParameters[i] = createTypeParameter(); if (i < maxLength) { - var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); + var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0); property.type = typeParameter; properties.push(property); } @@ -39193,25 +39559,27 @@ var ts; type.declaredNumberIndexInfo = undefined; type.minLength = minLength; type.hasRestElement = hasRestElement; + type.readonly = readonly; type.associatedNames = associatedNames; return type; } - function getTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { - var key = arity + (hasRestElement ? "+" : ",") + minLength + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : ""); + function getTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) { + var key = arity + (hasRestElement ? "+" : ",") + minLength + (readonly ? "R" : "") + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : ""); var type = tupleTypes.get(key); if (!type) { - tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames)); + tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames)); } return type; } - function createTupleType(elementTypes, minLength, hasRestElement, associatedNames) { + function createTupleType(elementTypes, minLength, hasRestElement, readonly, associatedNames) { if (minLength === void 0) { minLength = elementTypes.length; } if (hasRestElement === void 0) { hasRestElement = false; } + if (readonly === void 0) { readonly = false; } var arity = elementTypes.length; if (arity === 1 && hasRestElement) { - return createArrayType(elementTypes[0]); + return createArrayType(elementTypes[0], readonly); } - var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, associatedNames); + var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, readonly, associatedNames); return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType; } function getTypeFromTupleTypeNode(node) { @@ -39224,7 +39592,7 @@ var ts; var type = getTypeFromTypeNode(n); return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type; }); - links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1); + links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1, isReadonlyTypeOperator(node.parent)); } return links.resolvedType; } @@ -39234,7 +39602,7 @@ var ts; // don't slice off rest element index = Math.min(index, getTypeReferenceArity(type) - 1); } - return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.associatedNames && tuple.associatedNames.slice(index)); + return createTupleType((type.typeArguments || ts.emptyArray).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.readonly, tuple.associatedNames && tuple.associatedNames.slice(index)); } function getTypeFromOptionalTypeNode(node) { var type = getTypeFromTypeNode(node.type); @@ -39292,12 +39660,14 @@ var ts; // intersections of unit types into 'never' upon construction, but deferring the reduction makes it // easier to reason about their origin. if (!(flags & 131072 /* Never */ || flags & 2097152 /* Intersection */ && isEmptyIntersectionType(type))) { - includes |= flags & ~939524096 /* ConstructionFlags */; + includes |= flags & 1835007 /* IncludesMask */; + if (flags & 66846720 /* StructuredOrInstantiable */) + includes |= 262144 /* IncludesStructuredOrInstantiable */; if (type === wildcardType) - includes |= 268435456 /* Wildcard */; + includes |= 4194304 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { - if (!(flags & 134217728 /* ContainsWideningType */)) - includes |= 134217728 /* NonWideningType */; + if (!(ts.getObjectFlags(type) & 131072 /* ContainsWideningType */)) + includes |= 2097152 /* IncludesNonWideningType */; } else { var len = typeSet.length; @@ -39318,17 +39688,6 @@ var ts; } return includes; } - function isSubtypeOfAny(source, targets) { - for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) { - var target = targets_1[_i]; - if (source !== target && isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || - !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || - isTypeDerivedFrom(source, target))) { - return true; - } - } - return false; - } function isSetOfLiteralsFromSameEnum(types) { var first = types[0]; if (first.flags & 1024 /* EnumLiteral */) { @@ -39343,17 +39702,42 @@ var ts; } return false; } - function removeSubtypes(types) { - if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { - return; + function removeSubtypes(types, primitivesOnly) { + var len = types.length; + if (len === 0 || isSetOfLiteralsFromSameEnum(types)) { + return true; } - var i = types.length; + var i = len; + var count = 0; while (i > 0) { i--; - if (isSubtypeOfAny(types[i], types)) { - ts.orderedRemoveItemAt(types, i); + var source = types[i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var target = types_7[_i]; + if (source !== target) { + if (count === 100000) { + // After 100000 subtype checks we estimate the remaining amount of work by assuming the + // same ratio of checks per element. If the estimated number of remaining type checks is + // greater than an upper limit we deem the union type too complex to represent. The + // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example + // caps union types at 5000 unique literal types and 1000 unique object types. + var estimatedCount = (count / (len - i)) * len; + if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) { + error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent); + return false; + } + } + count++; + if (isTypeSubtypeOf(source, target) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) || + !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) || + isTypeDerivedFrom(source, target))) { + ts.orderedRemoveItemAt(types, i); + break; + } + } } } + return true; } function removeRedundantLiteralTypes(types, includes) { var i = types.length; @@ -39389,25 +39773,27 @@ var ts; var includes = addTypesToUnion(typeSet, 0, types); if (unionReduction !== 0 /* None */) { if (includes & 3 /* AnyOrUnknown */) { - return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType; + return includes & 1 /* Any */ ? includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; } switch (unionReduction) { case 1 /* Literal */: - if (includes & 8576 /* StringOrNumberLiteralOrUnique */ | 512 /* BooleanLiteral */) { + if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) { removeRedundantLiteralTypes(typeSet, includes); } break; case 2 /* Subtype */: - removeSubtypes(typeSet); + if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) { + return errorType; + } break; } if (typeSet.length === 0) { - return includes & 65536 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType : - includes & 32768 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : + return includes & 65536 /* Null */ ? includes & 2097152 /* IncludesNonWideningType */ ? nullType : nullWideningType : + includes & 32768 /* Undefined */ ? includes & 2097152 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType : neverType; } } - return getUnionTypeFromSortedList(typeSet, !(includes & 66994211 /* NotPrimitiveUnion */), aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 65536 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -39444,7 +39830,7 @@ var ts; : !ts.isIdentifierTypePredicate(b); } // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types, primitiveTypesOnly, aliasSymbol, aliasTypeArguments) { + function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -39454,11 +39840,10 @@ var ts; var id = getTypeListId(types); var type = unionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */); - type = createType(1048576 /* Union */ | propagatedFlags); + type = createType(1048576 /* Union */); unionTypes.set(id, type); + type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */); type.types = types; - type.primitiveTypesOnly = primitiveTypesOnly; /* Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type. For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol. @@ -39484,16 +39869,16 @@ var ts; return addTypesToIntersection(typeSet, includes, type.types); } if (isEmptyAnonymousObjectType(type)) { - if (!(includes & 536870912 /* EmptyObject */)) { - includes |= 536870912 /* EmptyObject */; + if (!(includes & 8388608 /* IncludesEmptyObject */)) { + includes |= 8388608 /* IncludesEmptyObject */; typeSet.push(type); } } else { - includes |= flags & ~939524096 /* ConstructionFlags */; + includes |= flags & 1835007 /* IncludesMask */; if (flags & 3 /* AnyOrUnknown */) { if (type === wildcardType) - includes |= 268435456 /* Wildcard */; + includes |= 4194304 /* IncludesWildcard */; } else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !ts.contains(typeSet, type)) { typeSet.push(type); @@ -39504,8 +39889,8 @@ var ts; // Add the given types to the given type set. Order is preserved, freshness is removed from literal // types, duplicates are removed, and nested types of the given kind are flattened into the set. function addTypesToIntersection(typeSet, includes, types) { - for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type = types_7[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -39548,7 +39933,7 @@ var ts; // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types) { var unionTypes; - var index = ts.findIndex(types, function (t) { return !!(t.flags & 1048576 /* Union */) && t.primitiveTypesOnly; }); + var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */); }); if (index < 0) { return false; } @@ -39557,7 +39942,7 @@ var ts; // the unionTypes array. while (i < types.length) { var t = types[i]; - if (t.flags & 1048576 /* Union */ && t.primitiveTypesOnly) { + if (ts.getObjectFlags(t) & 65536 /* PrimitiveUnion */) { (unionTypes || (unionTypes = [types[index]])).push(t); ts.orderedRemoveItemAt(types, i); } @@ -39586,7 +39971,7 @@ var ts; } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true); + types[index] = getUnionTypeFromSortedList(result, 65536 /* PrimitiveUnion */); return true; } // We normalize combinations of intersection and union types based on the distributive property of the '&' @@ -39606,7 +39991,7 @@ var ts; return neverType; } if (includes & 1 /* Any */) { - return includes & 268435456 /* Wildcard */ ? wildcardType : anyType; + return includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType; } if (!strictNullChecks && includes & 98304 /* Nullable */) { return includes & 32768 /* Undefined */ ? undefinedType : nullType; @@ -39617,7 +40002,7 @@ var ts; includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) { removeRedundantPrimitiveTypes(typeSet, includes); } - if (includes & 536870912 /* EmptyObject */ && includes & 524288 /* Object */) { + if (includes & 8388608 /* IncludesEmptyObject */ && includes & 524288 /* Object */) { ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); } if (typeSet.length === 0) { @@ -39642,9 +40027,9 @@ var ts; var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */); - type = createType(2097152 /* Intersection */ | propagatedFlags); + type = createType(2097152 /* Intersection */); intersectionTypes.set(id, type); + type.objectFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 98304 /* Nullable */); type.types = typeSet; type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. type.aliasTypeArguments = aliasTypeArguments; @@ -39699,7 +40084,7 @@ var ts; return neverType; } function getLiteralTypeFromProperties(type, include) { - return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromProperty(t, include); })); + return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); })); } function getNonEnumNumberIndexInfo(type) { var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); @@ -39741,6 +40126,9 @@ var ts; ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) : errorType; break; + case 133 /* ReadonlyKeyword */: + links.resolvedType = getTypeFromTypeNode(node.type); + break; } } return links.resolvedType; // TODO: GH#18217 @@ -39843,7 +40231,10 @@ var ts; return anyType; } if (accessExpression && !isConstEnumObjectType(objectType)) { - if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) { + error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } + else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); } @@ -39895,7 +40286,7 @@ var ts; : accessNode; } function isGenericObjectType(type) { - return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); + return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 131072 /* GenericMappedType */); } function isGenericIndexType(type) { return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */); @@ -39941,12 +40332,15 @@ var ts; // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. if (isGenericMappedType(objectType)) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var templateMapper = combineTypeMappers(objectType.mapper, mapper); - return type.simplified = mapType(instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper), getSimplifiedType); + return type.simplified = mapType(substituteIndexedMappedType(objectType, type.indexType), getSimplifiedType); } return type.simplified = type; } + function substituteIndexedMappedType(objectType, index) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]); + var templateMapper = combineTypeMappers(objectType.mapper, mapper); + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } function getIndexedAccessType(objectType, indexType, accessNode, missingType) { if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { @@ -40028,13 +40422,48 @@ var ts; function getActualTypeVariable(type) { return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type; } + /** + * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent + */ + function isIntersectionEmpty(type1, type2) { + return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */); + } function getConditionalType(root, mapper) { var checkType = instantiateType(root.checkType, mapper); var extendsType = instantiateType(root.extendsType, mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } - var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */); + var trueType = instantiateType(root.trueType, mapper); + var falseType = instantiateType(root.falseType, mapper); + var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType); + var result = conditionalTypes.get(instantiationId); + if (result) { + return result; + } + var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType); + conditionalTypes.set(instantiationId, newResult); + return newResult; + } + function getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType) { + // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`. + if (falseType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(trueType), getActualTypeVariable(checkType))) { + if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true + return trueType; + } + else if (isIntersectionEmpty(checkType, extendsType)) { // Always false + return neverType; + } + } + else if (trueType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(falseType), getActualTypeVariable(checkType))) { + if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true + return neverType; + } + else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false + return falseType; + } + } + var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */); var combinedMapper; if (root.inferTypeParameters) { var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); @@ -40044,25 +40473,25 @@ var ts; // types rules (i.e. proper contravariance) for inferences. inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */); } - combinedMapper = combineTypeMappers(mapper, context); + combinedMapper = combineTypeMappers(mapper, context.mapper); } // Instantiate the extends type including inferences for 'infer T' type parameters var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; // We attempt to resolve the conditional type only when the check and extends types are non-generic - if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */)) { + if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */)) { if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) { - return instantiateType(root.trueType, mapper); + return trueType; } // Return union of trueType and falseType for 'any' since it matches anything if (checkType.flags & 1 /* Any */) { - return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); + return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), falseType]); } - // Return falseType for a definitely false extends check. We check an instantations of the two + // Return falseType for a definitely false extends check. We check an instantiations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, - // then no instatiations will be and we can just return the false branch type. + // then no instantiations will be and we can just return the false branch type. if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) { - return instantiateType(root.falseType, mapper); + return falseType; } // Return trueType for a definitely true extends check. We check instantiations of the two // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter @@ -40074,6 +40503,9 @@ var ts; } } // Return a deferred type for a check that is neither definitely true nor definitely false + return getDeferredConditionalType(root, mapper, combinedMapper, checkType, extendsType, trueType, falseType); + } + function getDeferredConditionalType(root, mapper, combinedMapper, checkType, extendsType, trueType, falseType) { var erasedCheckType = getActualTypeVariable(checkType); var result = createType(16777216 /* Conditional */); result.root = root; @@ -40081,15 +40513,14 @@ var ts; result.extendsType = extendsType; result.mapper = mapper; result.combinedMapper = combinedMapper; + result.trueType = trueType; + result.falseType = falseType; result.aliasSymbol = root.aliasSymbol; result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 return result; } - function getTrueTypeFromConditionalType(type) { - return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); - } - function getFalseTypeFromConditionalType(type) { - return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); + function getInferredTrueTypeFromConditionalType(type) { + return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper || type.mapper)); } function getInferTypeParameters(node) { var result; @@ -40258,7 +40689,7 @@ var ts; * this function should be called in a left folding style, with left = previous result of getSpreadType * and right = the new element to be spread. */ - function getSpreadType(left, right, symbol, typeFlags, objectFlags) { + function getSpreadType(left, right, symbol, objectFlags, readonly) { if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { return anyType; } @@ -40272,10 +40703,10 @@ var ts; return left; } if (left.flags & 1048576 /* Union */) { - return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); }); + return mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); }); } if (right.flags & 1048576 /* Union */) { - return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); }); + return mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); }); } if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) { return left; @@ -40291,7 +40722,7 @@ var ts; var types = left.types; var lastLeft = types[types.length - 1]; if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) { - return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags)])); + return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)])); } } return getIntersectionType([left, right]); @@ -40315,7 +40746,7 @@ var ts; skippedPrivateMembers.set(rightProp.escapedName, true); } else if (isSpreadableProperty(rightProp)) { - members.set(rightProp.escapedName, getSpreadSymbol(rightProp)); + members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly)); } } for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { @@ -40339,12 +40770,11 @@ var ts; } } else { - members.set(leftProp.escapedName, getSpreadSymbol(leftProp)); + members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly)); } } - var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); - spread.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; - spread.objectFlags |= 128 /* ObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags; + var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); + spread.objectFlags |= 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */ | 1024 /* ContainsSpread */ | objectFlags; return spread; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ @@ -40352,25 +40782,21 @@ var ts; return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); } - function getSpreadSymbol(prop) { - var isReadonly = isReadonlySymbol(prop); + function getSpreadSymbol(prop, readonly) { var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); - if (!isReadonly && !isSetonlyAccessor) { + if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) { return prop; } var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */); - var result = createSymbol(flags, prop.escapedName); + var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0); result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop); result.declarations = prop.declarations; result.nameType = prop.nameType; result.syntheticOrigin = prop; return result; } - function getNonReadonlyIndexSignature(index) { - if (index && index.isReadonly) { - return createIndexInfo(index.type, /*isReadonly*/ false, index.declaration); - } - return index; + function getIndexInfoWithReadonly(info, readonly) { + return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info; } function createLiteralType(flags, value, symbol) { var type = createType(flags); @@ -40458,8 +40884,8 @@ var ts; function getTypeFromTypeNode(node) { switch (node.kind) { case 120 /* AnyKeyword */: - case 284 /* JSDocAllType */: - case 285 /* JSDocUnknownType */: + case 289 /* JSDocAllType */: + case 290 /* JSDocUnknownType */: return anyType; case 143 /* UnknownKeyword */: return unknownType; @@ -40506,23 +40932,23 @@ var ts; return getTypeFromUnionTypeNode(node); case 174 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 286 /* JSDocNullableType */: + case 291 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 288 /* JSDocOptionalType */: + case 293 /* JSDocOptionalType */: return addOptionality(getTypeFromTypeNode(node.type)); case 177 /* ParenthesizedType */: case 172 /* RestType */: - case 287 /* JSDocNonNullableType */: - case 283 /* JSDocTypeExpression */: + case 292 /* JSDocNonNullableType */: + case 288 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 290 /* JSDocVariadicType */: + case 295 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); case 165 /* FunctionType */: case 166 /* ConstructorType */: case 168 /* TypeLiteral */: - case 292 /* JSDocTypeLiteral */: - case 289 /* JSDocFunctionType */: - case 293 /* JSDocSignature */: + case 297 /* JSDocTypeLiteral */: + case 294 /* JSDocFunctionType */: + case 298 /* JSDocSignature */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); case 179 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); @@ -40598,16 +41024,8 @@ var ts; * Maps forward-references to later types parameters to the empty object type. * This is used during inference when instantiating type parameter defaults. */ - function createBackreferenceMapper(typeParameters, index) { - return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; - } - function isInferenceContext(mapper) { - return !!mapper.typeParameters; - } - function cloneTypeMapper(mapper) { - return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | 1 /* NoDefault */, mapper.compareTypes, mapper.inferences) : - mapper; + function createBackreferenceMapper(context, index) { + return function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? emptyObjectType : t; }; } function combineTypeMappers(mapper1, mapper2) { if (!mapper1) @@ -40690,7 +41108,7 @@ var ts; } // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and // also transient so that we can just store data on it directly. - var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */)); + var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */)); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -40786,7 +41204,7 @@ var ts; function getHomomorphicTypeVariable(type) { var constraintType = getConstraintTypeFromMappedType(type); if (constraintType.flags & 4194304 /* Index */) { - var typeVariable = constraintType.type; + var typeVariable = getActualTypeVariable(constraintType.type); if (typeVariable.flags & 262144 /* TypeParameter */) { return typeVariable; } @@ -40808,30 +41226,27 @@ var ts; if (typeVariable) { var mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - // If we are already in the process of creating an instantiation of this mapped type, - // return the error type. This situation only arises if we are instantiating the mapped - // type for an array or tuple type, as we then need to eagerly resolve the (possibly - // circular) element type(s). - if (type.instantiating) { - return errorType; - } - type.instantiating = true; - var result = mapType(mappedTypeVariable, function (t) { - if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType) { + return mapType(mappedTypeVariable, function (t) { + if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) { var replacementMapper = createReplacementMapper(typeVariable, t, mapper); - return isArrayType(t) ? createArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isReadonlyArrayType(t) ? createReadonlyArrayType(instantiateMappedTypeTemplate(type, numberType, /*isOptional*/ true, replacementMapper)) : - isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : - instantiateAnonymousType(type, replacementMapper); + return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) : + isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : + instantiateAnonymousType(type, replacementMapper); } return t; }); - type.instantiating = false; - return result; } } return instantiateAnonymousType(type, mapper); } + function getModifiedReadonlyState(state, modifiers) { + return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state; + } + function instantiateMappedArrayType(arrayType, mappedType, mapper) { + var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper); + return elementType === errorType ? errorType : + createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType))); + } function instantiateMappedTupleType(tupleType, mappedType, mapper) { var minLength = tupleType.target.minLength; var elementTypes = ts.map(tupleType.typeArguments || ts.emptyArray, function (_, i) { @@ -40841,7 +41256,9 @@ var ts; var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 : modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) : minLength; - return createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, tupleType.target.associatedNames); + var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers); + return ts.contains(elementTypes, errorType) ? errorType : + createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, newReadonly, tupleType.target.associatedNames); } function instantiateMappedTypeTemplate(type, key, isOptional, mapper) { var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key])); @@ -40907,6 +41324,7 @@ var ts; // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing // with a combination of infinite generic types that perpetually generate new type identities. We stop // the recursion here by yielding the error type. + error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); return errorType; } instantiationDepth++; @@ -40958,7 +41376,17 @@ var ts; return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); } if (flags & 33554432 /* Substitution */) { - return instantiateType(type.typeVariable, mapper); + var maybeVariable = instantiateType(type.typeVariable, mapper); + if (maybeVariable.flags & 8650752 /* TypeVariable */) { + return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper)); + } + else { + var sub = instantiateType(type.substitute, mapper); + if (sub.flags & 3 /* AnyOrUnknown */ || isTypeSubtypeOf(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) { + return maybeVariable; + } + return sub; + } } return type; } @@ -40967,8 +41395,20 @@ var ts; type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); } function getRestrictiveInstantiation(type) { - return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : - type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper)); + if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) { + return type; + } + if (type.restrictiveInstantiation) { + return type.restrictiveInstantiation; + } + type.restrictiveInstantiation = instantiateType(type, restrictiveMapper); + // We set the following so we don't attempt to set the restrictive instance of a restrictive instance + // which is redundant - we'll produce new type identities, but all type params have already been mapped. + // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint" + // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters + // are constrained to `unknown` and produce tons of false positives/negatives! + type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation; + return type.restrictiveInstantiation; } function instantiateIndexInfo(info, mapper) { return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); @@ -41167,7 +41607,7 @@ var ts; var resultObj = {}; checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); var diagnostic = resultObj.error; - addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(node, signatures === constructSignatures ? ts.Diagnostics.Did_you_mean_to_use_new_with_this_expression : ts.Diagnostics.Did_you_mean_to_call_this_expression)); return true; } } @@ -41202,7 +41642,7 @@ var ts; checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, /*chain*/ undefined, resultObj); if (resultObj.error) { if (target.symbol && ts.length(target.symbol.declarations)) { - addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); + ts.addRelatedInfo(resultObj.error, ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); } return true; } @@ -41249,13 +41689,13 @@ var ts; undefined; if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) { issuedElaboration = true; - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); + ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); } } if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0]; if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) { - addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetNode, ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 8192 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); } } } @@ -41326,7 +41766,7 @@ var ts; // child is of the type of the expression return { errorNode: child, innerExpression: child.expression, nameType: nameType }; case 11 /* JsxText */: - if (child.containsOnlyWhiteSpaces) { + if (child.containsOnlyTriviaWhiteSpaces) { break; // Whitespace only jsx text isn't real jsx text } // child is a string @@ -41349,7 +41789,7 @@ var ts; var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName); var childrenNameType = getLiteralType(childrenPropName); var childrenTargetType = getIndexedAccessType(target, childrenNameType); - var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyWhiteSpaces; }); + var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces; }); if (!ts.length(validChildren)) { return result; } @@ -41437,7 +41877,7 @@ var ts; return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); } // recreate a tuple from the elements, if possible - var tupleizedType = checkArrayLiteral(node, 3 /* Contextual */, /*forceTuple*/ true); + var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true); if (isTupleLikeType(tupleizedType)) { return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation); } @@ -41502,6 +41942,14 @@ var ts; return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; } + /** + * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any` + */ + function isAnySignature(s) { + return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && + s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + isTypeAny(getReturnTypeOfSignature(s)); + } /** * See signatureRelatedTo, compareSignaturesIdentical */ @@ -41510,13 +41958,16 @@ var ts; if (source === target) { return -1 /* True */; } + if (isAnySignature(target)) { + return -1 /* True */; + } var targetCount = getParameterCount(target); if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) { return 0 /* False */; } if (source.typeParameters && source.typeParameters !== target.typeParameters) { target = getCanonicalSignature(target); - source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); + source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes); } var sourceCount = getParameterCount(source); var sourceRestType = getNonArrayRestType(source); @@ -41587,7 +42038,7 @@ var ts; if (targetTypePredicate) { var sourceTypePredicate = getTypePredicateOfSignature(source); if (sourceTypePredicate) { - result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217 + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes); } else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { if (reportErrors) { @@ -41606,7 +42057,7 @@ var ts; } return result; } - function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) { + function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { if (source.kind !== target.kind) { if (reportErrors) { errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); @@ -41615,12 +42066,9 @@ var ts; return 0 /* False */; } if (source.kind === 1 /* Identifier */) { - var targetPredicate = target; - var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); - var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0); - if (sourceIndex !== targetIndex) { + if (source.parameterIndex !== target.parameterIndex) { if (reportErrors) { - errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName); + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName); errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); } return 0 /* False */; @@ -41821,7 +42269,7 @@ var ts; } var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation); if (relatedInfo) { - addRelatedInfo.apply(void 0, [diag].concat(relatedInfo)); + ts.addRelatedInfo.apply(void 0, [diag].concat(relatedInfo)); } if (errorOutputContainer) { errorOutputContainer.error = diag; @@ -42428,8 +42876,8 @@ var ts; if (source.root.isDistributive === target.root.isDistributive) { if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) { return result_3; } } @@ -42444,6 +42892,7 @@ var ts; } var result; var originalErrorInfo; + var varianceCheckFailed = false; var saveErrorInfo = errorInfo; // We limit alias variance probing to only object and conditional types since their alias behavior // is more predictable than other, interned types, which may or may not have an alias depending on @@ -42452,11 +42901,10 @@ var ts; source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { var variances = getAliasVariances(source.aliasSymbol); - if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) { - return result; + var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances); + if (varianceResult !== undefined) { + return varianceResult; } - originalErrorInfo = errorInfo; - errorInfo = saveErrorInfo; } if (target.flags & 262144 /* TypeParameter */) { // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q]. @@ -42513,16 +42961,26 @@ var ts; template.indexType === getTypeParameterFromMappedType(target)) { return -1 /* True */; } - // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. - if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { - var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); - var templateType = getTemplateTypeFromMappedType(target); - if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - return result; + if (!isGenericMappedType(source)) { + var targetConstraint = getConstraintTypeFromMappedType(target); + var sourceKeys_1 = getIndexType(source); + var hasOptionalUnionKeys = modifiers & 4 /* IncludeOptional */ && targetConstraint.flags & 1048576 /* Union */; + var filteredByApplicability = hasOptionalUnionKeys ? filterType(targetConstraint, function (t) { return !!isRelatedTo(t, sourceKeys_1); }) : undefined; + // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. + // A source type T is related to a target type { [P in Q]?: X } if some constituent Q' of Q is related to keyof T and T[Q'] is related to X. + if (hasOptionalUnionKeys + ? !(filteredByApplicability.flags & 131072 /* Never */) + : isRelatedTo(targetConstraint, sourceKeys_1)) { + var indexingType = hasOptionalUnionKeys ? filteredByApplicability : getTypeParameterFromMappedType(target); + var indexedAccessType = getIndexedAccessType(source, indexingType); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + return result; + } } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; } - originalErrorInfo = errorInfo; - errorInfo = saveErrorInfo; } } if (source.flags & 8650752 /* TypeVariable */) { @@ -42568,8 +43026,8 @@ var ts; // and Y1 is related to Y2. if (isTypeIdenticalTo(source.extendsType, target.extendsType) && (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { - if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { - result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); + if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) { + result &= isRelatedTo(source.falseType, target.falseType, reportErrors); } if (result) { errorInfo = saveErrorInfo; @@ -42618,36 +43076,19 @@ var ts; // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. var variances = getVariances(source.target); - if (result = typeArgumentsRelatedTo(source.typeArguments, target.typeArguments, variances, reportErrors)) { - return result; - } - // The type arguments did not relate appropriately, but it may be because we have no variance - // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type - // arguments). It might also be the case that the target type has a 'void' type argument for - // a covariant type parameter that is only used in return positions within the generic type - // (in which case any type argument is permitted on the source side). In those cases we proceed - // with a structural comparison. Otherwise, we know for certain the instantiations aren't - // related and we can return here. - if (variances !== ts.emptyArray && !hasCovariantVoidArgument(target, variances)) { - // In some cases generic types that are covariant in regular type checking mode become - // invariant in --strictFunctionTypes mode because one or more type parameters are used in - // both co- and contravariant positions. In order to make it easier to diagnose *why* such - // types are invariant, if any of the type parameters are invariant we reset the reported - // errors and instead force a structural comparison (which will include elaborations that - // reveal the reason). - if (!(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) { - return 0 /* False */; - } - // We remember the original error information so we can restore it in case the structural - // comparison unexpectedly succeeds. This can happen when the structural comparison result - // is a Ternary.Maybe for example caused by the recursion depth limiter. - originalErrorInfo = errorInfo; - errorInfo = saveErrorInfo; + var varianceResult = relateVariances(source.typeArguments, target.typeArguments, variances); + if (varianceResult !== undefined) { + return varianceResult; } } - else if (isTupleType(source) && (isArrayType(target) || isReadonlyArrayType(target)) || isArrayType(source) && isReadonlyArrayType(target)) { + else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) { return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors); } + // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})` + // and not `{} <- fresh({}) <- {[idx: string]: any}` + else if (relation === subtypeRelation && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) { + return 0 /* False */; + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates @@ -42669,16 +43110,56 @@ var ts; } } } - if (result) { - if (!originalErrorInfo) { - errorInfo = saveErrorInfo; - return result; - } - errorInfo = originalErrorInfo; + if (varianceCheckFailed && result) { + errorInfo = originalErrorInfo || errorInfo || saveErrorInfo; // Use variance error (there is no structural one) and return false + } + else if (result) { + return result; } } } return 0 /* False */; + function isNonGeneric(type) { + // If we're already in identity relationship checking, we should use `isRelatedTo` + // to catch the `Maybe` from an excessively deep type (which we then assume means + // that the type could possibly contain a generic) + if (relation === identityRelation) { + return isRelatedTo(type, getPermissiveInstantiation(type)) === -1 /* True */; + } + return isTypeIdenticalTo(type, getPermissiveInstantiation(type)); + } + function relateVariances(sourceTypeArguments, targetTypeArguments, variances) { + if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors)) { + return result; + } + var allowStructuralFallback = (targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances)) || isNonGeneric(source) || isNonGeneric(target); + varianceCheckFailed = !allowStructuralFallback; + // The type arguments did not relate appropriately, but it may be because we have no variance + // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type + // arguments). It might also be the case that the target type has a 'void' type argument for + // a covariant type parameter that is only used in return positions within the generic type + // (in which case any type argument is permitted on the source side). In those cases we proceed + // with a structural comparison. Otherwise, we know for certain the instantiations aren't + // related and we can return here. + if (variances !== ts.emptyArray && !allowStructuralFallback) { + // In some cases generic types that are covariant in regular type checking mode become + // invariant in --strictFunctionTypes mode because one or more type parameters are used in + // both co- and contravariant positions. In order to make it easier to diagnose *why* such + // types are invariant, if any of the type parameters are invariant we reset the reported + // errors and instead force a structural comparison (which will include elaborations that + // reveal the reason). + // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`, + // we can return `False` early here to skip calculating the structural error message we don't need. + if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return v === 0 /* Invariant */; }))) { + return 0 /* False */; + } + // We remember the original error information so we can restore it in case the structural + // comparison unexpectedly succeeds. This can happen when the structural comparison result + // is a Ternary.Maybe for example caused by the recursion depth limiter. + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + } } // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice @@ -43158,20 +43639,17 @@ var ts; return variances; } function getVariances(type) { - if (!strictFunctionTypes) { - return ts.emptyArray; - } - if (type === globalArrayType || type === globalReadonlyArrayType) { - // Arrays are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + // Arrays and tuples are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) { return ts.emptyArray; } return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); } // Return true if the given type reference has a 'void' type argument for a covariant type parameter. // See comment at call in recursiveTypeRelatedTo for when this case matters. - function hasCovariantVoidArgument(type, variances) { + function hasCovariantVoidArgument(typeArguments, variances) { for (var i = 0; i < variances.length; i++) { - if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 16384 /* Void */) { + if (variances[i] === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) { return true; } } @@ -43400,8 +43878,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var t = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -43434,7 +43912,7 @@ var ts; return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); } function isArrayType(type) { - return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType; + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType); } function isReadonlyArrayType(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType; @@ -43445,8 +43923,7 @@ var ts; function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray - return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isEmptyArrayLiteralType(type) { var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; @@ -43531,8 +44008,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; result |= getFalsyFlags(t); } return result; @@ -43646,7 +44123,7 @@ var ts; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags; - regularNew.objectFlags |= 128 /* ObjectLiteral */ | (ts.getObjectFlags(resolved) & 16384 /* JSLiteral */); + regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */; type.regularType = regularNew; return regularNew; } @@ -43732,7 +44209,7 @@ var ts; return getWidenedTypeWithContext(type, /*context*/ undefined); } function getWidenedTypeWithContext(type, context) { - if (type.flags & 402653184 /* RequiresWidening */) { + if (ts.getObjectFlags(type) & 393216 /* RequiresWidening */) { if (type.flags & 98304 /* Nullable */) { return anyType; } @@ -43769,7 +44246,7 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 134217728 /* ContainsWideningType */) { + if (ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) { if (type.flags & 1048576 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; @@ -43795,7 +44272,7 @@ var ts; for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (t.flags & 134217728 /* ContainsWideningType */) { + if (ts.getObjectFlags(t) & 131072 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -43841,7 +44318,7 @@ var ts; return; } break; - case 289 /* JSDocFunctionType */: + case 294 /* JSDocFunctionType */: error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; case 239 /* FunctionDeclaration */: @@ -43868,14 +44345,14 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 131072 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type); } } } - function forEachMatchingParameterType(source, target, callback) { + function applyToParameterTypes(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); var sourceRestType = getEffectiveRestType(source); @@ -43896,24 +44373,54 @@ var ts; callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } - function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { - var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo); - var context = mapper; - context.typeParameters = typeParameters; - context.signature = signature; - context.inferences = inferences; - context.flags = flags; - context.compareTypes = compareTypes || compareTypesAssignable; + function applyToReturnTypes(source, target, callback) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind && + (sourceTypePredicate.kind === 0 /* This */ || sourceTypePredicate.parameterIndex === targetTypePredicate.parameterIndex)) { + callback(sourceTypePredicate.type, targetTypePredicate.type); + } + else { + callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } + function createInferenceContext(typeParameters, signature, flags, compareTypes) { + return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable); + } + function cloneInferenceContext(context, extraFlags) { + if (extraFlags === void 0) { extraFlags = 0; } + return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes); + } + function cloneInferredPartOfContext(context) { + var inferences = ts.filter(context.inferences, hasInferenceCandidates); + return inferences.length ? + createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) : + undefined; + } + function createInferenceContextWorker(inferences, signature, flags, compareTypes) { + var context = { + inferences: inferences, + signature: signature, + flags: flags, + compareTypes: compareTypes, + mapper: function (t) { return mapToInferredType(context, t, /*fix*/ true); }, + nonFixingMapper: function (t) { return mapToInferredType(context, t, /*fix*/ false); }, + }; return context; - function mapper(t) { - for (var i = 0; i < inferences.length; i++) { - if (t === inferences[i].typeParameter) { - inferences[i].isFixed = true; - return getInferredType(context, i); + } + function mapToInferredType(context, t, fix) { + var inferences = context.inferences; + for (var i = 0; i < inferences.length; i++) { + var inference = inferences[i]; + if (t === inference.typeParameter) { + if (fix && !inference.isFixed) { + inference.isFixed = true; + inference.inferredType = undefined; } + return getInferredType(context, i); } - return t; } + return t; } function createInferenceInfo(typeParameter) { return { @@ -43937,6 +44444,9 @@ var ts; isFixed: inference.isFixed }; } + function getMapperFromContext(context) { + return context && context.mapper; + } // Return true if the given type could possibly reference a type parameter for which // we perform type inference (i.e. a type parameter of a generic function). We cache // results for union and intersection types for performance reasons. @@ -44001,23 +44511,20 @@ var ts; // is incomplete and we can't infer a meaningful input type. for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { var prop = properties_3[_i]; - if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) { + if (ts.getObjectFlags(getTypeOfSymbol(prop)) & 524288 /* ContainsAnyFunctionType */) { return undefined; } } // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been // applied to the element type(s). if (isArrayType(source)) { - return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); - } - if (isReadonlyArrayType(source)) { - return createReadonlyArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint)); + return createArrayType(inferReverseMappedType(source.typeArguments[0], target, constraint), isReadonlyArrayType(source)); } if (isTupleType(source)) { var elementTypes = ts.map(source.typeArguments || ts.emptyArray, function (t) { return inferReverseMappedType(t, target, constraint); }); var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength; - return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.associatedNames); + return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.readonly, source.target.associatedNames); } // For all other object types we infer a new object type where the reverse mapping has been // applied to the type of each property. @@ -44091,11 +44598,11 @@ var ts; inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : emptyObjectType; } - function inferTypes(inferences, originalSource, originalTarget, priority) { + function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) { if (priority === void 0) { priority = 0; } + if (contravariant === void 0) { contravariant = false; } var symbolStack; var visited; - var contravariant = false; var bivariant = false; var propagationType; var allowComplexConstraintInference = true; @@ -44171,7 +44678,7 @@ var ts; // not contain anyFunctionType when we come back to this argument for its second round // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard // when constructing types from type parameters that had no inference candidates). - if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) { + if (ts.getObjectFlags(source) & 524288 /* ContainsAnyFunctionType */ || source === silentNeverType || (priority & 8 /* ReturnType */ && (source === autoType || source === autoArrayType))) { return; } var inference = getInferenceInfoForType(target); @@ -44180,6 +44687,7 @@ var ts; if (inference.priority === undefined || priority < inference.priority) { inference.candidates = undefined; inference.contraCandidates = undefined; + inference.topLevel = true; inference.priority = priority; } if (priority === inference.priority) { @@ -44187,14 +44695,19 @@ var ts; // We make contravariant inferences only if we are in a pure contravariant position, // i.e. only if we have not descended into a bivariant position. if (contravariant && !bivariant) { - inference.contraCandidates = ts.appendIfUnique(inference.contraCandidates, candidate); + if (!ts.contains(inference.contraCandidates, candidate)) { + inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + inference.inferredType = undefined; + } } - else { - inference.candidates = ts.appendIfUnique(inference.candidates, candidate); + else if (!ts.contains(inference.candidates, candidate)) { + inference.candidates = ts.append(inference.candidates, candidate); + inference.inferredType = undefined; } } - if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 8 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; + inference.inferredType = undefined; } } return; @@ -44218,6 +44731,9 @@ var ts; } } } + else if (target.flags & 33554432 /* Substitution */) { + inferFromTypes(source, target.typeVariable); + } if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { // If source and target are references to the same generic type, infer from type arguments var sourceTypes = source.typeArguments || ts.emptyArray; @@ -44254,42 +44770,32 @@ var ts; else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); - inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); - inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); + inferFromTypes(source.trueType, target.trueType); + inferFromTypes(source.falseType, target.falseType); } - else if (target.flags & 16777216 /* Conditional */) { - inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + else if (target.flags & 16777216 /* Conditional */ && !contravariant) { + inferFromTypes(source, target.trueType); + inferFromTypes(source, target.falseType); } else if (target.flags & 3145728 /* UnionOrIntersection */) { - var targetTypes = target.types; - var typeVariableCount = 0; - var typeVariable = void 0; - // First infer to each type in union or intersection that isn't a type variable - for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { - var t = targetTypes_3[_d]; + for (var _d = 0, _e = target.types; _d < _e.length; _d++) { + var t = _e[_d]; + var savePriority = priority; + // Inferences directly to naked type variables are given lower priority as they are + // less specific. For example, when inferring from Promise to T | Promise, + // we want to infer string for T, not Promise | string. if (getInferenceInfoForType(t)) { - typeVariable = t; - typeVariableCount++; - } - else { - inferFromTypes(source, t); + priority |= 1 /* NakedTypeVariable */; } - } - // Next, if target containings a single naked type variable, make a secondary inference to that type - // variable. This gives meaningful results for union types in co-variant positions and intersection - // types in contra-variant positions (such as callback parameters). - if (typeVariableCount === 1) { - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; - inferFromTypes(source, typeVariable); + inferFromTypes(source, t); priority = savePriority; } } else if (source.flags & 1048576 /* Union */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; - for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { - var sourceType = sourceTypes_3[_e]; + for (var _f = 0, sourceTypes_3 = sourceTypes; _f < sourceTypes_3.length; _f++) { + var sourceType = sourceTypes_3[_f]; inferFromTypes(sourceType, target); } } @@ -44305,7 +44811,7 @@ var ts; // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit. - // TL;DR: If we ever become generally more memory efficienct (or our resource budget ever increases), we should just + // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just // remove this `allowComplexConstraintInference` flag. allowComplexConstraintInference = false; return inferFromTypes(apparentSource, target); @@ -44367,12 +44873,12 @@ var ts; } return undefined; } - function inferFromMappedTypeConstraint(source, target, constraintType) { + function inferToMappedType(source, target, constraintType) { if (constraintType.flags & 1048576 /* Union */) { var result = false; for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) { var type = _a[_i]; - result = inferFromMappedTypeConstraint(source, target, type) || result; + result = inferToMappedType(source, target, type) || result; } return result; } @@ -44394,12 +44900,22 @@ var ts; return true; } if (constraintType.flags & 262144 /* TypeParameter */) { - // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type - // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type + // parameter. First infer from 'keyof S' to K. var savePriority = priority; priority |= 4 /* MappedTypeConstraint */; inferFromTypes(getIndexType(source), constraintType); priority = savePriority; + // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X }, + // where K extends keyof T, we make the same inferences as for a homomorphic mapped type + // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a + // Pick. + var extendedConstraint = getConstraintOfType(constraintType); + if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) { + return true; + } + // If no inferences can be made to K's constraint, infer from a union of the property types + // in the source to the template type X. var valueTypes = ts.compact([ getIndexTypeOfType(source, 0 /* String */), getIndexTypeOfType(source, 1 /* Number */) @@ -44418,7 +44934,7 @@ var ts; } if (ts.getObjectFlags(target) & 32 /* Mapped */) { var constraintType = getConstraintTypeFromMappedType(target); - if (inferFromMappedTypeConstraint(source, target, constraintType)) { + if (inferToMappedType(source, target, constraintType)) { return; } } @@ -44431,11 +44947,11 @@ var ts; } } function inferFromProperties(source, target) { - if (isTupleType(source)) { + if (isArrayType(source) || isTupleType(source)) { if (isTupleType(target)) { - var sourceLength = getLengthOfTupleType(source); + var sourceLength = isTupleType(source) ? getLengthOfTupleType(source) : 0; var targetLength = getLengthOfTupleType(target); - var sourceRestType = getRestTypeOfTupleType(source); + var sourceRestType = isTupleType(source) ? getRestTypeOfTupleType(source) : getElementTypeOfArrayType(source); var targetRestType = getRestTypeOfTupleType(target); var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; for (var i = 0; i < fixedLength; i++) { @@ -44472,7 +44988,7 @@ var ts; var sourceLen = sourceSignatures.length; var targetLen = targetSignatures.length; var len = sourceLen < targetLen ? sourceLen : targetLen; - var skipParameters = !!(source.flags & 536870912 /* ContainsAnyFunctionType */); + var skipParameters = !!(ts.getObjectFlags(source) & 524288 /* ContainsAnyFunctionType */); for (var i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -44483,17 +44999,10 @@ var ts; var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; // Once we descend into a bivariant signature we remain bivariant for all nested inferences bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */; - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + applyToParameterTypes(source, target, inferFromContravariantTypes); bivariant = saveBivariant; } - var sourceTypePredicate = getTypePredicateOfSignature(source); - var targetTypePredicate = getTypePredicateOfSignature(target); - if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { - inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); - } - else { - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } + applyToReturnTypes(source, target, inferFromTypes); } function inferFromIndexTypes(source, target) { var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */); @@ -44516,8 +45025,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -44610,7 +45119,7 @@ var ts; if (defaultType) { // Instantiate the default type. Any forward reference to a type // parameter should be instantiated to the empty object type. - inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper)); } else { inferredType = getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */)); @@ -44623,7 +45132,7 @@ var ts; inference.inferredType = inferredType; var constraint = getConstraintOfTypeParameter(inference.typeParameter); if (constraint) { - var instantiatedConstraint = instantiateType(constraint, context); + var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper); if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { inference.inferredType = inferredType = instantiatedConstraint; } @@ -44648,17 +45157,23 @@ var ts; case "console": return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; case "$": - return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig; + return compilerOptions.types + ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig + : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; case "describe": case "suite": case "it": case "test": - return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig; + return compilerOptions.types + ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig + : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; case "process": case "require": case "Buffer": case "module": - return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig; + return compilerOptions.types + ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig + : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; case "Map": case "Set": case "Promise": @@ -44794,9 +45309,8 @@ var ts; } return false; } - function hasNarrowableDeclaredType(expr) { - var type = getDeclaredTypeOfReference(expr); - return !!(type && type.flags & 1048576 /* Union */); + function isSyntheticThisPropertyAccess(expr) { + return ts.isAccessExpression(expr) && expr.expression.kind === 100 /* ThisKeyword */ && !!(expr.expression.flags & 8 /* Synthesized */); } function findDiscriminantProperties(sourceProperties, target) { var result; @@ -44873,8 +45387,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; result |= getTypeFacts(t); } return result; @@ -45154,7 +45668,7 @@ var ts; if (type.flags & 1048576 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.primitiveTypesOnly); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); } return f(type) ? type : neverType; } @@ -45168,8 +45682,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var current = types_12[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -45251,8 +45765,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -45750,6 +46264,15 @@ var ts; assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); + if ((type.flags & 2 /* Unknown */) && (operator === 35 /* EqualsEqualsEqualsToken */) && assumeTrue) { + if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) { + return valueType; + } + if (valueType.flags & 524288 /* Object */) { + return nonPrimitiveType; + } + return type; + } if (valueType.flags & 98304 /* Nullable */) { if (!strictNullChecks) { return type; @@ -45779,9 +46302,9 @@ var ts; // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { - // For a reference of the form 'x.y', where 'x' has a narrowable declared type, a - // 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) { + // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the + // narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, target)) { return declaredType; } return type; @@ -45822,13 +46345,37 @@ var ts; } } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { - // We only narrow if all case expressions specify values with unit types + // We only narrow if all case expressions specify + // values with unit types, except for the case where + // `type` is unknown. In this instance we map object + // types to the nonPrimitive type and narrow with that. var switchTypes = getSwitchClauseTypes(switchStatement); if (!switchTypes.length) { return type; } var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); + if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) { + var groundClauseTypes = void 0; + for (var i = 0; i < clauseTypes.length; i += 1) { + var t = clauseTypes[i]; + if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) { + if (groundClauseTypes !== undefined) { + groundClauseTypes.push(t); + } + } + else if (t.flags & 524288 /* Object */) { + if (groundClauseTypes === undefined) { + groundClauseTypes = clauseTypes.slice(0, i); + } + groundClauseTypes.push(nonPrimitiveType); + } + else { + return type; + } + } + return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes); + } var discriminantType = getUnionType(clauseTypes); var caseType = discriminantType.flags & 131072 /* Never */ ? neverType : replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); @@ -45929,9 +46476,14 @@ var ts; function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { - // For a reference of the form 'x.y', where 'x' has a narrowable declared type, an - // 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) { + // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the + // narrowed type of 'y' to its declared type. We do this because preceding 'x.y' + // references might reference a different 'y' property. However, we make an exception + // for property accesses where x is a synthetic 'this' expression, indicating that we + // were called from isPropertyInitializedInConstructor. Without this exception, + // initializations of 'this' properties that occur before a 'this instanceof XXX' + // check would not be considered. + if (containsMatchingReference(reference, left) && !isSyntheticThisPropertyAccess(reference)) { return declaredType; } return type; @@ -45998,7 +46550,7 @@ var ts; return type; } if (ts.isIdentifierTypePredicate(predicate)) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; + var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); @@ -46075,7 +46627,7 @@ var ts; return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || node.kind === 245 /* ModuleBlock */ || - node.kind === 279 /* SourceFile */ || + node.kind === 284 /* SourceFile */ || node.kind === 154 /* PropertyDeclaration */; }); } @@ -46196,7 +46748,7 @@ var ts; // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container.kind !== 279 /* SourceFile */) { + while (container.kind !== 284 /* SourceFile */) { if (container.parent === declaration) { if (container.kind === 154 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */; @@ -46302,6 +46854,7 @@ var ts; function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || + ts.isSourceFile(symbol.valueDeclaration) || symbol.valueDeclaration.parent.kind === 274 /* CatchClause */) { return; } @@ -46489,22 +47042,27 @@ var ts; if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) { captureLexicalThis(node, container); } - var type = tryGetThisTypeAt(node, container); - if (!type && noImplicitThis) { - // With noImplicitThis, functions may not reference 'this' if it has type 'any' - var diag = error(node, capturedByArrowFunction && container.kind === 279 /* SourceFile */ ? - ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : - ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); - if (!ts.isSourceFile(container)) { - var outsideThis = tryGetThisTypeAt(container); - if (outsideThis) { - addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container); + if (noImplicitThis) { + var globalThisType_1 = getTypeOfSymbol(globalThisSymbol); + if (type === globalThisType_1 && capturedByArrowFunction) { + error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this); + } + else if (!type) { + // With noImplicitThis, functions may not reference 'this' if it has type 'any' + var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + if (!ts.isSourceFile(container)) { + var outsideThis = tryGetThisTypeAt(container); + if (outsideThis && outsideThis !== globalThisType_1) { + ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + } } } } return type || anyType; } - function tryGetThisTypeAt(node, container) { + function tryGetThisTypeAt(node, includeGlobalThis, container) { + if (includeGlobalThis === void 0) { includeGlobalThis = true; } if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } var isInJS = ts.isInJSFile(node); if (ts.isFunctionLike(container) && @@ -46549,6 +47107,16 @@ var ts; return getFlowTypeOfReference(node, type); } } + if (ts.isSourceFile(container)) { + // look up in the source file's locals or exports + if (container.commonJsModuleIndicator) { + var fileSymbol = getSymbolOfNode(container); + return fileSymbol && getTypeOfSymbol(fileSymbol); + } + else if (includeGlobalThis) { + return getTypeOfSymbol(globalThisSymbol); + } + } } function getClassNameFromPrototypeMethod(container) { // Check if it's the RHS of a x.prototype.y = function [name]() { .... } @@ -46604,7 +47172,7 @@ var ts; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 289 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 294 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -46618,7 +47186,7 @@ var ts; } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 151 /* Parameter */; }); + return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 151 /* Parameter */ && n.parent === constructorDecl; }); } function checkSuperExpression(node) { var isCallExpression = node.parent.kind === 191 /* CallExpression */ && node.parent.expression === node; @@ -46843,7 +47411,7 @@ var ts; while (type) { var thisType = getThisTypeFromContextualType(type); if (thisType) { - return instantiateType(thisType, getContextualMapper(containingLiteral)); + return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral))); } if (literal.parent.kind !== 275 /* PropertyAssignment */) { break; @@ -47138,7 +47706,15 @@ var ts; } function getTypeOfPropertyOfContextualType(type, name) { return mapType(type, function (t) { - if (t.flags & 3670016 /* StructuredType */) { + if (isGenericMappedType(t)) { + var constraint = getConstraintTypeFromMappedType(t); + var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint; + var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name)); + if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) { + return substituteIndexedMappedType(t, propertyNameType); + } + } + else if (t.flags & 3670016 /* StructuredType */) { var prop = getPropertyOfType(t, name); if (prop) { return getTypeOfSymbol(prop); @@ -47274,18 +47850,46 @@ var ts; // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { - var contextualType = getContextualType(node); - contextualType = contextualType && mapType(contextualType, getApparentType); - if (contextualType && contextualType.flags & 1048576 /* Union */) { - if (ts.isObjectLiteralExpression(node)) { - return discriminateContextualTypeByObjectMembers(node, contextualType); + var contextualType = instantiateContextualType(getContextualType(node), node); + if (contextualType) { + var apparentType = mapType(contextualType, getApparentType, /*noReductions*/ true); + if (apparentType.flags & 1048576 /* Union */) { + if (ts.isObjectLiteralExpression(node)) { + return discriminateContextualTypeByObjectMembers(node, apparentType); + } + else if (ts.isJsxAttributes(node)) { + return discriminateContextualTypeByJSXAttributes(node, apparentType); + } } - else if (ts.isJsxAttributes(node)) { - return discriminateContextualTypeByJSXAttributes(node, contextualType); + return apparentType; + } + } + // If the given contextual type contains instantiable types and if a mapper representing + // return type inferences is available, instantiate those types using that mapper. + function instantiateContextualType(contextualType, node) { + if (contextualType && maybeTypeOfKind(contextualType, 63176704 /* Instantiable */)) { + var inferenceContext = getInferenceContext(node); + if (inferenceContext && inferenceContext.returnMapper) { + return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper); } } return contextualType; } + // This function is similar to instantiateType, except that (a) it only instantiates types that + // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs + // no reductions on instantiated union types. + function instantiateInstantiableTypes(type, mapper) { + if (type.flags & 63176704 /* Instantiable */) { + return instantiateType(type, mapper); + } + if (type.flags & 1048576 /* Union */) { + return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */); + } + if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); })); + } + return type; + } /** * Woah! Do you really want to use this function? * @@ -47331,7 +47935,7 @@ var ts; return getContextualTypeForArgument(parent, node); case 194 /* TypeAssertionExpression */: case 212 /* AsExpression */: - return getTypeFromTypeNode(parent.type); + return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type); case 204 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); case 275 /* PropertyAssignment */: @@ -47365,9 +47969,9 @@ var ts; } return undefined; } - function getContextualMapper(node) { - var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); - return ancestor ? ancestor.contextualMapper : identityMapper; + function getInferenceContext(node) { + var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; }); + return ancestor && ancestor.inferenceContext; } function getContextualJsxElementAttributesType(node) { if (ts.isJsxOpeningElement(node) && node.parent.contextualType) { @@ -47548,8 +48152,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var current = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var current = types_15[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -47567,12 +48171,7 @@ var ts; } } // Result is union of signatures collected (return type is union of return types of this signature set) - var result; - if (signatureList) { - result = cloneSignature(signatureList[0]); - result.unionSignatures = signatureList; - } - return result; + return signatureList && createUnionSignature(signatureList[0], signatureList); } function checkSpreadExpression(node, checkMode) { if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { @@ -47592,6 +48191,7 @@ var ts; var elementTypes = []; var inDestructuringPattern = ts.isAssignmentTarget(node); var contextualType = getApparentTypeOfContextualType(node); + var inConstContext = isConstContext(node); for (var index = 0; index < elementCount; index++) { var e = elements[index]; if (inDestructuringPattern && e.kind === 208 /* SpreadElement */) { @@ -47634,21 +48234,24 @@ var ts; type.pattern = node; return type; } - else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount)) { + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, inConstContext)) { return tupleResult; } else if (forceTuple) { return createTupleType(elementTypes, minLength, hasRestElement); } } - return getArrayLiteralType(elementTypes, 2 /* Subtype */); + return createArrayType(elementTypes.length ? + getUnionType(elementTypes, 2 /* Subtype */) : + strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext); } - function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount) { + function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, readonly) { if (elementCount === void 0) { elementCount = elementTypes.length; } + if (readonly === void 0) { readonly = false; } // Infer a tuple type when the contextual type is or contains a tuple-like type - if (contextualType && forEachType(contextualType, isTupleLikeType)) { + if (readonly || (contextualType && forEachType(contextualType, isTupleLikeType))) { var minLength = elementCount - (hasRestElement ? 1 : 0); - var pattern = contextualType.pattern; + var pattern = contextualType && contextualType.pattern; // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting // tuple type with the corresponding binding or assignment element types to make the lengths equal. if (!hasRestElement && pattern && (pattern.kind === 185 /* ArrayBindingPattern */ || pattern.kind === 187 /* ArrayLiteralExpression */)) { @@ -47666,15 +48269,9 @@ var ts; } } } - return createTupleType(elementTypes, minLength, hasRestElement); + return createTupleType(elementTypes, minLength, hasRestElement, readonly); } } - function getArrayLiteralType(elementTypes, unionReduction) { - if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } - return createArrayType(elementTypes.length ? - getUnionType(elementTypes, unionReduction) : - strictNullChecks ? implicitNeverType : undefinedWideningType); - } function isNumericName(name) { switch (name.kind) { case 149 /* ComputedPropertyName */: @@ -47737,15 +48334,15 @@ var ts; } return links.resolvedType; } - function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { + function getObjectLiteralIndexInfo(node, offset, properties, kind) { var propTypes = []; for (var i = 0; i < properties.length; i++) { - if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) { + if (kind === 0 /* String */ || isNumericName(node.properties[i + offset].name)) { propTypes.push(getTypeOfSymbol(properties[i])); } } var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType; - return createIndexInfo(unionType, /*isReadonly*/ false); + return createIndexInfo(unionType, isConstContext(node)); } function getImmediateAliasedSymbol(symbol) { ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); @@ -47765,14 +48362,15 @@ var ts; var propertiesTable; var propertiesArray = []; var spread = emptyObjectType; - var propagatedFlags = 0; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 184 /* ObjectBindingPattern */ || contextualType.pattern.kind === 188 /* ObjectLiteralExpression */); + var inConstContext = isConstContext(node); + var checkFlags = inConstContext ? 8 /* Readonly */ : 0; var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node); var enumTag = ts.getJSDocEnumTag(node); var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; - var typeFlags = 0; + var objectFlags = freshObjectLiteralFlag; var patternWithComputedProperties = false; var hasComputedStringProperty = false; var hasComputedNumberProperty = false; @@ -47799,11 +48397,11 @@ var ts; checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - typeFlags |= type.flags; + objectFlags |= ts.getObjectFlags(type) & 917504 /* PropagatingFlags */; var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; var prop = nameType ? - createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), 2048 /* Late */) : - createSymbol(4 /* Property */ | member.flags, member.escapedName); + createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 2048 /* Late */) : + createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags); if (nameType) { prop.nameType = nameType; } @@ -47841,19 +48439,18 @@ var ts; checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext); propertiesArray = []; propertiesTable = ts.createSymbolTable(); hasComputedStringProperty = false; hasComputedNumberProperty = false; - typeFlags = 0; } var type = checkExpression(memberDecl.expression); if (!isValidSpreadType(type)) { error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return errorType; } - spread = getSpreadType(spread, type, node.symbol, propagatedFlags, 32768 /* FreshLiteral */); + spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext); offset = i + 1; continue; } @@ -47900,17 +48497,16 @@ var ts; } if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, 32768 /* FreshLiteral */); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext); } return spread; } return createObjectLiteralType(); function createObjectLiteralType() { - var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; - var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; + var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined; + var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags & 939524096 /* PropagatingFlags */; - result.objectFlags |= 128 /* ObjectLiteral */ | freshObjectLiteralFlag; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */; if (isJSObjectLiteral) { result.objectFlags |= 16384 /* JSLiteral */; } @@ -47920,7 +48516,6 @@ var ts; if (inDestructuringPattern) { result.pattern = node; } - propagatedFlags |= result.flags & 939524096 /* PropagatingFlags */; return result; } } @@ -47996,7 +48591,6 @@ var ts; var hasSpreadAnyType = false; var typeToIntersect; var explicitlySpecifyChildrenAttribute = false; - var typeFlags = 0; var objectFlags = 4096 /* JsxAttributes */; var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { @@ -48004,7 +48598,7 @@ var ts; var member = attributeDecl.symbol; if (ts.isJsxAttribute(attributeDecl)) { var exprType = checkJsxAttribute(attributeDecl, checkMode); - typeFlags |= exprType.flags & 939524096 /* PropagatingFlags */; + objectFlags |= ts.getObjectFlags(exprType) & 917504 /* PropagatingFlags */; var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; @@ -48021,7 +48615,7 @@ var ts; else { ts.Debug.assert(attributeDecl.kind === 269 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false); attributesTable = ts.createSymbolTable(); } var exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -48029,7 +48623,7 @@ var ts; hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags); + spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -48038,7 +48632,7 @@ var ts; } if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false); } } // Handle children attribute @@ -48066,7 +48660,7 @@ var ts; childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol; var childPropMap = ts.createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); - spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, typeFlags, objectFlags); + spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false); } } if (hasSpreadAnyType) { @@ -48084,8 +48678,7 @@ var ts; function createJsxAttributesType() { objectFlags |= freshObjectLiteralFlag; var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 268435456 /* ContainsObjectLiteral */ | typeFlags; - result.objectFlags |= 128 /* ObjectLiteral */ | objectFlags; + result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 262144 /* ContainsObjectLiteral */; return result; } } @@ -48096,7 +48689,7 @@ var ts; // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that // because then type of children property will have constituent of string type. if (child.kind === 11 /* JsxText */) { - if (!child.containsOnlyWhiteSpaces) { + if (!child.containsOnlyTriviaWhiteSpaces) { childrenTypes.push(stringType); } } @@ -48167,7 +48760,7 @@ var ts; var namespaceName = getJsxNamespace(location); var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false); if (resolvedNamespace) { - var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */); + var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */)); if (candidate) { if (links) { links.jsxNamespace = candidate; @@ -48372,7 +48965,7 @@ var ts; // Mark local symbol as referenced here because it might not have been marked // if jsx emit was not react as there wont be error being emitted reactSym.isReferenced = 67108863 /* All */; - // If react symbol is alias, mark it as refereced + // If react symbol is alias, mark it as referenced if (reactSym.flags & 2097152 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { markAliasSymbolAsReferenced(reactSym); } @@ -48610,6 +49203,15 @@ var ts; if (isJSLiteralType(leftType)) { return anyType; } + if (leftType.symbol === globalThisSymbol) { + if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) { + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType)); + } + else if (noImplicitAny) { + error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType)); + } + return anyType; + } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { reportNonexistentProperty(right, leftType.flags & 262144 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); } @@ -48688,7 +49290,7 @@ var ts; diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); } if (diagnosticMessage) { - addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName)); + ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName)); } } function isInPropertyInitializer(node) { @@ -48697,7 +49299,19 @@ var ts; case 154 /* PropertyDeclaration */: return true; case 275 /* PropertyAssignment */: - // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + case 277 /* SpreadAssignment */: + case 149 /* ComputedPropertyName */: + case 216 /* TemplateSpan */: + case 270 /* JsxExpression */: + case 267 /* JsxAttribute */: + case 268 /* JsxAttributes */: + case 269 /* JsxSpreadAttribute */: + case 262 /* JsxOpeningElement */: + case 211 /* ExpressionWithTypeArguments */: + case 273 /* HeritageClause */: return false; default: return ts.isExpressionNode(node) ? false : "quit"; @@ -48765,7 +49379,7 @@ var ts; } var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo); if (relatedInfo) { - addRelatedInfo(resultDiagnostic, relatedInfo); + ts.addRelatedInfo(resultDiagnostic, relatedInfo); } diagnostics.add(resultDiagnostic); } @@ -49164,38 +49778,34 @@ var ts; return undefined; } // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) - function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { + function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) { var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); - var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; - forEachMatchingParameterType(sourceSignature, signature, function (source, target) { + // We clone the inferenceContext to avoid fixing. For example, when the source signature is (x: T) => T[] and + // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any') + // for T but leave it possible to later infer '[any]' back to A. + var restType = getEffectiveRestType(contextualSignature); + var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper); + var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature; + applyToParameterTypes(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type inferTypes(context.inferences, source, target); }); - if (!contextualMapper) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); + if (!inferenceContext) { + applyToReturnTypes(contextualSignature, signature, function (source, target) { + inferTypes(context.inferences, source, target, 8 /* ReturnType */); + }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } - function inferJsxTypeArguments(node, signature, excludeArgument, context) { + function inferJsxTypeArguments(node, signature, checkMode, context) { var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); - var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] !== undefined ? identityMapper : context); + var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode); inferTypes(context.inferences, checkAttrType, paramType); return getInferredTypes(context); } - function inferTypeArguments(node, signature, args, excludeArgument, context) { - // Clear out all the inference results from the last time inferTypeArguments was called on this context - for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { - var inference = _a[_i]; - // As an optimization, we don't have to clear (and later recompute) inferred types - // for type parameters that have already been fixed on the previous call to inferTypeArguments. - // It would be just as correct to reset all of them. But then we'd be repeating the same work - // for the type parameters that were fixed, namely the work done by getInferredType. - if (!inference.isFixed) { - inference.inferredType = undefined; - } - } + function inferTypeArguments(node, signature, args, checkMode, context) { if (ts.isJsxOpeningLikeElement(node)) { - return inferJsxTypeArguments(node, signature, excludeArgument, context); + return inferJsxTypeArguments(node, signature, checkMode, context); } // If a contextual type is available, infer from that type to the return type of the call expression. For // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression @@ -49204,10 +49814,11 @@ var ts; if (node.kind !== 152 /* Decorator */) { var contextualType = getContextualType(node); if (contextualType) { - // We clone the contextual mapper to avoid disturbing a resolution in progress for an + // We clone the inference context to avoid disturbing a resolution in progress for an // outer call expression. Effectively we just want a snapshot of whatever has been // inferred for any outer call expression so far. - var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); + var outerMapper = getMapperFromContext(cloneInferenceContext(getInferenceContext(node), 1 /* NoDefault */)); + var instantiatedType = instantiateType(contextualType, outerMapper); // If the contextual type is a generic function type with a single call signature, we // instantiate the type with its own type parameters and type arguments. This ensures that // the type parameters are not erased to type any during type inference such that they can @@ -49222,6 +49833,9 @@ var ts; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */); + // Create a type mapper for instantiating generic contextual types using the inferences made + // from the return type. + context.returnMapper = getMapperFromContext(cloneInferredPartOfContext(context)); } } var thisType = getThisTypeOfSignature(signature); @@ -49236,10 +49850,7 @@ var ts; var arg = args[i]; if (arg.kind !== 210 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; - var argType = checkExpressionWithContextualType(arg, paramType, mapper); + var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode); inferTypes(context.inferences, argType, paramType); } } @@ -49263,7 +49874,7 @@ var ts; // and the argument are ...x forms. return arg.kind === 215 /* SyntheticExpression */ ? createArrayType(arg.type) : - getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context)); + getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */)); } } var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; @@ -49271,7 +49882,7 @@ var ts; var types = []; var spreadIndex = -1; for (var i = index; i < argCount; i++) { - var argType = checkExpressionWithContextualType(args[i], contextualType, context); + var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */); if (spreadIndex < 0 && isSpreadArgument(args[i])) { spreadIndex = i - index; } @@ -49321,19 +49932,18 @@ var ts; * @param node a JSX opening-like element we are trying to figure its call signature * @param signature a candidate signature we are trying whether it is a call signature * @param relation a relationship to check parameter and argument type - * @param excludeArgument */ - function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors) { + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors) { // Stateless function components can have maximum of three arguments: "props", "context", and "updater". // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, // can be specified by users through attributes property. var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); - var attributesType = checkExpressionWithContextualType(node.attributes, paramType, excludeArgument && excludeArgument[0] ? identityMapper : undefined); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode); return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes); } - function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { + function checkApplicableSignature(node, args, signature, relation, checkMode, reportErrors) { if (ts.isJsxOpeningLikeElement(node)) { - return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, excludeArgument, reportErrors); + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors); } var thisType = getThisTypeOfSignature(signature); if (thisType && thisType !== voidType && node.kind !== 192 /* NewExpression */) { @@ -49355,11 +49965,11 @@ var ts; var arg = args[i]; if (arg.kind !== 210 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); - var argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode); + // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive), // we obtain the regular type of any object literal arguments because we may not have inferred complete // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType; if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage)) { return false; } @@ -49516,25 +50126,41 @@ var ts; if (argCount <= max && hasSpreadArgument) { argCount--; } + var spanArray; var related; + var error = hasRestParameter || hasSpreadArgument ? hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : + hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : ts.Diagnostics.Expected_0_arguments_but_got_1; if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; if (paramDecl) { related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); } } - if (hasRestParameter || hasSpreadArgument) { - var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; - var diagnostic_1 = ts.createDiagnosticForNode(node, error_1, paramRange, argCount); - return related ? addRelatedInfo(diagnostic_1, related) : diagnostic_1; - } if (min < argCount && argCount < max) { return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - var diagnostic = ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); - return related ? addRelatedInfo(diagnostic, related) : diagnostic; + if (!hasSpreadArgument && argCount < min) { + var diagnostic_1 = ts.createDiagnosticForNode(node, error, paramRange, argCount); + return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1; + } + if (hasRestParameter || hasSpreadArgument) { + spanArray = ts.createNodeArray(args); + if (hasSpreadArgument && argCount) { + var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined; + spanArray = ts.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : max)); + } + } + else { + spanArray = ts.createNodeArray(args.slice(max)); + } + spanArray.pos = ts.first(spanArray).pos; + spanArray.end = ts.last(spanArray).end; + if (spanArray.end === spanArray.pos) { + spanArray.end++; + } + var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount); + return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { var argCount = typeArguments.length; @@ -49564,7 +50190,7 @@ var ts; } return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } - function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { + function resolveCall(node, signatures, candidatesOutArray, checkMode, fallbackError) { var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */; var isDecorator = node.kind === 152 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); @@ -49600,7 +50226,7 @@ var ts; // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - var excludeArgument = !isDecorator && !isSingleNonGenericCandidate ? getExcludeArgument(args) : undefined; + var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */; // The following variables are captured and modified by calls to chooseOverload. // If overload resolution or type argument inference fails, we want to report the // best error possible. The best error is one which says that an argument was not @@ -49628,7 +50254,7 @@ var ts; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = isForSignatureHelp && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 191 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -49654,12 +50280,7 @@ var ts; // skip the checkApplicableSignature check. if (reportErrors) { if (candidateForArgumentError) { - // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] - // The importance of excludeArgument is to prevent us from typing function expression parameters - // in arguments too early. If possible, we'd like to only type them once we know the correct - // overload. However, this matters for the case where the call is correct. When the call is - // an error, we don't need to exclude any arguments, although it would cause no harm to do so. - checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, 0 /* Normal */, /*reportErrors*/ true); } else if (candidateForArgumentArityError) { diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); @@ -49691,7 +50312,7 @@ var ts; if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { return undefined; } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { + if (!checkApplicableSignature(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false)) { candidateForArgumentError = candidate; return undefined; } @@ -49715,9 +50336,10 @@ var ts; } else { inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); - typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext); + argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */; } - checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters); // If the original signature has a generic rest type, instantiation may produce a // signature with different arity and we need to perform another arity check. if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { @@ -49728,21 +50350,21 @@ var ts; else { checkCandidate = candidate; } - if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) { // Give preference to error candidates that have no rest parameters (as they are more specific) if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { candidateForArgumentError = checkCandidate; } continue; } - if (excludeArgument) { + if (argCheckMode) { // If one or more context sensitive arguments were excluded, we start including // them now (and keeping do so for any subsequent candidates) and perform a second // round of type inference and applicability checking for this particular candidate. - excludeArgument = undefined; + argCheckMode = 0 /* Normal */; if (inferenceContext) { - var typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration)); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters); // If the original signature has a generic rest type, instantiation may produce a // signature with different arity and we need to perform another arity check. if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { @@ -49750,7 +50372,7 @@ var ts; continue; } } - if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { + if (!checkApplicableSignature(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false)) { // Give preference to error candidates that have no rest parameters (as they are more specific) if (!candidateForArgumentError || getEffectiveRestType(candidateForArgumentError) || !getEffectiveRestType(checkCandidate)) { candidateForArgumentError = checkCandidate; @@ -49764,20 +50386,6 @@ var ts; return undefined; } } - function getExcludeArgument(args) { - var excludeArgument; - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - } - } - return excludeArgument; - } // No signature was applicable. We have already reported the errors for the invalid signature. // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { @@ -49866,7 +50474,7 @@ var ts; } function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) { var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */); - var typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); + var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext); return createSignatureInstantiation(candidate, typeArgumentTypes); } function getLongestCandidateIndex(candidates, argsCount) { @@ -49885,7 +50493,7 @@ var ts; } return maxParamsIndex; } - function resolveCallExpression(node, candidatesOutArray, isForSignatureHelp) { + function resolveCallExpression(node, candidatesOutArray, checkMode) { if (node.expression.kind === 98 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); if (isTypeAny(superType)) { @@ -49901,7 +50509,7 @@ var ts; var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); if (baseTypeNode) { var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); - return resolveCall(node, baseConstructors, candidatesOutArray, isForSignatureHelp); + return resolveCall(node, baseConstructors, candidatesOutArray, checkMode); } } return resolveUntypedCall(node); @@ -49951,12 +50559,31 @@ var ts; } return resolveErrorCall(node); } + // When a call to a generic function is an argument to an outer call to a generic function for which + // inference is in process, we have a choice to make. If the inner call relies on inferences made from + // its contextual type to its return type, deferring the inner call processing allows the best possible + // contextual type to accumulate. But if the outer call relies on inferences made from the return type of + // the inner call, the inner call should be processed early. There's no sure way to know which choice is + // right (only a full unification algorithm can determine that), so we resort to the following heuristic: + // If no type arguments are specified in the inner call and at least one call signature is generic and + // returns a function type, we choose to defer processing. This narrowly permits function composition + // operators to flow inferences through return types, but otherwise processes calls right away. We + // use the resolvingSignature singleton to indicate that we deferred processing. This result will be + // propagated out and eventually turned into silentNeverType (a type that is assignable to anything and + // from which we never make inferences). + if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) { + skippedGenericFunction(node, checkMode); + return resolvingSignature; + } // If the function is explicitly marked with `@class`, then it must be constructed. if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) { error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode); + } + function isGenericFunctionReturningFunction(signature) { + return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature))); } /** * TS 1.0 spec: 4.12 @@ -49968,7 +50595,7 @@ var ts; return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) || !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } - function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { + function resolveNewExpression(node, candidatesOutArray, checkMode) { if (node.arguments && languageVersion < 1 /* ES5 */) { var spreadIndex = getSpreadArgumentIndex(node.arguments); if (spreadIndex >= 0) { @@ -50016,7 +50643,7 @@ var ts; error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class); return resolveErrorCall(node); } - return resolveCall(node, constructSignatures, candidatesOutArray, isForSignatureHelp); + return resolveCall(node, constructSignatures, candidatesOutArray, checkMode); } // If expressionType's apparent type is an object type with no construct signatures but // one or more call signatures, the expression is processed as a function call. A compile-time @@ -50024,7 +50651,7 @@ var ts; // operation is Any. It is an error to have a Void this type. var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode); if (!noImplicitAny) { if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); @@ -50046,13 +50673,12 @@ var ts; var firstBase = baseTypes[0]; if (firstBase.flags & 2097152 /* Intersection */) { var types = firstBase.types; - var mixinCount = ts.countWhere(types, isMixinConstructorType); + var mixinFlags = findMixins(types); var i = 0; for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) { var intersectionMember = _a[_i]; - i++; // We want to ignore mixin ctors - if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(intersectionMember)) { + if (!mixinFlags[i]) { if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) { if (intersectionMember.symbol === target) { return true; @@ -50062,6 +50688,7 @@ var ts; } } } + i++; } return false; } @@ -50105,7 +50732,7 @@ var ts; var diagnostic = error(node, (kind === 0 /* Call */ ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature), typeToString(apparentType)); - invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); + invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { @@ -50118,10 +50745,10 @@ var ts; var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); if (!sigs || !sigs.length) return; - addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); } } - function resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp) { + function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); if (apparentType === errorType) { @@ -50137,7 +50764,7 @@ var ts; invocationError(node, apparentType, 0 /* Call */); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode); } /** * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. @@ -50162,7 +50789,7 @@ var ts; /** * Resolves a decorator as if it were a call expression. */ - function resolveDecorator(node, candidatesOutArray, isForSignatureHelp) { + function resolveDecorator(node, candidatesOutArray, checkMode) { var funcType = checkExpression(node.expression); var apparentType = getApparentType(funcType); if (apparentType === errorType) { @@ -50187,7 +50814,7 @@ var ts; invocationErrorRecovery(apparentType, 0 /* Call */, diag); return resolveErrorCall(node); } - return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp, headMessage); + return resolveCall(node, callSignatures, candidatesOutArray, checkMode, headMessage); } function createSignatureForJSXIntrinsic(node, result) { var namespace = getJsxNamespaceAt(node); @@ -50206,11 +50833,11 @@ var ts; /*hasRestparameter*/ false, /*hasLiteralTypes*/ false); } - function resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp) { + function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) { if (isJsxIntrinsicIdentifier(node.tagName)) { var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); var fakeSignature = createSignatureForJSXIntrinsic(node, result); - checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), result, node.tagName, node.attributes); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes); return fakeSignature; } var exprTypes = checkExpression(node.tagName); @@ -50227,7 +50854,7 @@ var ts; error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); return resolveErrorCall(node); } - return resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp); + return resolveCall(node, signatures, candidatesOutArray, checkMode); } /** * Sometimes, we have a decorator that could accept zero arguments, @@ -50241,19 +50868,19 @@ var ts; signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } - function resolveSignature(node, candidatesOutArray, isForSignatureHelp) { + function resolveSignature(node, candidatesOutArray, checkMode) { switch (node.kind) { case 191 /* CallExpression */: - return resolveCallExpression(node, candidatesOutArray, isForSignatureHelp); + return resolveCallExpression(node, candidatesOutArray, checkMode); case 192 /* NewExpression */: - return resolveNewExpression(node, candidatesOutArray, isForSignatureHelp); + return resolveNewExpression(node, candidatesOutArray, checkMode); case 193 /* TaggedTemplateExpression */: - return resolveTaggedTemplateExpression(node, candidatesOutArray, isForSignatureHelp); + return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode); case 152 /* Decorator */: - return resolveDecorator(node, candidatesOutArray, isForSignatureHelp); + return resolveDecorator(node, candidatesOutArray, checkMode); case 262 /* JsxOpeningElement */: case 261 /* JsxSelfClosingElement */: - return resolveJsxOpeningLikeElement(node, candidatesOutArray, isForSignatureHelp); + return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode); } throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } @@ -50264,8 +50891,7 @@ var ts; * the function will fill it up with appropriate candidate signatures * @return a signature of the call-like expression or undefined if one can't be found */ - function getResolvedSignature(node, candidatesOutArray, isForSignatureHelp) { - if (isForSignatureHelp === void 0) { isForSignatureHelp = false; } + function getResolvedSignature(node, candidatesOutArray, checkMode) { var links = getNodeLinks(node); // If getResolvedSignature has already been called, we will have cached the resolvedSignature. // However, it is possible that either candidatesOutArray was not passed in the first time, @@ -50276,11 +50902,15 @@ var ts; return cached; } links.resolvedSignature = resolvingSignature; - var result = resolveSignature(node, candidatesOutArray, isForSignatureHelp); - // If signature resolution originated in control flow type analysis (for example to compute the - // assigned type in a flow assignment) we don't cache the result as it may be based on temporary - // types from the control flow analysis. - links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; + var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */); + // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call + // resolution should be deferred. + if (result !== resolvingSignature) { + // If signature resolution originated in control flow type analysis (for example to compute the + // assigned type in a flow assignment) we don't cache the result as it may be based on temporary + // types from the control flow analysis. + links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; + } return result; } /** @@ -50356,10 +50986,15 @@ var ts; * @param node The call/new expression to be checked. * @returns On success, the expression's signature's return type. On failure, anyType. */ - function checkCallExpression(node) { + function checkCallExpression(node, checkMode) { if (!checkGrammarTypeArguments(node, node.typeArguments)) checkGrammarArguments(node.arguments); - var signature = getResolvedSignature(node); + var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode); + if (signature === resolvingSignature) { + // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that + // returns a function type. We defer checking and return anyFunctionType. + return silentNeverType; + } if (node.expression.kind === 98 /* SuperKeyword */) { return voidType; } @@ -50459,7 +51094,7 @@ var ts; var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); anonymousSymbol.type = defaultContainingObject; - synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*typeFLags*/ 0, /*objectFlags*/ 0) : defaultContainingObject; + synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject; } else { synthType.syntheticType = type; @@ -50506,9 +51141,37 @@ var ts; function checkAssertion(node) { return checkAssertionWorker(node, node.type, node.expression); } + function isValidConstAssertionArgument(node) { + switch (node.kind) { + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + case 8 /* NumericLiteral */: + case 9 /* BigIntLiteral */: + case 102 /* TrueKeyword */: + case 87 /* FalseKeyword */: + case 187 /* ArrayLiteralExpression */: + case 188 /* ObjectLiteralExpression */: + return true; + case 195 /* ParenthesizedExpression */: + return isValidConstAssertionArgument(node.expression); + case 202 /* PrefixUnaryExpression */: + var op = node.operator; + var arg = node.operand; + return op === 39 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) || + op === 38 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */; + } + return false; + } function checkAssertionWorker(errNode, type, expression, checkMode) { - var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode))); + var exprType = checkExpression(expression, checkMode); + if (ts.isConstTypeReference(type)) { + if (!isValidConstAssertionArgument(expression)) { + error(expression, ts.Diagnostics.A_const_assertion_can_only_be_applied_to_a_string_number_boolean_array_or_object_literal); + } + return getRegularTypeOfLiteralType(exprType); + } checkSourceElement(type); + exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType)); var targetType = getTypeFromTypeNode(type); if (produceDiagnostics && targetType !== errorType) { var widenedType = getWidenedType(exprType); @@ -50547,7 +51210,7 @@ var ts; } } function checkImportMetaProperty(node) { - if (languageVersion < 6 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) { + if (languageVersion < 7 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) { error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options); } var file = ts.getSourceFileOfNode(node); @@ -50575,7 +51238,7 @@ var ts; if (isTupleType(restType)) { var associatedNames = restType.target.associatedNames; var index = pos - paramCount; - return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index; + return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index; } return restParameter.escapedName; } @@ -50588,33 +51251,37 @@ var ts; return getTypeOfParameter(signature.parameters[pos]); } if (signature.hasRestParameter) { + // We want to return the value undefined for an out of bounds parameter position, + // so we need to check bounds here before calling getIndexedAccessType (which + // otherwise would return the type 'undefined'). var restType = getTypeOfSymbol(signature.parameters[paramCount]); - if (isTupleType(restType)) { - if (pos - paramCount < getLengthOfTupleType(restType)) { - return restType.typeArguments[pos - paramCount]; - } - return getRestTypeOfTupleType(restType); + var index = pos - paramCount; + if (!isTupleType(restType) || restType.target.hasRestElement || index < (restType.typeArguments || ts.emptyArray).length) { + return getIndexedAccessType(restType, getLiteralType(index)); } - return getIndexTypeOfType(restType, 1 /* Number */); } return undefined; } function getRestTypeAtPosition(source, pos) { var paramCount = getParameterCount(source); var restType = getEffectiveRestType(source); - if (restType && pos === paramCount - 1) { + var nonRestCount = paramCount - (restType ? 1 : 0); + if (restType && pos === nonRestCount) { return restType; } - var start = restType ? Math.min(pos, paramCount - 1) : pos; var types = []; var names = []; - for (var i = start; i < paramCount; i++) { + for (var i = pos; i < nonRestCount; i++) { types.push(getTypeAtPosition(source, i)); names.push(getParameterNameAtPosition(source, i)); } + if (restType) { + types.push(getIndexedAccessType(restType, numberType)); + names.push(getParameterNameAtPosition(source, nonRestCount)); + } var minArgumentCount = getMinArgumentCount(source); - var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; - return createTupleType(types, minLength, !!restType, names); + var minLength = minArgumentCount < pos ? 0 : minArgumentCount - pos; + return createTupleType(types, minLength, !!restType, /*readonly*/ false, names); } function getParameterCount(signature) { var length = signature.parameters.length; @@ -50662,17 +51329,28 @@ var ts; function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) { return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; } - function inferFromAnnotatedParameters(signature, context, mapper) { + function inferFromAnnotatedParameters(signature, context, inferenceContext) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); for (var i = 0; i < len; i++) { var declaration = signature.parameters[i].valueDeclaration; if (declaration.type) { var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); if (typeNode) { - inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i)); + inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i)); } } } + var restType = getEffectiveRestType(context); + if (restType && restType.flags & 262144 /* TypeParameter */) { + // The contextual signature has a generic rest parameter. We first instantiate the contextual + // signature (without fixing type parameters) and assign types to contextually typed parameters. + var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper); + assignContextualParameterTypes(signature, instantiatedContext); + // We then infer from a tuple type representing the parameters that correspond to the contextual + // rest parameter. + var restPos = getParameterCount(context) - 1; + inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType); + } } function assignContextualParameterTypes(signature, context) { signature.typeParameters = context.typeParameters; @@ -50773,7 +51451,7 @@ var ts; var functionFlags = ts.getFunctionFlags(func); var type; if (func.body.kind !== 218 /* Block */) { - type = checkExpressionCached(func.body, checkMode); + type = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */); if (functionFlags & 2 /* Async */) { // From within an async function you can return either a non-promise value or a promise. Any // Promise/A+ compatible implementation will always assimilate any foreign promise, so the @@ -50951,7 +51629,7 @@ var ts; ts.forEachReturnStatement(func.body, function (returnStatement) { var expr = returnStatement.expression; if (expr) { - var type = checkExpressionCached(expr, checkMode); + var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */); if (functionFlags & 2 /* Async */) { // From within an async function you can return either a non-promise value or a promise. Any // Promise/A+ compatible implementation will always assimilate any foreign promise, so the @@ -51044,7 +51722,7 @@ var ts; ts.Debug.assert(node.kind !== 156 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); checkNodeDeferred(node); // The identityMapper object is used to indicate that function expressions are wildcards - if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { + if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) { // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage if (!ts.getEffectiveReturnTypeNode(node) && hasContextSensitiveReturnExpression(node)) { var links_1 = getNodeLinks(node); @@ -51054,7 +51732,7 @@ var ts; var returnType = getReturnTypeFromBody(node, checkMode); var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); - returnOnlyType.flags |= 536870912 /* ContainsAnyFunctionType */; + returnOnlyType.objectFlags |= 524288 /* ContainsAnyFunctionType */; return links_1.contextFreeType = returnOnlyType; } return anyFunctionType; @@ -51080,12 +51758,12 @@ var ts; if (contextualSignature) { var signature = getSignaturesOfType(type, 0 /* Call */)[0]; if (isContextSensitive(node)) { - var contextualMapper = getContextualMapper(node); - if (checkMode === 2 /* Inferential */) { - inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper); + var inferenceContext = getInferenceContext(node); + if (checkMode && checkMode & 2 /* Inferential */) { + inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext); } - var instantiatedContextualSignature = contextualMapper === identityMapper ? - contextualSignature : instantiateSignature(contextualSignature, contextualMapper); + var instantiatedContextualSignature = inferenceContext ? + instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature; assignContextualParameterTypes(signature, instantiatedContextualSignature); } if (!getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) { @@ -51351,13 +52029,13 @@ var ts; // Return true if type might be of the given kind. A union or intersection type might be of a given // kind if at least one constituent type is of the given kind. function maybeTypeOfKind(type, kind) { - if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) { + if (type.flags & kind & ~131072 /* GenericMappedType */ || kind & 131072 /* GenericMappedType */ && isGenericMappedType(type)) { return true; } if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -51461,7 +52139,7 @@ var ts; return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } else if (property.kind === 277 /* SpreadAssignment */) { - if (languageVersion < 6 /* ESNext */) { + if (languageVersion < 7 /* ESNext */) { checkExternalEmitHelpers(property, 4 /* Rest */); } var nonRestNames = []; @@ -51956,7 +52634,7 @@ var ts; // Async generator functions prior to ESNext require the __await, __asyncDelegator, // and __asyncValues helpers if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && - languageVersion < 6 /* ESNext */) { + languageVersion < 7 /* ESNext */) { checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); } // Generator functions prior to ES2015 require the __values helper @@ -52003,23 +52681,26 @@ var ts; } return node; } - function checkExpressionWithContextualType(node, contextualType, contextualMapper) { + function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) { var context = getContextNode(node); var saveContextualType = context.contextualType; - var saveContextualMapper = context.contextualMapper; + var saveInferenceContext = context.inferenceContext; context.contextualType = contextualType; - context.contextualMapper = contextualMapper; - var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ : - contextualMapper ? 2 /* Inferential */ : 3 /* Contextual */; - var result = checkExpression(node, checkMode); + context.inferenceContext = inferenceContext; + var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0)); + // We strip literal freshness when an appropriate contextual type is present such that contextually typed + // literals always preserve their literal types (otherwise they might widen during type inference). An alternative + // here would be to not mark contextually typed literals as fresh in the first place. + var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ? + getRegularTypeOfLiteralType(type) : type; context.contextualType = saveContextualType; - context.contextualMapper = saveContextualMapper; + context.inferenceContext = saveInferenceContext; return result; } function checkExpressionCached(node, checkMode) { var links = getNodeLinks(node); if (!links.resolvedType) { - if (checkMode) { + if (checkMode && checkMode !== 0 /* Normal */) { return checkExpression(node, checkMode); } // When computing a type that we're going to cache, we need to ignore any ongoing control flow @@ -52082,13 +52763,17 @@ var ts; } return false; } + function isConstContext(node) { + var parent = node.parent; + return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) || + (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) || + (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) && isConstContext(parent.parent); + } function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) { - if (arguments.length === 2) { - contextualType = getContextualType(node); - } var type = checkExpression(node, checkMode, forceTuple); - return isTypeAssertion(node) ? type : - getWidenedLiteralLikeTypeForContextualType(type, contextualType); + return isConstContext(node) ? getRegularTypeOfLiteralType(type) : + isTypeAssertion(node) ? type : + getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node)); } function checkPropertyAssignment(node, checkMode) { // Do not use hasDynamicName here, because that returns false for well known symbols. @@ -52112,20 +52797,129 @@ var ts; return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); } function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { - if (checkMode === 2 /* Inferential */) { + if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) { var signature = getSingleCallSignature(type); if (signature && signature.typeParameters) { + if (checkMode & 8 /* SkipGenericFunctions */) { + skippedGenericFunction(node, checkMode); + return anyFunctionType; + } var contextualType = getApparentTypeOfContextualType(node); if (contextualType) { var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType)); if (contextualSignature && !contextualSignature.typeParameters) { - return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node))); + var context = getInferenceContext(node); + // We have an expression that is an argument of a generic function for which we are performing + // type argument inference. The expression is of a function type with a single generic call + // signature and a contextual function type with a single non-generic call signature. Now check + // if the outer function returns a function type with a single non-generic call signature and + // if some of the outer function type parameters have no inferences so far. If so, we can + // potentially add inferred type parameters to the outer function return type. + var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature)); + if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) { + // Instantiate the signature with its own type parameters as type arguments, possibly + // renaming the type parameters to ensure they have unique names. + var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters); + var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters); + // Infer from the parameters of the instantiated signature to the parameters of the + // contextual signature starting with an empty set of inference candidates. + var inferences_2 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); }); + applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) { + inferTypes(inferences_2, source, target, /*priority*/ 0, /*contravariant*/ true); + }); + if (ts.some(inferences_2, hasInferenceCandidates)) { + // We have inference candidates, indicating that one or more type parameters are referenced + // in the parameter types of the contextual signature. Now also infer from the return type. + applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) { + inferTypes(inferences_2, source, target); + }); + // If the type parameters for which we produced candidates do not have any inferences yet, + // we adopt the new inference candidates and add the type parameters of the expression type + // to the set of inferred type parameters for the outer function return type. + if (!hasOverlappingInferences(context.inferences, inferences_2)) { + mergeInferences(context.inferences, inferences_2); + context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters); + return getOrCreateTypeFromSignature(instantiatedSignature); + } + } + } + return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context)); } } } } return type; } + function skippedGenericFunction(node, checkMode) { + if (checkMode & 2 /* Inferential */) { + // We have skipped a generic function during inferential typing. Obtain the inference context and + // indicate this has occurred such that we know a second pass of inference is be needed. + var context = getInferenceContext(node); + context.flags |= 4 /* SkippedGenericFunction */; + } + } + function hasInferenceCandidates(info) { + return !!(info.candidates || info.contraCandidates); + } + function hasOverlappingInferences(a, b) { + for (var i = 0; i < a.length; i++) { + if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) { + return true; + } + } + return false; + } + function mergeInferences(target, source) { + for (var i = 0; i < target.length; i++) { + if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) { + target[i] = source[i]; + } + } + } + function getUniqueTypeParameters(context, typeParameters) { + var result = []; + var oldTypeParameters; + var newTypeParameters; + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var tp = typeParameters_2[_i]; + var name = tp.symbol.escapedName; + if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) { + var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name); + var symbol = createSymbol(262144 /* TypeParameter */, newName); + var newTypeParameter = createTypeParameter(symbol); + newTypeParameter.target = tp; + oldTypeParameters = ts.append(oldTypeParameters, tp); + newTypeParameters = ts.append(newTypeParameters, newTypeParameter); + result.push(newTypeParameter); + } + else { + result.push(tp); + } + } + if (newTypeParameters) { + var mapper = createTypeMapper(oldTypeParameters, newTypeParameters); + for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) { + var tp = newTypeParameters_1[_a]; + tp.mapper = mapper; + } + } + return result; + } + function hasTypeParameterByName(typeParameters, name) { + return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; }); + } + function getUniqueTypeParameterName(typeParameters, baseName) { + var len = baseName.length; + while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */) + len--; + var s = baseName.slice(0, len); + for (var index = 1; true; index++) { + var augmentedName = (s + index); + if (!hasTypeParameterByName(typeParameters, augmentedName)) { + return augmentedName; + } + } + } /** * Returns the type of an expression. Unlike checkExpression, this function is simply concerned * with computing the type and may not fully check all contained sub-expressions for errors. @@ -52143,7 +52937,7 @@ var ts; return getReturnTypeOfSignature(signature); } } - else if (expr.kind === 194 /* TypeAssertionExpression */ || expr.kind === 212 /* AsExpression */) { + else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) { return getTypeFromTypeNode(expr.type); } // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions @@ -52165,40 +52959,40 @@ var ts; } var saveContextualType = node.contextualType; node.contextualType = anyType; - var type = links.contextFreeType = checkExpression(node, 1 /* SkipContextSensitive */); + var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */); node.contextualType = saveContextualType; return type; } - // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When - // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the - // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in - // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function - // object, it serves as an indicator that all contained function and arrow expressions should be considered to - // have the wildcard function type; this form of type check is used during overload resolution to exclude - // contextually typed function and arrow expressions in the initial phase. function checkExpression(node, checkMode, forceTuple) { - var type; - if (node.kind === 148 /* QualifiedName */) { - type = checkQualifiedName(node); + var saveCurrentNode = currentNode; + currentNode = node; + var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); + var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + if (isConstEnumObjectType(type)) { + checkConstEnumAccess(node, type); } - else { - var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple); - type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + currentNode = saveCurrentNode; + return type; + } + function checkConstEnumAccess(node, type) { + // enum object type for const enums are only permitted in: + // - 'left' in property access + // - 'object' in indexed access + // - target in rhs of import statement + var ok = (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 190 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 167 /* TypeQuery */ && node.parent.exprName === node)); + if (!ok) { + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } - if (isConstEnumObjectType(type)) { - // enum object type for const enums are only permitted in: - // - 'left' in property access - // - 'object' in indexed access - // - target in rhs of import statement - var ok = (node.parent.kind === 189 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 190 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 72 /* Identifier */ || node.kind === 148 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || - (node.parent.kind === 167 /* TypeQuery */ && node.parent.exprName === node)); - if (!ok) { - error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); + if (compilerOptions.isolatedModules) { + ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */)); + var constEnumDeclaration = type.symbol.valueDeclaration; + if (constEnumDeclaration.flags & 4194304 /* Ambient */) { + error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided); } } - return type; } function checkParenthesizedExpression(node, checkMode) { var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; @@ -52240,6 +53034,8 @@ var ts; return checkObjectLiteral(node, checkMode); case 189 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); + case 148 /* QualifiedName */: + return checkQualifiedName(node); case 190 /* ElementAccessExpression */: return checkIndexedAccess(node); case 191 /* CallExpression */: @@ -52248,7 +53044,7 @@ var ts; } /* falls through */ case 192 /* NewExpression */: - return checkCallExpression(node); + return checkCallExpression(node, checkMode); case 193 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); case 195 /* ParenthesizedExpression */: @@ -52313,9 +53109,8 @@ var ts; checkSourceElement(node.constraint); checkSourceElement(node.default); var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); - if (!hasNonCircularBaseConstraint(typeParameter)) { - error(ts.getEffectiveConstraintOfTypeParameter(node), ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); - } + // Resolve base constraint to reveal circularity errors + getBaseConstraintOfType(typeParameter); if (!hasNonCircularTypeParameterDefault(typeParameter)) { error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); } @@ -52357,7 +53152,7 @@ var ts; } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyArrayType)) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getTypeOfSymbol(node.symbol), anyReadonlyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -52368,7 +53163,8 @@ var ts; error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); return; } - var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); + var signature = getSignatureFromDeclaration(parent); + var typePredicate = getTypePredicateOfSignature(signature); if (!typePredicate) { return; } @@ -52379,12 +53175,12 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, + checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ undefined, leadingError); } } @@ -52451,7 +53247,7 @@ var ts; var functionFlags = ts.getFunctionFlags(node); if (!(functionFlags & 4 /* Invalid */)) { // Async generators prior to ESNext require the __await and __asyncGenerator helpers - if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 6 /* ESNext */) { + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 7 /* ESNext */) { checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); } // Async functions prior to ES2017 require the __awaiter helper @@ -52508,7 +53304,7 @@ var ts; checkAsyncFunctionReturnType(node, returnTypeNode); } } - if (node.kind !== 162 /* IndexSignature */ && node.kind !== 289 /* JSDocFunctionType */) { + if (node.kind !== 162 /* IndexSignature */ && node.kind !== 294 /* JSDocFunctionType */) { registerForUnusedIdentifiersCheck(node); } } @@ -53187,7 +53983,7 @@ var ts; for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { var signature = signatures_6[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { - error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); + ts.addRelatedInfo(error(signature.declaration, ts.Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), ts.createDiagnosticForNode(bodyDeclaration, ts.Diagnostics.The_implementation_signature_is_declared_here)); break; } } @@ -53264,8 +54060,8 @@ var ts; case 241 /* InterfaceDeclaration */: case 242 /* TypeAliasDeclaration */: // A jsdoc typedef and callback are, by definition, type aliases - case 304 /* JSDocTypedefTag */: - case 297 /* JSDocCallbackTag */: + case 309 /* JSDocTypedefTag */: + case 302 /* JSDocCallbackTag */: return 2 /* ExportType */; case 244 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ @@ -53274,7 +54070,7 @@ var ts; case 240 /* ClassDeclaration */: case 243 /* EnumDeclaration */: return 2 /* ExportType */ | 1 /* ExportValue */; - case 279 /* SourceFile */: + case 284 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; case 254 /* ExportAssignment */: // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values @@ -53639,8 +54435,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var typeNode = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var typeNode = types_17[_i]; while (typeNode.kind === 177 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -53915,7 +54711,7 @@ var ts; checkUnusedClassMembers(node, addDiagnostic); checkUnusedTypeParameters(node, addDiagnostic); break; - case 279 /* SourceFile */: + case 284 /* SourceFile */: case 244 /* ModuleDeclaration */: case 218 /* Block */: case 246 /* CaseBlock */: @@ -54008,8 +54804,8 @@ var ts; return; var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); var seenParentsWithEveryUnused = new ts.NodeSet(); - for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { - var typeParameter = typeParameters_2[_i]; + for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) { + var typeParameter = typeParameters_3[_i]; if (!isTypeParameterUnused(typeParameter)) continue; var name = ts.idText(typeParameter.name); @@ -54262,7 +55058,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -54277,7 +55073,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 279 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + if (parent.kind === 284 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -54334,7 +55130,7 @@ var ts; (container.kind === 218 /* Block */ && ts.isFunctionLike(container.parent) || container.kind === 245 /* ModuleBlock */ || container.kind === 244 /* ModuleDeclaration */ || - container.kind === 279 /* SourceFile */); + container.kind === 284 /* SourceFile */); // here we know that function scoped variable is shadowed by block scoped one // if they are defined in the same scope - binder has already reported redeclaration error // otherwise if variable has an initializer - show error that initialization will fail @@ -54434,7 +55230,7 @@ var ts; } } if (node.kind === 186 /* BindingElement */) { - if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { + if (node.parent.kind === 184 /* ObjectBindingPattern */ && languageVersion < 7 /* ESNext */) { checkExternalEmitHelpers(node, 4 /* Rest */); } // check computed properties inside property names of binding elements @@ -54445,7 +55241,7 @@ var ts; var parent = node.parent.parent; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; - if (!ts.isBindingPattern(name) && parentType) { + if (parentType && !ts.isBindingPattern(name)) { var exprType = getLiteralTypeFromPropertyName(name); if (isTypeUsableAsPropertyName(exprType)) { var nameText = getPropertyNameFromType(exprType); @@ -54632,7 +55428,7 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.awaitModifier) { var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); - if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) { + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 7 /* ESNext */) { // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); } @@ -55077,7 +55873,7 @@ var ts; // If the function has a return type, but promisedType is // undefined, an error will be reported in checkAsyncFunctionReturnType // so we don't need to report one here. - checkTypeAssignableTo(awaitedType, promisedType, node); + checkTypeAssignableToAndOptionallyElaborate(awaitedType, promisedType, node, node.expression); } } else { @@ -55948,10 +56744,6 @@ var ts; checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); - var enumIsConst = ts.isEnumConst(node); - if (compilerOptions.isolatedModules && enumIsConst && node.flags & 4194304 /* Ambient */) { - error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); - } // Spec 2014 - Section 9.3: // It isn't possible for one enum declaration to continue the automatic numbering sequence of another, // and when an enum type has multiple declarations, only one declaration is permitted to omit a value @@ -55962,9 +56754,10 @@ var ts; var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); if (node === firstDeclaration) { if (enumSymbol.declarations.length > 1) { + var enumIsConst_1 = ts.isEnumConst(node); // check that const is placed\omitted on all enum declarations ts.forEach(enumSymbol.declarations, function (decl) { - if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst) { + if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) { error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); @@ -56045,8 +56838,8 @@ var ts; var symbol = getSymbolOfNode(node); // The following checks only apply on a non-ambient instantiated module declaration. if (symbol.flags & 512 /* ValueModule */ - && symbol.declarations.length > 1 && !inAmbientContext + && symbol.declarations.length > 1 && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { @@ -56187,7 +56980,7 @@ var ts; return false; } var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule) { + if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule) { error(moduleName, node.kind === 255 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); @@ -56318,7 +57111,7 @@ var ts; var inAmbientExternalModule = node.parent.kind === 245 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 245 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 4194304 /* Ambient */; - if (node.parent.kind !== 279 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + if (node.parent.kind !== 284 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } @@ -56335,7 +57128,7 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 279 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */; + var isInAppropriateContext = node.parent.kind === 284 /* SourceFile */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 244 /* ModuleDeclaration */; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -56364,7 +57157,7 @@ var ts; // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent; if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); @@ -56457,9 +57250,14 @@ var ts; !!declaration.body; } function checkSourceElement(node) { - if (!node) { - return; + if (node) { + var saveCurrentNode = currentNode; + currentNode = node; + checkSourceElementWorker(node); + currentNode = saveCurrentNode; } + } + function checkSourceElementWorker(node) { if (ts.isInJSFile(node)) { ts.forEach(node.jsDoc, function (_a) { var tags = _a.tags; @@ -56529,32 +57327,32 @@ var ts; return checkInferType(node); case 183 /* ImportType */: return checkImportType(node); - case 295 /* JSDocAugmentsTag */: + case 300 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 304 /* JSDocTypedefTag */: - case 297 /* JSDocCallbackTag */: + case 309 /* JSDocTypedefTag */: + case 302 /* JSDocCallbackTag */: return checkJSDocTypeAliasTag(node); - case 303 /* JSDocTemplateTag */: + case 308 /* JSDocTemplateTag */: return checkJSDocTemplateTag(node); - case 302 /* JSDocTypeTag */: + case 307 /* JSDocTypeTag */: return checkJSDocTypeTag(node); - case 299 /* JSDocParameterTag */: + case 304 /* JSDocParameterTag */: return checkJSDocParameterTag(node); - case 289 /* JSDocFunctionType */: + case 294 /* JSDocFunctionType */: checkJSDocFunctionType(node); // falls through - case 287 /* JSDocNonNullableType */: - case 286 /* JSDocNullableType */: - case 284 /* JSDocAllType */: - case 285 /* JSDocUnknownType */: - case 292 /* JSDocTypeLiteral */: + case 292 /* JSDocNonNullableType */: + case 291 /* JSDocNullableType */: + case 289 /* JSDocAllType */: + case 290 /* JSDocUnknownType */: + case 297 /* JSDocTypeLiteral */: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 290 /* JSDocVariadicType */: + case 295 /* JSDocVariadicType */: checkJSDocVariadicType(node); return; - case 283 /* JSDocTypeExpression */: + case 288 /* JSDocTypeExpression */: return checkSourceElement(node.type); case 180 /* IndexedAccessType */: return checkIndexedAccessType(node); @@ -56708,32 +57506,35 @@ var ts; } function checkDeferredNodes(context) { var links = getNodeLinks(context); - if (!links.deferredNodes) { - return; + if (links.deferredNodes) { + links.deferredNodes.forEach(checkDeferredNode); } - links.deferredNodes.forEach(function (node) { - switch (node.kind) { - case 196 /* FunctionExpression */: - case 197 /* ArrowFunction */: - case 156 /* MethodDeclaration */: - case 155 /* MethodSignature */: - checkFunctionExpressionOrObjectLiteralMethodDeferred(node); - break; - case 158 /* GetAccessor */: - case 159 /* SetAccessor */: - checkAccessorDeclaration(node); - break; - case 209 /* ClassExpression */: - checkClassExpressionDeferred(node); - break; - case 261 /* JsxSelfClosingElement */: - checkJsxSelfClosingElementDeferred(node); - break; - case 260 /* JsxElement */: - checkJsxElementDeferred(node); - break; - } - }); + } + function checkDeferredNode(node) { + var saveCurrentNode = currentNode; + currentNode = node; + switch (node.kind) { + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 155 /* MethodSignature */: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: + checkAccessorDeclaration(node); + break; + case 209 /* ClassExpression */: + checkClassExpressionDeferred(node); + break; + case 261 /* JsxSelfClosingElement */: + checkJsxSelfClosingElementDeferred(node); + break; + case 260 /* JsxElement */: + checkJsxElementDeferred(node); + break; + } + currentNode = saveCurrentNode; } function checkSourceFile(node) { ts.performance.mark("beforeCheck"); @@ -56808,7 +57609,7 @@ var ts; throwIfNonDiagnosticsProducing(); if (sourceFile) { // Some global diagnostics are deferred until they are needed and - // may not be reported in the firt call to getGlobalDiagnostics. + // may not be reported in the first call to getGlobalDiagnostics. // We should catch these changes and report them. var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; @@ -56859,7 +57660,7 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 279 /* SourceFile */: + case 284 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; // falls through @@ -57078,10 +57879,10 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 299 /* JSDocParameterTag */) { + if (entityName.parent.kind === 304 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 303 /* JSDocTemplateTag */) { + if (entityName.parent.kind === 150 /* TypeParameter */ && entityName.parent.parent.kind === 308 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; @@ -57123,7 +57924,7 @@ var ts; return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 279 /* SourceFile */) { + if (node.kind === 284 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } var parent = node.parent; @@ -57465,7 +58266,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 279 /* SourceFile */) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 284 /* SourceFile */) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -57492,7 +58293,7 @@ var ts; return undefined; } function isSymbolOfDeclarationWithCollidingName(symbol) { - if (symbol.flags & 418 /* BlockScoped */) { + if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) { var links = getSymbolLinks(symbol); if (links.isDeclarationWithCollidingName === undefined) { var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); @@ -57580,7 +58381,7 @@ var ts; } function isTopLevelValueImportEqualsWithEntityName(nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 279 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + if (node === undefined || node.parent.kind !== 284 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -58009,7 +58810,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 279 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 284 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -58042,7 +58843,7 @@ var ts; if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 279 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 284 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -58156,8 +58957,8 @@ var ts; else { // Otherwise issue top-level error since the files appear very identical in terms of what they contain var list = ts.arrayFrom(conflictingSymbols.keys()).join(", "); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); - diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(ts.addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(ts.addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); } }); amalgamatedDuplicates = undefined; @@ -58274,7 +59075,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { @@ -58297,7 +59098,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + else if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } else if (node.kind === 151 /* Parameter */) { @@ -58342,7 +59143,7 @@ var ts; flags |= 1 /* Export */; break; case 80 /* DefaultKeyword */: - var container = node.parent.kind === 279 /* SourceFile */ ? node.parent : node.parent.parent; + var container = node.parent.kind === 284 /* SourceFile */ ? node.parent : node.parent.parent; if (container.kind === 244 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } @@ -58465,7 +59266,7 @@ var ts; case 151 /* Parameter */: return false; default: - if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + if (node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) { return false; } switch (node.kind) { @@ -58553,10 +59354,10 @@ var ts; var nonSimpleParameters = getNonSimpleParameters(node.parameters); if (ts.length(nonSimpleParameters)) { ts.forEach(nonSimpleParameters, function (parameter) { - addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); + ts.addRelatedInfo(error(parameter, ts.Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), ts.createDiagnosticForNode(useStrictDirective_1, ts.Diagnostics.use_strict_directive_used_here)); }); var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); }); - addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); + ts.addRelatedInfo.apply(void 0, [error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)].concat(diagnostics_1)); return true; } } @@ -58993,6 +59794,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here); } } + else if (node.operator === 133 /* ReadonlyKeyword */) { + if (node.type.kind !== 169 /* ArrayType */ && node.type.kind !== 170 /* TupleType */) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(139 /* SymbolKeyword */)); + } + } } function checkGrammarForInvalidDynamicName(node, message) { if (isNonBindableDynamicName(node)) { @@ -59383,7 +60189,7 @@ var ts; // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 279 /* SourceFile */) { + if (node.parent.kind === 218 /* Block */ || node.parent.kind === 245 /* ModuleBlock */ || node.parent.kind === 284 /* SourceFile */) { var links_2 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_2.hasReportedStatementInAmbientContext) { @@ -59423,7 +60229,7 @@ var ts; var literalType = ts.isLiteralTypeNode(node.parent) || ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent); if (!literalType) { - if (languageVersion < 6 /* ESNext */) { + if (languageVersion < 7 /* ESNext */) { if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ESNext)) { return true; } @@ -59588,10 +60394,11 @@ var ts; return createLiteralFromNode(value); } ts.createLiteral = createLiteral; - function createNumericLiteral(value) { + function createNumericLiteral(value, numericLiteralFlags) { + if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; } var node = createSynthesizedNode(8 /* NumericLiteral */); node.text = value; - node.numericLiteralFlags = 0; + node.numericLiteralFlags = numericLiteralFlags; return node; } ts.createNumericLiteral = createNumericLiteral; @@ -61436,14 +62243,14 @@ var ts; // JSDoc /* @internal */ function createJSDocTypeExpression(type) { - var node = createSynthesizedNode(283 /* JSDocTypeExpression */); + var node = createSynthesizedNode(288 /* JSDocTypeExpression */); node.type = type; return node; } ts.createJSDocTypeExpression = createJSDocTypeExpression; /* @internal */ function createJSDocTypeTag(typeExpression, comment) { - var tag = createJSDocTag(302 /* JSDocTypeTag */, "type"); + var tag = createJSDocTag(307 /* JSDocTypeTag */, "type"); tag.typeExpression = typeExpression; tag.comment = comment; return tag; @@ -61451,7 +62258,7 @@ var ts; ts.createJSDocTypeTag = createJSDocTypeTag; /* @internal */ function createJSDocReturnTag(typeExpression, comment) { - var tag = createJSDocTag(300 /* JSDocReturnTag */, "returns"); + var tag = createJSDocTag(305 /* JSDocReturnTag */, "returns"); tag.typeExpression = typeExpression; tag.comment = comment; return tag; @@ -61459,7 +62266,7 @@ var ts; ts.createJSDocReturnTag = createJSDocReturnTag; /* @internal */ function createJSDocParamTag(name, isBracketed, typeExpression, comment) { - var tag = createJSDocTag(299 /* JSDocParameterTag */, "param"); + var tag = createJSDocTag(304 /* JSDocParameterTag */, "param"); tag.typeExpression = typeExpression; tag.name = name; tag.isBracketed = isBracketed; @@ -61469,7 +62276,7 @@ var ts; ts.createJSDocParamTag = createJSDocParamTag; /* @internal */ function createJSDocComment(comment, tags) { - var node = createSynthesizedNode(291 /* JSDocComment */); + var node = createSynthesizedNode(296 /* JSDocComment */); node.comment = comment; node.tags = tags; return node; @@ -61550,6 +62357,28 @@ var ts; return node; } ts.createJsxFragment = createJsxFragment; + function createJsxText(text, containsOnlyTriviaWhiteSpaces) { + var node = createSynthesizedNode(11 /* JsxText */); + node.text = text; + node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces; + return node; + } + ts.createJsxText = createJsxText; + function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) { + return node.text !== text + || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces + ? updateNode(createJsxText(text, containsOnlyTriviaWhiteSpaces), node) + : node; + } + ts.updateJsxText = updateJsxText; + function createJsxOpeningFragment() { + return createSynthesizedNode(265 /* JsxOpeningFragment */); + } + ts.createJsxOpeningFragment = createJsxOpeningFragment; + function createJsxJsxClosingFragment() { + return createSynthesizedNode(266 /* JsxClosingFragment */); + } + ts.createJsxJsxClosingFragment = createJsxJsxClosingFragment; function updateJsxFragment(node, openingFragment, children, closingFragment) { return node.openingFragment !== openingFragment || node.children !== children @@ -61728,7 +62557,7 @@ var ts; (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) || (libReferences !== undefined && node.libReferenceDirectives !== libReferences) || (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) { - var updated = createSynthesizedNode(279 /* SourceFile */); + var updated = createSynthesizedNode(284 /* SourceFile */); updated.flags |= node.flags; updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; @@ -61812,7 +62641,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(307 /* NotEmittedStatement */); + var node = createSynthesizedNode(312 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -61824,7 +62653,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(311 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(316 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -61836,7 +62665,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(310 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(315 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -61851,7 +62680,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(308 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(313 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -61867,7 +62696,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 309 /* CommaListExpression */) { + if (node.kind === 314 /* CommaListExpression */) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { @@ -61877,7 +62706,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(309 /* CommaListExpression */); + var node = createSynthesizedNode(314 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -61890,33 +62719,197 @@ var ts; ts.updateCommaList = updateCommaList; function createBundle(sourceFiles, prepends) { if (prepends === void 0) { prepends = ts.emptyArray; } - var node = ts.createNode(280 /* Bundle */); + var node = ts.createNode(285 /* Bundle */); node.prepends = prepends; node.sourceFiles = sourceFiles; return node; } ts.createBundle = createBundle; - function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, map) { - var node = ts.createNode(281 /* UnparsedSource */); + var allUnscopedEmitHelpers; + function getAllUnscopedEmitHelpers() { + return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([ + ts.valuesHelper, + ts.readHelper, + ts.spreadHelper, + ts.restHelper, + ts.decorateHelper, + ts.metadataHelper, + ts.paramHelper, + ts.awaiterHelper, + ts.assignHelper, + ts.awaitHelper, + ts.asyncGeneratorHelper, + ts.asyncDelegator, + ts.asyncValues, + ts.extendsHelper, + ts.templateObjectHelper, + ts.generatorHelper, + ts.importStarHelper, + ts.importDefaultHelper + ], function (helper) { return helper.name; })); + } + function createUnparsedSource() { + var node = ts.createNode(286 /* UnparsedSource */); + node.prologues = ts.emptyArray; + node.referencedFiles = ts.emptyArray; + node.libReferenceDirectives = ts.emptyArray; + node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); }; + return node; + } + function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) { + var node = createUnparsedSource(); + var stripInternal; + var bundleFileInfo; if (!ts.isString(textOrInputFiles)) { ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts"); - node.fileName = mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath; + node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || ""; node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath; Object.defineProperties(node, { text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } }, sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } }, }); + if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) { + node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit; + ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean"); + stripInternal = mapTextOrStripInternal; + bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts; + if (node.oldFileOfCurrentEmit) { + parseOldFileOfCurrentEmit(node, ts.Debug.assertDefined(bundleFileInfo)); + return node; + } + } } else { + node.fileName = ""; node.text = textOrInputFiles; node.sourceMapPath = mapPathOrType; - node.sourceMapText = map; + node.sourceMapText = mapTextOrStripInternal; } + ts.Debug.assert(!node.oldFileOfCurrentEmit); + parseUnparsedSourceFile(node, bundleFileInfo, stripInternal); return node; } ts.createUnparsedSourceFile = createUnparsedSourceFile; - function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapText) { - var node = ts.createNode(282 /* InputFiles */); + function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) { + var prologues; + var helpers; + var referencedFiles; + var typeReferenceDirectives; + var libReferenceDirectives; + var texts; + for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) { + var section = _a[_i]; + switch (section.kind) { + case "prologue" /* Prologue */: + (prologues || (prologues = [])).push(createUnparsedNode(section, node)); + break; + case "emitHelpers" /* EmitHelpers */: + (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data)); + break; + case "no-default-lib" /* NoDefaultLib */: + node.hasNoDefaultLib = true; + break; + case "reference" /* Reference */: + (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data }); + break; + case "type" /* Type */: + (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data); + break; + case "lib" /* Lib */: + (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data }); + break; + case "prepend" /* Prepend */: + var prependNode = createUnparsedNode(section, node); + var prependTexts = void 0; + for (var _b = 0, _c = section.texts; _b < _c.length; _b++) { + var text = _c[_b]; + if (!stripInternal || text.kind !== "internal" /* Internal */) { + (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node)); + } + } + prependNode.texts = prependTexts || ts.emptyArray; + (texts || (texts = [])).push(prependNode); + break; + case "internal" /* Internal */: + if (stripInternal) + break; + // falls through + case "text" /* Text */: + (texts || (texts = [])).push(createUnparsedNode(section, node)); + break; + default: + ts.Debug.assertNever(section); + } + } + node.prologues = prologues || ts.emptyArray; + node.helpers = helpers; + node.referencedFiles = referencedFiles || ts.emptyArray; + node.typeReferenceDirectives = typeReferenceDirectives; + node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray; + node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)]; + } + function parseOldFileOfCurrentEmit(node, bundleFileInfo) { + ts.Debug.assert(!!node.oldFileOfCurrentEmit); + var texts; + var syntheticReferences; + for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) { + var section = _a[_i]; + switch (section.kind) { + case "internal" /* Internal */: + case "text" /* Text */: + (texts || (texts = [])).push(createUnparsedNode(section, node)); + break; + case "no-default-lib" /* NoDefaultLib */: + case "reference" /* Reference */: + case "type" /* Type */: + case "lib" /* Lib */: + (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node)); + break; + // Ignore + case "prologue" /* Prologue */: + case "emitHelpers" /* EmitHelpers */: + case "prepend" /* Prepend */: + break; + default: + ts.Debug.assertNever(section); + } + } + node.texts = texts || ts.emptyArray; + node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); }); + node.syntheticReferences = syntheticReferences; + return node; + } + function mapBundleFileSectionKindToSyntaxKind(kind) { + switch (kind) { + case "prologue" /* Prologue */: return 279 /* UnparsedPrologue */; + case "prepend" /* Prepend */: return 280 /* UnparsedPrepend */; + case "internal" /* Internal */: return 282 /* UnparsedInternalText */; + case "text" /* Text */: return 281 /* UnparsedText */; + case "emitHelpers" /* EmitHelpers */: + case "no-default-lib" /* NoDefaultLib */: + case "reference" /* Reference */: + case "type" /* Type */: + case "lib" /* Lib */: + return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind"); + default: + return ts.Debug.assertNever(kind); + } + } + function createUnparsedNode(section, parent) { + var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end); + node.parent = parent; + node.data = section.data; + return node; + } + function createUnparsedSyntheticReference(section, parent) { + var node = ts.createNode(283 /* UnparsedSyntheticReference */, section.pos, section.end); + node.parent = parent; + node.data = section.data; + node.section = section; + return node; + } + function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) { + var node = ts.createNode(287 /* InputFiles */); if (!ts.isString(javascriptTextOrReadFileText)) { var cache_1 = ts.createMap(); var textGetter_1 = function (path) { @@ -61933,15 +62926,25 @@ var ts; var result = textGetter_1(path); return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n"; }; + var buildInfo_1; + var getAndCacheBuildInfo_1 = function (getText) { + if (buildInfo_1 === undefined) { + var result = getText(); + buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false; + } + return buildInfo_1 || undefined; + }; node.javascriptPath = declarationTextOrJavascriptPath; node.javascriptMapPath = javascriptMapPath; node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath); node.declarationMapPath = declarationMapPath; + node.buildInfoPath = declarationMapTextOrBuildInfoPath; Object.defineProperties(node, { javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } }, javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } }, declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } }, - declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } } // TODO:: if there is inline sourceMap in dtsFile, use that + declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } }, + buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } } }); } else { @@ -61950,7 +62953,12 @@ var ts; node.javascriptMapText = javascriptMapTextOrDeclarationPath; node.declarationText = declarationTextOrJavascriptPath; node.declarationMapPath = declarationMapPath; - node.declarationMapText = declarationMapText; + node.declarationMapText = declarationMapTextOrBuildInfoPath; + node.javascriptPath = javascriptPath; + node.declarationPath = declarationPath, + node.buildInfoPath = buildInfoPath; + node.buildInfo = buildInfo; + node.oldFileOfCurrentEmit = oldFileOfCurrentEmit; } return node; } @@ -62088,10 +63096,10 @@ var ts; // To avoid holding onto transformation artifacts, we keep track of any // parse tree node we are annotating. This allows us to clean them up after // all transformations have completed. - if (node.kind === 279 /* SourceFile */) { + if (node.kind === 284 /* SourceFile */) { return node.emitNode = { annotatedNodes: [node] }; } - var sourceFile = ts.getSourceFileOfNode(node); + var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node))); getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); } node.emitNode = {}; @@ -62389,7 +63397,7 @@ var ts; ts.nullTransformationContext = { enableEmitNotification: ts.noop, enableSubstitution: ts.noop, - endLexicalEnvironment: function () { return undefined; }, + endLexicalEnvironment: ts.returnUndefined, getCompilerOptions: ts.notImplemented, getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, @@ -62534,38 +63542,38 @@ var ts; return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */); } ts.getHelperName = getHelperName; - var valuesHelper = { + ts.valuesHelper = { name: "typescript:values", scoped: false, text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };" }; function createValuesHelper(context, expression, location) { - context.requestEmitHelper(valuesHelper); + context.requestEmitHelper(ts.valuesHelper); return ts.setTextRange(ts.createCall(getHelperName("__values"), /*typeArguments*/ undefined, [expression]), location); } ts.createValuesHelper = createValuesHelper; - var readHelper = { + ts.readHelper = { name: "typescript:read", scoped: false, text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };" }; function createReadHelper(context, iteratorRecord, count, location) { - context.requestEmitHelper(readHelper); + context.requestEmitHelper(ts.readHelper); return ts.setTextRange(ts.createCall(getHelperName("__read"), /*typeArguments*/ undefined, count !== undefined ? [iteratorRecord, ts.createLiteral(count)] : [iteratorRecord]), location); } ts.createReadHelper = createReadHelper; - var spreadHelper = { + ts.spreadHelper = { name: "typescript:spread", scoped: false, text: "\n var __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n };" }; function createSpreadHelper(context, argumentList, location) { - context.requestEmitHelper(readHelper); - context.requestEmitHelper(spreadHelper); + context.requestEmitHelper(ts.readHelper); + context.requestEmitHelper(ts.spreadHelper); return ts.setTextRange(ts.createCall(getHelperName("__spread"), /*typeArguments*/ undefined, argumentList), location); } @@ -63411,7 +64419,7 @@ var ts; case 190 /* ElementAccessExpression */: case 189 /* PropertyAccessExpression */: case 213 /* NonNullExpression */: - case 308 /* PartiallyEmittedExpression */: + case 313 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -63427,7 +64435,7 @@ var ts; ts.parenthesizeConciseBody = parenthesizeConciseBody; function isCommaSequence(node) { return node.kind === 204 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || - node.kind === 309 /* CommaListExpression */; + node.kind === 314 /* CommaListExpression */; } ts.isCommaSequence = isCommaSequence; var OuterExpressionKinds; @@ -63446,7 +64454,7 @@ var ts; case 212 /* AsExpression */: case 213 /* NonNullExpression */: return (kinds & 2 /* Assertions */) !== 0; - case 308 /* PartiallyEmittedExpression */: + case 313 /* PartiallyEmittedExpression */: return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -63483,7 +64491,7 @@ var ts; case 194 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); case 212 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); case 213 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 308 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 313 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -64275,12 +65283,12 @@ var ts; case 278 /* EnumMember */: return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); // Top-level nodes - case 279 /* SourceFile */: + case 284 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 308 /* PartiallyEmittedExpression */: + case 313 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 309 /* CommaListExpression */: + case 314 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -64336,7 +65344,7 @@ var ts; case 220 /* EmptyStatement */: case 210 /* OmittedExpression */: case 236 /* DebuggerStatement */: - case 307 /* NotEmittedStatement */: + case 312 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names @@ -64713,14 +65721,14 @@ var ts; result = reduceNode(node.initializer, cbNode, result); break; // Top-level nodes - case 279 /* SourceFile */: + case 284 /* SourceFile */: result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 308 /* PartiallyEmittedExpression */: + case 313 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 309 /* CommaListExpression */: + case 314 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -64734,8 +65742,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) - : ts.addStatementsAfterPrologue(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements) + : ts.insertStatementsAfterStandardPrologue(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -65001,7 +66009,7 @@ var ts; } exit(); } - function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath) { + function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) { var _a; ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack"); ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative"); @@ -65011,6 +66019,14 @@ var ts; var nameIndexToNewNameIndexMap; var mappingIterator = decodeMappings(map.mappings); for (var _b = mappingIterator.next(), raw = _b.value, done = _b.done; !done; _a = mappingIterator.next(), raw = _a.value, done = _a.done, _a) { + if (end && (raw.generatedLine > end.line || + (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) { + break; + } + if (start && (raw.generatedLine < start.line || + (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) { + continue; + } // Then reencode all the updated mappings into the overall map var newSourceIndex = void 0; var newSourceLine = void 0; @@ -65039,8 +66055,10 @@ var ts; } } } - var newGeneratedLine = raw.generatedLine + generatedLine; - var newGeneratedCharacter = raw.generatedLine === 0 ? raw.generatedCharacter + generatedCharacter : raw.generatedCharacter; + var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0); + var newGeneratedLine = rawGeneratedLine + generatedLine; + var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter; + var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter; addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex); } exit(); @@ -65523,7 +66541,7 @@ var ts; function chainBundle(transformSourceFile) { return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - return node.kind === 279 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + return node.kind === 284 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); } function transformBundle(node) { return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); @@ -65999,8 +67017,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(element.transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -66066,7 +67084,7 @@ var ts; if (flattenContext.level >= 1 /* ObjectRest */) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (element.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -66184,7 +67202,7 @@ var ts; function makeAssignmentElement(name) { return name; } - var restHelper = { + ts.restHelper = { name: "typescript:rest", scoped: false, text: "\n var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\n t[p[i]] = s[p[i]];\n return t;\n };" @@ -66193,7 +67211,7 @@ var ts; * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);` */ function createRestCall(context, value, elements, computedTempVariables, location) { - context.requestEmitHelper(restHelper); + context.requestEmitHelper(ts.restHelper); var propertyNames = []; var computedTempVariableOffset = 0; for (var i = 0; i < elements.length - 1; i++) { @@ -66294,14 +67312,14 @@ var ts; var pendingExpressions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { - if (node.kind === 280 /* Bundle */) { + if (node.kind === 285 /* Bundle */) { return transformBundle(node); } return transformSourceFile(node); } function transformBundle(node) { return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 282 /* InputFiles */) { + if (prepend.kind === 287 /* InputFiles */) { return ts.createUnparsedSourceFile(prepend, "js"); } return prepend; @@ -66350,7 +67368,7 @@ var ts; */ function onBeforeVisitNode(node) { switch (node.kind) { - case 279 /* SourceFile */: + case 284 /* SourceFile */: case 246 /* CaseBlock */: case 245 /* ModuleBlock */: case 218 /* Block */: @@ -66394,14 +67412,9 @@ var ts; * @param node The node to visit. */ function visitorWorker(node) { - if (node.transformFlags & 1 /* TypeScript */) { - // This node is explicitly marked as TypeScript, so we should transform the node. + if (node.transformFlags & 1 /* ContainsTypeScript */) { return visitTypeScript(node); } - else if (node.transformFlags & 2 /* ContainsTypeScript */) { - // This node contains TypeScript, so we should visit its children. - return ts.visitEachChild(node, visitor, context); - } return node; } /** @@ -66435,7 +67448,7 @@ var ts; // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`, // and will trigger debug failures when debug verbosity is turned up - if (node.transformFlags & 2 /* ContainsTypeScript */) { + if (node.transformFlags & 1 /* ContainsTypeScript */) { // This node contains TypeScript, so we should visit its children. return ts.visitEachChild(node, visitor, context); } @@ -66477,15 +67490,9 @@ var ts; // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } - else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) { - // This node is explicitly marked as TypeScript, or is exported at the namespace - // level, so we should transform the node. + else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) { return visitTypeScript(node); } - else if (node.transformFlags & 2 /* ContainsTypeScript */) { - // This node contains TypeScript, so we should visit its children. - return ts.visitEachChild(node, visitor, context); - } return node; } /** @@ -66536,7 +67543,7 @@ var ts; * @param node The node to visit. */ function visitTypeScript(node) { - if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) { + if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) { // TypeScript ambient declarations are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); @@ -66603,7 +67610,7 @@ var ts; // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); case 240 /* ClassDeclaration */: - // This is a class declaration with TypeScript syntax extensions. + // This may be a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: // - decorators @@ -66614,7 +67621,7 @@ var ts; // - method overload signatures return visitClassDeclaration(node); case 209 /* ClassExpression */: - // This is a class expression with TypeScript syntax extensions. + // This may be a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: // - decorators @@ -66625,7 +67632,7 @@ var ts; // - method overload signatures return visitClassExpression(node); case 273 /* HeritageClause */: - // This is a heritage clause with TypeScript syntax extensions. + // This may be a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause @@ -66653,7 +67660,7 @@ var ts; // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); case 151 /* Parameter */: - // This is a parameter declaration with TypeScript syntax extensions. + // This may be a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: // - decorators @@ -66694,7 +67701,8 @@ var ts; // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: - return ts.Debug.failBadSyntaxKind(node); + // node contains some other TypeScript syntax + return ts.visitEachChild(node, visitor, context); } } function visitSourceFile(node) { @@ -66743,18 +67751,19 @@ var ts; facts |= 128 /* UseImmediatelyInvokedFunctionExpression */; return facts; } - /** - * Transforms a class declaration with TypeScript syntax into compatible ES6. - * - * This function will only be called when one of the following conditions are met: - * - The class has decorators. - * - The class has property declarations with initializers. - * - The class contains a constructor that contains parameters with accessibility modifiers. - * - The class is an export in a TypeScript namespace. - * - * @param node The node to transform. - */ + function hasTypeScriptClassSyntax(node) { + return !!(node.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */); + } + function isClassLikeDeclarationWithTypeScriptSyntax(node) { + return ts.some(node.decorators) + || ts.some(node.typeParameters) + || ts.some(node.heritageClauses, hasTypeScriptClassSyntax) + || ts.some(node.members, hasTypeScriptClassSyntax); + } function visitClassDeclaration(node) { + if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) { + return ts.visitEachChild(node, visitor, context); + } var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); @@ -66807,7 +67816,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -66984,16 +67993,10 @@ var ts; ts.setCommentRange(statement, node); return statement; } - /** - * Transforms a class expression with TypeScript syntax into compatible ES6. - * - * This function will only be called when one of the following conditions are met: - * - The class has property declarations with initializers. - * - The class contains a constructor that contains parameters with accessibility modifiers. - * - * @param node The node to transform. - */ function visitClassExpression(node) { + if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) { + return ts.visitEachChild(node, visitor, context); + } var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); @@ -67057,7 +68060,7 @@ var ts; var constructor = ts.getFirstConstructorWithBody(node); var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); var hasParameterPropertyAssignments = constructor && - constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + constructor.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. @@ -67348,11 +68351,14 @@ var ts; var decorators; if (node) { var parameters = node.parameters; - for (var i = 0; i < parameters.length; i++) { - var parameter = parameters[i]; + var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); + var firstParameterOffset = firstParameterIsThis ? 1 : 0; + var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i + firstParameterOffset]; if (decorators || parameter.decorators) { if (!decorators) { - decorators = new Array(parameters.length); + decorators = new Array(numParameters); } decorators[i] = parameter.decorators; } @@ -67852,8 +68858,12 @@ var ts; return serializeTypeList(node.types); case 175 /* ConditionalType */: return serializeTypeList([node.trueType, node.falseType]); - case 167 /* TypeQuery */: case 179 /* TypeOperator */: + if (node.operator === 133 /* ReadonlyKeyword */) { + return serializeTypeNode(node.type); + } + break; + case 167 /* TypeQuery */: case 180 /* IndexedAccessType */: case 181 /* MappedType */: case 168 /* TypeLiteral */: @@ -67871,8 +68881,8 @@ var ts; // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var typeNode = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var typeNode = types_18[_i]; while (typeNode.kind === 177 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -68014,7 +69024,7 @@ var ts; * available. */ function getGlobalBigIntNameWithFallback() { - return languageVersion < 6 /* ESNext */ + return languageVersion < 7 /* ESNext */ ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object")) : ts.createIdentifier("BigInt"); } @@ -68098,11 +69108,11 @@ var ts; * @param node The HeritageClause to transform. */ function visitHeritageClause(node) { - if (node.token === 86 /* ExtendsKeyword */) { - var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node); + if (node.token === 109 /* ImplementsKeyword */) { + // implements clauses are elided + return undefined; } - return undefined; + return ts.visitEachChild(node, visitor, context); } /** * Transforms an ExpressionWithTypeArguments with TypeScript syntax. @@ -68138,16 +69148,6 @@ var ts; } return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context)); } - /** - * Visits a method declaration of a class. - * - * This function will be called when one of the following conditions are met: - * - The node is an overload - * - The node is marked as abstract, public, private, protected, or readonly - * - The node has a computed property name - * - * @param node The method node. - */ function visitMethodDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; @@ -68174,15 +69174,6 @@ var ts; function shouldEmitAccessorDeclaration(node) { return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */)); } - /** - * Visits a get accessor declaration of a class. - * - * This function will be called when one of the following conditions are met: - * - The node is marked as abstract, public, private, or protected - * - The node has a computed property name - * - * @param node The get accessor node. - */ function visitGetAccessor(node) { if (!shouldEmitAccessorDeclaration(node)) { return undefined; @@ -68198,15 +69189,6 @@ var ts; } return updated; } - /** - * Visits a set accessor declaration of a class. - * - * This function will be called when one of the following conditions are met: - * - The node is marked as abstract, public, private, or protected - * - The node has a computed property name - * - * @param node The set accessor node. - */ function visitSetAccessor(node) { if (!shouldEmitAccessorDeclaration(node)) { return undefined; @@ -68221,16 +69203,6 @@ var ts; } return updated; } - /** - * Visits a function declaration. - * - * This function will be called when one of the following conditions are met: - * - The node is an overload - * - The node is exported from a TypeScript namespace - * - The node has decorators - * - * @param node The function node. - */ function visitFunctionDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createNotEmittedStatement(node); @@ -68246,14 +69218,6 @@ var ts; } return updated; } - /** - * Visits a function expression node. - * - * This function will be called when one of the following conditions are met: - * - The node has type annotations - * - * @param node The function expression node. - */ function visitFunctionExpression(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createOmittedExpression(); @@ -68263,51 +69227,31 @@ var ts; /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); return updated; } - /** - * @remarks - * This function will be called when one of the following conditions are met: - * - The node has type annotations - */ function visitArrowFunction(node) { var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); return updated; } - /** - * Visits a parameter declaration node. - * - * This function will be called when one of the following conditions are met: - * - The node has an accessibility modifier. - * - The node has a questionToken. - * - The node's kind is ThisKeyword. - * - * @param node The parameter declaration node. - */ function visitParameter(node) { if (ts.parameterIsThisKeyword(node)) { return undefined; } - var parameter = ts.createParameter( + var updated = ts.updateParameter(node, /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), /*questionToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setOriginalNode(parameter, node); - ts.setTextRange(parameter, ts.moveRangePastModifiers(node)); - ts.setCommentRange(parameter, node); - ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */); - return parameter; + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setTextRange(updated, ts.moveRangePastModifiers(node)); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */); + } + return updated; } - /** - * Visits a variable statement in a namespace. - * - * This function will be called when one of the following conditions are met: - * - The node is exported from a TypeScript namespace. - */ function visitVariableStatement(node) { if (isExportOfNamespace(node)) { var variables = ts.getInitializedVariables(node.declarationList); @@ -68336,12 +69280,6 @@ var ts; return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } - /** - * Visits a parenthesized expression that contains either a type assertion or an `as` - * expression. - * - * @param node The parenthesized expression node. - */ function visitParenthesizedExpression(node) { var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */); if (ts.isAssertionExpression(innerExpression)) { @@ -68478,7 +69416,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), @@ -68577,7 +69515,7 @@ var ts; // enums in any other scope are emitted as a `let` declaration. var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ], currentLexicalScope.kind === 279 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ], currentLexicalScope.kind === 284 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -68725,7 +69663,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -69142,7 +70080,7 @@ var ts; // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container && container.kind !== 279 /* SourceFile */) { + if (container && container.kind !== 284 /* SourceFile */) { var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 244 /* ModuleDeclaration */) || (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 243 /* EnumDeclaration */); if (substitute) { @@ -69193,39 +70131,39 @@ var ts; argumentsArray.push(descriptor); } } - context.requestEmitHelper(decorateHelper); + context.requestEmitHelper(ts.decorateHelper); return ts.setTextRange(ts.createCall(ts.getHelperName("__decorate"), /*typeArguments*/ undefined, argumentsArray), location); } - var decorateHelper = { + ts.decorateHelper = { name: "typescript:decorate", scoped: false, priority: 2, text: "\n var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n };" }; function createMetadataHelper(context, metadataKey, metadataValue) { - context.requestEmitHelper(metadataHelper); + context.requestEmitHelper(ts.metadataHelper); return ts.createCall(ts.getHelperName("__metadata"), /*typeArguments*/ undefined, [ ts.createLiteral(metadataKey), metadataValue ]); } - var metadataHelper = { + ts.metadataHelper = { name: "typescript:metadata", scoped: false, priority: 3, text: "\n var __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n };" }; function createParamHelper(context, expression, parameterOffset, location) { - context.requestEmitHelper(paramHelper); + context.requestEmitHelper(ts.paramHelper); return ts.setTextRange(ts.createCall(ts.getHelperName("__param"), /*typeArguments*/ undefined, [ ts.createLiteral(parameterOffset), expression ]), location); } - var paramHelper = { + ts.paramHelper = { name: "typescript:param", scoped: false, priority: 4, @@ -69280,7 +70218,7 @@ var ts; return visited; } function visitor(node) { - if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) { + if ((node.transformFlags & 32 /* ContainsES2017 */) === 0) { return node; } switch (node.kind) { @@ -69550,22 +70488,26 @@ var ts; } var savedCapturedSuperProperties = capturedSuperProperties; var savedHasSuperElementAccess = hasSuperElementAccess; - capturedSuperProperties = ts.createUnderscoreEscapedMap(); - hasSuperElementAccess = false; + if (!isArrowFunction) { + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + } var result; if (!isArrowFunction) { 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.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); - var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); - substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.addStatementsAfterPrologue(statements, [variableStatement]); + if (ts.hasEntries(capturedSuperProperties)) { + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + } } var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); @@ -69592,8 +70534,10 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; - capturedSuperProperties = savedCapturedSuperProperties; - hasSuperElementAccess = savedHasSuperElementAccess; + if (!isArrowFunction) { + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + } return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -69746,7 +70690,7 @@ var ts; /* typeParameters */ undefined, /* parameters */ [], /* type */ undefined, - /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */)))); if (hasBinding) { getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( /* modifiers */ undefined, @@ -69761,7 +70705,7 @@ var ts; /* initializer */ undefined) ], /* type */ undefined, - /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v"))))); } accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); }); @@ -69776,14 +70720,14 @@ var ts; ], 2 /* Const */)); } ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement; - var awaiterHelper = { + ts.awaiterHelper = { name: "typescript:awaiter", scoped: false, priority: 5, text: "\n var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n };" }; function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { - context.requestEmitHelper(awaiterHelper); + context.requestEmitHelper(ts.awaiterHelper); var generatorFunc = ts.createFunctionExpression( /*modifiers*/ undefined, ts.createToken(40 /* AsteriskToken */), /*name*/ undefined, @@ -69819,7 +70763,7 @@ var ts; /** Enables substitutions for async methods with `super` calls. */ ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {})); - function transformESNext(context) { + function transformES2018(context) { var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); @@ -69859,7 +70803,7 @@ var ts; return node; } function visitorWorker(node, noDestructuringValue) { - if ((node.transformFlags & 8 /* ContainsESNext */) === 0) { + if ((node.transformFlags & 16 /* ContainsES2018 */) === 0) { return node; } switch (node.kind) { @@ -69903,8 +70847,6 @@ var ts; return visitExpressionStatement(node); case 195 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, noDestructuringValue); - case 274 /* CatchClause */: - return visitCatchClause(node); case 189 /* PropertyAccessExpression */: if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 98 /* SuperKeyword */) { capturedSuperProperties.set(node.name.escapedText, true); @@ -69979,7 +70921,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign({a}, o, {b}); @@ -69999,19 +70941,13 @@ var ts; function visitParenthesizedExpression(node, noDestructuringValue) { return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); } - function visitCatchClause(node) { - if (!node.variableDeclaration) { - return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock)); - } - return ts.visitEachChild(node, visitor, context); - } /** * Visits a BinaryExpression that contains a destructuring assignment. * * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } else if (node.operatorToken.kind === 27 /* CommaToken */) { @@ -70026,7 +70962,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -70043,7 +70979,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (node.initializer.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -70140,7 +71076,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -70253,10 +71189,10 @@ var ts; enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.addStatementsAfterPrologue(statements, [variableStatement]); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); } statements.push(returnStatement); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { @@ -70282,7 +71218,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); - ts.addStatementsAfterPrologue(statements, leadingStatements); + ts.insertStatementsAfterStandardPrologue(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -70291,7 +71227,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (parameter.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -70422,8 +71358,8 @@ var ts; } } } - ts.transformESNext = transformESNext; - var assignHelper = { + ts.transformES2018 = transformES2018; + ts.assignHelper = { name: "typescript:assign", scoped: false, priority: 1, @@ -70434,28 +71370,28 @@ var ts; return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), /*typeArguments*/ undefined, attributesSegments); } - context.requestEmitHelper(assignHelper); + context.requestEmitHelper(ts.assignHelper); return ts.createCall(ts.getHelperName("__assign"), /*typeArguments*/ undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; - var awaitHelper = { + ts.awaitHelper = { name: "typescript:await", scoped: false, text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }" }; function createAwaitHelper(context, expression) { - context.requestEmitHelper(awaitHelper); + context.requestEmitHelper(ts.awaitHelper); return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]); } - var asyncGeneratorHelper = { + ts.asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" }; function createAsyncGeneratorHelper(context, generatorFunc) { - context.requestEmitHelper(awaitHelper); - context.requestEmitHelper(asyncGeneratorHelper); + context.requestEmitHelper(ts.awaitHelper); + context.requestEmitHelper(ts.asyncGeneratorHelper); // Mark this node as originally an async function (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; return ts.createCall(ts.getHelperName("__asyncGenerator"), @@ -70465,30 +71401,84 @@ var ts; generatorFunc ]); } - var asyncDelegator = { + ts.asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };" }; function createAsyncDelegatorHelper(context, expression, location) { - context.requestEmitHelper(awaitHelper); - context.requestEmitHelper(asyncDelegator); + context.requestEmitHelper(ts.awaitHelper); + context.requestEmitHelper(ts.asyncDelegator); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), /*typeArguments*/ undefined, [expression]), location); } - var asyncValues = { + ts.asyncValues = { name: "typescript:asyncValues", scoped: false, text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };" }; function createAsyncValuesHelper(context, expression, location) { - context.requestEmitHelper(asyncValues); + context.requestEmitHelper(ts.asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncValues"), /*typeArguments*/ undefined, [expression]), location); } })(ts || (ts = {})); /*@internal*/ var ts; +(function (ts) { + function transformES2019(context) { + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if ((node.transformFlags & 8 /* ContainsES2019 */) === 0) { + return node; + } + switch (node.kind) { + case 274 /* CatchClause */: + return visitCatchClause(node); + default: + return ts.visitEachChild(node, visitor, context); + } + } + function visitCatchClause(node) { + if (!node.variableDeclaration) { + return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock)); + } + return ts.visitEachChild(node, visitor, context); + } + } + ts.transformES2019 = transformES2019; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function transformESNext(context) { + return ts.chainBundle(transformSourceFile); + function transformSourceFile(node) { + if (node.isDeclarationFile) { + return node; + } + return ts.visitEachChild(node, visitor, context); + } + function visitor(node) { + if ((node.transformFlags & 4 /* ContainsESNext */) === 0) { + return node; + } + switch (node.kind) { + default: + return ts.visitEachChild(node, visitor, context); + } + } + } + ts.transformESNext = transformESNext; +})(ts || (ts = {})); +/*@internal*/ +var ts; (function (ts) { function transformJsx(context) { var compilerOptions = context.getCompilerOptions(); @@ -70509,7 +71499,7 @@ var ts; return visited; } function visitor(node) { - if (node.transformFlags & 4 /* ContainsJsx */) { + if (node.transformFlags & 2 /* ContainsJsx */) { return visitorWorker(node); } else { @@ -70626,7 +71616,7 @@ var ts; } } function visitJsxText(node) { - var fixed = fixupWhitespaceAndDecodeEntities(ts.getTextOfNode(node, /*includeTrivia*/ true)); + var fixed = fixupWhitespaceAndDecodeEntities(node.text); return fixed === undefined ? undefined : ts.createLiteral(fixed); } /** @@ -71011,7 +72001,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) { + if ((node.transformFlags & 64 /* ContainsES2016 */) === 0) { return node; } switch (node.kind) { @@ -71091,30 +72081,6 @@ var ts; Jump[Jump["Continue"] = 4] = "Continue"; Jump[Jump["Return"] = 8] = "Return"; })(Jump || (Jump = {})); - var SuperCaptureResult; - (function (SuperCaptureResult) { - /** - * A capture may have been added for calls to 'super', but - * the caller should emit subsequent statements normally. - */ - SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; - /** - * A call to 'super()' got replaced with a capturing statement like: - * - * var _this = _super.call(...) || this; - * - * Callers should skip the current statement. - */ - SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; - /** - * A call to 'super()' got replaced with a capturing statement like: - * - * return _super.call(...) || this; - * - * Callers should skip the current statement and avoid any returns of '_this'. - */ - SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; - })(SuperCaptureResult || (SuperCaptureResult = {})); // Facts we track as we traverse the tree var HierarchyFacts; (function (HierarchyFacts) { @@ -71135,12 +72101,12 @@ var ts; HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement"; HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement"; HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper"; - HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName"; // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below. + // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below. // // Ancestor masks // - HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask"; + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 8191] = "AncestorFactsMask"; // We are always in *some* kind of block scope, but only specific block-scope containers are // top-level or Blocks. HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes"; @@ -71150,16 +72116,16 @@ var ts; HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes"; // Functions, methods, and accessors are both new lexical scopes and new block scopes. HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes"; - HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes"; + HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 8094] = "FunctionExcludes"; HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes"; - HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 8086] = "AsyncFunctionBodyExcludes"; // Arrow functions are lexically scoped to their container, but are new block scopes. HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes"; - HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 8064] = "ArrowFunctionExcludes"; // Constructors are both new lexical scopes and new block scopes. Constructors are also // always considered non-static members of a class. HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes"; - HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes"; + HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 8086] = "ConstructorExcludes"; // 'do' and 'while' statements are not block scopes. We track that the subtree is contained // within an IterationStatement to indicate whether the embedded statement is an // IterationStatementBlock. @@ -71177,19 +72143,17 @@ var ts; HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes"; HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes"; HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes"; - // Computed property names track subtree flags differently than their containing members. - HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes"; - HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes"; // // Subtree facts // - HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget"; - HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName"; + HierarchyFacts[HierarchyFacts["NewTarget"] = 8192] = "NewTarget"; + HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 16384] = "CapturedLexicalThis"; // // Subtree masks // - HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask"; - HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask"; + HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -8192] = "SubtreeFactsMask"; + HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes"; + HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 24576] = "FunctionSubtreeExcludes"; })(HierarchyFacts || (HierarchyFacts = {})); function transformES2015(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; @@ -71238,7 +72202,7 @@ var ts; */ function enterSubtree(excludeFacts, includeFacts) { var ancestorFacts = hierarchyFacts; - hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 8191 /* AncestorFactsMask */; return ancestorFacts; } /** @@ -71249,7 +72213,7 @@ var ts; * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated. */ function exitSubtree(ancestorFacts, excludeFacts, includeFacts) { - hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -8192 /* SubtreeFactsMask */ | ancestorFacts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 @@ -71271,12 +72235,6 @@ var ts; return node; } } - function functionBodyVisitor(node) { - if (shouldVisitNode(node)) { - return visitBlock(node, /*isFunctionBody*/ true); - } - return node; - } function callExpressionVisitor(node) { if (node.kind === 98 /* SuperKeyword */) { return visitSuperKeyword(/*isExpressionOfCall*/ true); @@ -71383,18 +72341,19 @@ var ts; } function visitSourceFile(node) { var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */); + var prologue = []; var statements = []; startLexicalEnvironment(); - var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false); - addCaptureThisForNodeIfNeeded(statements, node); - statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor); + var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false); + statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureThisForNodeIfNeeded(prologue, node); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements)); } function visitSwitchStatement(node) { if (convertedLoopState !== undefined) { @@ -71434,6 +72393,9 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitThisKeyword(node) { + if (hierarchyFacts & 2 /* ArrowFunction */) { + hierarchyFacts |= 16384 /* CapturedLexicalThis */; + } if (convertedLoopState) { if (hierarchyFacts & 2 /* ArrowFunction */) { // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword. @@ -71647,7 +72609,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -71675,7 +72637,7 @@ var ts; function addConstructor(statements, node, extendsClauseElement) { var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); + var ancestorFacts = enterSubtree(8086 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); var constructorFunction = ts.createFunctionDeclaration( @@ -71689,7 +72651,7 @@ var ts; ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */); } statements.push(constructorFunction); - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; } /** @@ -71708,6 +72670,24 @@ var ts; return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) || []; } + function createDefaultConstructorBody(node, isDerivedClass) { + // We must be here because the user didn't write a constructor + // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. + // If that's the case we can just immediately return the result of a 'super()' call. + var statements = []; + resumeLexicalEnvironment(); + ts.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + if (isDerivedClass) { + // return _super !== null && _super.apply(this, arguments) || this; + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + } + var statementsArray = ts.createNodeArray(statements); + ts.setTextRange(statementsArray, node.members); + var block = ts.createBlock(statementsArray, /*multiLine*/ true); + ts.setTextRange(block, node); + ts.setEmitFlags(block, 1536 /* NoComments */); + return block; + } /** * Transforms the body of a constructor declaration of a class. * @@ -71718,59 +72698,137 @@ var ts; * synthesized `super` call. */ function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { + // determine whether the class is known syntactically to be a derived class (e.g. a + // class that extends a value that is not syntactically known to be `null`). + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */; + // When the subclass does not have a constructor, we synthesize a *default* constructor using the following + // representation: + // + // ``` + // // es2015 (source) + // class C extends Base { } + // + // // es5 (transformed) + // var C = (function (_super) { + // function C() { + // return _super.apply(this, arguments) || this; + // } + // return C; + // })(Base); + // ``` + if (!constructor) + return createDefaultConstructorBody(node, isDerivedClass); + // The prologue will contain all leading standard and custom prologue statements added by this transform + var prologue = []; var statements = []; resumeLexicalEnvironment(); - var statementOffset = -1; + // If a super call has already been synthesized, + // we're going to assume that we should just transform everything after that. + // The assumption is that no prior step in the pipeline has added any prologue directives. + var statementOffset = 0; + if (!hasSynthesizedSuper) + statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false); + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + if (!hasSynthesizedSuper) + statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); + // If the first statement is a call to `super()`, visit the statement directly + var superCallExpression; if (hasSynthesizedSuper) { - // If a super call has already been synthesized, - // we're going to assume that we should just transform everything after that. - // The assumption is that no prior step in the pipeline has added any prologue directives. - statementOffset = 0; - } - else if (constructor) { - statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false); + superCallExpression = createDefaultSuperCallOrThis(); } - if (constructor) { - addDefaultValueAssignmentsIfNeeded(statements, constructor); - addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); - if (!hasSynthesizedSuper) { - // If no super call has been synthesized, emit custom prologue directives. - statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); + else if (isDerivedClass && statementOffset < constructor.body.statements.length) { + var firstStatement = constructor.body.statements[statementOffset]; + if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) { + superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } - ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); - } - // determine whether the class is known syntactically to be a derived class (e.g. a - // class that extends a value that is not syntactically known to be `null`). - var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */; - var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); - // The last statement expression was replaced. Skip it. - if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { - statementOffset++; } - if (constructor) { - if (superCaptureStatus === 1 /* ReplaceSuperCapture */) { - hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */; + if (superCallExpression) { + hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */; + statementOffset++; // skip this statement, we will add it after visiting the rest of the body. + } + // visit the remaining statements + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); + if (isDerivedClass) { + if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 2048 /* ContainsLexicalThis */)) { + // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the + // following representation: + // + // ``` + // // es2015 (source) + // class C extends Base { + // constructor() { + // super("foo"); + // } + // } + // + // // es5 (transformed) + // var C = (function (_super) { + // function C() { + // return _super.call(this, "foo") || this; + // } + // return C; + // })(Base); + // ``` + var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression); + var returnStatement = ts.createReturn(superCallExpression); + ts.setCommentRange(returnStatement, ts.getCommentRange(superCall)); + ts.setEmitFlags(superCall, 1536 /* NoComments */); + statements.push(returnStatement); + } + else { + // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor: + // + // ``` + // // es2015 (source) + // class C extends Base { + // constructor() { + // super("foo"); + // this.x = 1; + // } + // } + // + // // es5 (transformed) + // var C = (function (_super) { + // function C() { + // var _this = _super.call(this, "foo") || this; + // _this.x = 1; + // return _this; + // } + // return C; + // })(Base); + // ``` + // Since the `super()` call was the first statement, we insert the `this` capturing call to + // `super()` at the top of the list of `statements` (after any pre-existing custom prologues). + insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis()); + if (!isSufficientlyCoveredByReturnStatements(constructor.body)) { + statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); + } } - ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); - } - // Return `_this` unless we're sure enough that it would be pointless to add a return statement. - // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return. - if (isDerivedClass - && superCaptureStatus !== 2 /* ReplaceWithReturn */ - && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { - statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - if (constructor) { - prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); + else { + // If a class is not derived from a base class or does not have a call to `super()`, `this` is only + // captured when necessitated by an arrow function capturing the lexical `this`: + // + // ``` + // // es2015 + // class C {} + // + // // es5 + // var C = (function () { + // function C() { + // } + // return C; + // })(); + // ``` + insertCaptureThisForNodeIfNeeded(prologue, constructor); } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), - /*location*/ constructor ? constructor.body.statements : node.members), + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), + /*location*/ constructor.body.statements), /*multiLine*/ true); - ts.setTextRange(block, constructor ? constructor.body : node); - if (!constructor) { - ts.setEmitFlags(block, 1536 /* NoComments */); - } + ts.setTextRange(block, constructor.body); return block; } /** @@ -71800,83 +72858,6 @@ var ts; } return false; } - /** - * Declares a `_this` variable for derived classes and for when arrow functions capture `this`. - * - * @returns The new statement offset into the `statements` array. - */ - function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) { - // If this isn't a derived class, just capture 'this' for arrow functions if necessary. - if (!isDerivedClass) { - if (ctor) { - addCaptureThisForNodeIfNeeded(statements, ctor); - } - return 0 /* NoReplacement */; - } - // We must be here because the user didn't write a constructor - // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. - // If that's the case we can just immediately return the result of a 'super()' call. - if (!ctor) { - statements.push(ts.createReturn(createDefaultSuperCallOrThis())); - return 2 /* ReplaceWithReturn */; - } - // The constructor exists, but it and the 'super()' call it contains were generated - // for something like property initializers. - // Create a captured '_this' variable and assume it will subsequently be used. - if (hasSynthesizedSuper) { - captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); - enableSubstitutionsForCapturedThis(); - return 1 /* ReplaceSuperCapture */; - } - // Most of the time, a 'super' call will be the first real statement in a constructor body. - // In these cases, we'd like to transform these into a *single* statement instead of a declaration - // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer, - // we'd get: - // - // var _this; - // _this = _super.call(...) || this; - // - // instead of - // - // var _this = _super.call(...) || this; - // - // Additionally, if the 'super()' call is the last statement, we should just avoid capturing - // entirely and immediately return the result like so: - // - // return _super.call(...) || this; - // - var firstStatement; - var superCallExpression; - var ctorStatements = ctor.body.statements; - if (statementOffset < ctorStatements.length) { - firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { - superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); - } - } - // Return the result if we have an immediate super() call on the last statement, - // but only if the constructor itself doesn't use 'this' elsewhere. - if (superCallExpression - && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { - var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 204 /* BinaryExpression */ - || superCallExpression.left.kind !== 191 /* CallExpression */) { - ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); - } - // Shift comments from the original super call to the return statement. - ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */))); - statements.push(returnStatement); - return 2 /* ReplaceWithReturn */; - } - // Perform the capture. - captureThisForNode(statements, ctor, superCallExpression || createActualThis()); - // If we're actually replacing the original statement, we need to signal this to the caller. - if (superCallExpression) { - return 1 /* ReplaceSuperCapture */; - } - return 0 /* NoReplacement */; - } function createActualThis() { return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */); } @@ -71922,14 +72903,9 @@ var ts; return node; } } - /** - * Gets a value indicating whether we need to add default value assignments for a - * function-like node. - * - * @param node A function-like node. - */ - function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; + function hasDefaultValueOrBindingPattern(node) { + return node.initializer !== undefined + || ts.isBindingPattern(node.name); } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -71939,9 +72915,10 @@ var ts; * @param node A function-like node. */ function addDefaultValueAssignmentsIfNeeded(statements, node) { - if (!shouldAddDefaultValueAssignments(node)) { - return; + if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) { + return false; } + var added = false; for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; @@ -71951,12 +72928,14 @@ var ts; continue; } if (ts.isBindingPattern(name)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer); + added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added; } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + added = true; } } + return added; } /** * Adds statements to the body of a function-like node for parameters with binding patterns @@ -71966,18 +72945,20 @@ var ts; * @param name The name of the parameter. * @param initializer The initializer for the parameter. */ - function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { - var temp = ts.getGeneratedNameForNode(parameter); + function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { // In cases where a binding pattern is simply '[]' or '{}', // we usually don't want to emit a var declaration; however, in the presence // of an initializer, we must emit that expression to preserve side effects. if (name.elements.length > 0) { - statements.push(ts.setEmitFlags(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */)); + ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */)); + return true; } else if (initializer) { - statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + return true; } + return false; } /** * Adds statements to the body of a function-like node for parameters with initializers. @@ -71987,7 +72968,7 @@ var ts; * @param name The name of the parameter. * @param initializer The initializer for the parameter. */ - function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) @@ -71995,7 +72976,7 @@ var ts; ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */); - statements.push(statement); + ts.insertStatementAfterCustomPrologue(statements, statement); } /** * Gets a value indicating whether we need to add statements to handle a rest parameter. @@ -72018,9 +72999,10 @@ var ts; * synthesized call to `super` */ function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var prologueStatements = []; var parameter = ts.lastOrUndefined(node.parameters); if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { - return; + return false; } // `declarationName` is the name of the local declaration for the parameter. var declarationName = parameter.name.kind === 72 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -72030,7 +73012,7 @@ var ts; var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); // var param = []; - statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, /*type*/ undefined, ts.createArrayLiteral([])) @@ -72049,25 +73031,30 @@ var ts; ])); ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); ts.startOnNewLine(forStatement); - statements.push(forStatement); + prologueStatements.push(forStatement); if (parameter.name.kind !== 72 /* Identifier */) { // do the actual destructuring of the rest parameter if necessary - statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */)); } + ts.insertStatementsAfterCustomPrologue(statements, prologueStatements); + return true; } /** * Adds a statement to capture the `this` of a function declaration if it is needed. + * NOTE: This must be executed *after* the subtree has been visited. * * @param statements The statements for the new function body. * @param node A node. */ - function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { - captureThisForNode(statements, node, ts.createThis()); + function insertCaptureThisForNodeIfNeeded(statements, node) { + if (hierarchyFacts & 16384 /* CapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { + insertCaptureThisForNode(statements, node, ts.createThis()); + return true; } + return false; } - function captureThisForNode(statements, node, initializer) { + function insertCaptureThisForNode(statements, node, initializer) { enableSubstitutionsForCapturedThis(); var captureThisStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ @@ -72076,10 +73063,10 @@ var ts; ])); ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); ts.setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + ts.insertStatementAfterCustomPrologue(statements, captureThisStatement); } - function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { - if (hierarchyFacts & 16384 /* NewTarget */) { + function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { + if (hierarchyFacts & 8192 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { case 197 /* ArrowFunction */: @@ -72110,10 +73097,11 @@ var ts; ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), /*type*/ undefined, newTarget) ])); + ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); if (copyOnWrite) { - return [captureNewTargetStatement].concat(statements); + statements = statements.slice(); } - statements.unshift(captureNewTargetStatement); + ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement); } return statements; } @@ -72165,7 +73153,6 @@ var ts; * @param member The MethodDeclaration node. */ function transformClassMethodDeclarationToStatement(receiver, member, container) { - var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); var commentRange = ts.getCommentRange(member); var sourceMapRange = ts.getSourceMapRange(member); var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name); @@ -72180,7 +73167,6 @@ var ts; // No source map should be emitted for this statement to align with the // old emitter. ts.setEmitFlags(statement, 48 /* NoSourceMap */); - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return statement; } /** @@ -72206,7 +73192,6 @@ var ts; */ function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) { var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; - var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); // To align with source maps in the old emitter, the receiver and property name // arguments are both mapped contiguously to the accessor name. var target = ts.getMutableClone(receiver); @@ -72242,7 +73227,6 @@ var ts; if (startsOnNewLine) { ts.startOnNewLine(call); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return call; } /** @@ -72251,12 +73235,12 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 8192 /* ContainsLexicalThis */) { - enableSubstitutionsForCapturedThis(); + if (node.transformFlags & 2048 /* ContainsLexicalThis */) { + hierarchyFacts |= 16384 /* CapturedLexicalThis */; } var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); + var ancestorFacts = enterSubtree(8064 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); var func = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, @@ -72266,7 +73250,11 @@ var ts; ts.setTextRange(func, node); ts.setOriginalNode(func, node); ts.setEmitFlags(func, 8 /* CapturesThis */); - exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + if (hierarchyFacts & 16384 /* CapturedLexicalThis */) { + enableSubstitutionsForCapturedThis(); + } + // If an arrow function contains + exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return func; } @@ -72277,18 +73265,16 @@ var ts; */ function visitFunctionExpression(node) { var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */ - ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) - : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + ? enterSubtree(8086 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) + : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & 64 /* ES2015 */ - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); - var name = hierarchyFacts & 16384 /* NewTarget */ + var body = transformFunctionBody(node); + var name = hierarchyFacts & 8192 /* NewTarget */ ? ts.getLocalName(node) : node.name; - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return ts.updateFunctionExpression(node, /*modifiers*/ undefined, node.asteriskToken, name, @@ -72303,15 +73289,13 @@ var ts; function visitFunctionDeclaration(node) { var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & 64 /* ES2015 */ - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); - var name = hierarchyFacts & 16384 /* NewTarget */ + var body = transformFunctionBody(node); + var name = hierarchyFacts & 8192 /* NewTarget */ ? ts.getLocalName(node) : node.name; - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return ts.updateFunctionDeclaration(node, /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, @@ -72329,14 +73313,14 @@ var ts; var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */) - ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) - : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + ? enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) + : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { + if (hierarchyFacts & 8192 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { name = ts.getGeneratedNameForNode(node); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression( /*modifiers*/ undefined, node.asteriskToken, name, @@ -72354,7 +73338,7 @@ var ts; var singleLine = false; // indicates whether the block *may* be emitted as a single line var statementsLocation; var closeBraceLocation; - var leadingStatements = []; + var prologue = []; var statements = []; var body = node.body; var statementOffset; @@ -72362,14 +73346,13 @@ var ts; if (ts.isBlock(body)) { // ensureUseStrict is false because no new prologue-directive should be added. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array - statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false); + statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false); } - addCaptureThisForNodeIfNeeded(leadingStatements, node); - addDefaultValueAssignmentsIfNeeded(leadingStatements, node); - addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false); + multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine; + multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine; if (ts.isBlock(body)) { // addCustomPrologue puts already-existing directives at the beginning of the target statement-array - statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor); statementsLocation = body.statements; ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); // If the original body was a multi-line block, this must be a multi-line block. @@ -72403,14 +73386,19 @@ var ts; // source map location for the close brace. closeBraceLocation = body; } - var lexicalEnvironment = context.endLexicalEnvironment(); - ts.addStatementsAfterPrologue(statements, lexicalEnvironment); - prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false); + insertCaptureThisForNodeIfNeeded(prologue, node); // If we added any final generated statements, this must be a multi-line block - if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { + if (ts.some(prologue)) { multiLine = true; } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); + statements.unshift.apply(statements, prologue); + if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) { + // no changes were made, preserve the tree + return body; + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine); ts.setTextRange(block, node.body); if (!multiLine && singleLine) { ts.setEmitFlags(block, 1 /* SingleLine */); @@ -72421,11 +73409,6 @@ var ts; ts.setOriginalNode(block, node.body); return block; } - function visitFunctionBodyDownLevel(node) { - var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context); - return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)), - /*location*/ updated.statements)); - } function visitBlock(node, isFunctionBody) { if (isFunctionBody) { // A function body is not a block scope. @@ -72530,7 +73513,7 @@ var ts; * @param node A VariableDeclarationList node. */ function visitVariableDeclarationList(node) { - if (node.transformFlags & 64 /* ES2015 */) { + if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 65536 /* ContainsBindingPattern */) { if (node.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } @@ -72543,7 +73526,7 @@ var ts; ts.setCommentRange(declarationList, node); // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. - if (node.transformFlags & 2097152 /* ContainsBindingPattern */ + if (node.transformFlags & 65536 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -72865,7 +73848,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 131072 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -73141,7 +74124,7 @@ var ts; */ function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = ts.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var containsYield = (node.initializer.transformFlags & 131072 /* ContainsYield */) !== 0; var emitFlags = 0 /* None */; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -73246,11 +74229,11 @@ var ts; statements.push(statement); } copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); - ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment); var loopBody = ts.createBlock(statements, /*multiLine*/ true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var containsYield = (node.statement.transformFlags & 131072 /* ContainsYield */) !== 0; var emitFlags = 0; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -73482,13 +74465,11 @@ var ts; * @param receiver The receiver for the assignment. */ function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) { - var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container)); ts.setTextRange(expression, method); if (startsOnNewLine) { ts.startOnNewLine(expression); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return expression; } function visitCatchClause(node) { @@ -73540,19 +74521,17 @@ var ts; ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); + var body = transformFunctionBody(node); if (node.kind === 158 /* GetAccessor */) { updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return updated; } @@ -73566,10 +74545,7 @@ var ts; /*location*/ node); } function visitComputedPropertyName(node) { - var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */); - var updated = ts.visitEachChild(node, visitor, context); - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */); - return updated; + return ts.visitEachChild(node, visitor, context); } /** * Visits a YieldExpression node. @@ -73586,7 +74562,7 @@ var ts; * @param node An ArrayLiteralExpression node. */ function visitArrayLiteralExpression(node) { - if (node.transformFlags & 64 /* ES2015 */) { + if (ts.some(node.elements, ts.isSpreadElement)) { // We are here because we contain a SpreadElementExpression. return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma); } @@ -73601,7 +74577,10 @@ var ts; if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) { return visitTypeScriptClassWrapper(node); } - if (node.transformFlags & 64 /* ES2015 */) { + var expression = ts.skipOuterExpressions(node.expression); + if (expression.kind === 98 /* SuperKeyword */ || + ts.isSuperProperty(expression) || + ts.some(node.arguments, ts.isSpreadElement)) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); } return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), @@ -73722,7 +74701,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || + if (node.transformFlags & 4096 /* ContainsRestOrSpread */ || node.expression.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -73730,7 +74709,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + if (node.transformFlags & 4096 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -73744,7 +74723,7 @@ var ts; // _super.apply(this, a.concat([b])) // _super.m.apply(this, a.concat([b])) // _super.prototype.m.apply(this, a.concat([b])) - resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); } else { // [source] @@ -73756,13 +74735,11 @@ var ts; // _super.call(this, a) // _super.m.call(this, a) // _super.prototype.m.call(this, a) - resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), /*location*/ node); } if (node.expression.kind === 98 /* SuperKeyword */) { - var actualThis = ts.createThis(); - ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); - var initializer = ts.createLogicalOr(resultingCall, actualThis); + var initializer = ts.createLogicalOr(resultingCall, createActualThis()); resultingCall = assignToCapturedThis ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer) : initializer; @@ -73777,7 +74754,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + if (ts.some(node.arguments, ts.isSpreadElement)) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -74040,12 +75017,7 @@ var ts; } function visitMetaProperty(node) { if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") { - if (hierarchyFacts & 8192 /* ComputedPropertyName */) { - hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; - } - else { - hierarchyFacts |= 16384 /* NewTarget */; - } + hierarchyFacts |= 8192 /* NewTarget */; return ts.createFileLevelUniqueName("_newTarget"); } return node; @@ -74060,7 +75032,7 @@ var ts; function onEmitNode(hint, node, emitCallback) { if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { // If we are tracking a captured `this`, keep track of the enclosing function. - var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */ + var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */ ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */ : 65 /* FunctionIncludes */); previousOnEmitNode(hint, node, emitCallback); @@ -74240,7 +75212,7 @@ var ts; } ts.transformES2015 = transformES2015; function createExtendsHelper(context, name) { - context.requestEmitHelper(extendsHelper); + context.requestEmitHelper(ts.extendsHelper); return ts.createCall(ts.getHelperName("__extends"), /*typeArguments*/ undefined, [ name, @@ -74248,20 +75220,20 @@ var ts; ]); } function createTemplateObjectHelper(context, cooked, raw) { - context.requestEmitHelper(templateObjectHelper); + context.requestEmitHelper(ts.templateObjectHelper); return ts.createCall(ts.getHelperName("__makeTemplateObject"), /*typeArguments*/ undefined, [ cooked, raw ]); } - var extendsHelper = { + ts.extendsHelper = { name: "typescript:extends", scoped: false, priority: 0, text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; - var templateObjectHelper = { + ts.templateObjectHelper = { name: "typescript:makeTemplateObject", scoped: false, priority: 0, @@ -74608,7 +75580,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 256 /* ContainsGenerator */) === 0) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -74628,10 +75600,10 @@ var ts; else if (inGeneratorFunctionBody) { return visitJavaScriptInGeneratorFunctionBody(node); } - else if (transformFlags & 256 /* Generator */) { + else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) { return visitGenerator(node); } - else if (transformFlags & 512 /* ContainsGenerator */) { + else if (transformFlags & 256 /* ContainsGenerator */) { return ts.visitEachChild(node, visitor, context); } else { @@ -74684,10 +75656,10 @@ var ts; case 230 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 4194304 /* ContainsYield */) { + if (node.transformFlags & 131072 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (256 /* ContainsGenerator */ | 262144 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -74863,7 +75835,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -74890,7 +75862,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 4194304 /* ContainsYield */) { + if (node.transformFlags & 131072 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -75948,7 +76920,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 131072 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -76955,7 +77927,7 @@ var ts; } ts.transformGenerators = transformGenerators; function createGeneratorHelper(context, body) { - context.requestEmitHelper(generatorHelper); + context.requestEmitHelper(ts.generatorHelper); return ts.createCall(ts.getHelperName("__generator"), /*typeArguments*/ undefined, [ts.createThis(), body]); } @@ -77018,7 +77990,7 @@ var ts; // entering a finally block. // // For examples of how these are used, see the comments in ./transformers/generators.ts - var generatorHelper = { + ts.generatorHelper = { name: "typescript:generator", scoped: false, priority: 6, @@ -77051,7 +78023,7 @@ var ts; context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(276 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. - context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableEmitNotification(284 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var currentSourceFile; // The current file. @@ -77067,7 +78039,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 16777216 /* ContainsDynamicImport */ || + node.transformFlags & 524288 /* ContainsDynamicImport */ || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } @@ -77104,7 +78076,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.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(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 @@ -77330,7 +78302,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -77393,9 +78365,9 @@ var ts; return visitFunctionDeclaration(node); case 240 /* ClassDeclaration */: return visitClassDeclaration(node); - case 310 /* MergeDeclarationMarker */: + case 315 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 311 /* EndOfDeclarationMarker */: + case 316 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); @@ -77404,13 +78376,13 @@ var ts; 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 & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 524288 /* ContainsDynamicImport */) && !(node.transformFlags & 512 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) { + else if (ts.isDestructuringAssignment(node)) { return visitDestructuringAssignment(node); } else { @@ -77471,7 +78443,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 2048 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -77553,7 +78525,7 @@ var ts; } var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); if (compilerOptions.esModuleInterop) { - context.requestEmitHelper(importStarHelper); + context.requestEmitHelper(ts.importStarHelper); return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]); } return promise; @@ -77567,7 +78539,7 @@ var ts; var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); if (compilerOptions.esModuleInterop) { - context.requestEmitHelper(importStarHelper); + context.requestEmitHelper(ts.importStarHelper); requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]); } var func; @@ -77601,11 +78573,11 @@ var ts; return innerExpr; } if (ts.getImportNeedsImportStarHelper(node)) { - context.requestEmitHelper(importStarHelper); + context.requestEmitHelper(ts.importStarHelper); return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]); } if (ts.getImportNeedsImportDefaultHelper(node)) { - context.requestEmitHelper(importDefaultHelper); + context.requestEmitHelper(ts.importDefaultHelper); return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]); } return innerExpr; @@ -78174,7 +79146,7 @@ var ts; * @param emit A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 279 /* SourceFile */) { + if (node.kind === 284 /* SourceFile */) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -78262,7 +79234,7 @@ var ts; } if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 284 /* SourceFile */) { return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), /*location*/ node); } @@ -78388,13 +79360,13 @@ var ts; text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" }; // emit helper for `import * as Name from "foo"` - var importStarHelper = { + ts.importStarHelper = { name: "typescript:commonjsimportstar", scoped: false, text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};" }; // emit helper for `import Name from "foo"` - var importDefaultHelper = { + ts.importDefaultHelper = { name: "typescript:commonjsimportdefault", scoped: false, text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};" @@ -78417,7 +79389,7 @@ var ts; context.enableSubstitution(204 /* BinaryExpression */); // Substitutes assignments to exported symbols. context.enableSubstitution(202 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(203 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableEmitNotification(279 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableEmitNotification(284 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var exportFunctionsMap = []; // The export function associated with a source file. @@ -78436,7 +79408,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 524288 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -78602,7 +79574,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.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -78987,7 +79959,7 @@ var ts; function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 - && (enclosingBlockScopedContainer.kind === 279 /* SourceFile */ + && (enclosingBlockScopedContainer.kind === 284 /* SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); } /** @@ -79330,9 +80302,9 @@ var ts; return visitCatchClause(node); case 218 /* Block */: return visitBlock(node); - case 310 /* MergeDeclarationMarker */: + case 315 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 311 /* EndOfDeclarationMarker */: + case 316 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -79514,14 +80486,13 @@ var ts; * @param node The node to visit. */ function destructuringAndImportCallVisitor(node) { - if (node.transformFlags & 1024 /* DestructuringAssignment */ - && node.kind === 204 /* BinaryExpression */) { + if (ts.isDestructuringAssignment(node)) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 512 /* ContainsDestructuringAssignment */) || (node.transformFlags & 524288 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -79580,7 +80551,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 279 /* SourceFile */; + return container !== undefined && container.kind === 284 /* SourceFile */; } else { return false; @@ -79613,7 +80584,7 @@ var ts; * @param emitCallback A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 279 /* SourceFile */) { + if (node.kind === 284 /* SourceFile */) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -79822,7 +80793,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); - if (exportContainer && exportContainer.kind === 279 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 284 /* SourceFile */) { exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -79861,7 +80832,7 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(279 /* SourceFile */); + context.enableEmitNotification(284 /* SourceFile */); context.enableSubstitution(72 /* Identifier */); var currentSourceFile; return ts.chainBundle(transformSourceFile); @@ -79971,7 +80942,8 @@ var ts; ts.isImportEqualsDeclaration(node) || ts.isTypeAliasDeclaration(node) || ts.isConstructorDeclaration(node) || - ts.isIndexSignatureDeclaration(node); + ts.isIndexSignatureDeclaration(node) || + ts.isPropertyAccessExpression(node); } ts.canProduceDiagnostics = canProduceDiagnostics; function createGetSymbolAccessibilityDiagnosticForNodeName(node) { @@ -80045,7 +81017,7 @@ var ts; } ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName; function createGetSymbolAccessibilityDiagnosticForNode(node) { - if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) { + if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) { return getVariableDeclarationTypeVisibilityError; } else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { @@ -80085,7 +81057,7 @@ var ts; } // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. - else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 153 /* PropertySignature */ || + else if (node.kind === 154 /* PropertyDeclaration */ || node.kind === 189 /* PropertyAccessExpression */ || node.kind === 153 /* PropertySignature */ || (node.kind === 151 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (ts.hasModifier(node, 32 /* Static */)) { @@ -80290,6 +81262,9 @@ var ts; case 241 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; + case 181 /* MappedType */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1; + break; case 166 /* ConstructorType */: case 161 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; @@ -80373,6 +81348,31 @@ var ts; return result.diagnostics; } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; + function hasInternalAnnotation(range, currentSourceFile) { + var comment = currentSourceFile.text.substring(range.pos, range.end); + return ts.stringContains(comment, "@internal"); + } + function isInternalDeclaration(node, currentSourceFile) { + var parseTreeNode = ts.getParseTreeNode(node); + if (parseTreeNode && parseTreeNode.kind === 151 /* Parameter */) { + var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode); + var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined; + var text = currentSourceFile.text; + var commentRanges = previousSibling + ? ts.concatenate( + // to handle + // ... parameters, /* @internal */ + // public param: string + ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos)) + : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true)); + return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile); + } + var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile); + return !!ts.forEach(leadingCommentRanges, function (range) { + return hasInternalAnnotation(range, currentSourceFile); + }); + } + ts.isInternalDeclaration = isInternalDeclaration; var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | @@ -80501,10 +81501,10 @@ var ts; } } function transformRoot(node) { - if (node.kind === 279 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { + if (node.kind === 284 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJS(node))) { return node; } - if (node.kind === 280 /* Bundle */) { + if (node.kind === 285 /* Bundle */) { isBundledEmit = true; refs = ts.createMap(); libs = ts.createMap(); @@ -80534,9 +81534,15 @@ var ts; var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); }), ts.mapDefined(node.prepends, function (prepend) { - if (prepend.kind === 282 /* InputFiles */) { - return ts.createUnparsedSourceFile(prepend, "dts"); - } + if (prepend.kind === 287 /* InputFiles */) { + var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal); + hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib; + collectReferences(sourceFile, refs); + recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives); + collectLibs(sourceFile, libs); + return sourceFile; + } + return prepend; })); bundle.syntheticFileReferences = []; bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); @@ -80628,7 +81634,7 @@ var ts; } } function collectReferences(sourceFile, ret) { - if (noResolve || ts.isSourceFileJS(sourceFile)) + if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile))) return ret; ts.forEach(sourceFile.referencedFiles, function (f) { var elem = ts.tryResolveScriptReference(host, sourceFile, f); @@ -81175,7 +82181,9 @@ var ts; if (!ts.isPropertyAccessExpression(p.valueDeclaration)) { return undefined; } + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration); var type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + getSymbolAccessibilityDiagnostic = oldDiag; var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl])); }); @@ -81218,7 +82226,7 @@ var ts; if (ctor) { var oldDiag_1 = getSymbolAccessibilityDiagnostic; parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { - if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) + if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param)) return; getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 72 /* Identifier */) { @@ -81354,18 +82362,8 @@ var ts; } errorNameNode = undefined; } - function hasInternalAnnotation(range) { - var comment = currentSourceFile.text.substring(range.pos, range.end); - return ts.stringContains(comment, "@internal"); - } function shouldStripInternal(node) { - if (stripInternal && node) { - var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile); - if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { - return true; - } - } - return false; + return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile); } function isScopeMarker(node) { return ts.isExportAssignment(node) || ts.isExportDeclaration(node); @@ -81387,7 +82385,7 @@ var ts; function ensureModifierFlags(node, privateDeclaration) { var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; - var parentIsFile = node.parent.kind === 279 /* SourceFile */; + var parentIsFile = node.parent.kind === 284 /* SourceFile */; if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) || hasScopeMarker(node.parent) ? 0 : 1 /* Export */) | 2 /* Ambient */); additions = 0 /* None */; @@ -81556,9 +82554,15 @@ var ts; if (jsx === 2 /* React */) { transformers.push(ts.transformJsx); } - if (languageVersion < 6 /* ESNext */) { + if (languageVersion < 7 /* ESNext */) { transformers.push(ts.transformESNext); } + if (languageVersion < 6 /* ES2019 */) { + transformers.push(ts.transformES2019); + } + if (languageVersion < 5 /* ES2018 */) { + transformers.push(ts.transformES2018); + } if (languageVersion < 4 /* ES2017 */) { transformers.push(ts.transformES2017); } @@ -81598,7 +82602,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(312 /* Count */); + var enabledSyntaxKindFeatures = new Array(317 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -81858,10 +82862,14 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var infoExtension = ".tsbundleinfo"; var brackets = createBracketsMap(); var syntheticParent = { pos: -1, end: -1 }; /*@internal*/ + function isBuildInfoFile(file) { + return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */); + } + ts.isBuildInfoFile = isBuildInfoFile; + /*@internal*/ /** * Iterates over the source files that are expected to have an emit output. * @@ -81871,13 +82879,14 @@ var ts; * If an array, the full list of source files to emit. * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit. */ - function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles, onlyBuildInfo, includeBuildInfo) { if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); var options = host.getCompilerOptions(); if (options.outFile || options.out) { - if (sourceFiles.length) { - var bundle = ts.createBundle(sourceFiles, host.getPrependNodes()); + var prepends = host.getPrependNodes(); + if (sourceFiles.length || prepends.length) { + var bundle = ts.createBundle(sourceFiles, prepends); var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); if (result) { return result; @@ -81885,31 +82894,61 @@ var ts; } } else { - for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { - var sourceFile = sourceFiles_1[_a]; - var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile); - if (result) { - return result; + if (!onlyBuildInfo) { + for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { + var sourceFile = sourceFiles_1[_a]; + var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile); + if (result) { + return result; + } } } + if (includeBuildInfo) { + var buildInfoPath = getOutputPathForBuildInfo(host.getCompilerOptions()); + if (buildInfoPath) + return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined); + } } } ts.forEachEmittedFile = forEachEmittedFile; /*@internal*/ + function getOutputPathForBuildInfo(options) { + var configFile = options.configFilePath; + if (!configFile || !ts.isIncrementalCompilation(options)) + return undefined; + if (options.tsBuildInfoFile) + return options.tsBuildInfoFile; + var outPath = options.outFile || options.out; + var buildInfoExtensionLess; + if (outPath) { + buildInfoExtensionLess = ts.removeFileExtension(outPath); + } + else { + var configFileExtensionLess = ts.removeFileExtension(configFile); + buildInfoExtensionLess = options.outDir ? + options.rootDir ? + ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) : + ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) : + configFileExtensionLess; + } + return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */; + } + ts.getOutputPathForBuildInfo = getOutputPathForBuildInfo; + /*@internal*/ function getOutputPathsForBundle(options, forceDtsPaths) { var outPath = options.outFile || options.out; var jsFilePath = options.emitDeclarationOnly ? undefined : outPath; var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined; var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; - var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; - return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; + var buildInfoPath = getOutputPathForBuildInfo(options); + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath }; } ts.getOutputPathsForBundle = getOutputPathsForBundle; /*@internal*/ function getOutputPathsFor(sourceFile, host, forceDtsPaths) { var options = host.getCompilerOptions(); - if (sourceFile.kind === 280 /* Bundle */) { + if (sourceFile.kind === 285 /* Bundle */) { return getOutputPathsForBundle(options, forceDtsPaths); } else { @@ -81923,19 +82962,13 @@ var ts; var isJs = ts.isSourceFileJS(sourceFile); var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; - return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined }; } } ts.getOutputPathsFor = getOutputPathsFor; function getSourceMapFilePath(jsFilePath, options) { return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined; } - function createDefaultBundleInfo() { - return { - originalOffset: -1, - totalLength: -1 - }; - } // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve @@ -81958,9 +82991,91 @@ var ts; return ".js" /* Js */; } ts.getOutputExtension = getOutputExtension; + function rootDirOfOptions(configFile) { + return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.assertDefined(configFile.options.configFilePath)); + } + function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) { + return outputDir ? + ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) : + inputFileName; + } + /* @internal */ + function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) { + ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && ts.hasTSFileExtension(inputFileName)); + return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */); + } + ts.getOutputDeclarationFileName = getOutputDeclarationFileName; + function getOutputJSFileName(inputFileName, configFile, ignoreCase) { + var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */); + var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ? + ".json" /* Json */ : + ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ? + ".jsx" /* Jsx */ : + ".js" /* Js */); + return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.assertDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ? + outputFileName : + undefined; + } + /*@internal*/ + function getAllProjectOutputs(configFile, ignoreCase) { + var outputs; + var addOutput = function (path) { return path && (outputs || (outputs = [])).push(path); }; + if (configFile.options.outFile || configFile.options.out) { + var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath; + addOutput(jsFilePath); + addOutput(sourceMapFilePath); + addOutput(declarationFilePath); + addOutput(declarationMapPath); + addOutput(buildInfoPath); + } + else { + for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) { + var inputFileName = _c[_b]; + if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */)) + continue; + var js = getOutputJSFileName(inputFileName, configFile, ignoreCase); + addOutput(js); + if (ts.fileExtensionIs(inputFileName, ".json" /* Json */)) + continue; + if (configFile.options.sourceMap) { + addOutput(js + ".map"); + } + if (ts.getEmitDeclarations(configFile.options) && ts.hasTSFileExtension(inputFileName)) { + var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase); + addOutput(dts); + if (configFile.options.declarationMap) { + addOutput(dts + ".map"); + } + } + } + addOutput(getOutputPathForBuildInfo(configFile.options)); + } + return outputs || ts.emptyArray; + } + ts.getAllProjectOutputs = getAllProjectOutputs; + /*@internal*/ + function getFirstProjectOutput(configFile, ignoreCase) { + if (configFile.options.outFile || configFile.options.out) { + var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath; + return ts.Debug.assertDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output"); + } + for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) { + var inputFileName = _b[_a]; + if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */)) + continue; + var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase); + if (jsFilePath) + return jsFilePath; + } + var buildInfoPath = getOutputPathForBuildInfo(configFile.options); + if (buildInfoPath) + return buildInfoPath; + return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output"); + } + ts.getFirstProjectOutput = getFirstProjectOutput; /*@internal*/ // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature - function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) { + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers, onlyBuildInfo) { var compilerOptions = host.getCompilerOptions(); var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; @@ -81968,12 +83083,12 @@ var ts; var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); var writer = ts.createTextWriter(newLine); var _a = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _a.enter, exit = _a.exit; - var bundleInfo = createDefaultBundleInfo(); + var bundleBuildInfo; var emitSkipped = false; var exportedModulesFromDeclarationEmit; // Emit each output file enter(); - forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); + forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles, onlyBuildInfo, !targetSourceFile); exit(); return { emitSkipped: emitSkipped, @@ -81983,9 +83098,16 @@ var ts; exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { - var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; - emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath); + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath; + if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) { + bundleBuildInfo = { + commonSourceDirectory: host.getCommonSourceDirectory(), + sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return file.fileName; }) + }; + } + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath); emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); + emitBuildInfo(bundleBuildInfo, buildInfoPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { if (jsFilePath) { @@ -81994,8 +83116,8 @@ var ts; if (sourceMapFilePath) { emittedFilesList.push(sourceMapFilePath); } - if (bundleInfoPath) { - emittedFilesList.push(bundleInfoPath); + if (buildInfoPath) { + emittedFilesList.push(buildInfoPath); } } if (declarationFilePath) { @@ -82006,8 +83128,21 @@ var ts; } } } - function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { - if (emitOnlyDtsFiles || !jsFilePath) { + function emitBuildInfo(bundle, buildInfoPath) { + // Write build information if applicable + if (!buildInfoPath || targetSourceFile || emitSkipped) + return; + var program = host.getProgramBuildInfo(); + if (!bundle && !program) + return; + if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) { + emitSkipped = true; + return; + } + ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: ts.version }), /*writeByteOrderMark*/ false); + } + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath) { + if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) { return; } // Make sure not to write js file and source map file if any of them cannot be written @@ -82027,6 +83162,7 @@ var ts; inlineSourceMap: compilerOptions.inlineSourceMap, inlineSources: compilerOptions.inlineSources, extendedDiagnostics: compilerOptions.extendedDiagnostics, + writeBundleFileInfo: !!bundleBuildInfo }; // Create a printer to print the nodes var printer = createPrinter(printerOptions, { @@ -82037,12 +83173,14 @@ var ts; substituteNode: transform.substituteNode, }); ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, compilerOptions); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions); // Clean up emit nodes on parse tree transform.dispose(); + if (bundleBuildInfo) + bundleBuildInfo.js = printer.bundleFileInfo; } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { + if (!sourceFileOrBundle || !(declarationFilePath && !ts.isInJSFile(sourceFileOrBundle))) { return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; @@ -82071,6 +83209,8 @@ var ts; inlineSourceMap: compilerOptions.inlineSourceMap, extendedDiagnostics: compilerOptions.extendedDiagnostics, onlyPrintJsDocStyle: true, + writeBundleFileInfo: !!bundleBuildInfo, + recordInternalSection: !!bundleBuildInfo }; var declarationPrinter = createPrinter(printerOptions, { // resolver hooks @@ -82083,18 +83223,20 @@ var ts; emitSkipped = emitSkipped || declBlocked; if (!declBlocked || emitOnlyDtsFiles) { ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); - printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, { + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, { sourceMap: compilerOptions.declarationMap, sourceRoot: compilerOptions.sourceRoot, mapRoot: compilerOptions.mapRoot, extendedDiagnostics: compilerOptions.extendedDiagnostics, }); - if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 279 /* SourceFile */) { + if (emitOnlyDtsFiles && declarationTransform.transformed[0].kind === 284 /* SourceFile */) { var sourceFile = declarationTransform.transformed[0]; exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit; } } declarationTransform.dispose(); + if (bundleBuildInfo) + bundleBuildInfo.dts = declarationPrinter.bundleFileInfo; } function collectLinkedAliases(node) { if (ts.isExportAssignment(node)) { @@ -82109,16 +83251,16 @@ var ts; } ts.forEachChild(node, collectLinkedAliases); } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapOptions) { - var bundle = sourceFileOrBundle.kind === 280 /* Bundle */ ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 279 /* SourceFile */ ? sourceFileOrBundle : undefined; + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) { + var bundle = sourceFileOrBundle.kind === 285 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 284 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; var sourceMapGenerator; if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) { sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions); } if (bundle) { - printer.writeBundle(bundle, bundleInfo, writer, sourceMapGenerator); + printer.writeBundle(bundle, writer, sourceMapGenerator); } else { printer.writeFile(sourceFile, writer, sourceMapGenerator); @@ -82147,18 +83289,12 @@ var ts; } // Write the output file ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); - // Write bundled offset information if applicable - if (bundleInfoPath) { - bundleInfo.totalLength = writer.getTextPos(); - ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false); - } // Reset state writer.clear(); - bundleInfo = createDefaultBundleInfo(); } function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { return (mapOptions.sourceMap || mapOptions.inlineSourceMap) - && (sourceFileOrBundle.kind !== 279 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); + && (sourceFileOrBundle.kind !== 284 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); } function getSourceRoot(mapOptions) { // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the @@ -82215,6 +83351,167 @@ var ts; } } ts.emitFiles = emitFiles; + /*@internal*/ + function getBuildInfoText(buildInfo) { + return JSON.stringify(buildInfo, undefined, 2); + } + ts.getBuildInfoText = getBuildInfoText; + /*@internal*/ + function getBuildInfo(buildInfoText) { + return JSON.parse(buildInfoText); + } + ts.getBuildInfo = getBuildInfo; + /*@internal*/ + ts.notImplementedResolver = { + hasGlobalName: ts.notImplemented, + getReferencedExportContainer: ts.notImplemented, + getReferencedImportDeclaration: ts.notImplemented, + getReferencedDeclarationWithCollidingName: ts.notImplemented, + isDeclarationWithCollidingName: ts.notImplemented, + isValueAliasDeclaration: ts.notImplemented, + isReferencedAliasDeclaration: ts.notImplemented, + isTopLevelValueImportEqualsWithEntityName: ts.notImplemented, + getNodeCheckFlags: ts.notImplemented, + isDeclarationVisible: ts.notImplemented, + isLateBound: function (_node) { return false; }, + collectLinkedAliases: ts.notImplemented, + isImplementationOfOverload: ts.notImplemented, + isRequiredInitializedParameter: ts.notImplemented, + isOptionalUninitializedParameterProperty: ts.notImplemented, + isExpandoFunctionDeclaration: ts.notImplemented, + getPropertiesOfContainerFunction: ts.notImplemented, + createTypeOfDeclaration: ts.notImplemented, + createReturnTypeOfSignatureDeclaration: ts.notImplemented, + createTypeOfExpression: ts.notImplemented, + createLiteralConstValue: ts.notImplemented, + isSymbolAccessible: ts.notImplemented, + isEntityNameVisible: ts.notImplemented, + // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant + getConstantValue: ts.notImplemented, + getReferencedValueDeclaration: ts.notImplemented, + getTypeReferenceSerializationKind: ts.notImplemented, + isOptionalParameter: ts.notImplemented, + moduleExportsSomeValue: ts.notImplemented, + isArgumentsLocalBinding: ts.notImplemented, + getExternalModuleFileFromDeclaration: ts.notImplemented, + getTypeReferenceDirectivesForEntityName: ts.notImplemented, + getTypeReferenceDirectivesForSymbol: ts.notImplemented, + isLiteralConstDeclaration: ts.notImplemented, + getJsxFactoryEntity: ts.notImplemented, + getAllAccessorDeclarations: ts.notImplemented, + getSymbolOfExternalModuleSpecifier: ts.notImplemented, + isBindingCapturedByNode: ts.notImplemented, + }; + function createSourceFilesFromBundleBuildInfo(bundle) { + var sourceFiles = bundle.sourceFiles.map(function (fileName) { + var sourceFile = ts.createNode(284 /* SourceFile */, 0, 0); + sourceFile.fileName = fileName; + sourceFile.text = ""; + sourceFile.statements = ts.createNodeArray(); + return sourceFile; + }); + var jsBundle = ts.Debug.assertDefined(bundle.js); + ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) { + var sourceFile = sourceFiles[prologueInfo.file]; + sourceFile.text = prologueInfo.text; + sourceFile.end = prologueInfo.text.length; + sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) { + var statement = ts.createNode(221 /* ExpressionStatement */, directive.pos, directive.end); + statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end); + statement.expression.text = directive.expression.text; + return statement; + })); + }); + return sourceFiles; + } + /*@internal*/ + function emitUsingBuildInfo(config, host, getCommandLine) { + var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; + var buildInfoText = host.readFile(ts.Debug.assertDefined(buildInfoPath)); + if (!buildInfoText) + return buildInfoPath; + var jsFileText = host.readFile(ts.Debug.assertDefined(jsFilePath)); + if (!jsFileText) + return jsFilePath; + var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath); + // error if no source map or for now if inline sourcemap + if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap) + return sourceMapFilePath || "inline sourcemap decoding"; + // read declaration text + var declarationText = declarationFilePath && host.readFile(declarationFilePath); + if (declarationFilePath && !declarationText) + return declarationFilePath; + var declarationMapText = declarationMapPath && host.readFile(declarationMapPath); + // error if no source map or for now if inline sourcemap + if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap) + return declarationMapPath || "inline sourcemap decoding"; + var buildInfo = getBuildInfo(buildInfoText); + if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts)) + return buildInfoPath; + var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, + /*onlyOwnText*/ true); + var outputFiles = []; + var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); }); + var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle); + var emitHost = { + getPrependNodes: ts.memoize(function () { return prependNodes.concat([ownPrependInput]); }), + getCanonicalFileName: host.getCanonicalFileName, + getCommonSourceDirectory: function () { return buildInfo.bundle.commonSourceDirectory; }, + getCompilerOptions: function () { return config.options; }, + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + getNewLine: function () { return host.getNewLine(); }, + getSourceFile: ts.returnUndefined, + getSourceFileByPath: ts.returnUndefined, + getSourceFiles: function () { return sourceFilesForJsEmit; }, + getLibFileFromReference: ts.notImplemented, + isSourceFileFromExternalLibrary: ts.returnFalse, + getResolvedProjectReferenceToRedirect: ts.returnUndefined, + writeFile: function (name, text, writeByteOrderMark) { + switch (name) { + case jsFilePath: + if (jsFileText === text) + return; + break; + case sourceMapFilePath: + if (sourceMapText === text) + return; + break; + case buildInfoPath: + var newBuildInfo = getBuildInfo(text); + newBuildInfo.program = buildInfo.program; + // Update sourceFileInfo + var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles; + newBuildInfo.bundle.js.sources = js.sources; + if (dts) { + newBuildInfo.bundle.dts.sources = dts.sources; + } + newBuildInfo.bundle.sourceFiles = sourceFiles; + outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark }); + return; + case declarationFilePath: + if (declarationText === text) + return; + break; + case declarationMapPath: + if (declarationMapText === text) + return; + break; + default: + ts.Debug.fail("Unexpected path: " + name); + } + outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); + }, + isEmitBlocked: ts.returnFalse, + readFile: function (f) { return host.readFile(f); }, + fileExists: function (f) { return host.fileExists(f); }, + directoryExists: host.directoryExists && (function (f) { return host.directoryExists(f); }), + useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, + getProgramBuildInfo: ts.returnUndefined + }; + emitFiles(ts.notImplementedResolver, emitHost, /*targetSourceFile*/ undefined, /*emitOnlyDtsFiles*/ false, ts.getTransformers(config.options)); + return outputFiles; + } + ts.emitUsingBuildInfo = emitUsingBuildInfo; var PipelinePhase; (function (PipelinePhase) { PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; @@ -82243,6 +83540,10 @@ var ts; var ownWriter; // Reusable `EmitTextWriter` for basic printing. var write = writeBase; var isOwnFileEmit; + var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined; + var recordInternalSection = printerOptions.recordInternalSection; + var sourceFileTextPos = 0; + var sourceFileTextKind = "text" /* Text */; // Source Maps var sourceMapsDisabled = true; var sourceMapGenerator; @@ -82268,7 +83569,8 @@ var ts; writeNode: writeNode, writeList: writeList, writeFile: writeFile, - writeBundle: writeBundle + writeBundle: writeBundle, + bundleFileInfo: bundleFileInfo }; function printNode(hint, node, sourceFile) { switch (hint) { @@ -82283,9 +83585,9 @@ var ts; break; } switch (node.kind) { - case 279 /* SourceFile */: return printFile(node); - case 280 /* Bundle */: return printBundle(node); - case 281 /* UnparsedSource */: return printUnparsedSource(node); + case 284 /* SourceFile */: return printFile(node); + case 285 /* Bundle */: return printBundle(node); + case 286 /* UnparsedSource */: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -82295,7 +83597,7 @@ var ts; return endPrint(); } function printBundle(bundle) { - writeBundle(bundle, /*bundleInfo*/ undefined, beginPrint(), /*sourceMapEmitter*/ undefined); + writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined); return endPrint(); } function printFile(sourceFile) { @@ -82323,7 +83625,49 @@ var ts; reset(); writer = previousWriter; } - function writeBundle(bundle, bundleInfo, output, sourceMapGenerator) { + function getTextPosWithWriteLine() { + return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos(); + } + function updateOrPushBundleFileTextLike(pos, end, kind) { + var last = ts.lastOrUndefined(bundleFileInfo.sections); + if (last && last.kind === kind) { + last.end = end; + } + else { + bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind }); + } + } + function recordBundleFileInternalSectionStart(node) { + if (recordInternalSection && + bundleFileInfo && + currentSourceFile && + (ts.isDeclaration(node) || ts.isVariableStatement(node)) && + ts.isInternalDeclaration(node, currentSourceFile) && + sourceFileTextKind !== "internal" /* Internal */) { + var prevSourceFileTextKind = sourceFileTextKind; + recordBundleFileTextLikeSection(writer.getTextPos()); + sourceFileTextPos = getTextPosWithWriteLine(); + sourceFileTextKind = "internal" /* Internal */; + return prevSourceFileTextKind; + } + return undefined; + } + function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) { + if (prevSourceFileTextKind) { + recordBundleFileTextLikeSection(writer.getTextPos()); + sourceFileTextPos = getTextPosWithWriteLine(); + sourceFileTextKind = prevSourceFileTextKind; + } + } + function recordBundleFileTextLikeSection(end) { + if (sourceFileTextPos < end) { + updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind); + return true; + } + return false; + } + function writeBundle(bundle, output, sourceMapGenerator) { + var _a; isOwnFileEmit = false; var previousWriter = writer; setWriter(output, sourceMapGenerator); @@ -82331,18 +83675,49 @@ var ts; emitPrologueDirectivesIfNeeded(bundle); emitHelpers(bundle); emitSyntheticTripleSlashReferencesIfNeeded(bundle); - for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { - var prepend = _b[_a]; + for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) { + var prepend = _c[_b]; writeLine(); + var pos = writer.getTextPos(); + var savedSections = bundleFileInfo && bundleFileInfo.sections; + if (savedSections) + bundleFileInfo.sections = []; print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); + if (bundleFileInfo) { + var newSections = bundleFileInfo.sections; + bundleFileInfo.sections = savedSections; + if (prepend.oldFileOfCurrentEmit) + (_a = bundleFileInfo.sections).push.apply(_a, newSections); + else { + newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); }); + bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prepend" /* Prepend */, data: prepend.fileName, texts: newSections }); + } + } } - if (bundleInfo) { - bundleInfo.originalOffset = writer.getTextPos(); - } - for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) { - var sourceFile = _d[_c]; + sourceFileTextPos = getTextPosWithWriteLine(); + for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) { + var sourceFile = _e[_d]; print(0 /* SourceFile */, sourceFile, sourceFile); } + if (bundleFileInfo && bundle.sourceFiles.length) { + var end = writer.getTextPos(); + if (recordBundleFileTextLikeSection(end)) { + // Store prologues + var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle); + if (prologues) { + if (!bundleFileInfo.sources) + bundleFileInfo.sources = {}; + bundleFileInfo.sources.prologues = prologues; + } + // Store helpes + var helpers = getHelpersFromBundledSourceFiles(bundle); + if (helpers) { + if (!bundleFileInfo.sources) + bundleFileInfo.sources = {}; + bundleFileInfo.sources.helpers = helpers; + } + } + } reset(); writer = previousWriter; } @@ -82412,8 +83787,10 @@ var ts; function emit(node) { if (node === undefined) return; + var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node); var pipelinePhase = getPipelinePhase(0 /* Notification */, node); pipelinePhase(4 /* Unspecified */, node); + recordBundleFileInternalSectionEnd(prevSourceFileTextKind); } function emitIdentifierName(node) { if (node === undefined) @@ -82440,12 +83817,12 @@ var ts; } // falls through case 2 /* Comments */: - if (!commentsDisabled && node.kind !== 279 /* SourceFile */) { + if (!commentsDisabled && node.kind !== 284 /* SourceFile */) { return pipelineEmitWithComments; } // falls through case 3 /* SourceMaps */: - if (!sourceMapsDisabled && node.kind !== 279 /* SourceFile */ && !ts.isInJsonFile(node)) { + if (!sourceMapsDisabled && node.kind !== 284 /* SourceFile */ && !ts.isInJsonFile(node)) { return pipelineEmitWithSourceMap; } // falls through @@ -82482,8 +83859,16 @@ var ts; case 16 /* TemplateMiddle */: case 17 /* TemplateTail */: return emitLiteral(node); - case 281 /* UnparsedSource */: - return emitUnparsedSource(node); + case 286 /* UnparsedSource */: + case 280 /* UnparsedPrepend */: + return emitUnparsedSourceOrPrepend(node); + case 279 /* UnparsedPrologue */: + return writeUnparsedNode(node); + case 281 /* UnparsedText */: + case 282 /* UnparsedInternalText */: + return emitUnparsedTextLike(node); + case 283 /* UnparsedSyntheticReference */: + return emitUnparsedSyntheticReference(node); // Identifiers case 72 /* Identifier */: return emitIdentifier(node); @@ -82527,7 +83912,7 @@ var ts; return emitTypeReference(node); case 165 /* FunctionType */: return emitFunctionType(node); - case 289 /* JSDocFunctionType */: + case 294 /* JSDocFunctionType */: return emitJSDocFunctionType(node); case 166 /* ConstructorType */: return emitConstructorType(node); @@ -82565,20 +83950,20 @@ var ts; return emitLiteralType(node); case 183 /* ImportType */: return emitImportTypeNode(node); - case 284 /* JSDocAllType */: + case 289 /* JSDocAllType */: writePunctuation("*"); return; - case 285 /* JSDocUnknownType */: + case 290 /* JSDocUnknownType */: writePunctuation("?"); return; - case 286 /* JSDocNullableType */: + case 291 /* JSDocNullableType */: return emitJSDocNullableType(node); - case 287 /* JSDocNonNullableType */: + case 292 /* JSDocNonNullableType */: return emitJSDocNonNullableType(node); - case 288 /* JSDocOptionalType */: + case 293 /* JSDocOptionalType */: return emitJSDocOptionalType(node); case 172 /* RestType */: - case 290 /* JSDocVariadicType */: + case 295 /* JSDocVariadicType */: return emitRestOrJSDocVariadicType(node); // Binding patterns case 184 /* ObjectBindingPattern */: @@ -82716,30 +84101,30 @@ var ts; case 278 /* EnumMember */: return emitEnumMember(node); // JSDoc nodes (only used in codefixes currently) - case 299 /* JSDocParameterTag */: - case 305 /* JSDocPropertyTag */: + case 304 /* JSDocParameterTag */: + case 310 /* JSDocPropertyTag */: return emitJSDocPropertyLikeTag(node); - case 300 /* JSDocReturnTag */: - case 302 /* JSDocTypeTag */: - case 301 /* JSDocThisTag */: - case 298 /* JSDocEnumTag */: + case 305 /* JSDocReturnTag */: + case 307 /* JSDocTypeTag */: + case 306 /* JSDocThisTag */: + case 303 /* JSDocEnumTag */: return emitJSDocSimpleTypedTag(node); - case 295 /* JSDocAugmentsTag */: + case 300 /* JSDocAugmentsTag */: return emitJSDocAugmentsTag(node); - case 303 /* JSDocTemplateTag */: + case 308 /* JSDocTemplateTag */: return emitJSDocTemplateTag(node); - case 304 /* JSDocTypedefTag */: + case 309 /* JSDocTypedefTag */: return emitJSDocTypedefTag(node); - case 297 /* JSDocCallbackTag */: + case 302 /* JSDocCallbackTag */: return emitJSDocCallbackTag(node); - case 293 /* JSDocSignature */: + case 298 /* JSDocSignature */: return emitJSDocSignature(node); - case 292 /* JSDocTypeLiteral */: + case 297 /* JSDocTypeLiteral */: return emitJSDocTypeLiteral(node); - case 296 /* JSDocClassTag */: - case 294 /* JSDocTag */: + case 301 /* JSDocClassTag */: + case 299 /* JSDocTag */: return emitJSDocSimpleTag(node); - case 291 /* JSDocComment */: + case 296 /* JSDocComment */: return emitJSDoc(node); // Transformation nodes (ignored) } @@ -82838,9 +84223,9 @@ var ts; case 264 /* JsxFragment */: return emitJsxFragment(node); // Transformation nodes - case 308 /* PartiallyEmittedExpression */: + case 313 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 309 /* CommaListExpression */: + case 314 /* CommaListExpression */: return emitCommaList(node); } } @@ -82856,22 +84241,45 @@ var ts; var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, node); pipelinePhase(hint, substituteNode(hint, node)); } + function getHelpersFromBundledSourceFiles(bundle) { + var result; + if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) { + return undefined; + } + var bundledHelpers = ts.createMap(); + for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) { + var sourceFile = _b[_a]; + var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined; + var helpers = getSortedEmitHelpers(sourceFile); + if (!helpers) + continue; + for (var _c = 0, helpers_3 = helpers; _c < helpers_3.length; _c++) { + var helper = helpers_3[_c]; + if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) { + bundledHelpers.set(helper.name, true); + (result || (result = [])).push(helper.name); + } + } + } + return result; + } function emitHelpers(node) { var helpersEmitted = false; - var bundle = node.kind === 280 /* Bundle */ ? node : undefined; + var bundle = node.kind === 285 /* Bundle */ ? node : undefined; if (bundle && moduleKind === ts.ModuleKind.None) { return; } - var numNodes = bundle ? bundle.sourceFiles.length : 1; + var numPrepends = bundle ? bundle.prepends.length : 0; + var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1; for (var i = 0; i < numNodes; i++) { - var currentNode = bundle ? bundle.sourceFiles[i] : node; - var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; - var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; - var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; - var helpers = ts.getEmitHelpers(currentNode); + var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node; + var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile; + var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.getExternalHelpersModuleName(sourceFile) !== undefined); + var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit; + var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode); if (helpers) { - for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) { - var helper = _b[_a]; + for (var _a = 0, helpers_4 = helpers; _a < helpers_4.length; _a++) { + var helper = helpers_4[_a]; if (!helper.scoped) { // Skip the helper if it can be skipped and the noEmitHelpers compiler // option is set, or if it can be imported and the importHelpers compiler @@ -82891,18 +84299,25 @@ var ts; // Skip the helper if it is scoped and we are emitting bundled helpers continue; } + var pos = getTextPosWithWriteLine(); if (typeof helper.text === "string") { writeLines(helper.text); } else { writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } + if (bundleFileInfo) + bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name }); helpersEmitted = true; } } } return helpersEmitted; } + function getSortedEmitHelpers(node) { + var helpers = ts.getEmitHelpers(node); + return helpers && ts.stableSort(helpers, ts.compareEmitHelpers); + } // // Literals/Pseudo-literals // @@ -82929,8 +84344,42 @@ var ts; } } // SyntaxKind.UnparsedSource - function emitUnparsedSource(unparsed) { - writer.rawWrite(unparsed.text); + // SyntaxKind.UnparsedPrepend + function emitUnparsedSourceOrPrepend(unparsed) { + for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) { + var text = _b[_a]; + writeLine(); + emit(text); + } + } + // SyntaxKind.UnparsedPrologue + // SyntaxKind.UnparsedText + // SyntaxKind.UnparsedInternal + // SyntaxKind.UnparsedSyntheticReference + function writeUnparsedNode(unparsed) { + writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end)); + } + // SyntaxKind.UnparsedText + // SyntaxKind.UnparsedInternal + function emitUnparsedTextLike(unparsed) { + var pos = getTextPosWithWriteLine(); + writeUnparsedNode(unparsed); + if (bundleFileInfo) { + updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 281 /* UnparsedText */ ? + "text" /* Text */ : + "internal" /* Internal */); + } + } + // SyntaxKind.UnparsedSyntheticReference + function emitUnparsedSyntheticReference(unparsed) { + var pos = getTextPosWithWriteLine(); + writeUnparsedNode(unparsed); + if (bundleFileInfo) { + var section = ts.clone(unparsed.section); + section.pos = pos; + section.end = writer.getTextPos(); + bundleFileInfo.sections.push(section); + } } // // Identifiers @@ -82985,7 +84434,7 @@ var ts; emit(node.dotDotDotToken); emitNodeWithWriter(node.name, writeParameter); emit(node.questionToken); - if (node.parent && node.parent.kind === 289 /* JSDocFunctionType */ && !node.name) { + if (node.parent && node.parent.kind === 294 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { @@ -83865,7 +85314,7 @@ var ts; } function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) { // Emit all the prologue directives (like "use strict"). - var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true); + var statementOffset = emitPrologueDirectives(body.statements); var pos = writer.getTextPos(); emitHelpers(body); if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) { @@ -84125,7 +85574,7 @@ var ts; writePunctuation(">"); } function emitJsxText(node) { - writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); + writer.writeLiteral(node.text); } function emitJsxClosingElementOrFragment(node) { writePunctuation(""); + if (bundleFileInfo) + bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ }); writeLine(); } if (currentSourceFile && currentSourceFile.moduleName) { @@ -84438,17 +85900,26 @@ var ts; } for (var _c = 0, files_1 = files; _c < files_1.length; _c++) { var directive = files_1[_c]; + var pos = writer.getTextPos(); writeComment("/// "); + if (bundleFileInfo) + bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_18 = types; _d < types_18.length; _d++) { - var directive = types_18[_d]; + for (var _d = 0, types_19 = types; _d < types_19.length; _d++) { + var directive = types_19[_d]; + var pos = writer.getTextPos(); writeComment("/// "); + if (bundleFileInfo) + bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName }); writeLine(); } for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) { var directive = libs_1[_e]; + var pos = writer.getTextPos(); writeComment("/// "); + if (bundleFileInfo) + bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName }); writeLine(); } } @@ -84473,16 +85944,22 @@ var ts; * Emits any prologue directives at the start of a Statement list, returning the * number of prologue directives written to the output. */ - function emitPrologueDirectives(statements, startWithNewLine, seenPrologueDirectives) { + function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) { + var needsToSetSourceFile = !!sourceFile; for (var i = 0; i < statements.length; i++) { var statement = statements[i]; if (ts.isPrologueDirective(statement)) { var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true; if (shouldEmitPrologueDirective) { - if (startWithNewLine || i > 0) { - writeLine(); + if (needsToSetSourceFile) { + needsToSetSourceFile = false; + setSourceFile(sourceFile); } + writeLine(); + var pos = writer.getTextPos(); emit(statement); + if (recordBundleFileSection && bundleFileInfo) + bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text }); if (seenPrologueDirectives) { seenPrologueDirectives.set(statement.expression.text, true); } @@ -84495,23 +85972,70 @@ var ts; } return statements.length; } + function emitUnparsedPrologues(prologues, seenPrologueDirectives) { + for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) { + var prologue = prologues_1[_a]; + if (!seenPrologueDirectives.has(prologue.data)) { + writeLine(); + var pos = writer.getTextPos(); + emit(prologue); + if (bundleFileInfo) + bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data }); + if (seenPrologueDirectives) { + seenPrologueDirectives.set(prologue.data, true); + } + } + } + } function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) { if (ts.isSourceFile(sourceFileOrBundle)) { - setSourceFile(sourceFileOrBundle); - emitPrologueDirectives(sourceFileOrBundle.statements); + emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle); } else { var seenPrologueDirectives = ts.createMap(); - for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) { - var sourceFile = _b[_a]; - setSourceFile(sourceFile); - emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives); + for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) { + var prepend = _b[_a]; + emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives); + } + for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) { + var sourceFile = _d[_c]; + emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true); } setSourceFile(undefined); } } + function getPrologueDirectivesFromBundledSourceFiles(bundle) { + var seenPrologueDirectives = ts.createMap(); + var prologues; + for (var index = 0; index < bundle.sourceFiles.length; index++) { + var sourceFile = bundle.sourceFiles[index]; + var directives = void 0; + var end = 0; + for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) { + var statement = _b[_a]; + if (!ts.isPrologueDirective(statement)) + break; + if (seenPrologueDirectives.has(statement.expression.text)) + continue; + seenPrologueDirectives.set(statement.expression.text, true); + (directives || (directives = [])).push({ + pos: statement.pos, + end: statement.end, + expression: { + pos: statement.expression.pos, + end: statement.expression.end, + text: statement.expression.text + } + }); + end = end < statement.end ? statement.end : end; + } + if (directives) + (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives }); + } + return prologues; + } function emitShebangIfNeeded(sourceFileOrBundle) { - if (ts.isSourceFile(sourceFileOrBundle)) { + if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) { var shebang = ts.getShebang(sourceFileOrBundle.text); if (shebang) { writeComment(shebang); @@ -84520,11 +86044,18 @@ var ts; } } else { - for (var _a = 0, _b = sourceFileOrBundle.sourceFiles; _a < _b.length; _a++) { - var sourceFile = _b[_a]; + for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) { + var prepend = _b[_a]; + ts.Debug.assertNode(prepend, ts.isUnparsedSource); + if (emitShebangIfNeeded(prepend)) { + return true; + } + } + for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) { + var sourceFile = _d[_c]; // Emit only the first encountered shebang if (emitShebangIfNeeded(sourceFile)) { - break; + return true; } } } @@ -84727,6 +86258,7 @@ var ts; } // Emit each child. var previousSibling = void 0; + var previousSourceFileTextKind = void 0; var shouldDecreaseIndentAfterEmit = false; for (var i = 0; i < count; i++) { var child = children[start + i]; @@ -84747,6 +86279,7 @@ var ts; emitLeadingCommentsOfPosition(previousSibling.end); } writeDelimiter(format); + recordBundleFileInternalSectionEnd(previousSourceFileTextKind); // Write either a line terminator or whitespace to separate the elements. if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { // If a synthesized node in a single-line list starts on a new @@ -84763,6 +86296,7 @@ var ts; } } // Emit this child. + previousSourceFileTextKind = recordBundleFileInternalSectionStart(child); if (shouldEmitInterveningComments) { if (emitTrailingCommentsOfPosition) { var commentRange = ts.getCommentRange(child); @@ -84797,6 +86331,7 @@ var ts; if (format & 128 /* Indented */) { decreaseIndent(); } + recordBundleFileInternalSectionEnd(previousSourceFileTextKind); // Write the closing line terminator or closing whitespace. if (shouldWriteClosingLineTerminator(parentNode, children, format)) { writeLine(); @@ -84898,7 +86433,6 @@ var ts; if (line.length) { writeLine(); write(line); - writer.rawWrite(newLine); } } } @@ -85412,7 +86946,7 @@ var ts; hasWrittenComment = false; var emitFlags = ts.getEmitFlags(node); var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; - var isEmittedNode = node.kind !== 307 /* NotEmittedStatement */; + var isEmittedNode = node.kind !== 312 /* NotEmittedStatement */; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */; @@ -85672,19 +87206,28 @@ var ts; return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd); } // Source Maps + function getParsedSourceMap(node) { + if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) { + node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false; + } + return node.parsedSourceMap || undefined; + } function pipelineEmitWithSourceMap(hint, node) { var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, node); - if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { - var parsed = ts.tryParseRawSourceMap(node.sourceMapText); - if (parsed) { - sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.sourceMapPath); + if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) { + pipelinePhase(hint, node); + } + else if (ts.isUnparsedNode(node)) { + var parsed = getParsedSourceMap(node.parent); + if (parsed && sourceMapGenerator) { + sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end)); } pipelinePhase(hint, node); } else { var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b; var emitFlags = ts.getEmitFlags(node); - if (node.kind !== 307 /* NotEmittedStatement */ + if (node.kind !== 312 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 && pos >= 0) { emitSourcePos(source, skipSourceTrivia(source, pos)); @@ -85697,7 +87240,7 @@ var ts; else { pipelinePhase(hint, node); } - if (node.kind !== 307 /* NotEmittedStatement */ + if (node.kind !== 312 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 && end >= 0) { emitSourcePos(source, end); @@ -85825,7 +87368,8 @@ var ts; writeFile: host.writeFile && writeFile, addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, addOrDeleteFile: addOrDeleteFile, - clearCache: clearCache + clearCache: clearCache, + realpath: host.realpath && realpath }; function toPath(fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); @@ -85922,7 +87466,7 @@ var ts; var rootDirPath = toPath(rootDir); var result = tryReadDirectory(rootDir, rootDirPath); if (result) { - return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries); + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath); } return host.readDirectory(rootDir, extensions, excludes, includes, depth); function getFileSystemEntries(dir) { @@ -85933,6 +87477,9 @@ var ts; return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; } } + function realpath(s) { + return host.realpath ? host.realpath(s) : s; + } function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); if (existingResult) { @@ -86203,11 +87750,7 @@ var ts; function createCompilerHostWorker(options, setParentNodes, system) { if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); - function getCanonicalFileName(fileName) { - // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. - // otherwise use toLowerCase as a canonical form. - return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - } + var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames); function getSourceFile(fileName, languageVersion, onError) { var text; try { @@ -86332,20 +87875,21 @@ var ts; var key = toPath(fileName); var value = readFileCache.get(key); if (value !== undefined) - return value || undefined; + return value !== false ? value : undefined; return setReadFileCache(key, fileName); }; var setReadFileCache = function (key, fileName) { var newValue = originalReadFile.call(host, fileName); - readFileCache.set(key, newValue || false); + readFileCache.set(key, newValue !== undefined ? newValue : false); return newValue; }; host.readFile = function (fileName) { var key = toPath(fileName); var value = readFileCache.get(key); if (value !== undefined) - return value; // could be .d.ts from output - if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) { + return value !== false ? value : undefined; // could be .d.ts from output + // Cache json or buildInfo + if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) { return originalReadFile.call(host, fileName); } return setReadFileCache(key, fileName); @@ -86376,7 +87920,7 @@ var ts; var key = toPath(fileName); fileExistsCache.delete(key); var value = readFileCache.get(key); - if (value && value !== data) { + if (value !== undefined && value !== data) { readFileCache.delete(key); sourceFileCache.delete(key); } @@ -86822,11 +88366,18 @@ var ts; if (rootNames.length) { for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) { var parsedRef = resolvedProjectReferences_1[_i]; - if (parsedRef) { - var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; - if (out) { - var dtsOutfile = ts.changeExtension(out, ".d.ts"); - processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + if (!parsedRef) + continue; + var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; + if (out) { + processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + } + else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) { + for (var _a = 0, _b = parsedRef.commandLine.fileNames; _a < _b.length; _a++) { + var fileName = _b[_a]; + if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && ts.hasTSFileExtension(fileName)) { + processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + } } } } @@ -86874,8 +88425,8 @@ var ts; // not part of the new program. if (oldProgram && host.onReleaseOldSourceFile) { var oldSourceFiles = oldProgram.getSourceFiles(); - for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { - var oldSourceFile = oldSourceFiles_1[_a]; + for (var _c = 0, oldSourceFiles_1 = oldSourceFiles; _c < oldSourceFiles_1.length; _c++) { + var oldSourceFile = oldSourceFiles_1[_c]; var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); if (shouldCreateNewSourceFile || !newFile || // old file wasnt redirect but new file is @@ -86931,7 +88482,8 @@ var ts; getProjectReferenceRedirect: getProjectReferenceRedirect, getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath, - forEachResolvedProjectReference: forEachResolvedProjectReference + forEachResolvedProjectReference: forEachResolvedProjectReference, + emitBuildInfo: emitBuildInfo }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -86960,7 +88512,7 @@ var ts; } function getCommonSourceDirectory() { if (commonSourceDirectory === undefined) { - var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); + var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect); }); if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { // If a rootDir is specified use it as the commonSourceDirectory commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); @@ -87349,7 +88901,8 @@ var ts; } function getEmitHost(writeFileCallback) { return __assign({ getPrependNodes: getPrependNodes, - getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, getLibFileFromReference: program.getLibFileFromReference, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { // Use local caches var path = toPath(f); if (getSourceFileByPath(path)) @@ -87358,7 +88911,20 @@ var ts; return false; // Before falling back to the host return host.fileExists(f); - } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); + } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); } }); + } + function emitBuildInfo(writeFileCallback) { + ts.Debug.assert(!options.out && !options.outFile); + ts.performance.mark("beforeEmit"); + var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), + /*targetSourceFile*/ undefined, + /*emitOnlyDtsFiles*/ false, + /*transformers*/ undefined, + /*declaraitonTransformers*/ undefined, + /*onlyBuildInfo*/ true); + ts.performance.mark("afterEmit"); + ts.performance.measure("Emit", "beforeEmit", "afterEmit"); + return emitResult; } function getResolvedProjectReferences() { return resolvedProjectReferences; @@ -87367,28 +88933,11 @@ var ts; return projectReferences; } function getPrependNodes() { - if (!projectReferences) { - return ts.emptyArray; - } - var nodes = []; - for (var i = 0; i < projectReferences.length; i++) { - var ref = projectReferences[i]; - var resolvedRefOpts = resolvedProjectReferences[i].commandLine; - if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { - var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; - // Upstream project didn't have outFile set -- skip (error will have been issued earlier) - if (!out) - continue; - var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath; - var node = ts.createInputFiles(function (fileName) { - var path = toPath(fileName); - var sourceFile = getSourceFileByPath(path); - return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path); - }, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath); - nodes.push(node); - } - } - return nodes; + return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) { + var path = toPath(fileName); + var sourceFile = getSourceFileByPath(path); + return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path); + }); } function isSourceFileFromExternalLibrary(file) { return !!sourceFilesFoundSearchingNodeModules.get(file.path); @@ -87460,8 +89009,7 @@ var ts; var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217 - emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -88073,7 +89621,6 @@ var ts; 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 @@ -88170,7 +89717,7 @@ var ts; var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out; return out ? ts.changeExtension(out, ".d.ts" /* Dts */) : - ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine); + ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames()); } /** * Get the referenced project if the file is input file from that reference project @@ -88463,18 +90010,29 @@ var ts; if (options.declaration === false) { createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); } + if (options.incremental === false) { + createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration"); + } + } + if (options.tsBuildInfoFile) { + if (!ts.isIncrementalCompilation(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite"); + } } verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list if (options.composite) { - var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }); - if (rootNames.length < sourceFiles.length) { - var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); - for (var _i = 0, _a = sourceFiles.map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); _i < _a.length; _i++) { - var file = _a[_i]; - if (normalizedRootNames.indexOf(file) === -1) { - 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)); - } + var rootPaths = rootNames.map(toPath); + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var file = files_3[_i]; + // Ignore declaration files + if (file.isDeclarationFile) + continue; + // Ignore json file thats from project reference + if (ts.isJsonSourceFile(file) && getResolvedProjectReferenceToRedirect(file.fileName)) + continue; + if (rootPaths.indexOf(file.path) === -1) { + 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.fileName)); } } } @@ -88657,6 +90215,7 @@ var ts; } } function verifyProjectReferences() { + var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getOutputPathForBuildInfo(options) : undefined; forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) { var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index]; var parentFile = parent && parent.sourceFile; @@ -88683,6 +90242,10 @@ var ts; createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); } } + if (!parent && buildInfoPath && buildInfoPath === ts.getOutputPathForBuildInfo(options)) { + createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path); + hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true); + } }); } function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { @@ -88827,11 +90390,32 @@ var ts; readFile: function (f) { return directoryStructureHost.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, - onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || (function () { return undefined; }), + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined, trace: host.trace ? function (s) { return host.trace(s); } : undefined }; } ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike; + /* @internal */ + function createPrependNodes(projectReferences, getCommandLine, readFile) { + if (!projectReferences) + return ts.emptyArray; + var nodes; + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = getCommandLine(ref, i); + if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out; + // Upstream project didn't have outFile set -- skip (error will have been issued earlier) + if (!out) + continue; + var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath; + var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath); + (nodes || (nodes = [])).push(node); + } + } + return nodes || ts.emptyArray; + } + ts.createPrependNodes = createPrependNodes; function resolveProjectReferencePath(hostOrRef, ref) { var passedInRef = ref ? ref : hostOrRef; return ts.resolveConfigFileProjectName(passedInRef.path); @@ -89028,7 +90612,7 @@ var ts; // Create the reference map, and set the file infos for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - var version_1 = sourceFile.version; + var version_1 = ts.Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set"); var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); @@ -89083,9 +90667,9 @@ var ts; */ function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { // Since the operation could be cancelled, the signatures are always stored in the cache - // They will be commited once it is safe to use them + // They will be committed once it is safe to use them // eg when calling this api from tsserver, if there is no cancellation of the operation - // In the other cases the affected files signatures are commited only after the iteration through the result is complete + // In the other cases the affected files signatures are committed only after the iteration through the result is complete var signatureCache = cacheToUpdateSignature || ts.createMap(); var sourceFile = programOfThisState.getSourceFileByPath(path); if (!sourceFile) { @@ -89375,11 +90959,14 @@ var ts; var affectedSignatures = oldState.currentAffectedFilesSignatures; ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); } + var changedFilesSet = oldState.changedFilesSet; if (canCopySemanticDiagnostics) { - ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); + ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); } // Copy old state's changed files set - ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + if (changedFilesSet) { + ts.copyEntries(changedFilesSet, state.changedFilesSet); + } if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) { state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit; state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex; @@ -89417,7 +91004,7 @@ var ts; // Unchanged file copy diagnostics var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { - state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics); if (!state.semanticDiagnosticsFromOldState) { state.semanticDiagnosticsFromOldState = ts.createMap(); } @@ -89425,8 +91012,45 @@ var ts; } } }); + if (oldCompilerOptions && + (oldCompilerOptions.outDir !== compilerOptions.outDir || + oldCompilerOptions.declarationDir !== compilerOptions.declarationDir || + (oldCompilerOptions.outFile || oldCompilerOptions.out) !== (compilerOptions.outFile || compilerOptions.out))) { + // Add all files to affectedFilesPendingEmit since emit changed + state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, newProgram.getSourceFiles().map(function (f) { return f.path; })); + if (state.affectedFilesPendingEmitIndex === undefined) { + state.affectedFilesPendingEmitIndex = 0; + } + ts.Debug.assert(state.seenAffectedFiles === undefined); + state.seenAffectedFiles = ts.createMap(); + } return state; } + function convertToDiagnostics(diagnostics, newProgram) { + if (!diagnostics.length) + return ts.emptyArray; + return diagnostics.map(function (diagnostic) { + var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram); + result.reportsUnnecessary = diagnostic.reportsUnnecessary; + result.source = diagnostic.source; + var relatedInformation = diagnostic.relatedInformation; + result.relatedInformation = relatedInformation ? + relatedInformation.length ? + relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram); }) : + ts.emptyArray : + undefined; + return result; + }); + } + function convertToDiagnosticRelatedInformation(diagnostic, newProgram) { + var file = diagnostic.file, messageText = diagnostic.messageText; + return __assign({}, diagnostic, { file: file && newProgram.getSourceFileByPath(file), messageText: messageText === undefined || ts.isString(messageText) ? + messageText : + convertToDiagnosticMessageChain(messageText, newProgram) }); + } + function convertToDiagnosticMessageChain(diagnostic, newProgram) { + return __assign({}, diagnostic, { next: diagnostic.next && convertToDiagnosticMessageChain(diagnostic.next, newProgram) }); + } /** * Releases program and other related not needed properties */ @@ -89646,8 +91270,11 @@ var ts; * This is called after completing operation on the next affected file. * The operations here are postponed to ensure that cancellation during the iteration is handled correctly */ - function doneWithAffectedFile(state, affected, isPendingEmit) { - if (affected === state.program) { + function doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit) { + if (isBuildInfoEmit) { + state.emittedBuildInfo = true; + } + else if (affected === state.program) { state.changedFilesSet.clear(); state.programEmitComplete = true; } @@ -89664,8 +91291,8 @@ var ts; /** * Returns the result with affected file */ - function toAffectedFileResult(state, result, affected, isPendingEmit) { - doneWithAffectedFile(state, affected, isPendingEmit); + function toAffectedFileResult(state, result, affected, isPendingEmit, isBuildInfoEmit) { + doneWithAffectedFile(state, affected, isPendingEmit, isBuildInfoEmit); return { result: result, affected: affected }; } /** @@ -89688,6 +91315,77 @@ var ts; } return diagnostics; } + /** + * Gets the program information to be emitted in buildInfo so that we can use it to create new program + */ + function getProgramBuildInfo(state) { + if (state.compilerOptions.outFile || state.compilerOptions.out) + return undefined; + var fileInfos = {}; + state.fileInfos.forEach(function (value, key) { + var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); + fileInfos[key] = signature === undefined ? value : { version: value.version, signature: signature }; + }); + var result = { fileInfos: fileInfos, options: state.compilerOptions }; + if (state.referencedMap) { + var referencedMap_1 = {}; + state.referencedMap.forEach(function (value, key) { + referencedMap_1[key] = ts.arrayFrom(value.keys()); + }); + result.referencedMap = referencedMap_1; + } + if (state.exportedModulesMap) { + var exportedModulesMap_1 = {}; + state.exportedModulesMap.forEach(function (value, key) { + var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key); + // Not in temporary cache, use existing value + if (newValue === undefined) + exportedModulesMap_1[key] = ts.arrayFrom(value.keys()); + // Value in cache and has updated value map, use that + else if (newValue) + exportedModulesMap_1[key] = ts.arrayFrom(newValue.keys()); + }); + result.exportedModulesMap = exportedModulesMap_1; + } + if (state.semanticDiagnosticsPerFile) { + var semanticDiagnosticsPerFile_1 = []; + // Currently not recording actual errors since those mean no emit for tsc --build + state.semanticDiagnosticsPerFile.forEach(function (value, key) { return semanticDiagnosticsPerFile_1.push(value.length ? + [ + key, + state.hasReusableDiagnostic ? + value : + convertToReusableDiagnostics(value) + ] : + key); }); + result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile_1; + } + return result; + } + function convertToReusableDiagnostics(diagnostics) { + ts.Debug.assert(!!diagnostics.length); + return diagnostics.map(function (diagnostic) { + var result = convertToReusableDiagnosticRelatedInformation(diagnostic); + result.reportsUnnecessary = diagnostic.reportsUnnecessary; + result.source = diagnostic.source; + var relatedInformation = diagnostic.relatedInformation; + result.relatedInformation = relatedInformation ? + relatedInformation.length ? + relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r); }) : + ts.emptyArray : + undefined; + return result; + }); + } + function convertToReusableDiagnosticRelatedInformation(diagnostic) { + var file = diagnostic.file, messageText = diagnostic.messageText; + return __assign({}, diagnostic, { file: file && file.path, messageText: messageText === undefined || ts.isString(messageText) ? + messageText : + convertToReusableDiagnosticMessageChain(messageText) }); + } + function convertToReusableDiagnosticMessageChain(diagnostic) { + return __assign({}, diagnostic, { next: diagnostic.next && convertToReusableDiagnosticMessageChain(diagnostic.next) }); + } var BuilderProgramKind; (function (BuilderProgramKind) { BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; @@ -89744,6 +91442,7 @@ var ts; var computeHash = host.createHash || ts.generateDjb2Hash; var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); var backupState; + newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state); }; // To ensure that we arent storing any references to old program or new program without state newProgram = undefined; // TODO: GH#18217 oldProgram = undefined; @@ -89787,7 +91486,16 @@ var ts; if (!state.compilerOptions.out && !state.compilerOptions.outFile) { affected = getNextAffectedFilePendingEmit(state); if (!affected) { - return undefined; + if (state.emittedBuildInfo) { + return undefined; + } + var affected_1 = ts.Debug.assertDefined(state.program); + return toAffectedFileResult(state, + // When whole program is affected, do emit only once (eg when --out or --outFile is specified) + // Otherwise just affected file + affected_1.emitBuildInfo(writeFile || host.writeFile, cancellationToken), affected_1, + /*isPendingEmitFile*/ false, + /*isBuildInfoEmit*/ true); } isPendingEmitFile = true; } @@ -89913,13 +91621,60 @@ var ts; } var diagnostics; for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) { - var sourceFile_2 = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); + var sourceFile_1 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken)); } return diagnostics || ts.emptyArray; } } ts.createBuilderProgram = createBuilderProgram; + function getMapOfReferencedSet(mapLike) { + if (!mapLike) + return undefined; + var map = ts.createMap(); + // Copies keys/values from template. Note that for..in will not throw if + // template is undefined, and instead will just exit the loop. + for (var key in mapLike) { + if (ts.hasProperty(mapLike, key)) { + map.set(key, ts.arrayToSet(mapLike[key])); + } + } + return map; + } + function createBuildProgramUsingProgramBuildInfo(program) { + var fileInfos = ts.createMapFromTemplate(program.fileInfos); + var state = { + fileInfos: fileInfos, + compilerOptions: program.options, + referencedMap: getMapOfReferencedSet(program.referencedMap), + exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap), + semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return ts.isString(value) ? value : value[0]; }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), + hasReusableDiagnostic: true + }; + return { + getState: function () { return state; }, + backupState: ts.noop, + restoreState: ts.noop, + getProgram: ts.notImplemented, + getProgramOrUndefined: ts.returnUndefined, + releaseProgram: ts.noop, + getCompilerOptions: function () { return state.compilerOptions; }, + getSourceFile: ts.notImplemented, + getSourceFiles: ts.notImplemented, + getOptionsDiagnostics: ts.notImplemented, + getGlobalDiagnostics: ts.notImplemented, + getConfigFileParsingDiagnostics: ts.notImplemented, + getSyntacticDiagnostics: ts.notImplemented, + getDeclarationDiagnostics: ts.notImplemented, + getSemanticDiagnostics: ts.notImplemented, + emit: ts.notImplemented, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: ts.notImplemented, + emitNextAffectedFile: ts.notImplemented, + getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented, + }; + } + ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { return { getState: ts.notImplemented, @@ -89939,7 +91694,7 @@ var ts; getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); }, emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); }, getAllDependencies: ts.notImplemented, - getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); } + getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); }, }; function getProgram() { return ts.Debug.assertDefined(state.program); @@ -89965,10 +91720,10 @@ var ts; /*@internal*/ var ts; (function (ts) { - function isPathInNodeModulesStartingWithDot(path) { - return ts.stringContains(path, "/node_modules/."); + function isPathIgnored(path) { + return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); }); } - ts.isPathInNodeModulesStartingWithDot = isPathInNodeModulesStartingWithDot; + ts.isPathIgnored = isPathIgnored; ts.maxNumberOfFilesToIterateForInvalidation = 256; function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; @@ -90490,7 +92245,7 @@ var ts; } else { // If something to do with folder/file starting with "." in node_modules folder, skip it - if (isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + if (isPathIgnored(fileOrDirectoryPath)) return false; // Some file or directory in the watching directory is created // Return early if it does not have any of the watching extension or not the custom failed lookup path @@ -90967,6 +92722,8 @@ var ts; case ".jsx" /* Jsx */: case ".json" /* Json */: return ext; + case ".tsbuildinfo" /* TsBuildInfo */: + return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName); default: return ts.Debug.assertNever(ext); } @@ -91087,22 +92844,18 @@ var ts; var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; ts.addRange(diagnostics, program.getSyntacticDiagnostics()); - var reportSemanticDiagnostics = false; // If we didn't have any syntactic errors, then also try getting the global and // semantic errors. if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics()); ts.addRange(diagnostics, program.getGlobalDiagnostics()); if (diagnostics.length === configFileParsingDiagnosticsLength) { - reportSemanticDiagnostics = true; + ts.addRange(diagnostics, program.getSemanticDiagnostics()); } } // Emit and report any errors we ran into. var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); - if (reportSemanticDiagnostics) { - ts.addRange(diagnostics, program.getSemanticDiagnostics()); - } ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); if (writeFileName) { var currentDir_1 = program.getCurrentDirectory(); @@ -91223,6 +92976,22 @@ var ts; } } ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost; + function setGetSourceFileAsHashVersioned(compilerHost, host) { + var originalGetSourceFile = compilerHost.getSourceFile; + var computeHash = host.createHash || ts.generateDjb2Hash; + compilerHost.getSourceFile = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); + if (result) { + result.version = computeHash.call(host, result.text); + } + return result; + }; + } + ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -91248,7 +93017,7 @@ var ts; writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, createHash: ts.maybeBind(system, system.createHash), - createProgram: createProgram + createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram }; } ts.createProgramHost = createProgramHost; @@ -91258,7 +93027,7 @@ var ts; function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { if (system === void 0) { system = ts.sys; } var writeFileName = function (s) { return system.write(s + system.newLine); }; - var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram); + var result = createProgramHost(system, createProgram); ts.copyProperties(result, createWatchHost(system, reportWatchStatus)); result.afterProgramCreate = function (builderProgram) { var compilerOptions = builderProgram.getCompilerOptions(); @@ -91297,6 +93066,49 @@ var ts; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; + function readBuilderProgram(compilerOptions, readFile) { + if (compilerOptions.out || compilerOptions.outFile) + return undefined; + var buildInfoPath = ts.getOutputPathForBuildInfo(compilerOptions); + if (!buildInfoPath) + return undefined; + var content = readFile(buildInfoPath); + if (!content) + return undefined; + var buildInfo = ts.getBuildInfo(content); + if (buildInfo.version !== ts.version) + return undefined; + if (!buildInfo.program) + return undefined; + return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); + } + ts.readBuilderProgram = readBuilderProgram; + function createIncrementalCompilerHost(options, system) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system); + host.createHash = ts.maybeBind(system, system.createHash); + setGetSourceFileAsHashVersioned(host, system); + ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); }); + return host; + } + ts.createIncrementalCompilerHost = createIncrementalCompilerHost; + function createIncrementalProgram(_a) { + var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram; + host = host || createIncrementalCompilerHost(options); + createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram; + var oldProgram = readBuilderProgram(options, function (path) { return host.readFile(path); }); + return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); + } + function performIncrementalCompilation(input) { + var system = input.system || ts.sys; + var host = input.host || (input.host = createIncrementalCompilerHost(input.options, system)); + var builderProgram = createIncrementalProgram(input); + var exitStatus = emitFilesAndReportErrors(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined); + if (input.afterProgramEmitAndDiagnostics) + input.afterProgramEmitAndDiagnostics(builderProgram); + return exitStatus; + } + ts.performIncrementalCompilation = performIncrementalCompilation; })(ts || (ts = {})); (function (ts) { function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { @@ -91308,7 +93120,6 @@ var ts; } } ts.createWatchCompilerHost = createWatchCompilerHost; - var initialVersion = 1; function createWatchProgram(host) { var builderProgram; var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc @@ -91349,10 +93160,12 @@ var ts; var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); + var configFileWatcher; if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */); + configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */); } var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost); + ts.setGetSourceFileAsHashVersioned(compilerHost, host); // Members for CompilerHost var getNewSourceFile = compilerHost.getSourceFile; compilerHost.getSourceFile = function (fileName) { @@ -91393,21 +93206,43 @@ var ts; (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + builderProgram = ts.readBuilderProgram(compilerOptions, function (path) { return compilerHost.readFile(path); }); synchronizeProgram(); // Update the wild card directory watch watchConfigFileWildCardDirectories(); return configFileName ? - { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : - { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close: close } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames, close: close }; + function close() { + resolutionCache.clear(); + ts.clearMap(sourceFilesCache, function (value) { + if (value && value.fileWatcher) { + value.fileWatcher.close(); + value.fileWatcher = undefined; + } + }); + if (configFileWatcher) { + configFileWatcher.close(); + configFileWatcher = undefined; + } + if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + watchedWildcardDirectories = undefined; + } + if (missingFilesMap) { + ts.clearMap(missingFilesMap, ts.closeFileWatcher); + missingFilesMap = undefined; + } + } function getCurrentBuilderProgram() { return builderProgram; } function getCurrentProgram() { - return builderProgram && builderProgram.getProgram(); + return builderProgram && builderProgram.getProgramOrUndefined(); } function synchronizeProgram() { writeLog("Synchronizing program"); - var program = getCurrentProgram(); + var program = getCurrentBuilderProgram(); if (hasChangedCompilerOptions) { newLine = updateNewLine(); if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { @@ -91423,19 +93258,19 @@ var ts; } } else { - createNewProgram(program, hasInvalidatedResolution); + createNewProgram(hasInvalidatedResolution); } if (host.afterProgramCreate) { host.afterProgramCreate(builderProgram); } return builderProgram; } - function createNewProgram(program, hasInvalidatedResolution) { + function createNewProgram(hasInvalidatedResolution) { // Compile the program writeLog("CreatingProgramWith::"); writeLog(" roots: " + JSON.stringify(rootFileNames)); writeLog(" options: " + JSON.stringify(compilerOptions)); - var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; resolutionCache.startCachingPerDirectoryResolution(); @@ -91475,10 +93310,10 @@ var ts; return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function isFileMissingOnHost(hostSourceFile) { - return typeof hostSourceFile === "number"; + return typeof hostSourceFile === "boolean"; } - function isFilePresentOnHost(hostSourceFile) { - return !!hostSourceFile.sourceFile; + function isFilePresenceUnknownOnHost(hostSourceFile) { + return typeof hostSourceFile.version === "boolean"; } function fileExists(fileName) { var path = toPath(fileName); @@ -91496,36 +93331,32 @@ var ts; return undefined; } // Create new source file if requested or the versions dont match - if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) { var sourceFile = getNewSourceFile(fileName, languageVersion, onError); if (hostSourceFile) { - if (shouldCreateNewSourceFile) { - hostSourceFile.version++; - } if (sourceFile) { // Set the source file and create file watcher now that file was present on the disk hostSourceFile.sourceFile = sourceFile; - sourceFile.version = hostSourceFile.version.toString(); + hostSourceFile.version = sourceFile.version; if (!hostSourceFile.fileWatcher) { hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); } } else { // There is no source file on host any more, close the watch, missing file paths will track it - if (isFilePresentOnHost(hostSourceFile)) { + if (hostSourceFile.fileWatcher) { hostSourceFile.fileWatcher.close(); } - sourceFilesCache.set(path, hostSourceFile.version); + sourceFilesCache.set(path, false); } } else { if (sourceFile) { - sourceFile.version = initialVersion.toString(); var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); - sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher }); } else { - sourceFilesCache.set(path, initialVersion); + sourceFilesCache.set(path, false); } } return sourceFile; @@ -91537,16 +93368,16 @@ var ts; if (hostSourceFile !== undefined) { if (isFileMissingOnHost(hostSourceFile)) { // The next version, lets set it as presence unknown file - sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 }); + sourceFilesCache.set(path, { version: false }); } else { - hostSourceFile.version++; + hostSourceFile.version = false; } } } function getSourceVersion(path) { var hostSourceFile = sourceFilesCache.get(path); - return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version; } function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); @@ -91554,7 +93385,7 @@ var ts; // remove the cached entry. // Note we arent deleting entry if file became missing in new program or // there was version update and new source file was created. - if (hostSourceFileInfo) { + if (hostSourceFileInfo !== undefined) { // record the missing file paths so they can be removed later if watchers arent tracking them if (isFileMissingOnHost(hostSourceFileInfo)) { (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); @@ -91643,7 +93474,7 @@ var ts; function onSourceFileChange(fileName, eventKind, path) { updateCachedSystemWithFile(fileName, path, eventKind); // Update the source file cache - if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { + if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) { resolutionCache.invalidateResolutionOfFile(path); } resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); @@ -91687,7 +93518,7 @@ var ts; cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } nextSourceFileVersion(fileOrDirectoryPath); - if (ts.isPathInNodeModulesStartingWithDot(fileOrDirectoryPath)) + if (ts.isPathIgnored(fileOrDirectoryPath)) return; // If the the added or created file or directory is not supported file name, ignore the file // But when watched directory is added/removed, we need to reload the file list @@ -91741,16 +93572,23 @@ var ts; * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. */ UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes"; - UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing"; - UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf"; - UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; - UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; - UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; - UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 8] = "ComputingUpstream"; + /** + * The project appears out of date because its upstream inputs are newer than its outputs, + * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. + * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project. + */ + UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend"; + UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream"; + UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate"; + UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked"; + UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream"; + UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate"; /** * Projects with no outputs (i.e. "solution" files) */ - UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 9] = "ContainerOnly"; + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly"; })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); function createFileMap(toPath) { // tslint:disable-next-line:no-null-keyword @@ -91798,61 +93636,6 @@ var ts; function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) { return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap); } - function getOutputDeclarationFileName(inputFileName, configFile) { - var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); - var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); - return ts.changeExtension(outputPath, ".d.ts" /* Dts */); - } - ts.getOutputDeclarationFileName = getOutputDeclarationFileName; - function getOutputJSFileName(inputFileName, configFile) { - var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); - var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); - var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : - ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; - return ts.changeExtension(outputPath, newExtension); - } - function getOutputFileNames(inputFileName, configFile) { - // outFile is handled elsewhere; .d.ts files don't generate outputs - if (configFile.options.outFile || configFile.options.out || ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */)) { - return ts.emptyArray; - } - var outputs = []; - var js = getOutputJSFileName(inputFileName, configFile); - outputs.push(js); - if (configFile.options.sourceMap) { - outputs.push(js + ".map"); - } - if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { - var dts = getOutputDeclarationFileName(inputFileName, configFile); - outputs.push(dts); - if (configFile.options.declarationMap) { - outputs.push(dts + ".map"); - } - } - return outputs; - } - function getOutFileOutputs(project) { - var out = project.options.outFile || project.options.out; - if (!out) { - return ts.Debug.fail("outFile must be set"); - } - var outputs = []; - outputs.push(out); - if (project.options.sourceMap) { - outputs.push(out + ".map"); - } - if (ts.getEmitDeclarations(project.options)) { - var dts = ts.changeExtension(out, ".d.ts" /* Dts */); - outputs.push(dts); - if (project.options.declarationMap) { - outputs.push(dts + ".map"); - } - } - return outputs; - } - function rootDirOfOptions(opts, configFileName) { - return opts.rootDir || ts.getDirectoryPath(configFileName); - } function newer(date1, date2) { return date2 > date1 ? date2 : date1; } @@ -91872,7 +93655,7 @@ var ts; ts.createBuilderStatusReporter = createBuilderStatusReporter; function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) { var host = ts.createProgramHost(system, createProgram); - host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; + host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined; host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system); @@ -91881,14 +93664,14 @@ var ts; } function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { if (system === void 0) { system = ts.sys; } - var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus); + var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus); host.reportErrorSummary = reportErrorSummary; return host; } ts.createSolutionBuilderHost = createSolutionBuilderHost; function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { if (system === void 0) { system = ts.sys; } - var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus); + var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus); var watchHost = ts.createWatchHost(system, reportWatchStatus); ts.copyProperties(host, watchHost); return host; @@ -91920,9 +93703,8 @@ var ts; var readFileWithCache = function (f) { return host.readFile(f); }; var projectCompilerOptions = baseCompilerOptions; var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; }); - var originalGetSourceFile = compilerHost.getSourceFile; - var computeHash = host.createHash || ts.generateDjb2Hash; - updateGetSourceFile(); + ts.setGetSourceFileAsHashVersioned(compilerHost, host); + var buildInfoChecked = createFileMap(toPath); // Watch state var builderPrograms = createFileMap(toPath); var diagnostics = createFileMap(toPath); @@ -91960,6 +93742,7 @@ var ts; projectStatus.clear(); missingRoots.clear(); globalDependencyGraph = undefined; + buildInfoChecked.clear(); diagnostics.clear(); projectPendingBuild.clear(); projectErrorsReported.clear(); @@ -91974,29 +93757,6 @@ var ts; ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); builderPrograms.clear(); - updateGetSourceFile(); - } - function updateGetSourceFile() { - if (options.watch) { - if (compilerHost.getSourceFile === originalGetSourceFile) { - compilerHost.getSourceFile = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); - if (result && options.watch) { - result.version = computeHash.call(host, result.text); - } - return result; - }; - } - } - else { - if (compilerHost.getSourceFile !== originalGetSourceFile) { - compilerHost.getSourceFile = originalGetSourceFile; - } - } } function isParsedCommandLine(entry) { return !!entry.options; @@ -92147,13 +93907,14 @@ var ts; newestInputFileTime = inputTime; } } - // Collect the expected outputs of this project - var outputs = getAllProjectOutputs(project); - if (outputs.length === 0) { + // Container if no files are specified in the project + if (!project.fileNames.length && !ts.canJsonReportNoInutFiles(project.raw)) { return { type: UpToDateStatusType.ContainerOnly }; } + // Collect the expected outputs of this project + var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames()); // Now see if all outputs are newer than the newest input var oldestOutputFileName = "(none)"; var oldestOutputFileTime = maximumDate; @@ -92228,25 +93989,28 @@ var ts; upstreamProjectName: ref.path }; } - // If the upstream project's newest file is older than our oldest output, we - // can't be out of date because of it - if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { - continue; - } - // If the upstream project has only change .d.ts files, and we've built - // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild - if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { - pseudoUpToDate = true; - upstreamChangedProject = ref.path; - continue; + // Check oldest output file name only if there is no missing output file name + if (!missingOutputFileName) { + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; } - // We have an output older than an upstream output - we are out of date - ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); - return { - type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: oldestOutputFileName, - newerProjectName: ref.path - }; } } if (missingOutputFileName !== undefined) { @@ -92262,9 +94026,33 @@ var ts; newerInputFileName: newestInputFileName }; } + else { + // Check tsconfig time + var configStatus = checkConfigFileUpToDateStatus(project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); + if (configStatus) + return configStatus; + // Check extended config time + var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName); }); + if (extendedConfigStatus) + return extendedConfigStatus; + } + if (!buildInfoChecked.hasKey(project.options.configFilePath)) { + buildInfoChecked.setValue(project.options.configFilePath, true); + var buildInfoPath = ts.getOutputPathForBuildInfo(project.options); + if (buildInfoPath) { + var value = readFileWithCache(buildInfoPath); + var buildInfo = value && ts.getBuildInfo(value); + if (buildInfo && buildInfo.version !== ts.version) { + return { + type: UpToDateStatusType.TsVersionOutputOfDate, + version: buildInfo.version + }; + } + } + } if (usesPrepend && pseudoUpToDate) { return { - type: UpToDateStatusType.OutOfDateWithUpstream, + type: UpToDateStatusType.OutOfDateWithPrepend, outOfDateOutputFileName: oldestOutputFileName, newerProjectName: upstreamChangedProject }; @@ -92280,6 +94068,17 @@ var ts; oldestOutputFileName: oldestOutputFileName }; } + function checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName) { + // Check tsconfig time + var tsconfigTime = host.getModifiedTime(configFile) || ts.missingFileModifiedTime; + if (oldestOutputFileTime < tsconfigTime) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: configFile + }; + } + } function invalidateProject(configFileName, reloadLevel) { invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); } @@ -92398,7 +94197,9 @@ var ts; updateOutputTimestamps(proj); return; } - var buildResult = buildSingleProject(resolved); + var buildResult = needsBuild(status, resolved) ? + buildSingleProject(resolved) : // Actual build + updateBundle(resolved); // Fake that files have been built by manipulating prepend and existing output if (buildResult & BuildResultFlags.AnyErrors) return; var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue; @@ -92414,17 +94215,26 @@ var ts; // If declaration output is changed, build the project // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps var status_1 = projectStatus.getValue(project); - if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) { - if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) { + if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) { + if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes || status_1.type === UpToDateStatusType.OutOfDateWithPrepend)) { projectStatus.setValue(project, { type: UpToDateStatusType.OutOfDateWithUpstream, - outOfDateOutputFileName: status_1.oldestOutputFileName, + outOfDateOutputFileName: status_1.type === UpToDateStatusType.OutOfDateWithPrepend ? status_1.outOfDateOutputFileName : status_1.oldestOutputFileName, newerProjectName: resolved }); } } else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) { - status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes; + if (prepend) { + projectStatus.setValue(project, { + type: UpToDateStatusType.OutOfDateWithPrepend, + outOfDateOutputFileName: status_1.oldestOutputFileName, + newerProjectName: resolved + }); + } + else { + status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes; + } } addProjToQueue(project); } @@ -92481,8 +94291,7 @@ var ts; } if (options.verbose) reportStatus(ts.Diagnostics.Building_project_0, proj); - var resultFlags = BuildResultFlags.None; - resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; + var resultFlags = BuildResultFlags.DeclarationOutputUnchanged; var configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file @@ -92498,8 +94307,7 @@ var ts; } // TODO: handle resolve module name to cache result in project reference redirect projectCompilerOptions = configFile.options; - var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences); - projectCompilerOptions = baseCompilerOptions; + var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, getOldProgram(proj, configFile), configFile.errors, configFile.projectReferences); // Don't emit anything in the presence of syntactic errors or options diagnostics var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { @@ -92555,17 +94363,19 @@ var ts; var status = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime, - oldestOutputFileName: outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(configFile) + oldestOutputFileName: outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(configFile, !host.useCaseSensitiveFileNames()) }; diagnostics.removeKey(proj); projectStatus.setValue(proj, status); afterProgramCreate(proj, program); + projectCompilerOptions = baseCompilerOptions; return resultFlags; function buildErrors(diagnostics, errorFlags, errorType) { resultFlags |= errorFlags; reportAndStoreErrors(proj, diagnostics); projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); afterProgramCreate(proj, program); + projectCompilerOptions = baseCompilerOptions; return resultFlags; } } @@ -92578,15 +94388,71 @@ var ts; builderPrograms.setValue(proj, program); } } + function getOldProgram(proj, parsed) { + if (options.force) + return undefined; + var value = builderPrograms.getValue(proj); + if (value) + return value; + return ts.readBuilderProgram(parsed.options, readFileWithCache); + } + function updateBundle(proj) { + if (options.dry) { + reportStatus(ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, proj); + return BuildResultFlags.Success; + } + if (options.verbose) + reportStatus(ts.Diagnostics.Updating_output_of_project_0, proj); + // Update js, and source map + var config = ts.Debug.assertDefined(parseConfigFile(proj)); + projectCompilerOptions = config.options; + var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) { return parseConfigFile(resolveProjectName(ref.path)); }); + if (ts.isString(outputFiles)) { + reportStatus(ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, proj, relName(outputFiles)); + return buildSingleProject(proj); + } + // Actual Emit + ts.Debug.assert(!!outputFiles.length); + var emitterDiagnostics = ts.createDiagnosticCollection(); + var emittedOutputs = createFileMap(toPath); + outputFiles.forEach(function (_a) { + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; + emittedOutputs.setValue(name, true); + ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); + }); + var emitDiagnostics = emitterDiagnostics.getDiagnostics(); + if (emitDiagnostics.length) { + reportAndStoreErrors(proj, emitDiagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Emit errors" }); + projectCompilerOptions = baseCompilerOptions; + return BuildResultFlags.DeclarationOutputUnchanged | BuildResultFlags.EmitErrors; + } + // Update timestamps for dts + var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(config, minimumDate, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); + var status = { + type: UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + oldestOutputFileName: outputFiles[0].name + }; + diagnostics.removeKey(proj); + projectStatus.setValue(proj, status); + projectCompilerOptions = baseCompilerOptions; + return BuildResultFlags.DeclarationOutputUnchanged; + } function updateOutputTimestamps(proj) { if (options.dry) { - return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + return reportStatus(ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath); } var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0); - projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + var status = { + type: UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: priorNewestUpdateTime, + oldestOutputFileName: ts.getFirstProjectOutput(proj, !host.useCaseSensitiveFileNames()) + }; + projectStatus.setValue(proj.options.configFilePath, status); } function updateOutputTimestampsWorker(proj, priorNewestUpdateTime, verboseMessage, skipOutputs) { - var outputs = getAllProjectOutputs(proj); + var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames()); if (!skipOutputs || outputs.length !== skipOutputs.getSize()) { if (options.verbose) { reportStatus(verboseMessage, proj.options.configFilePath); @@ -92620,7 +94486,7 @@ var ts; reportParseConfigFileDiagnostic(proj); continue; } - var outputs = getAllProjectOutputs(parsed); + var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames()); for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { var output = outputs_3[_b]; if (host.fileExists(output)) { @@ -92707,7 +94573,9 @@ var ts; // Do nothing continue; } - var buildResult = buildSingleProject(next); + var buildResult = needsBuild(status, next) ? + buildSingleProject(next) : // Actual build + updateBundle(next); // Fake that files have been built by manipulating prepend and existing output anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } reportErrorSummary(); @@ -92720,6 +94588,15 @@ var ts; readFileWithCache = savedReadFileWithCache; return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } + function needsBuild(status, configFile) { + if (status.type !== UpToDateStatusType.OutOfDateWithPrepend || options.force) + return true; + var config = parseConfigFile(configFile); + return !config || + config.fileNames.length === 0 || + !!config.errors.length || + !ts.isIncrementalCompilation(config.options); + } function reportParseConfigFileDiagnostic(proj) { reportAndStoreErrors(proj, [configFileCache.getValue(proj)]); } @@ -92759,33 +94636,6 @@ var ts; return ts.combinePaths(project, "tsconfig.json"); } ts.resolveConfigFileProjectName = resolveConfigFileProjectName; - function getAllProjectOutputs(project) { - if (project.options.outFile || project.options.out) { - return getOutFileOutputs(project); - } - else { - var outputs = []; - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - outputs.push.apply(outputs, getOutputFileNames(inputFile, project)); - } - return outputs; - } - } - ts.getAllProjectOutputs = getAllProjectOutputs; - function getFirstProjectOutput(project) { - if (project.options.outFile || project.options.out) { - return ts.first(getOutFileOutputs(project)); - } - for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { - var inputFile = _a[_i]; - var outputs = getOutputFileNames(inputFile, project); - if (outputs.length) { - return ts.first(outputs); - } - } - return ts.Debug.fail("project " + project.options.configFilePath + " expected to have at least one output"); - } function formatUpToDateStatus(configFileName, status, relName, formatMessage) { switch (status.type) { case UpToDateStatusType.OutOfDateWithSelf: @@ -92800,6 +94650,8 @@ var ts; } // Don't report anything for "up to date because it was already built" -- too verbose break; + case UpToDateStatusType.OutOfDateWithPrepend: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relName(configFileName), relName(status.newerProjectName)); case UpToDateStatusType.UpToDateWithUpstreamTypes: return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName)); case UpToDateStatusType.UpstreamOutOfDate: @@ -92808,6 +94660,8 @@ var ts; return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName)); case UpToDateStatusType.Unbuildable: return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); + case UpToDateStatusType.TsVersionOutputOfDate: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, relName(configFileName), status.version, ts.version); case UpToDateStatusType.ContainerOnly: // Don't report status on "solution" projects case UpToDateStatusType.ComputingUpstream: @@ -93206,8 +95060,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_7 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_7.config; + var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_1.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -93579,7 +95433,7 @@ var ts; /* @internal */ var ts; (function (ts) { - ts.scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ true); + ts.scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ true); var SemanticMeaning; (function (SemanticMeaning) { SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; @@ -93614,7 +95468,7 @@ var ts; case 242 /* TypeAliasDeclaration */: case 168 /* TypeLiteral */: return 2 /* Type */; - case 304 /* JSDocTypedefTag */: + case 309 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; case 278 /* EnumMember */: @@ -93639,14 +95493,14 @@ var ts; case 255 /* ExportDeclaration */: return 7 /* All */; // An external module can be a Value - case 279 /* SourceFile */: + case 284 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 7 /* All */; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { - if (node.kind === 279 /* SourceFile */) { + if (node.kind === 284 /* SourceFile */) { return 1 /* Value */; } else if (node.parent.kind === 254 /* ExportAssignment */ || node.parent.kind === 259 /* ExternalModuleReference */) { @@ -93852,7 +95706,7 @@ var ts; return undefined; } switch (node.kind) { - case 279 /* SourceFile */: + case 284 /* SourceFile */: case 156 /* MethodDeclaration */: case 155 /* MethodSignature */: case 239 /* FunctionDeclaration */: @@ -93870,7 +95724,7 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 279 /* SourceFile */: + case 284 /* SourceFile */: return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; case 244 /* ModuleDeclaration */: return "module" /* moduleElement */; @@ -93879,8 +95733,8 @@ var ts; return "class" /* classElement */; case 241 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; case 242 /* TypeAliasDeclaration */: - case 297 /* JSDocCallbackTag */: - case 304 /* JSDocTypedefTag */: + case 302 /* JSDocCallbackTag */: + case 309 /* JSDocTypedefTag */: return "type" /* typeElement */; case 243 /* EnumDeclaration */: return "enum" /* enumElement */; case 237 /* VariableDeclaration */: @@ -94297,8 +96151,8 @@ var ts; isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate_2 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); - return candidate_2 && findRightmostToken(candidate_2, sourceFile); + var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + return candidate_1 && findRightmostToken(candidate_1, sourceFile); } else { // candidate should be in this node @@ -94306,7 +96160,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 279 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 284 /* SourceFile */ || n.kind === 1 /* EndOfFileToken */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. @@ -94393,7 +96247,7 @@ var ts; } ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; function isWhiteSpaceOnlyJsxText(node) { - return ts.isJsxText(node) && node.containsOnlyWhiteSpaces; + return ts.isJsxText(node) && node.containsOnlyTriviaWhiteSpaces; } function isInTemplateString(sourceFile, position) { var token = getTokenAtPosition(sourceFile, position); @@ -95153,6 +97007,17 @@ var ts; return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName)); } ts.getScriptKind = getScriptKind; + function getSymbolTarget(symbol) { + var next = symbol; + while (isTransientSymbol(next) && next.target) { + next = next.target; + } + return next; + } + ts.getSymbolTarget = getSymbolTarget; + function isTransientSymbol(symbol) { + return (symbol.flags & 33554432 /* Transient */) !== 0; + } function getUniqueSymbolId(symbol, checker) { return ts.getSymbolId(ts.skipAlias(symbol, checker)); } @@ -95211,14 +97076,14 @@ var ts; ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); if (visited === node) { // This only happens for leaf nodes - internal nodes always see their children change. - var clone_8 = ts.getSynthesizedClone(node); - if (ts.isStringLiteral(clone_8)) { - clone_8.textSourceNode = node; + var clone_1 = ts.getSynthesizedClone(node); + if (ts.isStringLiteral(clone_1)) { + clone_1.textSourceNode = node; } - else if (ts.isNumericLiteral(clone_8)) { - clone_8.numericLiteralFlags = node.numericLiteralFlags; + else if (ts.isNumericLiteral(clone_1)) { + clone_1.numericLiteralFlags = node.numericLiteralFlags; } - return ts.setTextRange(clone_8, node); + return ts.setTextRange(clone_1, node); } // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update // the new node created by visitEachChild with the extra changes getSynthesizedClone @@ -95304,8 +97169,27 @@ var ts; return lastPos; } ts.getRenameLocation = getRenameLocation; - function copyComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) { - ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { + function copyLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) { + ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment)); + } + ts.copyLeadingComments = copyLeadingComments; + function copyTrailingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) { + ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticTrailingComment)); + } + ts.copyTrailingComments = copyTrailingComments; + /** + * This function copies the trailing comments for the token that comes before `sourceNode`, as leading comments of `targetNode`. + * This is useful because sometimes a comment that refers to `sourceNode` will be a leading comment for `sourceNode`, according to the + * notion of trivia ownership, and instead will be a trailing comment for the token before `sourceNode`, e.g.: + * `function foo(\* not leading comment for a *\ a: string) {}` + * The comment refers to `a` but belongs to the `(` token, but we might want to copy it. + */ + function copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) { + ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment)); + } + ts.copyTrailingAsLeadingComments = copyTrailingAsLeadingComments; + function getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, cb) { + return function (pos, end, kind, htnl) { if (kind === 3 /* MultiLineCommentTrivia */) { // Remove leading /* pos += 2; @@ -95316,10 +97200,9 @@ var ts; // Remove leading // pos += 2; } - ts.addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl); - }); + cb(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl); + }; } - ts.copyComments = copyComments; function indexInTextChange(change, name) { if (ts.startsWith(change, name)) return 0; @@ -95400,11 +97283,35 @@ var ts; return checker.getTypeAtLocation(caseClause.parent.parent.expression); } ts.getSwitchedType = getSwitchedType; + function getTypeNodeIfAccessible(type, enclosingScope, program, host) { + var checker = program.getTypeChecker(); + var typeIsAccessible = true; + var notAccessible = function () { typeIsAccessible = false; }; + var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { + trackSymbol: function (symbol, declaration, meaning) { + // TODO: GH#18217 + typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; + }, + reportInaccessibleThisError: notAccessible, + reportPrivateInBaseOfClassExpression: notAccessible, + reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } + }); + return typeIsAccessible ? res : undefined; + } + ts.getTypeNodeIfAccessible = getTypeNodeIfAccessible; })(ts || (ts = {})); var ts; (function (ts) { function createClassifier() { - var scanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false); + var scanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false); function getClassificationsForLine(text, lexState, syntacticClassifierAbsent) { return convertClassificationsToResult(getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent), text); } @@ -95643,7 +97550,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_1 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -95652,8 +97559,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_1, classification: convertClassification(type) }); + lastEnd = start + length_1; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -95958,8 +97865,8 @@ var ts; var spanStart = span.start; var spanLength = span.length; // Make a scanner we can get trivia from. - var triviaScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); - var mergeConflictScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var triviaScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); + var mergeConflictScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, sourceFile.languageVariant, sourceFile.text); var result = []; processElement(sourceFile); return { spans: result, endOfLineState: 0 /* None */ }; @@ -96051,18 +97958,18 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 299 /* JSDocParameterTag */: + case 304 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 303 /* JSDocTemplateTag */: + case 308 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); pos = tag.end; break; - case 302 /* JSDocTypeTag */: + case 307 /* JSDocTypeTag */: processElement(tag.typeExpression); pos = tag.end; break; - case 300 /* JSDocReturnTag */: + case 305 /* JSDocReturnTag */: processElement(tag.typeExpression); pos = tag.end; break; @@ -96315,7 +98222,7 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 7 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; } case 2 /* Types */: { @@ -96366,6 +98273,7 @@ var ts; case ".jsx" /* Jsx */: return ".jsx" /* jsxModifier */; case ".ts" /* Ts */: return ".ts" /* tsModifier */; case ".tsx" /* Tsx */: return ".tsx" /* tsxModifier */; + case ".tsbuildinfo" /* TsBuildInfo */: return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported."); case undefined: return "" /* none */; default: return ts.Debug.assertNever(extension); @@ -96596,8 +98504,8 @@ var ts; * both foo.ts and foo.tsx become foo */ var foundFiles = ts.createMap(); // maps file to its extension - for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { - var filePath = files_3[_i]; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var filePath = files_1[_i]; filePath = ts.normalizePath(filePath); if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { continue; @@ -96642,7 +98550,7 @@ var ts; continue; var patterns = paths[path]; if (patterns) { - var _loop_11 = function (name, kind, extension) { + var _loop_1 = function (name, kind, extension) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(function (entry) { return entry.name === name; })) { result.push(nameAndKind(name, kind, extension)); @@ -96650,7 +98558,7 @@ var ts; }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; - _loop_11(name, kind, extension); + _loop_1(name, kind, extension); } } } @@ -96685,7 +98593,7 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_12 = function (moduleName) { + var _loop_2 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); @@ -96693,7 +98601,7 @@ var ts; }; for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { var moduleName = _c[_b]; - _loop_12(moduleName); + _loop_2(moduleName); } } if (!foundGlobal) { @@ -96807,8 +98715,8 @@ var ts; // Check for typings specified in compiler options var seen = ts.createMap(); var typeRoots = tryAndIgnoreErrors(function () { return ts.getEffectiveTypeRoots(options, host); }) || ts.emptyArray; - for (var _i = 0, typeRoots_2 = typeRoots; _i < typeRoots_2.length; _i++) { - var root = typeRoots_2[_i]; + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; getCompletionEntriesFromDirectories(root); } // Also get all @types typings installed in visible node_modules directories @@ -96893,7 +98801,7 @@ var ts; var offset = index !== -1 ? index + 1 : 0; // If the range is an identifier, span is unnecessary. var length = text.length - offset; - return length === 0 || ts.isIdentifierText(text.substr(offset, length), 6 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length); + return length === 0 || ts.isIdentifierText(text.substr(offset, length), 7 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length); } // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..) function isPathRelativeToScript(path) { @@ -96978,6 +98886,7 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["Last"] = 6] = "Last"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -97023,7 +98932,7 @@ var ts; return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { - var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; + var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression; if (location && location.parent && ts.isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. @@ -97054,7 +98963,7 @@ var ts; } if (keywordFilters !== 0 /* None */) { var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); - for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) { var keywordEntry = _a[_i]; if (!entryNames.has(keywordEntry.name)) { entries.push(keywordEntry); @@ -97170,8 +99079,8 @@ var ts; // Based on the order we add things we will always see locals first, then globals, then module exports. // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. var uniques = ts.createMap(); - for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { - var symbol = symbols_3[_i]; + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); if (!entry) { @@ -97390,7 +99299,7 @@ var ts; return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); } function isModuleSymbol(symbol) { - return symbol.declarations.some(function (d) { return d.kind === 279 /* SourceFile */; }); + return symbol.declarations.some(function (d) { return d.kind === 284 /* SourceFile */; }); } function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) { var typeChecker = program.getTypeChecker(); @@ -97441,11 +99350,11 @@ var ts; if (tag.tagName.pos <= position && position <= tag.tagName.end) { return { kind: 1 /* JsDocTagName */ }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 283 /* JSDocTypeExpression */) { + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 288 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 305 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 310 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -97471,9 +99380,9 @@ var ts; // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { - var start_3 = ts.timestamp(); + var start_1 = ts.timestamp(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 - log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_3)); + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1)); } // Find the node where completion is requested on. // Also determine whether we are trying to complete with members of that node @@ -97498,6 +99407,14 @@ var ts; case 189 /* PropertyAccessExpression */: propertyAccessToConvert = parent; node = propertyAccessToConvert.expression; + if (node.end === contextToken.pos && + ts.isCallExpression(node) && + node.getChildCount(sourceFile) && + ts.last(node.getChildren(sourceFile)).kind !== 21 /* CloseParenToken */) { + // This is likely dot from incorrectly parsed call expression and user is starting to write spread + // eg: Math.min(./**/) + return undefined; + } break; case 148 /* QualifiedName */: node = parent.left; @@ -97613,14 +99530,29 @@ var ts; var contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker); var literals = ts.mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (t) { return t.isLiteral() ? t.value : undefined; }); var recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker); - return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; + return { + kind: 0 /* Data */, + symbols: symbols, + completionKind: completionKind, + isInSnippetScope: isInSnippetScope, + propertyAccessToConvert: propertyAccessToConvert, + isNewIdentifierLocation: isNewIdentifierLocation, + location: location, + keywordFilters: keywordFilters, + literals: literals, + symbolToOriginInfoMap: symbolToOriginInfoMap, + recommendedCompletion: recommendedCompletion, + previousToken: previousToken, + isJsxInitializer: isJsxInitializer, + insideJsDocTagTypeExpression: insideJsDocTagTypeExpression + }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 299 /* JSDocParameterTag */: - case 305 /* JSDocPropertyTag */: - case 300 /* JSDocReturnTag */: - case 302 /* JSDocTypeTag */: - case 304 /* JSDocTypedefTag */: + case 304 /* JSDocParameterTag */: + case 310 /* JSDocPropertyTag */: + case 305 /* JSDocReturnTag */: + case 307 /* JSDocTypeTag */: + case 309 /* JSDocTypedefTag */: return true; default: return false; @@ -97660,7 +99592,9 @@ var ts; } } // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). - if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 279 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) { + if (!isTypeLocation && + symbol.declarations && + symbol.declarations.some(function (d) { return d.kind !== 284 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) { addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); } return; @@ -97793,8 +99727,8 @@ var ts; var symbolMeanings = (isTypeOnly ? 0 /* None */ : 67220415 /* Value */) | 67897832 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` - if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 279 /* SourceFile */) { - var thisType = typeChecker.tryGetThisTypeAt(scopeNode); + if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 284 /* SourceFile */) { + var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); if (thisType) { for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { var symbol = _a[_i]; @@ -97826,7 +99760,7 @@ var ts; } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { - case 279 /* SourceFile */: + case 284 /* SourceFile */: case 206 /* TemplateExpression */: case 270 /* JsxExpression */: case 218 /* Block */: @@ -97885,6 +99819,8 @@ var ts; return parentKind === 242 /* TypeAliasDeclaration */; case 119 /* AsKeyword */: return parentKind === 212 /* AsExpression */; + case 86 /* ExtendsKeyword */: + return parentKind === 150 /* TypeParameter */; } } return false; @@ -98581,7 +100517,15 @@ var ts; } return res; }); - function getKeywordCompletions(keywordFilter) { + function getKeywordCompletions(keywordFilter, filterOutTsOnlyKeywords) { + if (!filterOutTsOnlyKeywords) + return getTypescriptKeywordCompletions(keywordFilter); + var index = keywordFilter + 6 /* Last */ + 1; + return _keywordCompletions[index] || + (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter) + .filter(function (entry) { return !isTypeScriptOnlyKeyword(ts.stringToToken(entry.name)); })); + } + function getTypescriptKeywordCompletions(keywordFilter) { return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) { var kind = ts.stringToToken(entry.name); switch (keywordFilter) { @@ -98605,6 +100549,39 @@ var ts; } })); } + function isTypeScriptOnlyKeyword(kind) { + switch (kind) { + case 118 /* AbstractKeyword */: + case 120 /* AnyKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 125 /* DeclareKeyword */: + case 84 /* EnumKeyword */: + case 145 /* GlobalKeyword */: + case 109 /* ImplementsKeyword */: + case 127 /* InferKeyword */: + case 110 /* InterfaceKeyword */: + case 128 /* IsKeyword */: + case 129 /* KeyOfKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 132 /* NeverKeyword */: + case 135 /* NumberKeyword */: + case 136 /* ObjectKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 133 /* ReadonlyKeyword */: + case 138 /* StringKeyword */: + case 139 /* SymbolKeyword */: + case 140 /* TypeKeyword */: + case 142 /* UniqueKeyword */: + case 143 /* UnknownKeyword */: + return true; + default: + return false; + } + } function isInterfaceOrTypeLiteralCompletionKeyword(kind) { return kind === 133 /* ReadonlyKeyword */; } @@ -98658,7 +100635,7 @@ var ts; function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { // class c { method() { } | method2() { } } switch (location.kind) { - case 306 /* SyntaxList */: + case 311 /* SyntaxList */: return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); case 1 /* EndOfFileToken */: var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); @@ -98843,7 +100820,7 @@ var ts; var child = throwStatement; while (child.parent) { var parent = child.parent; - if (ts.isFunctionBlock(parent) || parent.kind === 279 /* SourceFile */) { + if (ts.isFunctionBlock(parent) || parent.kind === 284 /* SourceFile */) { return parent; } // A throw-statement is only owned by a try-statement if the try-statement has @@ -98901,7 +100878,7 @@ var ts; var container = declaration.parent; switch (container.kind) { case 245 /* ModuleBlock */: - case 279 /* SourceFile */: + case 284 /* SourceFile */: case 218 /* Block */: case 271 /* CaseClause */: case 272 /* DefaultClause */: @@ -99399,7 +101376,7 @@ var ts; } else if (!isAvailableThroughGlobal) { var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); - ts.Debug.assert(sourceFileLike.kind === 279 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */); + ts.Debug.assert(sourceFileLike.kind === 284 /* SourceFile */ || sourceFileLike.kind === 244 /* ModuleDeclaration */); if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { addIndirectUsers(sourceFileLike); } @@ -99508,7 +101485,7 @@ var ts; } } /** - * `import x = require("./x") or `import * as x from "./x"`. + * `import x = require("./x")` or `import * as x from "./x"`. * An `export =` may be imported by this syntax, so it may be a direct import. * If it's not a direct import, it will be in `indirectUsers`, so we don't have to do anything here. */ @@ -99565,10 +101542,10 @@ var ts; function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var referencingFile = sourceFiles_3[_i]; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var referencingFile = sourceFiles_1[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; - if (searchSourceFile.kind === 279 /* SourceFile */) { + if (searchSourceFile.kind === 284 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { var ref = _b[_a]; if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { @@ -99596,8 +101573,8 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var sourceFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; if (cancellationToken) cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { @@ -99616,7 +101593,7 @@ var ts; } /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return ts.forEach(sourceFileLike.kind === 279 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return ts.forEach(sourceFileLike.kind === 284 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); }); } @@ -99840,7 +101817,7 @@ var ts; return node.getSourceFile(); } var parent = node.parent; - if (parent.kind === 279 /* SourceFile */) { + if (parent.kind === 284 /* SourceFile */) { return parent; } ts.Debug.assert(parent.kind === 245 /* ModuleBlock */); @@ -99902,16 +101879,16 @@ var ts; } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { - if (node.kind === 279 /* SourceFile */) { + if (node.kind === 284 /* SourceFile */) { return undefined; } var checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { - var result_8 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_8.push(nodeEntry(node)); }); - return result_8; + var result_1 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_1.push(nodeEntry(node)); }); + return result_1; } else if (node.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -99943,27 +101920,27 @@ var ts; case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 }; + var name_1 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_1, kind: kind_1, displayParts: displayParts_1 }; } case 1 /* Label */: { - var node_3 = def.node; - return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; + var node_1 = def.node; + return { node: node_1, name: node_1.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_1.text, ts.SymbolDisplayPartKind.text)] }; } case 2 /* Keyword */: { - var node_4 = def.node; - var name_5 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] }; + var node_2 = def.node; + var name_2 = ts.tokenToString(node_2.kind); + return { node: node_2, name: name_2, kind: "keyword" /* keyword */, displayParts: [{ text: name_2, kind: "keyword" /* keyword */ }] }; } case 3 /* This */: { - var node_5 = def.node; - var symbol = checker.getSymbolAtLocation(node_5); - var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; - return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; + var node_3 = def.node; + var symbol = checker.getSymbolAtLocation(node_3); + var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_3.getSourceFile(), ts.getContainerNode(node_3), node_3).displayParts || [ts.textPart("this")]; + return { node: node_3, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } case 4 /* String */: { - var node_6 = def.node; - return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; + var node_4 = def.node; + return { node: node_4, name: node_4.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_4), ts.SymbolDisplayPartKind.stringLiteral)] }; } default: return ts.Debug.assertNever(def); @@ -100122,8 +102099,8 @@ var ts; case 248 /* ImportEqualsDeclaration */: case 253 /* ImportSpecifier */: case 241 /* InterfaceDeclaration */: - case 297 /* JSDocCallbackTag */: - case 304 /* JSDocTypedefTag */: + case 302 /* JSDocCallbackTag */: + case 309 /* JSDocTypedefTag */: case 267 /* JsxAttribute */: case 244 /* ModuleDeclaration */: case 247 /* NamespaceExportDeclaration */: @@ -100148,8 +102125,8 @@ var ts; return !!decl.initializer || ts.isCatchClause(decl.parent); case 155 /* MethodSignature */: case 153 /* PropertySignature */: - case 305 /* JSDocPropertyTag */: - case 299 /* JSDocParameterTag */: + case 310 /* JSDocPropertyTag */: + case 304 /* JSDocParameterTag */: return false; default: return ts.Debug.failBadSyntaxKind(decl); @@ -100241,7 +102218,7 @@ var ts; result = references; continue; } - var _loop_13 = function (entry) { + var _loop_3 = function (entry) { if (!entry.definition || entry.definition.type !== 0 /* Symbol */) { result.push(entry); return "continue"; @@ -100273,7 +102250,7 @@ var ts; }; for (var _b = 0, references_1 = references; _b < references_1.length; _b++) { var entry = references_1[_b]; - _loop_13(entry); + _loop_3(entry); } } return result; @@ -100309,7 +102286,7 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; switch (decl.kind) { - case 279 /* SourceFile */: + case 284 /* SourceFile */: // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) break; case 244 /* ModuleDeclaration */: @@ -100382,23 +102359,26 @@ var ts; } else { var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); - // Try to get the smallest valid scope that we can limit our search to; - // otherwise we'll need to search globally (i.e. include each file). - var scope = getSymbolScope(symbol); - if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope))); - } - else { - // Global search - for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { - var sourceFile = _a[_i]; - state.cancellationToken.throwIfCancellationRequested(); - searchForName(sourceFile, search, state); - } - } + getReferencesInContainerOrFiles(symbol, state, search); } return result; } + function getReferencesInContainerOrFiles(symbol, state, search) { + // Try to get the smallest valid scope that we can limit our search to; + // otherwise we'll need to search globally (i.e. include each file). + var scope = getSymbolScope(symbol); + if (scope) { + getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(state.sourceFiles, scope))); + } + else { + // Global search + for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + state.cancellationToken.throwIfCancellationRequested(); + searchForName(sourceFile, search, state); + } + } + } function getSpecialSearchKind(node) { switch (node.kind) { case 124 /* ConstructorKeyword */: @@ -100450,9 +102430,7 @@ var ts; * Unlike `Search`, there is only one `State`. */ var State = /** @class */ (function () { - function State(sourceFiles, sourceFilesSet, - /** True if we're searching for constructor references. */ - specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { + function State(sourceFiles, sourceFilesSet, specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { this.sourceFiles = sourceFiles; this.sourceFilesSet = sourceFilesSet; this.specialSearchKind = specialSearchKind; @@ -100533,8 +102511,8 @@ var ts; var sourceId = ts.getNodeId(sourceFile); var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = ts.createMap()); var anyNewSymbols = false; - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var sym = symbols_4[_i]; + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var sym = symbols_2[_i]; anyNewSymbols = ts.addToSeen(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols; } return anyNewSymbols; @@ -100673,14 +102651,14 @@ var ts; return undefined; } var scope; - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; + for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { + var declaration = declarations_1[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out return undefined; } - if (!container || container.kind === 279 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + if (!container || container.kind === 284 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -100725,8 +102703,8 @@ var ts; if (!signature.name || !ts.isIdentifier(signature.name)) return; var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { var name = _b[_a]; if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) @@ -100767,8 +102745,8 @@ var ts; // We found a match. Make sure it's not part of a larger word (i.e. the char // before and after it have to be a non-identifier char). var endPosition = position + symbolNameLength; - if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 6 /* Latest */)) && - (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 6 /* Latest */))) { + if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 7 /* Latest */)) && + (endPosition === sourceLength || !ts.isIdentifierPart(text.charCodeAt(endPosition), 7 /* Latest */))) { // Found a real match. Keep searching. positions.push(position); } @@ -100917,7 +102895,9 @@ var ts; } // For `export { foo as bar }`, rename `foo`, but not `bar`. if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) { - var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; + var isDefaultExport = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ + || exportSpecifier.name.originalKeywordKind === 80 /* DefaultKeyword */; + var exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */; var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); @@ -101004,6 +102984,7 @@ var ts; var classExtending = tryGetClassByExtendingIdentifier(referenceLocation); if (classExtending) { findSuperConstructorAccesses(classExtending, pusher()); + findInheritedConstructorReferences(classExtending, state); } } } @@ -101036,33 +103017,41 @@ var ts; * Reference the constructor and all calls to `new this()`. */ function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { - for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile); - ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword); - addNode(ctrKeyword); - } - classSymbol.exports.forEach(function (member) { - var decl = member.valueDeclaration; - if (decl && decl.kind === 156 /* MethodDeclaration */) { - var body = decl.body; - if (body) { - forEachDescendantOfKind(body, 100 /* ThisKeyword */, function (thisKeyword) { - if (ts.isNewExpressionTarget(thisKeyword)) { - addNode(thisKeyword); - } - }); - } + var constructorSymbol = getClassConstructorSymbol(classSymbol); + if (constructorSymbol) { + for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile); + ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword); + addNode(ctrKeyword); } - }); + } + if (classSymbol.exports) { + classSymbol.exports.forEach(function (member) { + var decl = member.valueDeclaration; + if (decl && decl.kind === 156 /* MethodDeclaration */) { + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 100 /* ThisKeyword */, function (thisKeyword) { + if (ts.isNewExpressionTarget(thisKeyword)) { + addNode(thisKeyword); + } + }); + } + } + }); + } + } + function getClassConstructorSymbol(classSymbol) { + return classSymbol.members && classSymbol.members.get("__constructor" /* Constructor */); } /** Find references to `super` in the constructor of an extending class. */ - function findSuperConstructorAccesses(cls, addNode) { - var ctr = cls.symbol.members.get("__constructor" /* Constructor */); - if (!ctr) { + function findSuperConstructorAccesses(classDeclaration, addNode) { + var constructor = getClassConstructorSymbol(classDeclaration.symbol); + if (!constructor) { return; } - for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { + for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) { var decl = _a[_i]; ts.Debug.assert(decl.kind === 157 /* Constructor */); var body = decl.body; @@ -101075,6 +103064,16 @@ var ts; } } } + function hasOwnConstructor(classDeclaration) { + return !!getClassConstructorSymbol(classDeclaration.symbol); + } + function findInheritedConstructorReferences(classDeclaration, state) { + if (hasOwnConstructor(classDeclaration)) + return; + var classSymbol = classDeclaration.symbol; + var search = state.createSearch(/*location*/ undefined, classSymbol, /*comingFrom*/ undefined); + getReferencesInContainerOrFiles(classSymbol, state, search); + } function addImplementationReferences(refNode, addReference, state) { // Check if we found a function/propertyAssignment/method with an implementation or initializer if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { @@ -101239,7 +103238,7 @@ var ts; staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 279 /* SourceFile */: + case 284 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) { return undefined; } @@ -101252,7 +103251,7 @@ var ts; default: return undefined; } - var references = ts.flatMap(searchSpaceNode.kind === 279 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { + var references = ts.flatMap(searchSpaceNode.kind === 284 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { cancellationToken.throwIfCancellationRequested(); return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) { if (!ts.isThis(node)) { @@ -101271,8 +103270,8 @@ var ts; // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag; - case 279 /* SourceFile */: - return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node); + case 284 /* SourceFile */: + return container.kind === 284 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node); } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); @@ -101428,8 +103427,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { - var declaration = declarations_12[_i]; + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -101578,8 +103577,8 @@ var ts; // Type annotation needed due to #7294 var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer]; var foundExactMatch = false; - for (var _i = 0, elements_5 = elements; _i < elements_5.length; _i++) { - var element = elements_5[_i]; + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var element = elements_1[_i]; foundExactMatch = tryUpdateString(element) || foundExactMatch; } return foundExactMatch; @@ -101601,7 +103600,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_14 = function (sourceFile) { + var _loop_4 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -101633,7 +103632,7 @@ var ts; }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_14(sourceFile); + _loop_4(sourceFile); } } function combineNormal(pathA, pathB) { @@ -101663,9 +103662,9 @@ var ts; return undefined; // First try resolved module if (resolved.resolvedModule) { - var result_9 = tryChange(resolved.resolvedModule.resolvedFileName); - if (result_9) - return result_9; + var result_2 = tryChange(resolved.resolvedModule.resolvedFileName); + if (result_2) + return result_2; } // Then failed lookups except package.json since we dont want to touch them (only included ts/js files) var result = ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson); @@ -101775,10 +103774,10 @@ var ts; // bar(({pr/*goto*/op1})=>{}); if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && (node === (parent.propertyName || parent.name))) { - var name_6 = ts.getNameFromPropertyName(node); + var name_3 = ts.getNameFromPropertyName(node); var type = typeChecker.getTypeAtLocation(parent.parent); - return name_6 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) { - var prop = t.getProperty(name_6); + return name_3 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) { + var prop = t.getProperty(name_3); return prop && getDefinitionFromSymbol(typeChecker, prop, node); }); } @@ -102126,11 +104125,11 @@ var ts; JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 299 /* JSDocParameterTag */: - case 305 /* JSDocPropertyTag */: + case 304 /* JSDocParameterTag */: + case 310 /* JSDocPropertyTag */: return [declaration]; - case 297 /* JSDocCallbackTag */: - case 304 /* JSDocTypedefTag */: + case 302 /* JSDocCallbackTag */: + case 309 /* JSDocTypedefTag */: return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); @@ -102151,16 +104150,16 @@ var ts; function getCommentText(tag) { var comment = tag.comment; switch (tag.kind) { - case 295 /* JSDocAugmentsTag */: + case 300 /* JSDocAugmentsTag */: return withNode(tag.class); - case 303 /* JSDocTemplateTag */: + case 308 /* JSDocTemplateTag */: return withList(tag.typeParameters); - case 302 /* JSDocTypeTag */: + case 307 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 304 /* JSDocTypedefTag */: - case 297 /* JSDocCallbackTag */: - case 305 /* JSDocPropertyTag */: - case 299 /* JSDocParameterTag */: + case 309 /* JSDocTypedefTag */: + case 302 /* JSDocCallbackTag */: + case 310 /* JSDocPropertyTag */: + case 304 /* JSDocParameterTag */: var name = tag.name; return name ? withNode(name) : comment; default: @@ -102371,7 +104370,7 @@ var ts; : undefined; return { commentOwner: commentOwner, parameters: parameters_1 }; } - case 279 /* SourceFile */: + case 284 /* SourceFile */: return "quit"; case 244 /* ModuleDeclaration */: // If in walking up the tree, we hit a a nested namespace declaration, @@ -102423,7 +104422,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_15 = function (sourceFile) { + var _loop_5 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -102433,9 +104432,9 @@ var ts; }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; - _loop_15(sourceFile); + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var sourceFile = sourceFiles_4[_i]; + _loop_5(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -102448,8 +104447,8 @@ var ts; if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { - var declaration = declarations_13[_i]; + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; if (!shouldKeepItem(declaration, checker)) continue; if (patternMatcher.patternContainsDots) { @@ -102931,7 +104930,7 @@ var ts; } } switch (node.kind) { - case 279 /* SourceFile */: + case 284 /* SourceFile */: var sourceFile = node; return ts.isExternalModule(sourceFile) ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" @@ -102983,10 +104982,10 @@ var ts; case 243 /* EnumDeclaration */: case 241 /* InterfaceDeclaration */: case 244 /* ModuleDeclaration */: - case 279 /* SourceFile */: + case 284 /* SourceFile */: case 242 /* TypeAliasDeclaration */: - case 304 /* JSDocTypedefTag */: - case 297 /* JSDocCallbackTag */: + case 309 /* JSDocTypedefTag */: + case 302 /* JSDocCallbackTag */: return true; case 157 /* Constructor */: case 156 /* MethodDeclaration */: @@ -103007,7 +105006,7 @@ var ts; } switch (navigationBarNodeKind(item.parent)) { case 245 /* ModuleBlock */: - case 279 /* SourceFile */: + case 284 /* SourceFile */: case 156 /* MethodDeclaration */: case 157 /* Constructor */: return true; @@ -103092,7 +105091,7 @@ var ts; return !member.name || member.name.kind === 149 /* ComputedPropertyName */; } function getNodeSpan(node) { - return node.kind === 279 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); + return node.kind === 284 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); } function getModifiers(node) { if (node.parent && node.parent.kind === 237 /* VariableDeclaration */) { @@ -103213,8 +105212,8 @@ var ts; else { // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { - useNonAdjustedStartPosition: true, - useNonAdjustedEndPosition: false, + leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include, suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), }); } @@ -103228,7 +105227,7 @@ var ts; function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); - var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); + var jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { var importDecl = oldImports_1[_i]; @@ -103552,8 +105551,8 @@ var ts; var lastSingleLineCommentEnd = -1; var singleLineCommentCount = 0; var sourceText = sourceFile.getFullText(); - for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { - var _a = comments_2[_i], kind = _a.kind, pos = _a.pos, end = _a.end; + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var _a = comments_1[_i], kind = _a.kind, pos = _a.pos, end = _a.end; cancellationToken.throwIfCancellationRequested(); switch (kind) { case 2 /* SingleLineCommentTrivia */: @@ -103939,7 +105938,7 @@ var ts; if (ch >= 65 /* A */ && ch <= 90 /* Z */) { return true; } - if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) { + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 7 /* Latest */)) { return false; } // TODO: find a way to determine this for any unicode characters in a @@ -103952,7 +105951,7 @@ var ts; if (ch >= 97 /* a */ && ch <= 122 /* z */) { return true; } - if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 6 /* Latest */)) { + if (ch < 127 /* maxAsciiCharacter */ || !ts.isUnicodeIdentifierStart(ch, 7 /* Latest */)) { return false; } // TODO: find a way to determine this for any unicode characters in a @@ -103963,15 +105962,15 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_16 = function (start) { + var _loop_6 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_4 = _loop_16(start); - if (typeof state_4 === "object") - return state_4.value; + var state_1 = _loop_6(start); + if (typeof state_1 === "object") + return state_1.value; } return -1; } @@ -104982,7 +106981,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { - var _loop_17 = function (n) { + var _loop_7 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); @@ -104992,9 +106991,9 @@ var ts; } }; for (var n = node; !ts.isSourceFile(n) && (isManuallyInvoked || !ts.isBlock(n)); n = n.parent) { - var state_5 = _loop_17(n); - if (typeof state_5 === "object") - return state_5.value; + var state_2 = _loop_7(n); + if (typeof state_2 === "object") + return state_2.value; } return undefined; } @@ -105069,13 +107068,13 @@ var ts; var parameters = (typeParameters || ts.emptyArray).map(function (t) { return createSignatureHelpParameterForTypeParameter(t, checker, enclosingDeclaration, sourceFile, printer); }); var parameterParts = ts.mapToDisplayParts(function (writer) { var thisParameter = candidateSignature.thisParameter ? [checker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; - var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); + var params = ts.createNodeArray(thisParameter.concat(checker.getExpandedParameters(candidateSignature).map(function (param) { return checker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); printer.writeList(2576 /* CallExpressionArguments */, params, sourceFile, writer); }); return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(28 /* LessThanToken */)], suffix: [ts.punctuationPart(30 /* GreaterThanToken */)].concat(parameterParts) }; } function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { - var isVariadic = candidateSignature.hasRestParameter; + var isVariadic = checker.hasEffectiveRestParameter(candidateSignature); var printer = ts.createPrinter({ removeComments: true }); var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { @@ -105083,7 +107082,7 @@ var ts; printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer); } }); - var parameters = candidateSignature.parameters.map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); }); + var parameters = checker.getExpandedParameters(candidateSignature).map(function (p) { return createSignatureHelpParameterForParameter(p, checker, enclosingDeclaration, sourceFile, printer); }); return { isVariadic: isVariadic, parameters: parameters, prefix: typeParameterParts.concat([ts.punctuationPart(20 /* OpenParenToken */)]), suffix: [ts.punctuationPart(21 /* CloseParenToken */)] }; } function createSignatureHelpParameterForParameter(parameter, checker, enclosingDeclaration, sourceFile, printer) { @@ -105272,8 +107271,8 @@ var ts; var name = importNameForConvertToDefaultImport(importNode); if (!name) continue; - var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text); - var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName); + var module = ts.getResolvedModule(sourceFile, moduleSpecifier.text); + var resolvedFile = module && program.getSourceFile(module.resolvedFileName); if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) { diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import)); } @@ -105288,8 +107287,8 @@ var ts; case 196 /* FunctionExpression */: var decl = ts.getDeclarationOfExpando(node); if (decl) { - var symbol_2 = decl.symbol; - if (symbol_2 && (symbol_2.exports && symbol_2.exports.size || symbol_2.members && symbol_2.members.size)) { + var symbol_1 = decl.symbol; + if (symbol_1 && (symbol_1.exports && symbol_1.exports.size || symbol_1.members && symbol_1.members.size)) { diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); break; } @@ -105726,7 +107725,7 @@ var ts; displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } - if (symbolFlags & 1536 /* Module */) { + if (symbolFlags & 1536 /* Module */ && !isThisExpression) { prefixNextMeaning(); var declaration = ts.getDeclarationOfKind(symbol, 244 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 72 /* Identifier */; @@ -105910,7 +107909,7 @@ var ts; // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 279 /* SourceFile */; })) { + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 284 /* SourceFile */; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!declaration.parent || declaration.parent.kind !== 204 /* BinaryExpression */) { @@ -106035,7 +108034,7 @@ var ts; // If the parent is not sourceFile or module block it is local variable for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { // Reached source file or module block - if (parent.kind === 279 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) { + if (parent.kind === 284 /* SourceFile */ || parent.kind === 245 /* ModuleBlock */) { return false; } } @@ -106149,7 +108148,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_18 = function (opt) { + var _loop_8 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -106168,7 +108167,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_18(opt); + _loop_8(opt); } return options; } @@ -106264,8 +108263,8 @@ var ts; (function (ts) { var formatting; (function (formatting) { - var standardScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */); - var jsxScanner = ts.createScanner(6 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */); + var standardScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */); + var jsxScanner = ts.createScanner(7 /* Latest */, /*skipTrivia*/ false, 1 /* JSX */); var ScanAction; (function (ScanAction) { ScanAction[ScanAction["Scan"] = 0] = "Scan"; @@ -106859,7 +108858,7 @@ var ts; case 226 /* ForInStatement */: // "in" keyword in [P in keyof T]: T[P] case 150 /* TypeParameter */: - return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */; + return context.currentTokenSpan.kind === 93 /* InKeyword */ || context.nextTokenSpan.kind === 93 /* InKeyword */ || context.currentTokenSpan.kind === 59 /* EqualsToken */ || context.nextTokenSpan.kind === 59 /* EqualsToken */; // Technically, "of" is not a binary operator, but format it the same way as "in" case 227 /* ForOfStatement */: return context.currentTokenSpan.kind === 147 /* OfKeyword */ || context.nextTokenSpan.kind === 147 /* OfKeyword */; @@ -107360,7 +109359,7 @@ var ts; case 244 /* ModuleDeclaration */: var body = parent.body; return !!body && body.kind === 245 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); - case 279 /* SourceFile */: + case 284 /* SourceFile */: case 218 /* Block */: case 245 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); @@ -108479,7 +110478,7 @@ var ts; // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && - (parent.kind === 279 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 284 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -108567,7 +110566,7 @@ var ts; case 209 /* ClassExpression */: case 241 /* InterfaceDeclaration */: case 242 /* TypeAliasDeclaration */: - case 303 /* JSDocTemplateTag */: + case 308 /* JSDocTemplateTag */: return getList(node.typeParameters); case 192 /* NewExpression */: case 191 /* CallExpression */: @@ -108816,11 +110815,23 @@ var ts; ts.Debug.assert(typeof end === "number"); n.__end = end; } - var Position; - (function (Position) { - Position[Position["FullStart"] = 0] = "FullStart"; - Position[Position["Start"] = 1] = "Start"; - })(Position = textChanges_3.Position || (textChanges_3.Position = {})); + var LeadingTriviaOption; + (function (LeadingTriviaOption) { + /** Exclude all leading trivia (use getStart()) */ + LeadingTriviaOption[LeadingTriviaOption["Exclude"] = 0] = "Exclude"; + /** Include leading trivia and, + * if there are no line breaks between the node and the previous token, + * include all trivia between the node and the previous token + */ + LeadingTriviaOption[LeadingTriviaOption["IncludeAll"] = 1] = "IncludeAll"; + })(LeadingTriviaOption = textChanges_3.LeadingTriviaOption || (textChanges_3.LeadingTriviaOption = {})); + var TrailingTriviaOption; + (function (TrailingTriviaOption) { + /** Exclude all trailing trivia (use getEnd()) */ + TrailingTriviaOption[TrailingTriviaOption["Exclude"] = 0] = "Exclude"; + /** Include trailing trivia */ + TrailingTriviaOption[TrailingTriviaOption["Include"] = 1] = "Include"; + })(TrailingTriviaOption = textChanges_3.TrailingTriviaOption || (textChanges_3.TrailingTriviaOption = {})); function skipWhitespacesAndLineBreaks(text, start) { return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } @@ -108836,9 +110847,9 @@ var ts; } return false; } - textChanges_3.useNonAdjustedPositions = { - useNonAdjustedStartPosition: true, - useNonAdjustedEndPosition: true, + var useNonAdjustedPositions = { + leadingTriviaOption: LeadingTriviaOption.Exclude, + trailingTriviaOption: TrailingTriviaOption.Exclude, }; var ChangeKind; (function (ChangeKind) { @@ -108848,10 +110859,11 @@ var ts; ChangeKind[ChangeKind["Text"] = 3] = "Text"; })(ChangeKind || (ChangeKind = {})); function getAdjustedRange(sourceFile, startNode, endNode, options) { - return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) }; + return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) }; } - function getAdjustedStartPosition(sourceFile, node, options, position) { - if (options.useNonAdjustedStartPosition) { + function getAdjustedStartPosition(sourceFile, node, options) { + var leadingTriviaOption = options.leadingTriviaOption; + if (leadingTriviaOption === LeadingTriviaOption.Exclude) { return node.getStart(sourceFile); } var fullStart = node.getFullStart(); @@ -108869,7 +110881,7 @@ var ts; // fullstart // when b is replaced - we usually want to keep the leading trvia // when b is deleted - we delete it - return position === Position.Start ? start : fullStart; + return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start; } // get start position of the line following the line that contains fullstart position // (but only if the fullstart isn't the very beginning of the file) @@ -108881,11 +110893,12 @@ var ts; } function getAdjustedEndPosition(sourceFile, node, options) { var end = node.end; - if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { + var trailingTriviaOption = options.trailingTriviaOption; + if (trailingTriviaOption === TrailingTriviaOption.Exclude || (ts.isExpression(node) && trailingTriviaOption !== TrailingTriviaOption.Include)) { return end; } var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); - return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)) + return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))) ? newEnd : end; } @@ -108930,15 +110943,15 @@ var ts; this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); }; ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) { - if (options === void 0) { options = {}; } - var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); + if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options); var endPosition = getAdjustedEndPosition(sourceFile, endNode, options); this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); }; ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) { - if (options === void 0) { options = {}; } - var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); - var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart); + if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options); + var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options); this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); }; ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { @@ -108946,11 +110959,11 @@ var ts; this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); }; ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { - if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + if (options === void 0) { options = useNonAdjustedPositions; } this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); }; ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { - if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + if (options === void 0) { options = useNonAdjustedPositions; } this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options); }; ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { @@ -108958,14 +110971,14 @@ var ts; this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes }); }; ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { - if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + if (options === void 0) { options = useNonAdjustedPositions; } this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); }; ChangeTracker.prototype.replaceNodeWithText = function (sourceFile, oldNode, text) { - this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, textChanges_3.useNonAdjustedPositions), text); + this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text); }; ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { - if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + if (options === void 0) { options = useNonAdjustedPositions; } this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); }; ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { @@ -108993,7 +111006,7 @@ var ts; }; ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) { if (blankLineBetween === void 0) { blankLineBetween = false; } - this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); + this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); }; ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { var pos = before.getStart(sourceFile); @@ -109100,7 +111113,7 @@ var ts; this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true)); }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { - var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); + var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}); this.insertNodeAt(sourceFile, pos, newNode, { prefix: ts.isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken().pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, suffix: this.newLineCharacter @@ -109340,7 +111353,7 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_19 = function (sourceFile, node) { + var _loop_9 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); @@ -109353,7 +111366,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_19(sourceFile, node); + _loop_9(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -109390,7 +111403,7 @@ var ts; textChanges_3.ChangeTracker = ChangeTracker; // find first non-whitespace position in the leading trivia of the node function startPositionToDeleteNodeInList(sourceFile, node) { - return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } function getClassOrObjectBraceEnds(cls, sourceFile) { return [ts.findChildOfKind(cls, 18 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 19 /* CloseBraceToken */, sourceFile).end]; @@ -109410,14 +111423,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_20 = function (i) { + var _loop_10 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_20(i); + _loop_10(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -109434,7 +111447,7 @@ var ts; function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); - var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true, scriptKind); + var sourceFile = ts.createSourceFile("any file name", nonFormattedText, 7 /* ESNext */, /*setParentNodes*/ true, scriptKind); var changes = ts.formatting.formatDocument(sourceFile, formatContext); return applyChanges(nonFormattedText, changes) + newLineCharacter; } @@ -109727,7 +111740,7 @@ var ts; case 249 /* ImportDeclaration */: deleteNode(changes, sourceFile, node, // For first import, leave header comment in place - node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined); + node === sourceFile.imports[0].parent ? { leadingTriviaOption: LeadingTriviaOption.Exclude } : undefined); break; case 186 /* BindingElement */: var pattern = node.parent; @@ -109765,7 +111778,7 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } else { - deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined); + deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { trailingTriviaOption: TrailingTriviaOption.Exclude } : undefined); } } } @@ -109836,8 +111849,8 @@ var ts; /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */ // Exported for tests only! (TODO: improve tests to not need this) function deleteNode(changes, sourceFile, node, options) { - if (options === void 0) { options = {}; } - var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); + if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } + var startPosition = getAdjustedStartPosition(sourceFile, node, options); var endPosition = getAdjustedEndPosition(sourceFile, node, options); changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); } @@ -110130,18 +112143,18 @@ var ts; } function transformJSDocType(node) { switch (node.kind) { - case 284 /* JSDocAllType */: - case 285 /* JSDocUnknownType */: + case 289 /* JSDocAllType */: + case 290 /* JSDocUnknownType */: return ts.createTypeReferenceNode("any", ts.emptyArray); - case 288 /* JSDocOptionalType */: + case 293 /* JSDocOptionalType */: return transformJSDocOptionalType(node); - case 287 /* JSDocNonNullableType */: + case 292 /* JSDocNonNullableType */: return transformJSDocType(node.type); - case 286 /* JSDocNullableType */: + case 291 /* JSDocNullableType */: return transformJSDocNullableType(node); - case 290 /* JSDocVariadicType */: + case 295 /* JSDocVariadicType */: return transformJSDocVariadicType(node); - case 289 /* JSDocFunctionType */: + case 294 /* JSDocFunctionType */: return transformJSDocFunctionType(node); case 164 /* TypeReference */: return transformJSDocTypeReference(node); @@ -110165,7 +112178,7 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 290 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 + var isRest = node.type.kind === 295 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 var name = node.name || (isRest ? "rest" : "arg" + index); var dotdotdot = isRest ? ts.createToken(25 /* DotDotDotToken */) : node.dotDotDotToken; return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); @@ -110321,7 +112334,7 @@ var ts; } if (ts.isPropertyAccessExpression(parent)) { var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); - var typeNode = getTypeNodeIfAccessible(type, parent, program, host); + var typeNode = ts.getTypeNodeIfAccessible(type, parent, program, host); if (typeNode) { // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags var typeTag = ts.createJSDocTypeTag(ts.createJSDocTypeExpression(typeNode), /*comment*/ ""); @@ -110425,7 +112438,7 @@ var ts; } } function annotate(changes, sourceFile, declaration, type, program, host) { - var typeNode = getTypeNodeIfAccessible(type, declaration, program, host); + var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { if (ts.isInJSFile(sourceFile) && declaration.kind !== 153 /* PropertySignature */) { var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration; @@ -110451,7 +112464,7 @@ var ts; // only infer parameters that have (1) no type and (2) an accessible inferred type if (param.initializer || ts.getJSDocType(param) || !ts.isIdentifier(param.name)) return; - var typeNode = inference.type && getTypeNodeIfAccessible(inference.type, param, program, host); + var typeNode = inference.type && ts.getTypeNodeIfAccessible(inference.type, param, program, host); var name = ts.getSynthesizedClone(param.name); ts.setEmitFlags(name, 1536 /* NoComments */ | 2048 /* NoNestedComments */); return typeNode && ts.createJSDocParamTag(name, !!inference.isOptional, ts.createJSDocTypeExpression(typeNode), ""); @@ -110468,47 +112481,33 @@ var ts; return !!merged; }); }); var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray((oldTags || ts.emptyArray).concat(unmergedNewTags))); - changes.insertJsdocCommentBefore(sourceFile, parent, tag); + var jsDocNode = parent.kind === 197 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent; + jsDocNode.jsDoc = parent.jsDoc; + jsDocNode.jsDocCache = parent.jsDocCache; + changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag); + } + function getJsDocNodeForArrowFunction(signature) { + if (signature.parent.kind === 154 /* PropertyDeclaration */) { + return signature.parent; + } + return signature.parent.parent; } function tryMergeJsdocTags(oldTag, newTag) { if (oldTag.kind !== newTag.kind) { return undefined; } switch (oldTag.kind) { - case 299 /* JSDocParameterTag */: { + case 304 /* JSDocParameterTag */: { var oldParam = oldTag; var newParam = newTag; return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText ? ts.createJSDocParamTag(newParam.name, newParam.isBracketed, newParam.typeExpression, oldParam.comment) : undefined; } - case 300 /* JSDocReturnTag */: + case 305 /* JSDocReturnTag */: return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment); } } - function getTypeNodeIfAccessible(type, enclosingScope, program, host) { - var checker = program.getTypeChecker(); - var typeIsAccessible = true; - var notAccessible = function () { typeIsAccessible = false; }; - var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { - trackSymbol: function (symbol, declaration, meaning) { - // TODO: GH#18217 - typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; - }, - reportInaccessibleThisError: notAccessible, - reportPrivateInBaseOfClassExpression: notAccessible, - reportInaccessibleUniqueSymbolError: notAccessible, - moduleResolverHost: { - readFile: host.readFile, - fileExists: host.fileExists, - directoryExists: host.directoryExists, - getSourceFiles: program.getSourceFiles, - getCurrentDirectory: program.getCurrentDirectory, - getCommonSourceDirectory: program.getCommonSourceDirectory, - } - }); - return typeIsAccessible ? res : undefined; - } function getReferences(token, program, cancellationToken) { // Position shouldn't matter since token is not a SourceFile. return ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), function (entry) { @@ -110807,8 +112806,8 @@ var ts; } function removeLowPriorityInferences(inferences, priorities) { var toRemove = []; - for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) { - var i = inferences_2[_i]; + for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { + var i = inferences_1[_i]; for (var _a = 0, priorities_1 = priorities; _a < priorities_1.length; _a++) { var _b = priorities_1[_a], high = _b.high, low = _b.low; if (high(i)) { @@ -110900,8 +112899,8 @@ var ts; types.push.apply(types, (usageContext.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); })); if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217 - var types_19 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); - types_19.push(checker.createPromiseType(types_19.length ? checker.getUnionType(types_19, 2 /* Subtype */) : checker.getAnyType())); + var types_1 = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); + types_1.push(checker.createPromiseType(types_1.length ? checker.getUnionType(types_1, 2 /* Subtype */) : checker.getAnyType())); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("push"))) { types.push(checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker))); @@ -110910,7 +112909,7 @@ var ts; types.push(checker.createArrayType(recur(usageContext.numberIndexContext))); } else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.stringIndexContext) { - var members_6 = ts.createUnderscoreEscapedMap(); + var members_1 = ts.createUnderscoreEscapedMap(); var callSignatures = []; var constructSignatures = []; var stringIndexInfo = void 0; @@ -110918,7 +112917,7 @@ var ts; usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); symbol.type = recur(context); - members_6.set(name, symbol); + members_1.set(name, symbol); }); } if (usageContext.callContexts) { @@ -110936,7 +112935,7 @@ var ts; if (usageContext.stringIndexContext) { stringIndexInfo = checker.createIndexInfo(recur(usageContext.stringIndexContext), /*isReadonly*/ false); } - types.push(checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217 + types.push(checker.createAnonymousType(/*symbol*/ undefined, members_1, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217 } return types; function recur(innerContext) { @@ -111021,7 +113020,7 @@ var ts; precedingNode = ctorDeclaration.parent.parent; newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); if (ctorDeclaration.parent.declarations.length === 1) { - ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217 + ts.copyLeadingComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217 changes.delete(sourceFile, precedingNode); } else { @@ -111032,7 +113031,7 @@ var ts; if (!newClassDeclaration) { return undefined; } - ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile); + ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile); // Because the preceding node could be touched, we need to insert nodes before delete nodes. changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); function createClassElementsFromSymbol(symbol) { @@ -111085,7 +113084,7 @@ var ts; var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 121 /* AsyncKeyword */)); var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); - ts.copyComments(assignmentBinaryExpression, method, sourceFile); + ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); return method; } case 197 /* ArrowFunction */: { @@ -111103,7 +113102,7 @@ var ts; var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 121 /* AsyncKeyword */)); var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); - ts.copyComments(assignmentBinaryExpression, method, sourceFile); + ts.copyLeadingComments(assignmentBinaryExpression, method, sourceFile); return method; } default: { @@ -111113,7 +113112,7 @@ var ts; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentBinaryExpression.right); - ts.copyComments(assignmentBinaryExpression.parent, prop, sourceFile); + ts.copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); return prop; } } @@ -111205,7 +113204,7 @@ var ts; var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } - var _loop_21 = function (statement) { + var _loop_11 = function (statement) { ts.forEachChild(statement, function visit(node) { if (ts.isCallExpression(node)) { startTransformation(node, statement); @@ -111217,7 +113216,7 @@ var ts; }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; - _loop_21(statement); + _loop_11(statement); } } function getReturnStatementsWithPromiseHandlers(body) { @@ -111542,8 +113541,8 @@ var ts; if (innerCbBody.length > 0) { return innerCbBody; } - var type_6 = transformer.checker.getTypeAtLocation(func); - var returnType_1 = getLastCallSignature(type_6, transformer.checker).getReturnType(); + var type_1 = transformer.checker.getTypeAtLocation(func); + var returnType_1 = getLastCallSignature(type_1, transformer.checker).getReturnType(); var rightHandSide = ts.getSynthesizedDeepClone(funcBody); var possiblyAwaitedRightHandSide = !!transformer.checker.getPromisedTypeOfPromise(returnType_1) ? ts.createAwait(rightHandSide) : rightHandSide; if (!shouldReturn) { @@ -112869,7 +114868,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = getAllSupers(classDeclaration, checker); - var _loop_22 = function (info) { + var _loop_12 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -112896,7 +114895,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_22(info); + _loop_12(info); } }); })); @@ -113862,7 +115861,7 @@ var ts; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; - if (typeNode.kind === 286 /* JSDocNullableType */) { + if (typeNode.kind === 291 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` actions.push(fix(checker.getNullableType(type, 32768 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); @@ -113882,7 +115881,7 @@ var ts; if (!info) return; var typeNode = info.typeNode, type = info.type; - var fixedType = typeNode.kind === 286 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; + var fixedType = typeNode.kind === 291 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; doChange(changes, sourceFile, typeNode, fixedType, checker); }); } @@ -114131,8 +116130,8 @@ var ts; outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); break; } - for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) { - var signature = signatures_7[_i]; + for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { + var signature = signatures_1[_i]; // Need to ensure nodes are fresh each time so they can have different positions. outputMethod(signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false)); } @@ -114179,7 +116178,7 @@ var ts; ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); var contextualType = checker.getContextualType(call); - var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker) || ts.createKeywordTypeNode(120 /* AnyKeyword */); + var returnType = (inJs || !contextualType) ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, @@ -114215,8 +116214,8 @@ var ts; var maxArgsSignature = signatures[0]; var minArgumentCount = signatures[0].minArgumentCount; var someSigHasRestParameter = false; - for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { - var sig = signatures_8[_i]; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var sig = signatures_2[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); if (sig.hasRestParameter) { someSigHasRestParameter = true; @@ -114375,8 +116374,8 @@ var ts; ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); } if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) { - var sourceFile_3 = context.sourceFile; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_3, expr, ts.createPropertyAccess(expr, "default"), {}); }); + var sourceFile_1 = context.sourceFile; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_1, expr, ts.createPropertyAccess(expr, "default"), {}); }); fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member)); } return fixes; @@ -114514,6 +116513,7 @@ var ts; return ts.textChanges.getNewFileText(toStatements(valueInfo, outputKind), 3 /* TS */, formatSettings.newLineCharacter || "\n", ts.formatting.getFormatContext(formatSettings)); } ts.valueInfoToDeclarationFileText = valueInfoToDeclarationFileText; + /* @internal */ var OutputKind; (function (OutputKind) { OutputKind[OutputKind["ExportEquals"] = 0] = "ExportEquals"; @@ -114648,16 +116648,16 @@ var ts; } } function toPropertyName(name) { - return ts.isIdentifierText(name, 6 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name); + return ts.isIdentifierText(name, 7 /* ESNext */) ? ts.createIdentifier(name) : ts.createStringLiteral(name); } // Parses assignments to "this.x" in the constructor into class property declarations function getConstructorFunctionInstanceProperties(fnAst, members) { forEachOwnNodeOfFunction(fnAst, function (node) { if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 100 /* ThisKeyword */) { - var name_7 = node.left.name.text; - if (!ts.isJsPrivate(name_7)) { - ts.getOrUpdate(members, name_7, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_7, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); }); + var name_4 = node.left.name.text; + if (!ts.isJsPrivate(name_4)) { + ts.getOrUpdate(members, name_4, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_4, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); }); } } }); @@ -114692,7 +116692,7 @@ var ts; } function parseExpression(expr) { var text = "const _ = " + expr; - var srcFile = ts.createSourceFile("test.ts", text, 6 /* Latest */, /*setParentNodes*/ true); + var srcFile = ts.createSourceFile("test.ts", text, 7 /* Latest */, /*setParentNodes*/ true); return ts.first(ts.cast(ts.first(srcFile.statements), ts.isVariableStatement).declarationList.declarations).initializer; } function inferParameterType(_fn, _param) { @@ -114709,7 +116709,7 @@ var ts; } function isValidIdentifier(name) { var keyword = ts.stringToToken(name); - return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 6 /* ESNext */); + return !(keyword && ts.isNonContextualKeyword(keyword)) && ts.isIdentifierText(name, 7 /* ESNext */); } function addComment(node, comment) { if (comment !== undefined) @@ -115164,7 +117164,7 @@ var ts; function doChangeNamedToNamespace(sourceFile, checker, changes, toConvert) { var importDecl = toConvert.parent.parent; var moduleSpecifier = importDecl.moduleSpecifier; - var preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 6 /* ESNext */) : "module"; + var preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 7 /* ESNext */) : "module"; var namespaceNameConflicts = toConvert.elements.some(function (element) { return ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { return !!checker.resolveName(preferredName, id, 67108863 /* All */, /*excludeGlobals*/ true); @@ -115172,7 +117172,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_23 = function (element) { + var _loop_13 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -115191,7 +117191,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_23(element); + _loop_13(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -115681,7 +117681,7 @@ var ts; // * Module/namespace or source file if (isScope(current)) { scopes.push(current); - if (current.kind === 279 /* SourceFile */) { + if (current.kind === 284 /* SourceFile */) { return scopes; } } @@ -116246,8 +118246,8 @@ var ts; ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one. var prevMember; var allProperties = true; - for (var _i = 0, members_7 = members; _i < members_7.length; _i++) { - var member = members_7[_i]; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; if (member.pos > maxPos) { return prevMember || members[0]; } @@ -116421,7 +118421,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_24 = function (i) { + var _loop_14 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -116461,7 +118461,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_24(i); + _loop_14(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -116695,7 +118695,7 @@ var ts; function isBlockLike(node) { switch (node.kind) { case 218 /* Block */: - case 279 /* SourceFile */: + case 284 /* SourceFile */: case 245 /* ModuleBlock */: case 271 /* CaseClause */: return true; @@ -117012,10 +119012,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_25 = function (sourceFile) { + var _loop_15 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_26 = function (statement) { + var _loop_16 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -117037,12 +119037,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_26(statement); + _loop_16(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_25(sourceFile); + _loop_15(sourceFile); } } function getNamespaceLikeImport(node) { @@ -117059,7 +119059,7 @@ var ts; } } function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) { - var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 6 /* ESNext */); + var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 7 /* ESNext */); var needUniqueName = false; var toChange = []; ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) { @@ -117157,9 +119157,9 @@ var ts; if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) { - var exports_2 = addExport(statement, useEs6Exports); - if (exports_2) - return exports_2; + var exports = addExport(statement, useEs6Exports); + if (exports) + return exports; } return statement; }); @@ -117285,7 +119285,7 @@ var ts; var movedSymbols = new SymbolSet(); var oldImportsNeededByNewFile = new SymbolSet(); var newFileImportsFromOldFile = new SymbolSet(); - var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 4 /* ContainsJsx */); }); + var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 2 /* ContainsJsx */); }); var jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx); if (jsxNamespaceSymbol) { // Might not exist (e.g. in non-compiling code) oldImportsNeededByNewFile.add(jsxNamespaceSymbol); @@ -117319,7 +119319,7 @@ var ts; if (ts.contains(toMove, statement)) continue; // jsxNamespaceSymbol will only be set iff it is in oldImportsNeededByNewFile. - if (jsxNamespaceSymbol && !!(statement.transformFlags & 4 /* ContainsJsx */)) { + if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) { unusedImportsFromOldFile.delete(jsxNamespaceSymbol); } forEachReference(statement, checker, function (symbol) { @@ -117634,13 +119634,13 @@ var ts; var returnStatement_1 = ts.createReturn(expression); body = ts.createBlock([returnStatement_1], /* multiLine */ true); ts.suppressLeadingAndTrailingTrivia(body); - ts.copyComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true); + ts.copyLeadingComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true); } else if (actionName === removeBracesActionName && returnStatement) { var actualExpression = expression || ts.createVoidZero(); body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression; ts.suppressLeadingAndTrailingTrivia(body); - ts.copyComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); + ts.copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); } else { ts.Debug.fail("invalid action"); @@ -117679,6 +119679,459 @@ var ts; })(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var convertParamsToDestructuredObject; + (function (convertParamsToDestructuredObject) { + var refactorName = "Convert parameters to destructured object"; + var minimumParameterLength = 2; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition; + var isJSFile = ts.isSourceFileJS(file); + if (isJSFile) + return ts.emptyArray; // TODO: GH#30113 + var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker()); + if (!functionDeclaration) + return ts.emptyArray; + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_parameters_to_destructured_object); + return [{ + name: refactorName, + description: description, + actions: [{ + name: refactorName, + description: description + }] + }]; + } + function getEditsForAction(context, actionName) { + ts.Debug.assert(actionName === refactorName); + var file = context.file, startPosition = context.startPosition, program = context.program, cancellationToken = context.cancellationToken, host = context.host; + var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker()); + if (!functionDeclaration || !cancellationToken) + return undefined; + var groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken); + if (groupedReferences.valid) { + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(file, program, host, t, functionDeclaration, groupedReferences); }); + return { renameFilename: undefined, renameLocation: undefined, edits: edits }; + } + return { edits: [] }; // TODO: GH#30113 + } + function doChange(sourceFile, program, host, changes, functionDeclaration, groupedReferences) { + var newParamDeclaration = ts.map(createNewParameters(functionDeclaration, program, host), function (param) { return ts.getSynthesizedDeepClone(param); }); + changes.replaceNodeRangeWithNodes(sourceFile, ts.first(functionDeclaration.parameters), ts.last(functionDeclaration.parameters), newParamDeclaration, { joiner: ", ", + // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter + indentation: 0, + leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include + }); + var functionCalls = ts.sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ function (a, b) { return ts.compareValues(a.pos, b.pos); }); + for (var _i = 0, functionCalls_1 = functionCalls; _i < functionCalls_1.length; _i++) { + var call = functionCalls_1[_i]; + if (call.arguments && call.arguments.length) { + var newArgument = ts.getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true); + changes.replaceNodeRange(ts.getSourceFileOfNode(call), ts.first(call.arguments), ts.last(call.arguments), newArgument, { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Include }); + } + } + } + function getGroupedReferences(functionDeclaration, program, cancellationToken) { + var functionNames = getFunctionNames(functionDeclaration); + var classNames = ts.isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : []; + var names = ts.deduplicate(functionNames.concat(classNames), ts.equateValues); + var checker = program.getTypeChecker(); + var references = ts.flatMap(names, /*mapfn*/ function (/*mapfn*/ name) { return ts.FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken); }); + var groupedReferences = groupReferences(references); + if (!ts.every(groupedReferences.declarations, /*callback*/ function (/*callback*/ decl) { return ts.contains(names, decl); })) { + groupedReferences.valid = false; + } + return groupedReferences; + function groupReferences(referenceEntries) { + var classReferences = { accessExpressions: [], typeUsages: [] }; + var groupedReferences = { functionCalls: [], declarations: [], classReferences: classReferences, valid: true }; + var functionSymbols = ts.map(functionNames, checker.getSymbolAtLocation); + var classSymbols = ts.map(classNames, checker.getSymbolAtLocation); + var isConstructor = ts.isConstructorDeclaration(functionDeclaration); + for (var _i = 0, referenceEntries_1 = referenceEntries; _i < referenceEntries_1.length; _i++) { + var entry = referenceEntries_1[_i]; + if (entry.kind !== 1 /* Node */) { + groupedReferences.valid = false; + continue; + } + /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function. + Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test: + class A { foo(a: number, b: number) { return a + b; } } + class B { foo(c: number, d: number) { return c + d; } } + declare const ab: A | B; + ab.foo(1, 2); + Find all references will return `ab.foo(1, 2)` as a reference to A's `foo` but we could be calling B's `foo`. + When looking for constructor calls, however, the symbol on the constructor call reference is going to be the corresponding class symbol. + So we need to add a special case for this because when calling a constructor of a class through one of its subclasses, + the symbols are going to be different. + */ + if (ts.contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer) || ts.isNewExpressionTarget(entry.node)) { + var decl = entryToDeclaration(entry); + if (decl) { + groupedReferences.declarations.push(decl); + continue; + } + var call = entryToFunctionCall(entry); + if (call) { + groupedReferences.functionCalls.push(call); + continue; + } + } + // if the refactored function is a constructor, we must also check if the references to its class are valid + if (isConstructor && ts.contains(classSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) { + var decl = entryToDeclaration(entry); + if (decl) { + groupedReferences.declarations.push(decl); + continue; + } + var accessExpression = entryToAccessExpression(entry); + if (accessExpression) { + classReferences.accessExpressions.push(accessExpression); + continue; + } + // Only class declarations are allowed to be used as a type (in a heritage clause), + // otherwise `findAllReferences` might not be able to track constructor calls. + if (ts.isClassDeclaration(functionDeclaration.parent)) { + var type = entryToType(entry); + if (type) { + classReferences.typeUsages.push(type); + continue; + } + } + } + groupedReferences.valid = false; + } + return groupedReferences; + } + } + function symbolComparer(a, b) { + return ts.getSymbolTarget(a) === ts.getSymbolTarget(b); + } + function entryToDeclaration(entry) { + if (ts.isDeclaration(entry.node.parent)) { + return entry.node; + } + return undefined; + } + function entryToFunctionCall(entry) { + if (entry.node.parent) { + var functionReference = entry.node; + var parent = functionReference.parent; + switch (parent.kind) { + // Function call (foo(...) or super(...)) + case 191 /* CallExpression */: + var callExpression = ts.tryCast(parent, ts.isCallExpression); + if (callExpression && callExpression.expression === functionReference) { + return callExpression; + } + break; + // Constructor call (new Foo(...)) + case 192 /* NewExpression */: + var newExpression = ts.tryCast(parent, ts.isNewExpression); + if (newExpression && newExpression.expression === functionReference) { + return newExpression; + } + break; + // Method call (x.foo(...)) + case 189 /* PropertyAccessExpression */: + var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression); + if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { + var callExpression_1 = ts.tryCast(propertyAccessExpression.parent, ts.isCallExpression); + if (callExpression_1 && callExpression_1.expression === propertyAccessExpression) { + return callExpression_1; + } + } + break; + // Method call (x["foo"](...)) + case 190 /* ElementAccessExpression */: + var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression); + if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { + var callExpression_2 = ts.tryCast(elementAccessExpression.parent, ts.isCallExpression); + if (callExpression_2 && callExpression_2.expression === elementAccessExpression) { + return callExpression_2; + } + } + break; + } + } + return undefined; + } + function entryToAccessExpression(entry) { + if (entry.node.parent) { + var reference = entry.node; + var parent = reference.parent; + switch (parent.kind) { + // `C.foo` + case 189 /* PropertyAccessExpression */: + var propertyAccessExpression = ts.tryCast(parent, ts.isPropertyAccessExpression); + if (propertyAccessExpression && propertyAccessExpression.expression === reference) { + return propertyAccessExpression; + } + break; + // `C["foo"]` + case 190 /* ElementAccessExpression */: + var elementAccessExpression = ts.tryCast(parent, ts.isElementAccessExpression); + if (elementAccessExpression && elementAccessExpression.expression === reference) { + return elementAccessExpression; + } + break; + } + } + return undefined; + } + function entryToType(entry) { + var reference = entry.node; + if (ts.getMeaningFromLocation(reference) === 2 /* Type */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) { + return reference; + } + return undefined; + } + function getFunctionDeclarationAtPosition(file, startPosition, checker) { + var node = ts.getTouchingToken(file, startPosition); + var functionDeclaration = ts.getContainingFunction(node); + // don't offer refactor on top-level JSDoc + if (isTopLevelJSDoc(node)) + return undefined; + if (functionDeclaration + && isValidFunctionDeclaration(functionDeclaration, checker) + && ts.rangeContainsRange(functionDeclaration, node) + && !(functionDeclaration.body && ts.rangeContainsRange(functionDeclaration.body, node))) + return functionDeclaration; + return undefined; + } + function isTopLevelJSDoc(node) { + var containingJSDoc = ts.findAncestor(node, ts.isJSDocNode); + if (containingJSDoc) { + var containingNonJSDoc = ts.findAncestor(containingJSDoc, function (n) { return !ts.isJSDocNode(n); }); + return !!containingNonJSDoc && ts.isFunctionLikeDeclaration(containingNonJSDoc); + } + return false; + } + function isValidFunctionDeclaration(functionDeclaration, checker) { + if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) + return false; + switch (functionDeclaration.kind) { + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + return !!functionDeclaration.name + && !!functionDeclaration.body + && !checker.isImplementationOfOverload(functionDeclaration); + case 157 /* Constructor */: + if (ts.isClassDeclaration(functionDeclaration.parent)) { + return !!functionDeclaration.body + && !!functionDeclaration.parent.name + && !checker.isImplementationOfOverload(functionDeclaration); + } + else { + return isValidVariableDeclaration(functionDeclaration.parent.parent) + && !!functionDeclaration.body + && !checker.isImplementationOfOverload(functionDeclaration); + } + case 196 /* FunctionExpression */: + case 197 /* ArrowFunction */: + return isValidVariableDeclaration(functionDeclaration.parent); + } + return false; + } + function isValidParameterNodeArray(parameters, checker) { + return getRefactorableParametersLength(parameters) >= minimumParameterLength + && ts.every(parameters, /*callback*/ function (/*callback*/ paramDecl) { return isValidParameterDeclaration(paramDecl, checker); }); + } + function isValidParameterDeclaration(parameterDeclaration, checker) { + if (ts.isRestParameter(parameterDeclaration)) { + var type = checker.getTypeAtLocation(parameterDeclaration); + if (!checker.isArrayType(type) && !checker.isTupleType(type)) + return false; + } + return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && ts.isIdentifier(parameterDeclaration.name); + } + function isValidVariableDeclaration(node) { + return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113 + } + function hasThisParameter(parameters) { + return parameters.length > 0 && ts.isThis(parameters[0].name); + } + function getRefactorableParametersLength(parameters) { + if (hasThisParameter(parameters)) { + return parameters.length - 1; + } + return parameters.length; + } + function getRefactorableParameters(parameters) { + if (hasThisParameter(parameters)) { + parameters = ts.createNodeArray(parameters.slice(1), parameters.hasTrailingComma); + } + return parameters; + } + function createPropertyOrShorthandAssignment(name, initializer) { + if (ts.isIdentifier(initializer) && ts.getTextOfIdentifierOrLiteral(initializer) === name) { + return ts.createShorthandPropertyAssignment(name); + } + return ts.createPropertyAssignment(name, initializer); + } + function createNewArgument(functionDeclaration, functionArguments) { + var parameters = getRefactorableParameters(functionDeclaration.parameters); + var hasRestParameter = ts.isRestParameter(ts.last(parameters)); + var nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments; + var properties = ts.map(nonRestArguments, function (arg, i) { + var parameterName = getParameterName(parameters[i]); + var property = createPropertyOrShorthandAssignment(parameterName, arg); + ts.suppressLeadingAndTrailingTrivia(property.name); + if (ts.isPropertyAssignment(property)) + ts.suppressLeadingAndTrailingTrivia(property.initializer); + copyComments(arg, property); + return property; + }); + if (hasRestParameter && functionArguments.length >= parameters.length) { + var restArguments = functionArguments.slice(parameters.length - 1); + var restProperty = ts.createPropertyAssignment(getParameterName(ts.last(parameters)), ts.createArrayLiteral(restArguments)); + properties.push(restProperty); + } + var objectLiteral = ts.createObjectLiteral(properties, /*multiLine*/ false); + return objectLiteral; + } + function createNewParameters(functionDeclaration, program, host) { + var checker = program.getTypeChecker(); + var refactorableParameters = getRefactorableParameters(functionDeclaration.parameters); + var bindingElements = ts.map(refactorableParameters, createBindingElementFromParameterDeclaration); + var objectParameterName = ts.createObjectBindingPattern(bindingElements); + var objectParameterType = createParameterTypeNode(refactorableParameters); + var objectInitializer; + // If every parameter in the original function was optional, add an empty object initializer to the new object parameter + if (ts.every(refactorableParameters, isOptionalParameter)) { + objectInitializer = ts.createObjectLiteral(); + } + var objectParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, objectParameterName, + /*questionToken*/ undefined, objectParameterType, objectInitializer); + if (hasThisParameter(functionDeclaration.parameters)) { + var thisParameter = functionDeclaration.parameters[0]; + var newThisParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, thisParameter.name, + /*questionToken*/ undefined, thisParameter.type); + ts.suppressLeadingAndTrailingTrivia(newThisParameter.name); + copyComments(thisParameter.name, newThisParameter.name); + if (thisParameter.type) { + ts.suppressLeadingAndTrailingTrivia(newThisParameter.type); + copyComments(thisParameter.type, newThisParameter.type); + } + return ts.createNodeArray([newThisParameter, objectParameter]); + } + return ts.createNodeArray([objectParameter]); + function createBindingElementFromParameterDeclaration(parameterDeclaration) { + var element = ts.createBindingElement( + /*dotDotDotToken*/ undefined, + /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer); + ts.suppressLeadingAndTrailingTrivia(element); + if (parameterDeclaration.initializer && element.initializer) { + copyComments(parameterDeclaration.initializer, element.initializer); + } + return element; + } + function createParameterTypeNode(parameters) { + var members = ts.map(parameters, createPropertySignatureFromParameterDeclaration); + var typeNode = ts.addEmitFlags(ts.createTypeLiteralNode(members), 1 /* SingleLine */); + return typeNode; + } + function createPropertySignatureFromParameterDeclaration(parameterDeclaration) { + var parameterType = parameterDeclaration.type; + if (!parameterType && (parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration))) { + parameterType = getTypeNode(parameterDeclaration); + } + var propertySignature = ts.createPropertySignature( + /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? ts.createToken(56 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType, + /*initializer*/ undefined); + ts.suppressLeadingAndTrailingTrivia(propertySignature); + copyComments(parameterDeclaration.name, propertySignature.name); + if (parameterDeclaration.type && propertySignature.type) { + copyComments(parameterDeclaration.type, propertySignature.type); + } + return propertySignature; + } + function getTypeNode(node) { + var type = checker.getTypeAtLocation(node); + return ts.getTypeNodeIfAccessible(type, node, program, host); + } + function isOptionalParameter(parameterDeclaration) { + if (ts.isRestParameter(parameterDeclaration)) { + var type = checker.getTypeAtLocation(parameterDeclaration); + return !checker.isTupleType(type); + } + return checker.isOptionalParameter(parameterDeclaration); + } + } + function copyComments(sourceNode, targetNode) { + var sourceFile = sourceNode.getSourceFile(); + var text = sourceFile.text; + if (hasLeadingLineBreak(sourceNode, text)) { + ts.copyLeadingComments(sourceNode, targetNode, sourceFile); + } + else { + ts.copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile); + } + ts.copyTrailingComments(sourceNode, targetNode, sourceFile); + } + function hasLeadingLineBreak(node, text) { + var start = node.getFullStart(); + var end = node.getStart(); + for (var i = start; i < end; i++) { + if (text.charCodeAt(i) === 10 /* lineFeed */) + return true; + } + return false; + } + function getParameterName(paramDeclaration) { + return ts.getTextOfIdentifierOrLiteral(paramDeclaration.name); + } + function getClassNames(constructorDeclaration) { + switch (constructorDeclaration.parent.kind) { + case 240 /* ClassDeclaration */: + var classDeclaration = constructorDeclaration.parent; + return [classDeclaration.name]; + case 209 /* ClassExpression */: + var classExpression = constructorDeclaration.parent; + var variableDeclaration = constructorDeclaration.parent.parent; + var className = classExpression.name; + if (className) + return [className, variableDeclaration.name]; + return [variableDeclaration.name]; + } + } + function getFunctionNames(functionDeclaration) { + switch (functionDeclaration.kind) { + case 239 /* FunctionDeclaration */: + case 156 /* MethodDeclaration */: + return [functionDeclaration.name]; + case 157 /* Constructor */: + var ctrKeyword = ts.findChildOfKind(functionDeclaration, 124 /* ConstructorKeyword */, functionDeclaration.getSourceFile()); + if (functionDeclaration.parent.kind === 209 /* ClassExpression */) { + var variableDeclaration = functionDeclaration.parent.parent; + return [variableDeclaration.name, ctrKeyword]; + } + return [ctrKeyword]; + case 197 /* ArrowFunction */: + return [functionDeclaration.parent.name]; + case 196 /* FunctionExpression */: + if (functionDeclaration.name) + return [functionDeclaration.name, functionDeclaration.parent.name]; + return [functionDeclaration.parent.name]; + default: + return ts.Debug.assertNever(functionDeclaration); + } + } + })(convertParamsToDestructuredObject = refactor.convertParamsToDestructuredObject || (refactor.convertParamsToDestructuredObject = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); var ts; (function (ts) { /** The version of the language service API */ @@ -117696,7 +120149,8 @@ var ts; this.pos = pos; this.end = end; this.flags = 0 /* None */; - this.transformFlags = undefined; // TODO: GH#18217 + this.modifierFlagsCache = 0 /* None */; + this.transformFlags = 0 /* None */; this.parent = undefined; this.kind = kind; } @@ -117758,7 +120212,7 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 283 /* FirstJSDocNode */ || kid.kind > 305 /* LastJSDocNode */; }); + var child = ts.find(children, function (kid) { return kid.kind < 288 /* FirstJSDocNode */ || kid.kind > 310 /* LastJSDocNode */; }); return child.kind < 148 /* FirstNode */ ? child : child.getFirstToken(sourceFile); @@ -117828,11 +120282,11 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(306 /* SyntaxList */, nodes.pos, nodes.end, parent); + var list = createNode(311 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; - for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { - var node = nodes_7[_i]; + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; addSyntheticNodes(list._children, pos, node.pos, parent); list._children.push(node); pos = node.end; @@ -117846,6 +120300,8 @@ var ts; this.pos = pos; this.end = end; this.flags = 0 /* None */; + this.modifierFlagsCache = 0 /* None */; + this.transformFlags = 0 /* None */; this.parent = undefined; } TokenOrIdentifierObject.prototype.getSourceFile = function () { @@ -118074,8 +120530,8 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { - var declaration = declarations_14[_i]; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) @@ -118421,7 +120877,7 @@ var ts; var sourceFile; if (this.currentFileName !== fileName) { // This is a new file, just parse it - sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 6 /* Latest */, version, /*setNodeParents*/ true, scriptKind); + sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, 7 /* Latest */, version, /*setNodeParents*/ true, scriptKind); } else if (this.currentFileVersion !== version) { // This is the same file, just a newer version. Incrementally parse the file. @@ -118545,9 +121001,9 @@ var ts; }()); ts.ThrottledCancellationToken = ThrottledCancellationToken; 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 _a; var syntaxTreeCache = new SyntaxTreeCache(host); var program; var lastProjectVersion; @@ -118578,7 +121034,7 @@ var ts; function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { - throw new Error("Could not find file: '" + fileName + "'."); + throw new Error("Could not find sourceFile: '" + fileName + "' in " + (program && JSON.stringify(program.getSourceFiles().map(function (f) { return f.fileName; }))) + "."); } return sourceFile; } @@ -118827,14 +121283,14 @@ var ts; var typeChecker = program.getTypeChecker(); var symbol = getSymbolAtLocationForQuickInfo(node, typeChecker); if (!symbol || typeChecker.isUnknownSymbol(symbol)) { - var type_7 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; - return type_7 && { + var type_2 = shouldGetType(sourceFile, node, position) ? typeChecker.getTypeAtLocation(node) : undefined; + return type_2 && { kind: "" /* unknown */, kindModifiers: "" /* none */, textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_7, ts.getContainerNode(node)); }), - documentation: type_7.symbol ? type_7.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type_7.symbol ? type_7.symbol.getJsDocTags() : undefined + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_2, ts.getContainerNode(node)); }), + documentation: type_2.symbol ? type_2.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_2.symbol ? type_2.symbol.getJsDocTags() : undefined }; } var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { @@ -120945,4 +123401,6 @@ var TypeScript; // TODO: it should be moved into a namespace though. /* @internal */ var toolsVersion = ts.versionMajorMinor; -//# sourceMappingURL=typescriptServices.out.js.map \ No newline at end of file + + +//# sourceMappingURL=typescript.js.map diff --git a/packages/schematics/schematics/blank/project-files/package.json.template b/packages/schematics/schematics/blank/project-files/package.json.template index e1ebe4957f82..ca350c4d8679 100644 --- a/packages/schematics/schematics/blank/project-files/package.json.template +++ b/packages/schematics/schematics/blank/project-files/package.json.template @@ -18,6 +18,6 @@ "@types/jasmine": "^3.3.9", "@types/node": "^8.0.31", "jasmine": "^3.3.1", - "typescript": "~3.2.2" + "typescript": "~3.4.3" } } diff --git a/packages/schematics/schematics/schematic/files/package.json b/packages/schematics/schematics/schematic/files/package.json index b41f04a1cd27..7db6a01326dd 100644 --- a/packages/schematics/schematics/schematic/files/package.json +++ b/packages/schematics/schematics/schematic/files/package.json @@ -18,6 +18,6 @@ "@types/jasmine": "^3.3.9", "@types/node": "^8.0.31", "jasmine": "^3.3.1", - "typescript": "~3.3.3333" + "typescript": "3.4.3" } } diff --git a/yarn.lock b/yarn.lock index 89a71efa6f86..1ae285714a49 100644 --- a/yarn.lock +++ b/yarn.lock @@ -9541,6 +9541,11 @@ typescript@3.3.4000: resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.3.4000.tgz#76b0f89cfdbf97827e1112d64f283f1151d6adf0" integrity sha512-jjOcCZvpkl2+z7JFn0yBOoLQyLoIkNZAs/fYJkUG6VKy6zLPHJGfQJYFHzibB6GJaF/8QrcECtlQ5cpvRHSMEA== +typescript@3.4.3: + version "3.4.3" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.4.3.tgz#0eb320e4ace9b10eadf5bc6103286b0f8b7c224f" + integrity sha512-FFgHdPt4T/duxx6Ndf7hwgMZZjZpB+U0nMNGVCYPq0rEzWKjEDobm4J6yb3CS7naZ0yURFqdw9Gwc7UOh/P9oQ== + uglify-js@^3.1.4: version "3.4.9" resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.4.9.tgz#af02f180c1207d76432e473ed24a28f4a782bae3"