diff --git a/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/BUILD.bazel b/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/BUILD.bazel index 710e9441be..56e2e12b75 100644 --- a/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/BUILD.bazel +++ b/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/BUILD.bazel @@ -1,7 +1,7 @@ load("//tools:defaults.bzl", "ts_library") -# files fetched on 2020-01-09 from -# https://github.com/Microsoft/TypeScript/tree/v3.7.4 +# files fetched on 2020-05-20 from +# https://github.com/Microsoft/TypeScript/tree/v3.9.3 licenses(["notice"]) # Apache 2.0 ts_library( 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 86288e69e6..62e8560ae4 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 @@ -1,20 +1,20 @@ /*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - +License at http://www.apache.org/licenses/LICENSE-2.0 + THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.8"; + const versionMajorMinor = "3.9"; /** The version of the TypeScript compiler release */ const version: string; /** @@ -383,29 +383,30 @@ declare namespace ts { JSDocSignature = 305, JSDocTag = 306, JSDocAugmentsTag = 307, - JSDocAuthorTag = 308, - JSDocClassTag = 309, - JSDocPublicTag = 310, - JSDocPrivateTag = 311, - JSDocProtectedTag = 312, - JSDocReadonlyTag = 313, - JSDocCallbackTag = 314, - JSDocEnumTag = 315, - JSDocParameterTag = 316, - JSDocReturnTag = 317, - JSDocThisTag = 318, - JSDocTypeTag = 319, - JSDocTemplateTag = 320, - JSDocTypedefTag = 321, - JSDocPropertyTag = 322, - SyntaxList = 323, - NotEmittedStatement = 324, - PartiallyEmittedExpression = 325, - CommaListExpression = 326, - MergeDeclarationMarker = 327, - EndOfDeclarationMarker = 328, - SyntheticReferenceExpression = 329, - Count = 330, + JSDocImplementsTag = 308, + JSDocAuthorTag = 309, + JSDocClassTag = 310, + JSDocPublicTag = 311, + JSDocPrivateTag = 312, + JSDocProtectedTag = 313, + JSDocReadonlyTag = 314, + JSDocCallbackTag = 315, + JSDocEnumTag = 316, + JSDocParameterTag = 317, + JSDocReturnTag = 318, + JSDocThisTag = 319, + JSDocTypeTag = 320, + JSDocTemplateTag = 321, + JSDocTypedefTag = 322, + JSDocPropertyTag = 323, + SyntaxList = 324, + NotEmittedStatement = 325, + PartiallyEmittedExpression = 326, + CommaListExpression = 327, + MergeDeclarationMarker = 328, + EndOfDeclarationMarker = 329, + SyntheticReferenceExpression = 330, + Count = 331, FirstAssignment = 62, LastAssignment = 74, FirstCompoundAssignment = 63, @@ -434,9 +435,9 @@ declare namespace ts { LastStatement = 241, FirstNode = 153, FirstJSDocNode = 294, - LastJSDocNode = 322, + LastJSDocNode = 323, FirstJSDocTagNode = 306, - LastJSDocTagNode = 322, + LastJSDocTagNode = 323, } export enum NodeFlags { None = 0, @@ -1136,7 +1137,7 @@ declare namespace ts { export interface CallChain extends CallExpression { _optionalChainBrand: any; } - export type OptionalChain = PropertyAccessChain | ElementAccessChain | CallChain; + export type OptionalChain = PropertyAccessChain | ElementAccessChain | CallChain | NonNullChain; export interface SuperCall extends CallExpression { expression: SuperExpression; } @@ -1145,7 +1146,7 @@ declare namespace ts { } export interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent: HeritageClause | JSDocAugmentsTag; + parent: HeritageClause | JSDocAugmentsTag | JSDocImplementsTag; expression: LeftHandSideExpression; } export interface NewExpression extends PrimaryExpression, Declaration { @@ -1176,6 +1177,9 @@ declare namespace ts { kind: SyntaxKind.NonNullExpression; expression: Expression; } + export interface NonNullChain extends NonNullExpression { + _optionalChainBrand: any; + } export interface MetaProperty extends PrimaryExpression { kind: SyntaxKind.MetaProperty; keywordToken: SyntaxKind.NewKeyword | SyntaxKind.ImportKeyword; @@ -1635,6 +1639,12 @@ declare namespace ts { expression: Identifier | PropertyAccessEntityNameExpression; }; } + export interface JSDocImplementsTag extends JSDocTag { + kind: SyntaxKind.JSDocImplementsTag; + class: ExpressionWithTypeArguments & { + expression: Identifier | PropertyAccessEntityNameExpression; + }; + } export interface JSDocAuthorTag extends JSDocTag { kind: SyntaxKind.JSDocAuthorTag; } @@ -1726,10 +1736,9 @@ declare namespace ts { SwitchClause = 128, ArrayMutation = 256, Call = 512, - Referenced = 1024, - Shared = 2048, - PreFinally = 4096, - AfterFinally = 8192, + ReduceLabel = 1024, + Referenced = 2048, + Shared = 4096, Label = 12, Condition = 96 } @@ -1776,6 +1785,11 @@ declare namespace ts { node: CallExpression | BinaryExpression; antecedent: FlowNode; } + export interface FlowReduceLabel extends FlowNodeBase { + target: FlowLabel; + antecedents: FlowNode[]; + antecedent: FlowNode; + } export type FlowType = Type | IncompleteType; export interface IncompleteType { flags: TypeFlags; @@ -1914,6 +1928,7 @@ declare namespace ts { throwIfCancellationRequested(): void; } export interface Program extends ScriptReferenceHost { + getCurrentDirectory(): string; /** * Get a list of root file names that were passed to a 'createProgram' */ @@ -1948,6 +1963,7 @@ declare namespace ts { getIdentifierCount(): number; getSymbolCount(): number; getTypeCount(): number; + getInstantiationCount(): number; getRelationCacheSizes(): { assignable: number; identity: number; @@ -2119,6 +2135,7 @@ declare namespace ts { OmitParameterModifiers = 8192, UseAliasDefinedOutsideCurrentScope = 16384, UseSingleQuotesForStringLiteralType = 268435456, + NoTypeReduction = 536870912, AllowThisInObjectLiteral = 32768, AllowQualifedNameInPlaceOfIdentifier = 65536, AllowAnonymousIdentifier = 131072, @@ -2147,6 +2164,7 @@ declare namespace ts { OmitParameterModifiers = 8192, UseAliasDefinedOutsideCurrentScope = 16384, UseSingleQuotesForStringLiteralType = 268435456, + NoTypeReduction = 536870912, AllowUniqueESSymbolType = 1048576, AddUndefined = 131072, WriteArrowStyleSignature = 262144, @@ -2155,7 +2173,7 @@ declare namespace ts { InFirstTypeArgument = 4194304, InTypeAlias = 8388608, /** @deprecated */ WriteOwnNameForAnyLike = 0, - NodeBuilderFlagsMask = 277904747 + NodeBuilderFlagsMask = 814775659 } export enum SymbolFormatFlags { None = 0, @@ -2510,7 +2528,7 @@ declare namespace ts { resolvedFalseType: Type; } export interface SubstitutionType extends InstantiableType { - typeVariable: TypeVariable; + baseType: Type; substitute: Type; } export enum SignatureKind { @@ -2905,7 +2923,7 @@ declare namespace ts { } export interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; - readonly failedLookupLocations: readonly string[]; + readonly failedLookupLocations: string[]; } export interface CompilerHost extends ModuleResolutionHost { getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; @@ -2972,6 +2990,7 @@ declare namespace ts { readonly scoped: boolean; readonly text: string | ((node: EmitHelperUniqueNameCallback) => string); readonly priority?: number; + readonly dependencies?: EmitHelper[]; } export interface UnscopedEmitHelper extends EmitHelper { readonly scoped: false; @@ -3168,11 +3187,6 @@ declare namespace ts { directoryExists?(directoryName: string): boolean; getCurrentDirectory?(): string; } - export interface ModuleSpecifierResolutionHost extends GetEffectiveTypeRootsHost { - useCaseSensitiveFileNames?(): boolean; - fileExists?(path: string): boolean; - readFile?(path: string): string | undefined; - } export interface TextSpan { start: number; length: number; @@ -3213,6 +3227,7 @@ declare namespace ts { NoInterveningComments = 262144, NoSpaceIfEmpty = 524288, SingleElement = 1048576, + SpaceAfterList = 2097152, Modifiers = 262656, HeritageClauses = 512, SingleLineTypeLiteralMembers = 768, @@ -3244,7 +3259,7 @@ declare namespace ts { CaseOrDefaultClauseStatements = 163969, HeritageClauseTypes = 528, SourceFileStatements = 131073, - Decorators = 49153, + Decorators = 2146305, TypeArguments = 53776, TypeParameters = 53776, Parameters = 2576, @@ -3259,7 +3274,7 @@ declare namespace ts { readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "auto" | "relative" | "non-relative"; /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ - readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; + readonly importModuleSpecifierEnding?: "auto" | "minimal" | "index" | "js"; readonly allowTextChangesInNewFiles?: boolean; readonly providePrefixAndSuffixTextForRename?: boolean; } @@ -3345,7 +3360,8 @@ declare namespace ts { isUnterminated(): boolean; reScanGreaterToken(): SyntaxKind; reScanSlashToken(): SyntaxKind; - reScanTemplateToken(): SyntaxKind; + reScanTemplateToken(isTaggedTemplate: boolean): SyntaxKind; + reScanTemplateHeadOrNoSubstitutionTemplate(): SyntaxKind; scanJsxIdentifier(): SyntaxKind; scanJsxAttributeValue(): SyntaxKind; reScanJsxAttributeValue(): SyntaxKind; @@ -3384,7 +3400,7 @@ declare namespace ts { /** Optionally, get the shebang */ function getShebang(text: string): string | undefined; function isIdentifierStart(ch: number, languageVersion: ScriptTarget | undefined): boolean; - function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined): boolean; + function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined, identifierVariant?: LanguageVariant): boolean; function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; } declare namespace ts { @@ -3509,6 +3525,8 @@ declare namespace ts { function hasJSDocParameterTags(node: FunctionLikeDeclaration | SignatureDeclaration): boolean; /** Gets the JSDoc augments tag for the node if present */ function getJSDocAugmentsTag(node: Node): JSDocAugmentsTag | undefined; + /** Gets the JSDoc implements tags for the node if present */ + function getJSDocImplementsTags(node: Node): readonly JSDocImplementsTag[]; /** Gets the JSDoc class tag for the node if present */ function getJSDocClassTag(node: Node): JSDocClassTag | undefined; /** Gets the JSDoc public tag for the node if present */ @@ -3550,7 +3568,9 @@ declare namespace ts { function getJSDocReturnType(node: Node): TypeNode | undefined; /** Get all JSDoc tags related to a node, including those on parent nodes. */ function getJSDocTags(node: Node): readonly JSDocTag[]; - /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + /** Gets all JSDoc tags that match a specified predicate */ + function getAllJSDocTags(node: Node, predicate: (tag: JSDocTag) => tag is T): readonly T[]; + /** Gets all JSDoc tags of a specified kind */ function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): readonly JSDocTag[]; /** * Gets the effective type parameters. If the node was parsed in a @@ -3615,7 +3635,7 @@ declare namespace ts { function isElementAccessChain(node: Node): node is ElementAccessChain; function isCallExpression(node: Node): node is CallExpression; function isCallChain(node: Node): node is CallChain; - function isOptionalChain(node: Node): node is PropertyAccessChain | ElementAccessChain | CallChain; + function isOptionalChain(node: Node): node is PropertyAccessChain | ElementAccessChain | CallChain | NonNullChain; function isNullishCoalesce(node: Node): boolean; function isNewExpression(node: Node): node is NewExpression; function isTaggedTemplateExpression(node: Node): node is TaggedTemplateExpression; @@ -3642,6 +3662,7 @@ declare namespace ts { function isExpressionWithTypeArguments(node: Node): node is ExpressionWithTypeArguments; function isAsExpression(node: Node): node is AsExpression; function isNonNullExpression(node: Node): node is NonNullExpression; + function isNonNullChain(node: Node): node is NonNullChain; function isMetaProperty(node: Node): node is MetaProperty; function isTemplateSpan(node: Node): node is TemplateSpan; function isSemicolonClassElement(node: Node): node is SemicolonClassElement; @@ -3726,6 +3747,7 @@ declare namespace ts { function isJSDoc(node: Node): node is JSDoc; function isJSDocAuthorTag(node: Node): node is JSDocAuthorTag; function isJSDocAugmentsTag(node: Node): node is JSDocAugmentsTag; + function isJSDocImplementsTag(node: Node): node is JSDocImplementsTag; function isJSDocClassTag(node: Node): node is JSDocClassTag; function isJSDocPublicTag(node: Node): node is JSDocPublicTag; function isJSDocPrivateTag(node: Node): node is JSDocPrivateTag; @@ -3787,6 +3809,8 @@ declare namespace ts { function isJSDocCommentContainingNode(node: Node): boolean; function isSetAccessor(node: Node): node is SetAccessorDeclaration; function isGetAccessor(node: Node): node is GetAccessorDeclaration; + /** True if has initializer node attached to it. */ + function hasOnlyExpressionInitializer(node: Node): node is HasExpressionInitializer; function isObjectLiteralElement(node: Node): node is ObjectLiteralElement; function isStringLiteralLike(node: Node): node is StringLiteralLike; } @@ -3839,7 +3863,7 @@ declare namespace ts { /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ - export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions): ParsedCommandLine | undefined; + export function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost, extendedConfigCache?: Map, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): ParsedCommandLine | undefined; /** * Read tsconfig.json file * @param fileName The path to the config file @@ -4130,6 +4154,8 @@ declare namespace ts { function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression; function createNonNullExpression(expression: Expression): NonNullExpression; function updateNonNullExpression(node: NonNullExpression, expression: Expression): NonNullExpression; + function createNonNullChain(expression: Expression): NonNullChain; + function updateNonNullChain(node: NonNullChain, expression: Expression): NonNullChain; function createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; function updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; @@ -4434,7 +4460,8 @@ declare namespace ts { * Starts a new lexical environment and visits a parameter list, suspending the lexical * environment upon completion. */ - function visitParameterList(nodes: NodeArray | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes): NodeArray; + function visitParameterList(nodes: NodeArray, visitor: Visitor, context: TransformationContext, nodesVisitor?: (nodes: NodeArray, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number) => NodeArray): NodeArray; + function visitParameterList(nodes: NodeArray | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: (nodes: NodeArray | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number) => NodeArray | undefined): NodeArray | undefined; /** * Resumes a suspended lexical environment and visits a function body, ending the lexical * environment and merging hoisted declarations upon completion. @@ -4736,6 +4763,8 @@ declare namespace ts { resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions): (ResolvedTypeReferenceDirective | undefined)[]; } interface WatchCompilerHost extends ProgramHost, WatchHost { + /** Instead of using output d.ts file from project reference, use its source file */ + useSourceOfProjectReferenceRedirect?(): boolean; /** If provided, callback to invoke after every new program creation */ afterProgramCreate?(program: T): void; } @@ -4760,6 +4789,7 @@ declare namespace ts { /** Options to extend */ optionsToExtend?: CompilerOptions; watchOptionsToExtend?: WatchOptions; + extraFileExtensions?: readonly FileExtensionInfo[]; /** * Used to generate source file names from the config file and its include, exclude, files rules * and also to cache the directory stucture @@ -4787,7 +4817,7 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, watchOptionsToExtend?: WatchOptions): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, watchOptionsToExtend?: WatchOptions, extraFileExtensions?: readonly FileExtensionInfo[]): WatchCompilerHostOfConfigFile; function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: readonly ProjectReference[], watchOptions?: WatchOptions): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options @@ -5078,7 +5108,7 @@ declare namespace ts { fileName: Path; packageName: string; } - interface LanguageServiceHost extends ModuleSpecifierResolutionHost { + interface LanguageServiceHost extends GetEffectiveTypeRootsHost { getCompilationSettings(): CompilerOptions; getNewLine?(): string; getProjectVersion?(): string; @@ -5094,6 +5124,7 @@ declare namespace ts { log?(s: string): void; trace?(s: string): void; error?(s: string): void; + useCaseSensitiveFileNames?(): boolean; readDirectory?(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; readFile?(path: string, encoding?: string): string | undefined; realpath?(path: string): string; @@ -5115,25 +5146,88 @@ declare namespace ts { metadata?: unknown; }; interface LanguageService { + /** This is used as a part of restarting the language service. */ cleanupSemanticCache(): void; + /** + * Gets errors indicating invalid syntax in a file. + * + * In English, "this cdeo have, erorrs" is syntactically invalid because it has typos, + * grammatical errors, and misplaced punctuation. Likewise, examples of syntax + * errors in TypeScript are missing parentheses in an `if` statement, mismatched + * curly braces, and using a reserved keyword as a variable name. + * + * These diagnostics are inexpensive to compute and don't require knowledge of + * other files. Note that a non-empty result increases the likelihood of false positives + * from `getSemanticDiagnostics`. + * + * While these represent the majority of syntax-related diagnostics, there are some + * that require the type system, which will be present in `getSemanticDiagnostics`. + * + * @param fileName A path to the file you want syntactic diagnostics for + */ getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; - /** The first time this is called, it will return global diagnostics (no location). */ + /** + * Gets warnings or errors indicating type system issues in a given file. + * Requesting semantic diagnostics may start up the type system and + * run deferred work, so the first call may take longer than subsequent calls. + * + * Unlike the other get*Diagnostics functions, these diagnostics can potentially not + * include a reference to a source file. Specifically, the first time this is called, + * it will return global diagnostics with no associated location. + * + * To contrast the differences between semantic and syntactic diagnostics, consider the + * sentence: "The sun is green." is syntactically correct; those are real English words with + * correct sentence structure. However, it is semantically invalid, because it is not true. + * + * @param fileName A path to the file you want semantic diagnostics for + */ getSemanticDiagnostics(fileName: string): Diagnostic[]; + /** + * Gets suggestion diagnostics for a specific file. These diagnostics tend to + * proactively suggest refactors, as opposed to diagnostics that indicate + * potentially incorrect runtime behavior. + * + * @param fileName A path to the file you want semantic diagnostics for + */ getSuggestionDiagnostics(fileName: string): DiagnosticWithLocation[]; + /** + * Gets global diagnostics related to the program configuration and compiler options. + */ getCompilerOptionsDiagnostics(): Diagnostic[]; - /** - * @deprecated Use getEncodedSyntacticClassifications instead. - */ + /** @deprecated Use getEncodedSyntacticClassifications instead. */ getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; - /** - * @deprecated Use getEncodedSemanticClassifications instead. - */ + /** @deprecated Use getEncodedSemanticClassifications instead. */ getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; + /** + * Gets completion entries at a particular position in a file. + * + * @param fileName The path to the file + * @param position A zero-based index of the character where you want the entries + * @param options An object describing how the request was triggered and what kinds + * of code actions can be returned with the completions. + */ getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): WithMetadata | undefined; - getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; + /** + * Gets the extended details for a completion entry retrieved from `getCompletionsAtPosition`. + * + * @param fileName The path to the file + * @param position A zero based index of the character where you want the entries + * @param entryName The name from an existing completion which came from `getCompletionsAtPosition` + * @param formatOptions How should code samples in the completions be formatted, can be undefined for backwards compatibility + * @param source Source code for the current file, can be undefined for backwards compatibility + * @param preferences User settings, can be undefined for backwards compatibility + */ + getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; + /** + * Gets semantic information about the identifier at a particular position in a + * file. Quick info is what you typically see when you hover in an editor. + * + * @param fileName The path to the file + * @param position A zero-based index of the character where you want the quick info + */ getQuickInfoAtPosition(fileName: string, position: number): QuickInfo | undefined; getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan | undefined; getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; @@ -5488,6 +5582,7 @@ declare namespace ts { newLineCharacter?: string; convertTabsToSpaces?: boolean; indentStyle?: IndentStyle; + trimTrailingWhitespace?: boolean; } interface FormatCodeOptions extends EditorOptions { InsertSpaceAfterCommaDelimiter: boolean; @@ -5517,6 +5612,7 @@ declare namespace ts { readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; readonly insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + readonly insertSpaceAfterOpeningAndBeforeClosingEmptyBraces?: boolean; readonly insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; readonly insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; readonly insertSpaceAfterTypeAssertion?: boolean; 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 38f13a0a68..423d4c3161 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 @@ -1,14 +1,14 @@ /*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - +License at http://www.apache.org/licenses/LICENSE-2.0 + THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ @@ -242,9 +242,9 @@ var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "3.8"; + ts.versionMajorMinor = "3.9"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".2"; + ts.version = "3.9.3"; /** * Returns the native Map implementation if it is available and compatible (i.e. supports iteration). */ @@ -1030,6 +1030,18 @@ var ts; return to; } ts.append = append; + function combine(xs, ys) { + if (xs === undefined) + return ys; + if (ys === undefined) + return xs; + if (isArray(xs)) + return isArray(ys) ? concatenate(xs, ys) : append(xs, ys); + if (isArray(ys)) + return append(ys, xs); + return [xs, ys]; + } + ts.combine = combine; /** * Gets the actual offset into an array for a relative offset. Negative offsets indicate a * position offset from the end of the array. @@ -1489,6 +1501,10 @@ var ts; } } } + function createUnderscoreEscapedMultiMap() { + return createMultiMap(); + } + ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap; /** * Tests whether a value is an array. */ @@ -2164,54 +2180,68 @@ var ts; } } } + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + ts.padLeft = padLeft; + function padRight(s, length) { + while (s.length < length) { + s = s + " "; + } + return s; + } + ts.padRight = padRight; })(ts || (ts = {})); /* @internal */ var ts; (function (ts) { var Debug; (function (Debug) { - /* eslint-disable prefer-const */ - Debug.currentAssertionLevel = 0 /* None */; + var currentAssertionLevel = 0 /* None */; + // eslint-disable-next-line prefer-const Debug.isDebugging = false; - /* eslint-enable prefer-const */ + var assertionCache = {}; + function getAssertionLevel() { + return currentAssertionLevel; + } + Debug.getAssertionLevel = getAssertionLevel; + function setAssertionLevel(level) { + var prevAssertionLevel = currentAssertionLevel; + currentAssertionLevel = level; + if (level > prevAssertionLevel) { + // restore assertion functions for the current assertion level (see `shouldAssertFunction`). + for (var _i = 0, _a = ts.getOwnKeys(assertionCache); _i < _a.length; _i++) { + var key = _a[_i]; + var cachedFunc = assertionCache[key]; + if (cachedFunc !== undefined && Debug[key] !== cachedFunc.assertion && level >= cachedFunc.level) { + Debug[key] = cachedFunc; + assertionCache[key] = undefined; + } + } + } + } + Debug.setAssertionLevel = setAssertionLevel; function shouldAssert(level) { - return Debug.currentAssertionLevel >= level; + return currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; - function assert(expression, message, verboseDebugInfo, stackCrawlMark) { - if (!expression) { - if (verboseDebugInfo) { - message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); - } - fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); + /** + * Tests whether an assertion function should be executed. If it shouldn't, it is cached and replaced with `ts.noop`. + * Replaced assertion functions are restored when `Debug.setAssertionLevel` is set to a high enough level. + * @param level The minimum assertion level required. + * @param name The name of the current assertion function. + */ + function shouldAssertFunction(level, name) { + if (!shouldAssert(level)) { + assertionCache[name] = { level: level, assertion: Debug[name] }; + Debug[name] = ts.noop; + return false; } + return true; } - Debug.assert = assert; - function assertEqual(a, b, msg, msg2) { - if (a !== b) { - var message = msg ? msg2 ? msg + " " + msg2 : msg : ""; - fail("Expected " + a + " === " + b + ". " + message); - } - } - Debug.assertEqual = assertEqual; - function assertLessThan(a, b, msg) { - if (a >= b) { - fail("Expected " + a + " < " + b + ". " + (msg || "")); - } - } - Debug.assertLessThan = assertLessThan; - function assertLessThanOrEqual(a, b) { - if (a > b) { - fail("Expected " + a + " <= " + b); - } - } - Debug.assertLessThanOrEqual = assertLessThanOrEqual; - function assertGreaterThanOrEqual(a, b) { - if (a < b) { - fail("Expected " + a + " >= " + b); - } - } - Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual; function fail(message, stackCrawlMark) { debugger; var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); @@ -2221,27 +2251,121 @@ var ts; throw e; } Debug.fail = fail; - function assertDefined(value, message) { + function failBadSyntaxKind(node, message, stackCrawlMark) { + return fail((message || "Unexpected node.") + "\r\nNode " + formatSyntaxKind(node.kind) + " was unexpected.", stackCrawlMark || failBadSyntaxKind); + } + Debug.failBadSyntaxKind = failBadSyntaxKind; + function assert(expression, message, verboseDebugInfo, stackCrawlMark) { + if (!expression) { + message = message ? "False expression: " + message : "False expression."; + if (verboseDebugInfo) { + message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); + } + fail(message, stackCrawlMark || assert); + } + } + Debug.assert = assert; + function assertEqual(a, b, msg, msg2, stackCrawlMark) { + if (a !== b) { + var message = msg ? msg2 ? msg + " " + msg2 : msg : ""; + fail("Expected " + a + " === " + b + ". " + message, stackCrawlMark || assertEqual); + } + } + Debug.assertEqual = assertEqual; + function assertLessThan(a, b, msg, stackCrawlMark) { + if (a >= b) { + fail("Expected " + a + " < " + b + ". " + (msg || ""), stackCrawlMark || assertLessThan); + } + } + Debug.assertLessThan = assertLessThan; + function assertLessThanOrEqual(a, b, stackCrawlMark) { + if (a > b) { + fail("Expected " + a + " <= " + b, stackCrawlMark || assertLessThanOrEqual); + } + } + Debug.assertLessThanOrEqual = assertLessThanOrEqual; + function assertGreaterThanOrEqual(a, b, stackCrawlMark) { + if (a < b) { + fail("Expected " + a + " >= " + b, stackCrawlMark || assertGreaterThanOrEqual); + } + } + Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual; + function assertIsDefined(value, message, stackCrawlMark) { // eslint-disable-next-line no-null/no-null - if (value === undefined || value === null) - return fail(message); + if (value === undefined || value === null) { + fail(message, stackCrawlMark || assertIsDefined); + } + } + Debug.assertIsDefined = assertIsDefined; + function checkDefined(value, message, stackCrawlMark) { + assertIsDefined(value, message, stackCrawlMark || checkDefined); return value; } - Debug.assertDefined = assertDefined; - function assertEachDefined(value, message) { + Debug.checkDefined = checkDefined; + /** + * @deprecated Use `checkDefined` to check whether a value is defined inline. Use `assertIsDefined` to check whether + * a value is defined at the statement level. + */ + Debug.assertDefined = checkDefined; + function assertEachIsDefined(value, message, stackCrawlMark) { for (var _i = 0, value_1 = value; _i < value_1.length; _i++) { var v = value_1[_i]; - assertDefined(v, message); + assertIsDefined(v, message, stackCrawlMark || assertEachIsDefined); } + } + Debug.assertEachIsDefined = assertEachIsDefined; + function checkEachDefined(value, message, stackCrawlMark) { + assertEachIsDefined(value, message, stackCrawlMark || checkEachDefined); return value; } - Debug.assertEachDefined = assertEachDefined; + Debug.checkEachDefined = checkEachDefined; + /** + * @deprecated Use `checkEachDefined` to check whether the elements of an array are defined inline. Use `assertEachIsDefined` to check whether + * the elements of an array are defined at the statement level. + */ + Debug.assertEachDefined = checkEachDefined; function assertNever(member, message, stackCrawlMark) { if (message === void 0) { message = "Illegal value:"; } var detail = typeof member === "object" && ts.hasProperty(member, "kind") && ts.hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind(member.kind) : JSON.stringify(member); return fail(message + " " + detail, stackCrawlMark || assertNever); } Debug.assertNever = assertNever; + function assertEachNode(nodes, test, message, stackCrawlMark) { + if (shouldAssertFunction(1 /* Normal */, "assertEachNode")) { + assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertEachNode); + } + } + Debug.assertEachNode = assertEachNode; + function assertNode(node, test, message, stackCrawlMark) { + if (shouldAssertFunction(1 /* Normal */, "assertNode")) { + assert(node !== undefined && (test === undefined || test(node)), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertNode); + } + } + Debug.assertNode = assertNode; + function assertNotNode(node, test, message, stackCrawlMark) { + if (shouldAssertFunction(1 /* Normal */, "assertNotNode")) { + assert(node === undefined || test === undefined || !test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " should not have passed test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertNotNode); + } + } + Debug.assertNotNode = assertNotNode; + function assertOptionalNode(node, test, message, stackCrawlMark) { + if (shouldAssertFunction(1 /* Normal */, "assertOptionalNode")) { + assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertOptionalNode); + } + } + Debug.assertOptionalNode = assertOptionalNode; + function assertOptionalToken(node, kind, message, stackCrawlMark) { + if (shouldAssertFunction(1 /* Normal */, "assertOptionalToken")) { + assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was not a '" + formatSyntaxKind(kind) + "' token."; }, stackCrawlMark || assertOptionalToken); + } + } + Debug.assertOptionalToken = assertOptionalToken; + function assertMissingNode(node, message, stackCrawlMark) { + if (shouldAssertFunction(1 /* Normal */, "assertMissingNode")) { + assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, stackCrawlMark || assertMissingNode); + } + } + Debug.assertMissingNode = assertMissingNode; function getFunctionName(func) { if (typeof func !== "function") { return ""; @@ -2339,28 +2463,6 @@ var ts; return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true); } Debug.formatObjectFlags = formatObjectFlags; - function failBadSyntaxKind(node, message) { - return fail((message || "Unexpected node.") + "\r\nNode " + formatSyntaxKind(node.kind) + " was unexpected.", failBadSyntaxKind); - } - Debug.failBadSyntaxKind = failBadSyntaxKind; - Debug.assertEachNode = shouldAssert(1 /* Normal */) - ? function (nodes, test, message) { return assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }, Debug.assertEachNode); } - : ts.noop; - Debug.assertNode = shouldAssert(1 /* Normal */) - ? function (node, test, message) { return assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, Debug.assertNode); } - : ts.noop; - Debug.assertNotNode = shouldAssert(1 /* Normal */) - ? function (node, test, message) { return assert(test === undefined || !test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " should not have passed test '" + getFunctionName(test) + "'."; }, Debug.assertNode); } - : ts.noop; - Debug.assertOptionalNode = shouldAssert(1 /* Normal */) - ? function (node, test, message) { return assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, Debug.assertOptionalNode); } - : ts.noop; - Debug.assertOptionalToken = shouldAssert(1 /* Normal */) - ? function (node, kind, message) { return assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was not a '" + formatSyntaxKind(kind) + "' token."; }, Debug.assertOptionalToken); } - : ts.noop; - Debug.assertMissingNode = shouldAssert(1 /* Normal */) - ? function (node, message) { return assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } - : ts.noop; var isDebugInfoEnabled = false; var extendedDebugModule; function extendedDebug() { @@ -2646,7 +2748,7 @@ var ts; if (prerelease === void 0) { prerelease = ""; } if (build === void 0) { build = ""; } if (typeof major === "string") { - var result = ts.Debug.assertDefined(tryParseComponents(major), "Invalid version"); + var result = ts.Debug.checkDefined(tryParseComponents(major), "Invalid version"); (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build); } ts.Debug.assert(major >= 0, "Invalid argument: major"); @@ -2777,7 +2879,7 @@ var ts; */ var VersionRange = /** @class */ (function () { function VersionRange(spec) { - this._alternatives = spec ? ts.Debug.assertDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; + this._alternatives = spec ? ts.Debug.checkDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray; } VersionRange.tryParse = function (text) { var sets = parseRange(text); @@ -3317,32 +3419,33 @@ var ts; SyntaxKind[SyntaxKind["JSDocSignature"] = 305] = "JSDocSignature"; SyntaxKind[SyntaxKind["JSDocTag"] = 306] = "JSDocTag"; SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 307] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 308] = "JSDocAuthorTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 309] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocPublicTag"] = 310] = "JSDocPublicTag"; - SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 311] = "JSDocPrivateTag"; - SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 312] = "JSDocProtectedTag"; - SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 313] = "JSDocReadonlyTag"; - SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 314] = "JSDocCallbackTag"; - SyntaxKind[SyntaxKind["JSDocEnumTag"] = 315] = "JSDocEnumTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 316] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 317] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocThisTag"] = 318] = "JSDocThisTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 319] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 320] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 321] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 322] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 308] = "JSDocImplementsTag"; + SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 309] = "JSDocAuthorTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 310] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocPublicTag"] = 311] = "JSDocPublicTag"; + SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 312] = "JSDocPrivateTag"; + SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 313] = "JSDocProtectedTag"; + SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 314] = "JSDocReadonlyTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 315] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocEnumTag"] = 316] = "JSDocEnumTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 317] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 318] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 319] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 320] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 321] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 322] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 323] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 323] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 324] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 324] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 325] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 326] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 327] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 328] = "EndOfDeclarationMarker"; - SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 329] = "SyntheticReferenceExpression"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 325] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 326] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 327] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 328] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 329] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 330] = "SyntheticReferenceExpression"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 330] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 331] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 62] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 74] = "LastAssignment"; @@ -3372,9 +3475,9 @@ var ts; SyntaxKind[SyntaxKind["LastStatement"] = 241] = "LastStatement"; SyntaxKind[SyntaxKind["FirstNode"] = 153] = "FirstNode"; SyntaxKind[SyntaxKind["FirstJSDocNode"] = 294] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 322] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 323] = "LastJSDocNode"; SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 306] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 322] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 323] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 122] = "FirstContextualKeyword"; /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 152] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); @@ -3507,6 +3610,8 @@ var ts; /* @internal */ TokenFlags[TokenFlags["UnicodeEscape"] = 1024] = "UnicodeEscape"; /* @internal */ + TokenFlags[TokenFlags["ContainsInvalidEscape"] = 2048] = "ContainsInvalidEscape"; + /* @internal */ TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; /* @internal */ TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; @@ -3524,13 +3629,18 @@ var ts; FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause"; FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation"; FlowFlags[FlowFlags["Call"] = 512] = "Call"; - FlowFlags[FlowFlags["Referenced"] = 1024] = "Referenced"; - FlowFlags[FlowFlags["Shared"] = 2048] = "Shared"; - FlowFlags[FlowFlags["PreFinally"] = 4096] = "PreFinally"; - FlowFlags[FlowFlags["AfterFinally"] = 8192] = "AfterFinally"; + FlowFlags[FlowFlags["ReduceLabel"] = 1024] = "ReduceLabel"; + FlowFlags[FlowFlags["Referenced"] = 2048] = "Referenced"; + FlowFlags[FlowFlags["Shared"] = 4096] = "Shared"; FlowFlags[FlowFlags["Label"] = 12] = "Label"; FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); + /* @internal */ + var CommentDirectiveType; + (function (CommentDirectiveType) { + CommentDirectiveType[CommentDirectiveType["ExpectError"] = 0] = "ExpectError"; + CommentDirectiveType[CommentDirectiveType["Ignore"] = 1] = "Ignore"; + })(CommentDirectiveType = ts.CommentDirectiveType || (ts.CommentDirectiveType = {})); var OperationCanceledException = /** @class */ (function () { function OperationCanceledException() { } @@ -3605,6 +3715,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; + NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; // Error handling NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral"; NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier"; @@ -3643,6 +3754,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers"; TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope"; TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType"; + TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction"; // Error Handling TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; // TypeFormatFlags exclusive @@ -3654,7 +3766,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 277904747] = "NodeBuilderFlagsMask"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -3832,6 +3944,9 @@ var ts; CheckFlags[CheckFlags["OptionalParameter"] = 16384] = "OptionalParameter"; CheckFlags[CheckFlags["RestParameter"] = 32768] = "RestParameter"; CheckFlags[CheckFlags["DeferredType"] = 65536] = "DeferredType"; + CheckFlags[CheckFlags["HasNeverType"] = 131072] = "HasNeverType"; + CheckFlags[CheckFlags["Mapped"] = 262144] = "Mapped"; + CheckFlags[CheckFlags["StripOptional"] = 524288] = "StripOptional"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; CheckFlags[CheckFlags["Discriminant"] = 192] = "Discriminant"; CheckFlags[CheckFlags["Partial"] = 48] = "Partial"; @@ -3948,6 +4063,8 @@ var ts; TypeFlags[TypeFlags["ObjectFlagsType"] = 3899393] = "ObjectFlagsType"; /* @internal */ TypeFlags[TypeFlags["Simplifiable"] = 25165824] = "Simplifiable"; + /* @internal */ + TypeFlags[TypeFlags["Substructure"] = 66584576] = "Substructure"; // '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"; @@ -3956,19 +4073,16 @@ var ts; TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion"; // The following flags are aggregated during union and intersection type construction /* @internal */ - TypeFlags[TypeFlags["IncludesMask"] = 68943871] = "IncludesMask"; + TypeFlags[TypeFlags["IncludesMask"] = 71041023] = "IncludesMask"; // The following flags are used for different purposes during union and intersection type construction /* @internal */ TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable"; /* @internal */ - TypeFlags[TypeFlags["IncludesNonWideningType"] = 2097152] = "IncludesNonWideningType"; + TypeFlags[TypeFlags["IncludesNonWideningType"] = 4194304] = "IncludesNonWideningType"; /* @internal */ - TypeFlags[TypeFlags["IncludesWildcard"] = 4194304] = "IncludesWildcard"; + TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard"; /* @internal */ - TypeFlags[TypeFlags["IncludesEmptyObject"] = 8388608] = "IncludesEmptyObject"; - // The following flag is used for different purposes by maybeTypeOfKind - /* @internal */ - TypeFlags[TypeFlags["GenericMappedType"] = 131072] = "GenericMappedType"; + TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); var ObjectFlags; (function (ObjectFlags) { @@ -3998,6 +4112,24 @@ var ts; ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral"; /* @internal */ ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType"; + /* @internal */ + ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType"; + /* @internal */ + ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType"; + /* @internal */ + ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables"; + /* @internal */ + ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed"; + /* @internal */ + ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection"; ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface"; /* @internal */ ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening"; @@ -4037,6 +4169,7 @@ var ts; SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes"; SignatureFlags[SignatureFlags["IsInnerCallChain"] = 4] = "IsInnerCallChain"; SignatureFlags[SignatureFlags["IsOuterCallChain"] = 8] = "IsOuterCallChain"; + SignatureFlags[SignatureFlags["IsUntypedSignatureInJSFile"] = 16] = "IsUntypedSignatureInJSFile"; // We do not propagate `IsInnerCallChain` to instantiated signatures, as that would result in us // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when // instantiating the return type. @@ -4048,6 +4181,15 @@ var ts; IndexKind[IndexKind["String"] = 0] = "String"; IndexKind[IndexKind["Number"] = 1] = "Number"; })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); + /* @internal */ + var TypeMapKind; + (function (TypeMapKind) { + TypeMapKind[TypeMapKind["Simple"] = 0] = "Simple"; + TypeMapKind[TypeMapKind["Array"] = 1] = "Array"; + TypeMapKind[TypeMapKind["Function"] = 2] = "Function"; + TypeMapKind[TypeMapKind["Composite"] = 3] = "Composite"; + TypeMapKind[TypeMapKind["Merged"] = 4] = "Merged"; + })(TypeMapKind = ts.TypeMapKind || (ts.TypeMapKind = {})); var InferencePriority; (function (InferencePriority) { InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; @@ -4469,6 +4611,7 @@ var ts; EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper"; + /*@internal*/ EmitFlags[EmitFlags["IgnoreSourceNewlines"] = 134217728] = "IgnoreSourceNewlines"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); /** * Used by the checker, this enum keeps track of external emit helpers that should be type @@ -4497,8 +4640,9 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 131072] = "MakeTemplateObject"; ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldGet"] = 262144] = "ClassPrivateFieldGet"; ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldSet"] = 524288] = "ClassPrivateFieldSet"; + ExternalEmitHelpers[ExternalEmitHelpers["CreateBinding"] = 1048576] = "CreateBinding"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 524288] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 1048576] = "LastEmitHelper"; // Helpers included by ES2015 for..of ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; // Helpers included by ES2017 for..await..of @@ -4520,6 +4664,13 @@ var ts; EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement"; EmitHint[EmitHint["JsxAttributeValue"] = 6] = "JsxAttributeValue"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + /* @internal */ + var LexicalEnvironmentFlags; + (function (LexicalEnvironmentFlags) { + LexicalEnvironmentFlags[LexicalEnvironmentFlags["None"] = 0] = "None"; + LexicalEnvironmentFlags[LexicalEnvironmentFlags["InParameters"] = 1] = "InParameters"; + LexicalEnvironmentFlags[LexicalEnvironmentFlags["VariablesHoistedInParameters"] = 2] = "VariablesHoistedInParameters"; // a temp variable was hoisted while visiting a parameter list + })(LexicalEnvironmentFlags = ts.LexicalEnvironmentFlags || (ts.LexicalEnvironmentFlags = {})); /*@internal*/ var BundleFileSectionKind; (function (BundleFileSectionKind) { @@ -4569,6 +4720,7 @@ var ts; ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments"; ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty"; ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement"; + ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList"; // Precomputed Formats ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers"; ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses"; @@ -4601,7 +4753,7 @@ var ts; ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements"; ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes"; ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements"; - ListFormat[ListFormat["Decorators"] = 49153] = "Decorators"; + ListFormat[ListFormat["Decorators"] = 2146305] = "Decorators"; ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments"; ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters"; ListFormat[ListFormat["Parameters"] = 2576] = "Parameters"; @@ -4981,7 +5133,7 @@ var ts; callbacksCache.add(path, callback); return { close: function () { - var watcher = ts.Debug.assertDefined(cache.get(path)); + var watcher = ts.Debug.checkDefined(cache.get(path)); callbacksCache.remove(path, callback); watcher.refCount--; if (watcher.refCount) @@ -5079,7 +5231,7 @@ var ts; return { dirName: dirName, close: function () { - var directoryWatcher = ts.Debug.assertDefined(cache.get(dirPath)); + var directoryWatcher = ts.Debug.checkDefined(cache.get(dirPath)); if (callbackToAdd) callbackCache.remove(dirPath, callbackToAdd); directoryWatcher.refCount--; @@ -5266,7 +5418,7 @@ var ts; }; function watchFile(fileName, callback, pollingInterval, options) { options = updateOptionsForWatchFile(options, useNonPollingWatchers); - var watchFileKind = ts.Debug.assertDefined(options.watchFile); + var watchFileKind = ts.Debug.checkDefined(options.watchFile); switch (watchFileKind) { case ts.WatchFileKind.FixedPollingInterval: return pollingWatchFile(fileName, callback, PollingInterval.Low, /*options*/ undefined); @@ -5346,7 +5498,7 @@ var ts; function nonRecursiveWatchDirectory(directoryName, callback, recursive, options) { ts.Debug.assert(!recursive); options = updateOptionsForWatchDirectory(options); - var watchDirectoryKind = ts.Debug.assertDefined(options.watchDirectory); + var watchDirectoryKind = ts.Debug.checkDefined(options.watchDirectory); switch (watchDirectoryKind) { case ts.WatchDirectoryKind.FixedPollingInterval: return pollingWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, @@ -5526,7 +5678,7 @@ var ts; enableCPUProfiler: enableCPUProfiler, disableCPUProfiler: disableCPUProfiler, realpath: realpath, - debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), + debugMode: !!process.env.NODE_INSPECTOR_IPC || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { try { require("source-map-support").install(); @@ -5952,48 +6104,8 @@ var ts; return hash.digest("hex"); } } - function getChakraSystem() { - var realpath = ChakraHost.realpath && (function (path) { return ChakraHost.realpath(path); }); - return { - newLine: ChakraHost.newLine || "\r\n", - args: ChakraHost.args, - useCaseSensitiveFileNames: !!ChakraHost.useCaseSensitiveFileNames, - write: ChakraHost.echo, - readFile: function (path, _encoding) { - // encoding is automatically handled by the implementation in ChakraHost - return ChakraHost.readFile(path); - }, - writeFile: function (path, data, writeByteOrderMark) { - // If a BOM is required, emit one - if (writeByteOrderMark) { - data = byteOrderMarkIndicator + data; - } - ChakraHost.writeFile(path, data); - }, - resolvePath: ChakraHost.resolvePath, - fileExists: ChakraHost.fileExists, - deleteFile: ChakraHost.deleteFile, - getModifiedTime: ChakraHost.getModifiedTime, - setModifiedTime: ChakraHost.setModifiedTime, - directoryExists: ChakraHost.directoryExists, - createDirectory: ChakraHost.createDirectory, - getExecutingFilePath: function () { return ChakraHost.executingFile; }, - getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, - getDirectories: ChakraHost.getDirectories, - getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), - readDirectory: function (path, extensions, excludes, includes, _depth) { - var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); - return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); - }, - exit: ChakraHost.quit, - realpath: realpath - }; - } var sys; - if (typeof ChakraHost !== "undefined") { - sys = getChakraSystem(); - } - else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { + if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { // process and process.nextTick checks if current environment is node-like // process.browser check excludes webpack and browserify sys = getNodeSystem(); @@ -6006,9 +6118,9 @@ var ts; })(); if (ts.sys && ts.sys.getEnvironmentVariable) { setCustomPollingValues(ts.sys); - ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) ? 1 /* Normal */ - : 0 /* None */; + : 0 /* None */); } if (ts.sys && ts.sys.debugMode) { ts.Debug.isDebugging = true; @@ -6436,6 +6548,7 @@ var ts; * * ```ts * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + * ``` */ function getNormalizedPathComponents(path, currentDirectory) { return reducePathComponents(getPathComponents(path, currentDirectory)); @@ -6680,6 +6793,10 @@ var ts; } } ts.forEachAncestorDirectory = forEachAncestorDirectory; + function isNodeModulesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules"); + } + ts.isNodeModulesDirectory = isNodeModulesDirectory; })(ts || (ts = {})); // // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' @@ -6711,6 +6828,7 @@ var ts; An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + An_index_signature_cannot_have_a_trailing_comma: diag(1025, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_trailing_comma_1025", "An index signature cannot have a trailing comma."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), @@ -6843,6 +6961,7 @@ var ts; Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + export_Asterisk_does_not_re_export_a_default: diag(1195, ts.DiagnosticCategory.Error, "export_Asterisk_does_not_re_export_a_default_1195", "'export *' does not re-export a default."), Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), @@ -6974,6 +7093,10 @@ var ts; Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1378, ts.DiagnosticCategory.Error, "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_t_1378", "Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type: diag(1379, ts.DiagnosticCategory.Error, "An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type_1379", "An import alias cannot reference a declaration that was exported using 'export type'."), An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type: diag(1380, ts.DiagnosticCategory.Error, "An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type_1380", "An import alias cannot reference a declaration that was imported using 'import type'."), + Unexpected_token_Did_you_mean_or_rbrace: diag(1381, ts.DiagnosticCategory.Error, "Unexpected_token_Did_you_mean_or_rbrace_1381", "Unexpected token. Did you mean `{'}'}` or `}`?"), + Unexpected_token_Did_you_mean_or_gt: diag(1382, ts.DiagnosticCategory.Error, "Unexpected_token_Did_you_mean_or_gt_1382", "Unexpected token. Did you mean `{'>'}` or `>`?"), + Only_named_exports_may_use_export_type: diag(1383, ts.DiagnosticCategory.Error, "Only_named_exports_may_use_export_type_1383", "Only named exports may use 'export type'."), + A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list: diag(1384, ts.DiagnosticCategory.Error, "A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list_1384", "A 'new' expression with type arguments must always be followed by a parenthesized argument list."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -6987,7 +7110,7 @@ var ts; Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."), Module_0_has_no_exported_member_1: diag(2305, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."), File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."), - Cannot_find_module_0: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_2307", "Cannot find module '{0}'."), + Cannot_find_module_0_or_its_corresponding_type_declarations: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_or_its_corresponding_type_declarations_2307", "Cannot find module '{0}' or its corresponding type declarations."), Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."), An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), @@ -7052,8 +7175,8 @@ var ts; A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), - Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), - Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."), + Parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Parameter '{0}' cannot reference identifier '{1}' declared after it."), Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers."), @@ -7078,6 +7201,7 @@ var ts; 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}'."), + constructor_cannot_be_used_as_a_parameter_property_name: diag(2398, ts.DiagnosticCategory.Error, "constructor_cannot_be_used_as_a_parameter_property_name_2398", "'constructor' cannot be used as a parameter property name."), Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."), Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."), Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: diag(2401, ts.DiagnosticCategory.Error, "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."), @@ -7218,7 +7342,6 @@ var ts; Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), - Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_pro_2547", "The type returned by the '{0}()' method of an async iterator must be a promise for a type with a 'value' property."), Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), @@ -7247,6 +7370,7 @@ 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."), + Unused_ts_expect_error_directive: diag(2578, ts.DiagnosticCategory.Error, "Unused_ts_expect_error_directive_2578", "Unused '@ts-expect-error' directive."), 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`."), @@ -7262,6 +7386,10 @@ var ts; 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."), This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag: diag(2594, ts.DiagnosticCategory.Error, "This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the__2594", "This module is declared with using 'export =', and can only be used with a default import when using the '{0}' flag."), + _0_can_only_be_imported_by_using_a_default_import: diag(2595, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_default_import_2595", "'{0}' can only be imported by using a default import."), + _0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2596, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import_2596", "'{0}' can only be imported by turning on the 'esModuleInterop' flag and using a default import."), + _0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import: diag(2597, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import_2597", "'{0}' can only be imported by using a 'require' call or by using a default import."), + _0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2598, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using__2598", "'{0}' can only be imported by using a 'require' call or by turning on the 'esModuleInterop' flag and using a default import."), 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."), @@ -7277,6 +7405,9 @@ var ts; Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), + Type_of_property_0_circularly_references_itself_in_mapped_type_1: diag(2615, ts.DiagnosticCategory.Error, "Type_of_property_0_circularly_references_itself_in_mapped_type_1_2615", "Type of property '{0}' circularly references itself in mapped type '{1}'."), + _0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import: diag(2616, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import_2616", "'{0}' can only be imported by using 'import {1} = require({2})' or a default import."), + _0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import: diag(2617, ts.DiagnosticCategory.Error, "_0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_us_2617", "'{0}' can only be imported by using 'import {1} = require({2})' or by turning on the 'esModuleInterop' flag and using a default import."), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -7359,7 +7490,7 @@ var ts; Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String: diag(2731, ts.DiagnosticCategory.Error, "Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_i_2731", "Implicit conversion of a 'symbol' to a 'string' will fail at runtime. Consider wrapping this expression in 'String(...)'."), Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension: diag(2732, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension_2732", "Cannot find module '{0}'. Consider using '--resolveJsonModule' to import module with '.json' extension"), Property_0_was_also_declared_here: diag(2733, ts.DiagnosticCategory.Error, "Property_0_was_also_declared_here_2733", "Property '{0}' was also declared here."), - It_is_highly_likely_that_you_are_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "It_is_highly_likely_that_you_are_missing_a_semicolon_2734", "It is highly likely that you are missing a semicolon."), + Are_you_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "Are_you_missing_a_semicolon_2734", "Are you missing a semicolon?"), Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1: diag(2735, ts.DiagnosticCategory.Error, "Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1_2735", "Did you mean for '{0}' to be constrained to type 'new (...args: any[]) => {1}'?"), Operator_0_cannot_be_applied_to_type_1: diag(2736, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_type_1_2736", "Operator '{0}' cannot be applied to type '{1}'."), BigInt_literals_are_not_available_when_targeting_lower_than_ES2020: diag(2737, ts.DiagnosticCategory.Error, "BigInt_literals_are_not_available_when_targeting_lower_than_ES2020_2737", "BigInt literals are not available when targeting lower than ES2020."), @@ -7374,7 +7505,7 @@ var ts; 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."), + _0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0: diag(2749, ts.DiagnosticCategory.Error, "_0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0_2749", "'{0}' refers to a value, but is being used as a type here. Did you mean 'typeof {0}'?"), 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."), @@ -7408,6 +7539,13 @@ var ts; The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access: diag(2780, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access_2780", "The left-hand side of a 'for...in' statement may not be an optional property access."), The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access: diag(2781, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access_2781", "The left-hand side of a 'for...of' statement may not be an optional property access."), _0_needs_an_explicit_type_annotation: diag(2782, ts.DiagnosticCategory.Message, "_0_needs_an_explicit_type_annotation_2782", "'{0}' needs an explicit type annotation."), + _0_is_specified_more_than_once_so_this_usage_will_be_overwritten: diag(2783, ts.DiagnosticCategory.Error, "_0_is_specified_more_than_once_so_this_usage_will_be_overwritten_2783", "'{0}' is specified more than once, so this usage will be overwritten."), + get_and_set_accessors_cannot_declare_this_parameters: diag(2784, ts.DiagnosticCategory.Error, "get_and_set_accessors_cannot_declare_this_parameters_2784", "'get' and 'set' accessors cannot declare 'this' parameters."), + This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."), + _0_cannot_be_used_as_a_JSX_component: diag(2786, ts.DiagnosticCategory.Error, "_0_cannot_be_used_as_a_JSX_component_2786", "'{0}' cannot be used as a JSX component."), + Its_return_type_0_is_not_a_valid_JSX_element: diag(2787, ts.DiagnosticCategory.Error, "Its_return_type_0_is_not_a_valid_JSX_element_2787", "Its return type '{0}' is not a valid JSX element."), + Its_instance_type_0_is_not_a_valid_JSX_element: diag(2788, ts.DiagnosticCategory.Error, "Its_instance_type_0_is_not_a_valid_JSX_element_2788", "Its instance type '{0}' is not a valid JSX element."), + Its_element_type_0_is_not_a_valid_JSX_element: diag(2789, ts.DiagnosticCategory.Error, "Its_element_type_0_is_not_a_valid_JSX_element_2789", "Its element type '{0}' is not a valid JSX element."), 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}'."), @@ -7542,6 +7680,8 @@ var ts; Unknown_watch_option_0_Did_you_mean_1: diag(5079, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_Did_you_mean_1_5079", "Unknown watch option '{0}'. Did you mean '{1}'?"), Watch_option_0_requires_a_value_of_type_1: diag(5080, ts.DiagnosticCategory.Error, "Watch_option_0_requires_a_value_of_type_1_5080", "Watch option '{0}' requires a value of type {1}."), Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0: diag(5081, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_current_directory_Colon_0_5081", "Cannot find a tsconfig.json file at the current directory: {0}."), + _0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1: diag(5082, ts.DiagnosticCategory.Error, "_0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1_5082", "'{0}' could be instantiated with an arbitrary type which could be unrelated to '{1}'."), + Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -7595,7 +7735,7 @@ var ts; File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, ts.DiagnosticCategory.Error, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."), Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, ts.DiagnosticCategory.Message, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."), NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"), - Option_0_can_only_be_specified_in_tsconfig_json_file: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", "Option '{0}' can only be specified in 'tsconfig.json' file."), + Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line_6064", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'null' on command line."), Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."), Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."), Enables_experimental_support_for_ES7_async_functions: diag(6068, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_async_functions_6068", "Enables experimental support for ES7 async functions."), @@ -7756,6 +7896,11 @@ var ts; Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling'."), Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority'."), Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively: diag(6228, ts.DiagnosticCategory.Message, "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6228", "Synchronously call callbacks and update the state of directory watchers on platforms that don't support recursive watching natively."), + Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3: diag(6229, ts.DiagnosticCategory.Error, "Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3_6229", "Tag '{0}' expects at least '{1}' arguments, but the JSX factory '{2}' provides at most '{3}'."), + Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line: diag(6230, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line_6230", "Option '{0}' can only be specified in 'tsconfig.json' file or set to 'false' or 'null' on command line."), + Could_not_resolve_the_path_0_with_the_extensions_Colon_1: diag(6231, ts.DiagnosticCategory.Error, "Could_not_resolve_the_path_0_with_the_extensions_Colon_1_6231", "Could not resolve the path '{0}' with the extensions: {1}."), + Declaration_augments_declaration_in_another_file_This_cannot_be_serialized: diag(6232, ts.DiagnosticCategory.Error, "Declaration_augments_declaration_in_another_file_This_cannot_be_serialized_6232", "Declaration augments declaration in another file. This cannot be serialized."), + This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file: diag(6233, ts.DiagnosticCategory.Error, "This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_fil_6233", "This is the declaration being augmented. Consider moving the augmenting declaration into the same file."), Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), @@ -7952,6 +8097,7 @@ var ts; Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), + Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"), Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), @@ -8017,6 +8163,8 @@ var ts; Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"), Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"), + Add_missing_call_parentheses: diag(95067, ts.DiagnosticCategory.Message, "Add_missing_call_parentheses_95067", "Add missing call parentheses"), + Add_all_missing_call_parentheses: diag(95068, ts.DiagnosticCategory.Message, "Add_all_missing_call_parentheses_95068", "Add all missing call parentheses"), Add_unknown_conversion_for_non_overlapping_types: diag(95069, ts.DiagnosticCategory.Message, "Add_unknown_conversion_for_non_overlapping_types_95069", "Add 'unknown' conversion for non-overlapping types"), Add_unknown_to_all_conversions_of_non_overlapping_types: diag(95070, ts.DiagnosticCategory.Message, "Add_unknown_to_all_conversions_of_non_overlapping_types_95070", "Add 'unknown' to all conversions of non-overlapping types"), Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), @@ -8048,6 +8196,23 @@ var ts; Add_export_to_make_this_file_into_a_module: diag(95097, ts.DiagnosticCategory.Message, "Add_export_to_make_this_file_into_a_module_95097", "Add 'export {}' to make this file into a module"), Set_the_target_option_in_your_configuration_file_to_0: diag(95098, ts.DiagnosticCategory.Message, "Set_the_target_option_in_your_configuration_file_to_0_95098", "Set the 'target' option in your configuration file to '{0}'"), Set_the_module_option_in_your_configuration_file_to_0: diag(95099, ts.DiagnosticCategory.Message, "Set_the_module_option_in_your_configuration_file_to_0_95099", "Set the 'module' option in your configuration file to '{0}'"), + Convert_invalid_character_to_its_html_entity_code: diag(95100, ts.DiagnosticCategory.Message, "Convert_invalid_character_to_its_html_entity_code_95100", "Convert invalid character to its html entity code"), + Convert_all_invalid_characters_to_HTML_entity_code: diag(95101, ts.DiagnosticCategory.Message, "Convert_all_invalid_characters_to_HTML_entity_code_95101", "Convert all invalid characters to HTML entity code"), + Add_class_tag: diag(95102, ts.DiagnosticCategory.Message, "Add_class_tag_95102", "Add '@class' tag"), + Add_this_tag: diag(95103, ts.DiagnosticCategory.Message, "Add_this_tag_95103", "Add '@this' tag"), + Add_this_parameter: diag(95104, ts.DiagnosticCategory.Message, "Add_this_parameter_95104", "Add 'this' parameter."), + Convert_function_expression_0_to_arrow_function: diag(95105, ts.DiagnosticCategory.Message, "Convert_function_expression_0_to_arrow_function_95105", "Convert function expression '{0}' to arrow function"), + Convert_function_declaration_0_to_arrow_function: diag(95106, ts.DiagnosticCategory.Message, "Convert_function_declaration_0_to_arrow_function_95106", "Convert function declaration '{0}' to arrow function"), + Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"), + Wrap_invalid_character_in_an_expression_container: diag(95108, ts.DiagnosticCategory.Message, "Wrap_invalid_character_in_an_expression_container_95108", "Wrap invalid character in an expression container"), + Wrap_all_invalid_characters_in_an_expression_container: diag(95109, ts.DiagnosticCategory.Message, "Wrap_all_invalid_characters_in_an_expression_container_95109", "Wrap all invalid characters in an expression container"), + Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file: diag(95110, ts.DiagnosticCategory.Message, "Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file_95110", "Visit https://aka.ms/tsconfig.json to read more about this file"), + Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"), + Remove_block_body_braces: diag(95112, ts.DiagnosticCategory.Message, "Remove_block_body_braces_95112", "Remove block body braces"), + Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal: diag(95113, ts.DiagnosticCategory.Message, "Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal_95113", "Wrap the following body with parentheses which should be an object literal"), + Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"), + Remove_all_incorrect_body_block_braces: diag(95115, ts.DiagnosticCategory.Message, "Remove_all_incorrect_body_block_braces_95115", "Remove all incorrect body block braces"), + Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -8070,6 +8235,9 @@ var ts; Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."), Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."), An_optional_chain_cannot_contain_private_identifiers: diag(18030, ts.DiagnosticCategory.Error, "An_optional_chain_cannot_contain_private_identifiers_18030", "An optional chain cannot contain private identifiers."), + The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents: diag(18031, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituent_18031", "The intersection '{0}' was reduced to 'never' because property '{1}' has conflicting types in some constituents."), + The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some: diag(18032, ts.DiagnosticCategory.Error, "The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_pr_18032", "The intersection '{0}' was reduced to 'never' because property '{1}' exists in multiple constituents and is private in some."), + Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead: diag(18033, ts.DiagnosticCategory.Error, "Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhau_18033", "Only numeric enums can have computed members, but this expression has type '{0}'. If you do not need exhaustiveness checks, consider using an object literal instead."), }; })(ts || (ts = {})); var ts; @@ -8220,6 +8388,14 @@ var ts; */ var unicodeESNextIdentifierStart = [65, 90, 97, 122, 170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2144, 2154, 2208, 2228, 2230, 2237, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2809, 2809, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3133, 3160, 3162, 3168, 3169, 3200, 3200, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69376, 69404, 69415, 69415, 69424, 69445, 69600, 69622, 69635, 69687, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70751, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71680, 71723, 71840, 71903, 71935, 71935, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 123136, 123180, 123191, 123197, 123214, 123214, 123584, 123627, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101]; var unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2208, 2228, 2230, 2237, 2259, 2273, 2275, 2403, 2406, 2415, 2417, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2556, 2556, 2558, 2558, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2809, 2815, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3168, 3171, 3174, 3183, 3200, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3328, 3331, 3333, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7673, 7675, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43047, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65071, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69376, 69404, 69415, 69415, 69424, 69456, 69600, 69622, 69632, 69702, 69734, 69743, 69759, 69818, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69958, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70096, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70206, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70751, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71680, 71738, 71840, 71913, 71935, 71935, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123584, 123641, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101, 917760, 917999]; + /** + * Test for whether a single line comment's text contains a directive. + */ + var commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/; + /** + * Test for whether a multi-line comment's last line contains a directive. + */ + var commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/; function lookupInUnicodeMap(code, map) { // Bail out quickly if it couldn't possibly be in the map. if (code < map[0]) { @@ -8344,11 +8520,20 @@ var ts; } ts.getLineStarts = getLineStarts; /* @internal */ + function computeLineAndCharacterOfPosition(lineStarts, position) { + var lineNumber = computeLineOfPosition(lineStarts, position); + return { + line: lineNumber, + character: position - lineStarts[lineNumber] + }; + } + ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition; /** + * @internal * We assume the first line starts at position 0 and 'position' is non-negative. */ - function computeLineAndCharacterOfPosition(lineStarts, position) { - var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues); + function computeLineOfPosition(lineStarts, position, lowerBound) { + var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues, lowerBound); if (lineNumber < 0) { // If the actual position was not found, // the binary search returns the 2's-complement of the next line start @@ -8360,12 +8545,22 @@ var ts; lineNumber = ~lineNumber - 1; ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file"); } - return { - line: lineNumber, - character: position - lineStarts[lineNumber] - }; + return lineNumber; } - ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition; + ts.computeLineOfPosition = computeLineOfPosition; + /** @internal */ + function getLinesBetweenPositions(sourceFile, pos1, pos2) { + if (pos1 === pos2) + return 0; + var lineStarts = getLineStarts(sourceFile); + var lower = Math.min(pos1, pos2); + var isNegative = lower === pos2; + var upper = isNegative ? pos1 : pos2; + var lowerLine = computeLineOfPosition(lineStarts, lower); + var upperLine = computeLineOfPosition(lineStarts, upper, lowerLine); + return isNegative ? lowerLine - upperLine : upperLine - lowerLine; + } + ts.getLinesBetweenPositions = getLinesBetweenPositions; function getLineAndCharacterOfPosition(sourceFile, position) { return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position); } @@ -8412,6 +8607,12 @@ var ts; function isDigit(ch) { return ch >= 48 /* _0 */ && ch <= 57 /* _9 */; } + function isHexDigit(ch) { + return isDigit(ch) || ch >= 65 /* A */ && ch <= 70 /* F */ || ch >= 97 /* a */ && ch <= 102 /* f */; + } + function isCodePoint(code) { + return code <= 0x10FFFF; + } /* @internal */ function isOctalDigit(ch) { return ch >= 48 /* _0 */ && ch <= 55 /* _7 */; @@ -8745,20 +8946,22 @@ var ts; ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion); } ts.isIdentifierStart = isIdentifierStart; - function isIdentifierPart(ch, languageVersion) { + function isIdentifierPart(ch, languageVersion, identifierVariant) { return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ || ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ || + // "-" and ":" are valid in JSX Identifiers + (identifierVariant === 1 /* JSX */ ? (ch === 45 /* minus */ || ch === 58 /* colon */) : false) || ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); } ts.isIdentifierPart = isIdentifierPart; /* @internal */ - function isIdentifierText(name, languageVersion) { + function isIdentifierText(name, languageVersion, identifierVariant) { var ch = codePointAt(name, 0); if (!isIdentifierStart(ch, languageVersion)) { return false; } for (var i = charSize(ch); i < name.length; i += charSize(ch)) { - if (!isIdentifierPart(ch = codePointAt(name, i), languageVersion)) { + if (!isIdentifierPart(ch = codePointAt(name, i), languageVersion, identifierVariant)) { return false; } } @@ -8780,6 +8983,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var commentDirectives; var inJSDocType = 0; setText(text, start, length); var scanner = { @@ -8795,10 +8999,12 @@ var ts; isIdentifier: function () { return token === 75 /* Identifier */ || token > 112 /* LastReservedWord */; }, isReservedWord: function () { return token >= 77 /* FirstReservedWord */ && token <= 112 /* LastReservedWord */; }, isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; }, + getCommentDirectives: function () { return commentDirectives; }, getTokenFlags: function () { return tokenFlags; }, reScanGreaterToken: reScanGreaterToken, reScanSlashToken: reScanSlashToken, reScanTemplateToken: reScanTemplateToken, + reScanTemplateHeadOrNoSubstitutionTemplate: reScanTemplateHeadOrNoSubstitutionTemplate, scanJsxIdentifier: scanJsxIdentifier, scanJsxAttributeValue: scanJsxAttributeValue, reScanJsxAttributeValue: reScanJsxAttributeValue, @@ -8809,6 +9015,7 @@ var ts; scanJsDocToken: scanJsDocToken, scan: scan, getText: getText, + clearCommentDirectives: clearCommentDirectives, setText: setText, setScriptTarget: setScriptTarget, setLanguageVariant: setLanguageVariant, @@ -9047,7 +9254,7 @@ var ts; * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or * a literal component of a TemplateExpression. */ - function scanTemplateAndSetTokenValue() { + function scanTemplateAndSetTokenValue(isTaggedTemplate) { var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */; pos++; var start = pos; @@ -9079,7 +9286,7 @@ var ts; // Escape character if (currChar === 92 /* backslash */) { contents += text.substring(start, pos); - contents += scanEscapeSequence(); + contents += scanEscapeSequence(isTaggedTemplate); start = pos; continue; } @@ -9101,7 +9308,8 @@ var ts; tokenValue = contents; return resultingToken; } - function scanEscapeSequence() { + function scanEscapeSequence(isTaggedTemplate) { + var start = pos; pos++; if (pos >= end) { error(ts.Diagnostics.Unexpected_end_of_text); @@ -9111,6 +9319,12 @@ var ts; pos++; switch (ch) { case 48 /* _0 */: + // '\01' + if (isTaggedTemplate && pos < end && isDigit(text.charCodeAt(pos))) { + pos++; + tokenFlags |= 2048 /* ContainsInvalidEscape */; + return text.substring(start, pos); + } return "\0"; case 98 /* b */: return "\b"; @@ -9129,16 +9343,55 @@ var ts; case 34 /* doubleQuote */: return "\""; case 117 /* u */: + if (isTaggedTemplate) { + // '\u' or '\u0' or '\u00' or '\u000' + for (var escapePos = pos; escapePos < pos + 4; escapePos++) { + if (escapePos < end && !isHexDigit(text.charCodeAt(escapePos)) && text.charCodeAt(escapePos) !== 123 /* openBrace */) { + pos = escapePos; + tokenFlags |= 2048 /* ContainsInvalidEscape */; + return text.substring(start, pos); + } + } + } // '\u{DDDDDDDD}' if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) { - tokenFlags |= 8 /* ExtendedUnicodeEscape */; pos++; + // '\u{' + if (isTaggedTemplate && !isHexDigit(text.charCodeAt(pos))) { + tokenFlags |= 2048 /* ContainsInvalidEscape */; + return text.substring(start, pos); + } + if (isTaggedTemplate) { + var savePos = pos; + var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false); + var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1; + // '\u{Not Code Point' or '\u{CodePoint' + if (!isCodePoint(escapedValue) || text.charCodeAt(pos) !== 125 /* closeBrace */) { + tokenFlags |= 2048 /* ContainsInvalidEscape */; + return text.substring(start, pos); + } + else { + pos = savePos; + } + } + tokenFlags |= 8 /* ExtendedUnicodeEscape */; return scanExtendedUnicodeEscape(); } tokenFlags |= 1024 /* UnicodeEscape */; // '\uDDDD' return scanHexadecimalEscape(/*numDigits*/ 4); case 120 /* x */: + if (isTaggedTemplate) { + if (!isHexDigit(text.charCodeAt(pos))) { + tokenFlags |= 2048 /* ContainsInvalidEscape */; + return text.substring(start, pos); + } + else if (!isHexDigit(text.charCodeAt(pos + 1))) { + pos++; + tokenFlags |= 2048 /* ContainsInvalidEscape */; + return text.substring(start, pos); + } + } // '\xDD' return scanHexadecimalEscape(/*numDigits*/ 2); // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence), @@ -9412,7 +9665,7 @@ var ts; tokenValue = scanString(); return token = 10 /* StringLiteral */; case 96 /* backtick */: - return token = scanTemplateAndSetTokenValue(); + return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ false); case 37 /* percent */: if (text.charCodeAt(pos + 1) === 61 /* equals */) { return pos += 2, token = 68 /* PercentEqualsToken */; @@ -9492,6 +9745,7 @@ var ts; } pos++; } + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos); if (skipTrivia) { continue; } @@ -9506,6 +9760,7 @@ var ts; tokenFlags |= 2 /* PrecedingJSDocComment */; } var commentClosed = false; + var lastLineStart = tokenPos; while (pos < end) { var ch_1 = text.charCodeAt(pos); if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { @@ -9513,11 +9768,13 @@ var ts; commentClosed = true; break; } + pos++; if (isLineBreak(ch_1)) { + lastLineStart = pos; tokenFlags |= 1 /* PrecedingLineBreak */; } - pos++; } + commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart); if (!commentClosed) { error(ts.Diagnostics.Asterisk_Slash_expected); } @@ -9846,13 +10103,40 @@ var ts; } return token; } + function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) { + var type = getDirectiveFromComment(text, commentDirectiveRegEx); + if (type === undefined) { + return commentDirectives; + } + return ts.append(commentDirectives, { + range: { pos: lineStart, end: pos }, + type: type, + }); + } + function getDirectiveFromComment(text, commentDirectiveRegEx) { + var match = commentDirectiveRegEx.exec(text); + if (!match) { + return undefined; + } + switch (match[1]) { + case "ts-expect-error": + return 0 /* ExpectError */; + case "ts-ignore": + return 1 /* Ignore */; + } + return undefined; + } /** * Unconditionally back up and scan a template expression portion. */ - function reScanTemplateToken() { + function reScanTemplateToken(isTaggedTemplate) { ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'"); pos = tokenPos; - return token = scanTemplateAndSetTokenValue(); + return token = scanTemplateAndSetTokenValue(isTaggedTemplate); + } + function reScanTemplateHeadOrNoSubstitutionTemplate() { + pos = tokenPos; + return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true); } function reScanJsxToken() { pos = tokenPos = startPos; @@ -9910,6 +10194,12 @@ var ts; } break; } + if (char === 62 /* greaterThan */) { + error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_gt, pos, 1); + } + if (char === 125 /* closeBrace */) { + error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1); + } if (lastNonWhitespace > 0) lastNonWhitespace++; // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces. @@ -10075,6 +10365,7 @@ var ts; var saveToken = token; var saveTokenValue = tokenValue; var saveTokenFlags = tokenFlags; + var saveErrorExpectations = commentDirectives; setText(text, start, length); var result = callback(); end = saveEnd; @@ -10084,6 +10375,7 @@ var ts; token = saveToken; tokenValue = saveTokenValue; tokenFlags = saveTokenFlags; + commentDirectives = saveErrorExpectations; return result; } function lookAhead(callback) { @@ -10095,6 +10387,9 @@ var ts; function getText() { return text; } + function clearCommentDirectives() { + commentDirectives = undefined; + } function setText(newText, start, length) { text = newText || ""; end = length === undefined ? text.length : start + length; @@ -10658,8 +10953,8 @@ var ts; switch (declaration.kind) { case 75 /* Identifier */: return declaration; - case 322 /* JSDocPropertyTag */: - case 316 /* JSDocParameterTag */: { + case 323 /* JSDocPropertyTag */: + case 317 /* JSDocParameterTag */: { var name = declaration.name; if (name.kind === 153 /* QualifiedName */) { return name.right; @@ -10683,9 +10978,9 @@ var ts; return undefined; } } - case 321 /* JSDocTypedefTag */: + case 322 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); - case 315 /* JSDocEnumTag */: + case 316 /* JSDocEnumTag */: return nameForNamelessJSDocTypedef(declaration); case 259 /* ExportAssignment */: { var expression = declaration.expression; @@ -10789,6 +11084,11 @@ var ts; return getFirstJSDocTag(node, isJSDocAugmentsTag); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + /** Gets the JSDoc implements tags for the node if present */ + function getJSDocImplementsTags(node) { + return getAllJSDocTags(node, isJSDocImplementsTag); + } + ts.getJSDocImplementsTags = getJSDocImplementsTags; /** Gets the JSDoc class tag for the node if present */ function getJSDocClassTag(node) { return getFirstJSDocTag(node, isJSDocClassTag); @@ -10881,7 +11181,7 @@ var ts; var sig = ts.find(type.members, isCallSignatureDeclaration); return sig && sig.type; } - if (isFunctionTypeNode(type)) { + if (isFunctionTypeNode(type) || isJSDocFunctionType(type)) { return type.type; } } @@ -10903,7 +11203,12 @@ var ts; function getFirstJSDocTag(node, predicate) { return ts.find(getJSDocTags(node), predicate); } - /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ + /** Gets all JSDoc tags that match a specified predicate */ + function getAllJSDocTags(node, predicate) { + return getJSDocTags(node).filter(predicate); + } + ts.getAllJSDocTags = getAllJSDocTags; + /** Gets all JSDoc tags of a specified kind */ function getAllJSDocTagsOfKind(node, kind) { return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } @@ -11190,12 +11495,13 @@ var ts; return !!(node.flags & 32 /* OptionalChain */) && (kind === 194 /* PropertyAccessExpression */ || kind === 195 /* ElementAccessExpression */ - || kind === 196 /* CallExpression */); + || kind === 196 /* CallExpression */ + || kind === 218 /* NonNullExpression */); } ts.isOptionalChain = isOptionalChain; /* @internal */ function isOptionalChainRoot(node) { - return isOptionalChain(node) && !!node.questionDotToken; + return isOptionalChain(node) && !isNonNullExpression(node) && !!node.questionDotToken; } ts.isOptionalChainRoot = isOptionalChainRoot; /** @@ -11210,17 +11516,18 @@ var ts; * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`: * * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`) - * 2. For `(a?.b.c).d`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.` since parens end the chain) - * 3. For `a?.b.c?.d`, both `a?.b.c` and `a?.b.c?.d` are outermost (`c` is the end of the chain starting at `a?.`, and `d` is + * 2. For `a?.b!`, the outermost chain is `a?.b` (`b` is the end of the chain starting at `a?.`) + * 3. For `(a?.b.c).d`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.` since parens end the chain) + * 4. For `a?.b.c?.d`, both `a?.b.c` and `a?.b.c?.d` are outermost (`c` is the end of the chain starting at `a?.`, and `d` is * the end of the chain starting at `c?.`) - * 4. For `a?.(b?.c).d`, both `b?.c` and `a?.(b?.c)d` are outermost (`c` is the end of the chain starting at `b`, and `d` is + * 5. For `a?.(b?.c).d`, both `b?.c` and `a?.(b?.c)d` are outermost (`c` is the end of the chain starting at `b`, and `d` is * the end of the chain starting at `a?.`) */ /* @internal */ function isOutermostOptionalChain(node) { - return !isOptionalChain(node.parent) // cases 1 and 2 - || isOptionalChainRoot(node.parent) // case 3 - || node !== node.parent.expression; // case 4 + return !isOptionalChain(node.parent) // cases 1, 2, and 3 + || isOptionalChainRoot(node.parent) // case 4 + || node !== node.parent.expression; // case 5 } ts.isOutermostOptionalChain = isOutermostOptionalChain; function isNullishCoalesce(node) { @@ -11249,10 +11556,7 @@ var ts; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 325 /* PartiallyEmittedExpression */) { - node = node.expression; - } - return node; + return ts.skipOuterExpressions(node, 8 /* PartiallyEmittedExpressions */); } ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; function isFunctionExpression(node) { @@ -11327,6 +11631,10 @@ var ts; return node.kind === 218 /* NonNullExpression */; } ts.isNonNullExpression = isNonNullExpression; + function isNonNullChain(node) { + return isNonNullExpression(node) && !!(node.flags & 32 /* OptionalChain */); + } + ts.isNonNullChain = isNonNullChain; function isMetaProperty(node) { return node.kind === 219 /* MetaProperty */; } @@ -11673,67 +11981,71 @@ var ts; } ts.isJSDoc = isJSDoc; function isJSDocAuthorTag(node) { - return node.kind === 308 /* JSDocAuthorTag */; + return node.kind === 309 /* JSDocAuthorTag */; } ts.isJSDocAuthorTag = isJSDocAuthorTag; function isJSDocAugmentsTag(node) { return node.kind === 307 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocImplementsTag(node) { + return node.kind === 308 /* JSDocImplementsTag */; + } + ts.isJSDocImplementsTag = isJSDocImplementsTag; function isJSDocClassTag(node) { - return node.kind === 309 /* JSDocClassTag */; + return node.kind === 310 /* JSDocClassTag */; } ts.isJSDocClassTag = isJSDocClassTag; function isJSDocPublicTag(node) { - return node.kind === 310 /* JSDocPublicTag */; + return node.kind === 311 /* JSDocPublicTag */; } ts.isJSDocPublicTag = isJSDocPublicTag; function isJSDocPrivateTag(node) { - return node.kind === 311 /* JSDocPrivateTag */; + return node.kind === 312 /* JSDocPrivateTag */; } ts.isJSDocPrivateTag = isJSDocPrivateTag; function isJSDocProtectedTag(node) { - return node.kind === 312 /* JSDocProtectedTag */; + return node.kind === 313 /* JSDocProtectedTag */; } ts.isJSDocProtectedTag = isJSDocProtectedTag; function isJSDocReadonlyTag(node) { - return node.kind === 313 /* JSDocReadonlyTag */; + return node.kind === 314 /* JSDocReadonlyTag */; } ts.isJSDocReadonlyTag = isJSDocReadonlyTag; function isJSDocEnumTag(node) { - return node.kind === 315 /* JSDocEnumTag */; + return node.kind === 316 /* JSDocEnumTag */; } ts.isJSDocEnumTag = isJSDocEnumTag; function isJSDocThisTag(node) { - return node.kind === 318 /* JSDocThisTag */; + return node.kind === 319 /* JSDocThisTag */; } ts.isJSDocThisTag = isJSDocThisTag; function isJSDocParameterTag(node) { - return node.kind === 316 /* JSDocParameterTag */; + return node.kind === 317 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 317 /* JSDocReturnTag */; + return node.kind === 318 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 319 /* JSDocTypeTag */; + return node.kind === 320 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 320 /* JSDocTemplateTag */; + return node.kind === 321 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 321 /* JSDocTypedefTag */; + return node.kind === 322 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 322 /* JSDocPropertyTag */; + return node.kind === 323 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 322 /* JSDocPropertyTag */ || node.kind === 316 /* JSDocParameterTag */; + return node.kind === 323 /* JSDocPropertyTag */ || node.kind === 317 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { @@ -11741,7 +12053,7 @@ var ts; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; function isJSDocCallbackTag(node) { - return node.kind === 314 /* JSDocCallbackTag */; + return node.kind === 315 /* JSDocCallbackTag */; } ts.isJSDocCallbackTag = isJSDocCallbackTag; function isJSDocSignature(node) { @@ -11756,7 +12068,7 @@ var ts; // they may be used with transformations. /* @internal */ function isSyntaxList(n) { - return n.kind === 323 /* SyntaxList */; + return n.kind === 324 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -11892,6 +12204,7 @@ var ts; function isPropertyName(node) { var kind = node.kind; return kind === 75 /* Identifier */ + || kind === 76 /* PrivateIdentifier */ || kind === 10 /* StringLiteral */ || kind === 8 /* NumericLiteral */ || kind === 154 /* ComputedPropertyName */; @@ -12228,8 +12541,8 @@ var ts; case 213 /* SpreadElement */: case 217 /* AsExpression */: case 215 /* OmittedExpression */: - case 326 /* CommaListExpression */: - case 325 /* PartiallyEmittedExpression */: + case 327 /* CommaListExpression */: + case 326 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -12243,17 +12556,17 @@ var ts; ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 325 /* PartiallyEmittedExpression */; + return node.kind === 326 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 324 /* NotEmittedStatement */; + return node.kind === 325 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ function isSyntheticReference(node) { - return node.kind === 329 /* SyntheticReferenceExpression */; + return node.kind === 330 /* SyntheticReferenceExpression */; } ts.isSyntheticReference = isSyntheticReference; /* @internal */ @@ -12386,9 +12699,9 @@ var ts; || kind === 247 /* TypeAliasDeclaration */ || kind === 155 /* TypeParameter */ || kind === 242 /* VariableDeclaration */ - || kind === 321 /* JSDocTypedefTag */ - || kind === 314 /* JSDocCallbackTag */ - || kind === 322 /* JSDocPropertyTag */; + || kind === 322 /* JSDocTypedefTag */ + || kind === 315 /* JSDocCallbackTag */ + || kind === 323 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { return kind === 244 /* FunctionDeclaration */ @@ -12423,14 +12736,14 @@ var ts; || kind === 225 /* VariableStatement */ || kind === 229 /* WhileStatement */ || kind === 236 /* WithStatement */ - || kind === 324 /* NotEmittedStatement */ - || kind === 328 /* EndOfDeclarationMarker */ - || kind === 327 /* MergeDeclarationMarker */; + || kind === 325 /* NotEmittedStatement */ + || kind === 329 /* EndOfDeclarationMarker */ + || kind === 328 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { if (node.kind === 155 /* TypeParameter */) { - return (node.parent && node.parent.kind !== 320 /* JSDocTemplateTag */) || ts.isInJSFile(node); + return (node.parent && node.parent.kind !== 321 /* JSDocTemplateTag */) || ts.isInJSFile(node); } return isDeclarationKind(node.kind); } @@ -12525,18 +12838,18 @@ var ts; /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 294 /* FirstJSDocNode */ && node.kind <= 322 /* LastJSDocNode */; + return node.kind >= 294 /* FirstJSDocNode */ && node.kind <= 323 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 303 /* JSDocComment */ || isJSDocTag(node) || isJSDocTypeLiteral(node) || isJSDocSignature(node); + return node.kind === 303 /* JSDocComment */ || node.kind === 302 /* JSDocNamepathType */ || isJSDocTag(node) || isJSDocTypeLiteral(node) || isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 306 /* FirstJSDocTagNode */ && node.kind <= 322 /* LastJSDocTagNode */; + return node.kind >= 306 /* FirstJSDocTagNode */ && node.kind <= 323 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { @@ -12568,9 +12881,19 @@ var ts; } ts.hasInitializer = hasInitializer; /** True if has initializer node attached to it. */ - /* @internal */ function hasOnlyExpressionInitializer(node) { - return hasInitializer(node) && !isForStatement(node) && !isForInStatement(node) && !isForOfStatement(node) && !isJsxAttribute(node); + switch (node.kind) { + case 242 /* VariableDeclaration */: + case 156 /* Parameter */: + case 191 /* BindingElement */: + case 158 /* PropertySignature */: + case 159 /* PropertyDeclaration */: + case 281 /* PropertyAssignment */: + case 284 /* EnumMember */: + return true; + default: + return false; + } } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { @@ -12621,6 +12944,7 @@ var ts; ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; ts.defaultMaximumTruncationLength = 160; + ts.noTruncationMaximumTruncationLength = 1000000; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; if (declarations) { @@ -13037,6 +13361,33 @@ var ts; text.charCodeAt(start + 2) === 33 /* exclamation */; } ts.isPinnedComment = isPinnedComment; + function createCommentDirectivesMap(sourceFile, commentDirectives) { + var directivesByLine = ts.createMapFromEntries(commentDirectives.map(function (commentDirective) { return ([ + "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line, + commentDirective, + ]); })); + var usedLines = ts.createMap(); + return { getUnusedExpectations: getUnusedExpectations, markUsed: markUsed }; + function getUnusedExpectations() { + return ts.arrayFrom(directivesByLine.entries()) + .filter(function (_a) { + var line = _a[0], directive = _a[1]; + return directive.type === 0 /* ExpectError */ && !usedLines.get(line); + }) + .map(function (_a) { + var _ = _a[0], directive = _a[1]; + return directive; + }); + } + function markUsed(line) { + if (!directivesByLine.has("" + line)) { + return false; + } + usedLines.set("" + line, true); + return true; + } + } + ts.createCommentDirectivesMap = createCommentDirectivesMap; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't* // want to skip trivia because this will launch us forward to the next token. @@ -13047,13 +13398,13 @@ var ts; return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } if (includeJsDoc && ts.hasJSDocNodes(node)) { - return getTokenPosOfNode(node.jsDoc[0]); + return getTokenPosOfNode(node.jsDoc[0], sourceFile); } // For a syntax list, it is possible that one of its children has JSDocComment nodes, while // 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 === 323 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 324 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -13311,8 +13662,8 @@ var ts; ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 314 /* JSDocCallbackTag */: - case 321 /* JSDocTypedefTag */: + case 315 /* JSDocCallbackTag */: + case 322 /* JSDocTypedefTag */: case 305 /* JSDocSignature */: return true; default: @@ -13334,7 +13685,7 @@ var ts; case 214 /* ClassExpression */: case 246 /* InterfaceDeclaration */: case 247 /* TypeAliasDeclaration */: - case 320 /* JSDocTemplateTag */: + case 321 /* JSDocTemplateTag */: case 244 /* FunctionDeclaration */: case 161 /* MethodDeclaration */: case 162 /* Constructor */: @@ -13397,6 +13748,10 @@ var ts; return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; } ts.getNameFromIndexInfo = getNameFromIndexInfo; + function isComputedNonLiteralName(name) { + return name.kind === 154 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression); + } + ts.isComputedNonLiteralName = isComputedNonLiteralName; function getTextOfPropertyName(name) { switch (name.kind) { case 75 /* Identifier */: @@ -13417,12 +13772,15 @@ var ts; ts.getTextOfPropertyName = getTextOfPropertyName; function entityNameToString(name) { switch (name.kind) { + case 104 /* ThisKeyword */: + return "this"; + case 76 /* PrivateIdentifier */: case 75 /* Identifier */: return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); case 153 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); case 194 /* PropertyAccessExpression */: - if (ts.isIdentifier(name.name)) { + if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) { return entityNameToString(name.expression) + "." + entityNameToString(name.name); } else { @@ -13462,6 +13820,17 @@ var ts; }; } ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain; + function createDiagnosticForRange(sourceFile, range, message) { + return { + file: sourceFile, + start: range.pos, + length: range.end - range.pos, + code: message.code, + category: message.category, + messageText: message.message, + }; + } + ts.createDiagnosticForRange = createDiagnosticForRange; function getSpanOfTokenAtPosition(sourceFile, pos) { var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos); scanner.scan(); @@ -13589,6 +13958,25 @@ var ts; && node.expression.kind === 10 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; + function isCustomPrologue(node) { + return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */); + } + ts.isCustomPrologue = isCustomPrologue; + function isHoistedFunction(node) { + return isCustomPrologue(node) + && ts.isFunctionDeclaration(node); + } + ts.isHoistedFunction = isHoistedFunction; + function isHoistedVariable(node) { + return ts.isIdentifier(node.name) + && !node.initializer; + } + function isHoistedVariableStatement(node) { + return isCustomPrologue(node) + && ts.isVariableStatement(node) + && ts.every(node.declarationList.declarations, isHoistedVariable); + } + ts.isHoistedVariableStatement = isHoistedVariableStatement; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } @@ -13672,7 +14060,7 @@ var ts; return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); case 155 /* TypeParameter */: return node === parent.constraint; - case 320 /* JSDocTemplateTag */: + case 321 /* JSDocTemplateTag */: return node === parent.constraint; case 159 /* PropertyDeclaration */: case 158 /* PropertySignature */: @@ -14358,6 +14746,15 @@ var ts; return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; + function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) { + return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(node.initializer, requireStringLiteralLikeArgument); + } + ts.isRequireVariableDeclaration = isRequireVariableDeclaration; + function isRequireVariableDeclarationStatement(node, requireStringLiteralLikeArgument) { + if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; } + return ts.isVariableStatement(node) && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); }); + } + ts.isRequireVariableDeclarationStatement = isRequireVariableDeclarationStatement; function isSingleOrDoubleQuote(charCode) { return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */; } @@ -14557,10 +14954,13 @@ var ts; return ts.isIdentifier(node) && node.escapedText === "exports"; } ts.isExportsIdentifier = isExportsIdentifier; + function isModuleIdentifier(node) { + return ts.isIdentifier(node) && node.escapedText === "module"; + } + ts.isModuleIdentifier = isModuleIdentifier; function isModuleExportsAccessExpression(node) { return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node)) - && ts.isIdentifier(node.expression) - && node.expression.escapedText === "module" + && isModuleIdentifier(node.expression) && getElementOrPropertyAccessName(node) === "exports"; } ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression; @@ -14594,7 +14994,7 @@ var ts; ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess; /** Any series of property and element accesses. */ function isBindableStaticAccessExpression(node, excludeThisKeyword) { - return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) + return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) || isBindableStaticElementAccessExpression(node, excludeThisKeyword); } ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression; @@ -14697,7 +15097,7 @@ var ts; // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ... return 1 /* ExportsProperty */; } - if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs) && lhs.expression.kind !== 104 /* ThisKeyword */)) { + if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs))) { // F.G...x = expr return 5 /* Property */; } @@ -14723,6 +15123,17 @@ var ts; !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function setValueDeclaration(symbol, node) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) && + (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; + } + } + ts.setValueDeclaration = setValueDeclaration; function isFunctionSymbol(symbol) { if (!symbol || !symbol.valueDeclaration) { return false; @@ -14821,7 +15232,7 @@ var ts; } ts.isJSDocConstructSignature = isJSDocConstructSignature; function isJSDocTypeAlias(node) { - return node.kind === 321 /* JSDocTypedefTag */ || node.kind === 314 /* JSDocCallbackTag */ || node.kind === 315 /* JSDocEnumTag */; + return node.kind === 322 /* JSDocTypedefTag */ || node.kind === 315 /* JSDocCallbackTag */ || node.kind === 316 /* JSDocEnumTag */; } ts.isJSDocTypeAlias = isJSDocTypeAlias; function isTypeAlias(node) { @@ -14936,21 +15347,24 @@ var ts; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { - return getHostSignatureFromJSDocHost(getJSDocHost(node)); + var host = getEffectiveJSDocHost(node); + return host && ts.isFunctionLike(host) ? host : undefined; } ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; - function getHostSignatureFromJSDocHost(host) { + function getEffectiveJSDocHost(node) { + var host = getJSDocHost(node); var decl = getSourceOfDefaultedAssignment(host) || getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || getSingleVariableOfVariableStatement(host) || getNestedModuleDeclaration(host) || host; - return decl && ts.isFunctionLike(decl) ? decl : undefined; + return decl; } - ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; + ts.getEffectiveJSDocHost = getEffectiveJSDocHost; + /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments. */ function getJSDocHost(node) { - return ts.Debug.assertDefined(findAncestor(node.parent, ts.isJSDoc)).parent; + return ts.Debug.checkDefined(findAncestor(node.parent, ts.isJSDoc)).parent; } ts.getJSDocHost = getJSDocHost; function getTypeParameterFromJsDoc(node) { @@ -15074,10 +15488,7 @@ var ts; } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; function skipParentheses(node) { - while (node.kind === 200 /* ParenthesizedExpression */) { - node = node.expression; - } - return node; + return ts.skipOuterExpressions(node, 1 /* Parentheses */); } ts.skipParentheses = skipParentheses; function skipParenthesesUp(node) { @@ -15264,15 +15675,20 @@ var ts; return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement; - function getClassImplementsHeritageClauseElements(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 113 /* ImplementsKeyword */); - return heritageClause ? heritageClause.types : undefined; + function getEffectiveImplementsTypeNodes(node) { + if (isInJSFile(node)) { + return ts.getJSDocImplementsTags(node).map(function (n) { return n.class; }); + } + else { + var heritageClause = getHeritageClause(node.heritageClauses, 113 /* ImplementsKeyword */); + return heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.types; + } } - ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + ts.getEffectiveImplementsTypeNodes = getEffectiveImplementsTypeNodes; /** Returns the node in an `extends` or `implements` clause of a class or interface. */ function getAllSuperTypeNodes(node) { return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray : - ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray : + ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getEffectiveImplementsTypeNodes(node)) || ts.emptyArray : ts.emptyArray; } ts.getAllSuperTypeNodes = getAllSuperTypeNodes; @@ -15595,7 +16011,7 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 326 /* CommaListExpression */: + case 327 /* CommaListExpression */: return 0; case 213 /* SpreadElement */: return 1; @@ -15787,6 +16203,13 @@ var ts; function escapeTemplateSubstitution(str) { return str.replace(templateSubstitutionRegExp, "\\${"); } + /** @internal */ + function hasInvalidEscape(template) { + return template && !!(ts.isNoSubstitutionTemplateLiteral(template) + ? template.templateFlags + : (template.head.templateFlags || ts.some(template.templateSpans, function (span) { return !!span.literal.templateFlags; }))); + } + ts.hasInvalidEscape = hasInvalidEscape; // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator, // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in // the language service. These characters should be escaped when printing, and if any characters are added, @@ -15795,7 +16218,7 @@ var ts; var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; // Template strings should be preserved as much as possible - var backtickQuoteEscapedCharsRegExp = /[\\\`]/g; + var backtickQuoteEscapedCharsRegExp = /[\\`]/g; var escapedCharsMap = ts.createMapFromTemplate({ "\t": "\\t", "\v": "\\v", @@ -15969,8 +16392,8 @@ var ts; write(s); } } - function writeLine() { - if (!lineStart) { + function writeLine(force) { + if (!lineStart || force) { output += newLine; lineCount++; linePos = output.length; @@ -16081,6 +16504,14 @@ var ts; } }); } ts.getTrailingSemicolonDeferringWriter = getTrailingSemicolonDeferringWriter; + function hostUsesCaseSensitiveFileNames(host) { + return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false; + } + ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames; + function hostGetCanonicalFileName(host) { + return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); + } + ts.hostGetCanonicalFileName = hostGetCanonicalFileName; function getResolvedExternalModuleName(host, file, referenceFile) { return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } @@ -16201,12 +16632,13 @@ var ts; } } ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories; - function getLineOfLocalPosition(currentSourceFile, pos) { - return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; + function getLineOfLocalPosition(sourceFile, pos) { + var lineStarts = ts.getLineStarts(sourceFile); + return ts.computeLineOfPosition(lineStarts, pos); } ts.getLineOfLocalPosition = getLineOfLocalPosition; function getLineOfLocalPositionFromLineMap(lineMap, pos) { - return ts.computeLineAndCharacterOfPosition(lineMap, pos).line; + return ts.computeLineOfPosition(lineMap, pos); } ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; function getFirstConstructorWithBody(node) { @@ -16280,9 +16712,11 @@ var ts; secondAccessor = member; } if (member.kind === 163 /* GetAccessor */ && !getAccessor) { + // eslint-disable-next-line getAccessor = member; } if (member.kind === 164 /* SetAccessor */ && !setAccessor) { + // eslint-disable-next-line setAccessor = member; } } @@ -16555,6 +16989,9 @@ var ts; } ts.getSelectedModifierFlags = getSelectedModifierFlags; function getModifierFlags(node) { + if (node.kind >= 0 /* FirstToken */ && node.kind <= 152 /* LastToken */) { + return 0 /* None */; + } if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) { return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */; } @@ -16676,7 +17113,7 @@ var ts; } ts.isDottedName = isDottedName; function isPropertyAccessEntityNameExpression(node) { - return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression); } ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; function tryGetPropertyAccessOrIdentifierToString(expr) { @@ -16969,7 +17406,7 @@ var ts; } ts.rangeIsOnSingleLine = rangeIsOnSingleLine; function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) { - return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile); + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile); } ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine; function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) { @@ -16977,26 +17414,53 @@ var ts; } ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine; function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) { - return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile); + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), range2.end, sourceFile); } ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd; function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) { - return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile); + return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile); } ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart; + function getLinesBetweenRangeEndAndRangeStart(range1, range2, sourceFile, includeSecondRangeComments) { + var range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments); + return ts.getLinesBetweenPositions(sourceFile, range1.end, range2Start); + } + ts.getLinesBetweenRangeEndAndRangeStart = getLinesBetweenRangeEndAndRangeStart; + function getLinesBetweenRangeEndPositions(range1, range2, sourceFile) { + return ts.getLinesBetweenPositions(sourceFile, range1.end, range2.end); + } + ts.getLinesBetweenRangeEndPositions = getLinesBetweenRangeEndPositions; function isNodeArrayMultiLine(list, sourceFile) { return !positionsAreOnSameLine(list.pos, list.end, sourceFile); } ts.isNodeArrayMultiLine = isNodeArrayMultiLine; function positionsAreOnSameLine(pos1, pos2, sourceFile) { - return pos1 === pos2 || - getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2); + return ts.getLinesBetweenPositions(sourceFile, pos1, pos2) === 0; } ts.positionsAreOnSameLine = positionsAreOnSameLine; - function getStartPositionOfRange(range, sourceFile) { - return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + function getStartPositionOfRange(range, sourceFile, includeComments) { + return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments); } ts.getStartPositionOfRange = getStartPositionOfRange; + function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { + var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments); + var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile); + return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos); + } + ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter; + function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) { + var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments); + return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos)); + } + ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter; + function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) { + if (stopPos === void 0) { stopPos = 0; } + while (pos-- > stopPos) { + if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) { + return pos; + } + } + } /** * Determines whether a name was originally the declaration name of an enum or namespace * declaration. @@ -17288,6 +17752,14 @@ var ts; return node.kind === 194 /* PropertyAccessExpression */ || node.kind === 195 /* ElementAccessExpression */; } ts.isAccessExpression = isAccessExpression; + function getNameOfAccessExpression(node) { + if (node.kind === 194 /* PropertyAccessExpression */) { + return node.name; + } + ts.Debug.assert(node.kind === 195 /* ElementAccessExpression */); + return node.argumentExpression; + } + ts.getNameOfAccessExpression = getNameOfAccessExpression; function isBundleFileTextLike(section) { switch (section.kind) { case "text" /* Text */: @@ -17298,10 +17770,6 @@ var ts; } } ts.isBundleFileTextLike = isBundleFileTextLike; - function getDotOrQuestionDotToken(node) { - return node.questionDotToken || ts.createNode(24 /* DotToken */, node.expression.end, node.name.pos); - } - ts.getDotOrQuestionDotToken = getDotOrQuestionDotToken; function isNamedImportsOrExports(node) { return node.kind === 257 /* NamedImports */ || node.kind === 261 /* NamedExports */; } @@ -17338,6 +17806,26 @@ var ts; this.parent = undefined; this.original = undefined; } + function Token(kind, pos, end) { + this.pos = pos; + this.end = end; + this.kind = kind; + this.id = 0; + this.flags = 0 /* None */; + this.transformFlags = 0 /* None */; + this.parent = undefined; + } + function Identifier(kind, pos, end) { + this.pos = pos; + this.end = end; + this.kind = kind; + this.id = 0; + this.flags = 0 /* None */; + this.transformFlags = 0 /* None */; + this.parent = undefined; + this.original = undefined; + this.flowNode = undefined; + } function SourceMapSource(fileName, text, skipTrivia) { this.fileName = fileName; this.text = text; @@ -17346,8 +17834,8 @@ var ts; // eslint-disable-next-line prefer-const ts.objectAllocator = { getNodeConstructor: function () { return Node; }, - getTokenConstructor: function () { return Node; }, - getIdentifierConstructor: function () { return Node; }, + getTokenConstructor: function () { return Token; }, + getIdentifierConstructor: function () { return Identifier; }, getPrivateIdentifierConstructor: function () { return Node; }, getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, @@ -17361,7 +17849,7 @@ var ts; ts.setObjectAllocator = setObjectAllocator; function formatStringFromArgs(text, args, baseIndex) { if (baseIndex === void 0) { baseIndex = 0; } - return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.assertDefined(args[+index + baseIndex]); }); + return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.checkDefined(args[+index + baseIndex]); }); } ts.formatStringFromArgs = formatStringFromArgs; /* @internal */ @@ -18361,11 +18849,15 @@ var ts; function isValidTypeOnlyAliasUseSite(useSite) { return !!(useSite.flags & 8388608 /* Ambient */) || isPartOfTypeQuery(useSite) - || isFirstIdentifierOfNonEmittingHeritageClause(useSite) + || isIdentifierInNonEmittingHeritageClause(useSite) || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite) || !isExpressionNode(useSite); } ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite; + function typeOnlyDeclarationIsExport(typeOnlyDeclaration) { + return typeOnlyDeclaration.kind === 263 /* ExportSpecifier */; + } + ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport; function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) { while (node.kind === 75 /* Identifier */ || node.kind === 194 /* PropertyAccessExpression */) { node = node.parent; @@ -18379,13 +18871,40 @@ var ts; var containerKind = node.parent.parent.kind; return containerKind === 246 /* InterfaceDeclaration */ || containerKind === 173 /* TypeLiteral */; } - /** Returns true for the first identifier of 1) an `implements` clause, and 2) an `extends` clause of an interface. */ - function isFirstIdentifierOfNonEmittingHeritageClause(node) { - var _a, _b; - // Number of parents to climb from identifier is 2 for `implements I`, 3 for `implements x.I` - var heritageClause = (_a = ts.tryCast(node.parent.parent, ts.isHeritageClause)) !== null && _a !== void 0 ? _a : ts.tryCast((_b = node.parent.parent) === null || _b === void 0 ? void 0 : _b.parent, ts.isHeritageClause); + /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */ + function isIdentifierInNonEmittingHeritageClause(node) { + if (node.kind !== 75 /* Identifier */) + return false; + var heritageClause = findAncestor(node.parent, function (parent) { + switch (parent.kind) { + case 279 /* HeritageClause */: + return true; + case 194 /* PropertyAccessExpression */: + case 216 /* ExpressionWithTypeArguments */: + return false; + default: + return "quit"; + } + }); return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 113 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 246 /* InterfaceDeclaration */; } + function isIdentifierTypeReference(node) { + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName); + } + ts.isIdentifierTypeReference = isIdentifierTypeReference; + function arrayIsHomogeneous(array, comparer) { + if (comparer === void 0) { comparer = ts.equateValues; } + if (array.length < 2) + return true; + var first = array[0]; + for (var i = 1, length_1 = array.length; i < length_1; i++) { + var target = array[i]; + if (!comparer(first, target)) + return false; + } + return true; + } + ts.arrayIsHomogeneous = arrayIsHomogeneous; })(ts || (ts = {})); var ts; (function (ts) { @@ -18814,7 +19333,7 @@ var ts; return visitNode(cbNode, node.expression); case 264 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 326 /* CommaListExpression */: + case 327 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); case 266 /* JsxElement */: return visitNode(cbNode, node.openingElement) || @@ -18854,24 +19373,27 @@ var ts; visitNode(cbNode, node.type); case 303 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 316 /* JSDocParameterTag */: - case 322 /* JSDocPropertyTag */: + case 317 /* JSDocParameterTag */: + case 323 /* 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 308 /* JSDocAuthorTag */: + case 309 /* JSDocAuthorTag */: return visitNode(cbNode, node.tagName); + case 308 /* JSDocImplementsTag */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.class); case 307 /* JSDocAugmentsTag */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.class); - case 320 /* JSDocTemplateTag */: + case 321 /* JSDocTemplateTag */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); - case 321 /* JSDocTypedefTag */: + case 322 /* JSDocTypedefTag */: return visitNode(cbNode, node.tagName) || (node.typeExpression && node.typeExpression.kind === 294 /* JSDocTypeExpression */ @@ -18879,14 +19401,14 @@ var ts; visitNode(cbNode, node.fullName) : visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression)); - case 314 /* JSDocCallbackTag */: + case 315 /* JSDocCallbackTag */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 317 /* JSDocReturnTag */: - case 319 /* JSDocTypeTag */: - case 318 /* JSDocThisTag */: - case 315 /* JSDocEnumTag */: + case 318 /* JSDocReturnTag */: + case 320 /* JSDocTypeTag */: + case 319 /* JSDocThisTag */: + case 316 /* JSDocEnumTag */: return visitNode(cbNode, node.tagName) || visitNode(cbNode, node.typeExpression); case 305 /* JSDocSignature */: @@ -18896,17 +19418,85 @@ var ts; case 304 /* JSDocTypeLiteral */: return ts.forEach(node.jsDocPropertyTags, cbNode); case 306 /* JSDocTag */: - case 309 /* JSDocClassTag */: - case 310 /* JSDocPublicTag */: - case 311 /* JSDocPrivateTag */: - case 312 /* JSDocProtectedTag */: - case 313 /* JSDocReadonlyTag */: + case 310 /* JSDocClassTag */: + case 311 /* JSDocPublicTag */: + case 312 /* JSDocPrivateTag */: + case 313 /* JSDocProtectedTag */: + case 314 /* JSDocReadonlyTag */: return visitNode(cbNode, node.tagName); - case 325 /* PartiallyEmittedExpression */: + case 326 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } ts.forEachChild = forEachChild; + /** @internal */ + /** + * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes + * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; additionally, + * unlike `forEachChild`, embedded arrays are flattened and the 'cbNode' callback is invoked for each element. + * If a callback returns a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. + * + * @param node a given node to visit its children + * @param cbNode a callback to be invoked for all child nodes + * @param cbNodes a callback to be invoked for embedded array + * + * @remarks Unlike `forEachChild`, `forEachChildRecursively` handles recursively invoking the traversal on each child node found, + * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure. + */ + function forEachChildRecursively(rootNode, cbNode, cbNodes) { + var stack = [rootNode]; + while (stack.length) { + var parent = stack.pop(); + var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent)); + if (res) { + return res; + } + } + return; + function gatherPossibleChildren(node) { + var children = []; + forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal + return children; + function addWorkItem(n) { + children.unshift(n); + } + } + function visitAllPossibleChildren(parent, children) { + for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { + var child = children_1[_i]; + if (ts.isArray(child)) { + if (cbNodes) { + var res = cbNodes(child, parent); + if (res) { + if (res === "skip") + continue; + return res; + } + } + for (var i = child.length - 1; i >= 0; i--) { + var realChild = child[i]; + var res = cbNode(realChild, parent); + if (res) { + if (res === "skip") + continue; + return res; + } + stack.push(realChild); + } + } + else { + stack.push(child); + var res = cbNode(child, parent); + if (res) { + if (res === "skip") + continue; + return res; + } + } + } + } + } + ts.forEachChildRecursively = forEachChildRecursively; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } ts.performance.mark("beforeParse"); @@ -19207,6 +19797,7 @@ var ts; } function clearState() { // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. + scanner.clearCommentDirectives(); scanner.setText(""); scanner.setOnError(undefined); // Clear any data. We don't want to accidentally hold onto it for too long. @@ -19233,6 +19824,7 @@ var ts; ts.Debug.assert(token() === 1 /* EndOfFileToken */); sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); setExternalModuleIndicator(sourceFile); + sourceFile.commentDirectives = scanner.getCommentDirectives(); sourceFile.nodeCount = nodeCount; sourceFile.identifierCount = identifierCount; sourceFile.identifiers = identifiers; @@ -19257,30 +19849,14 @@ var ts; // a syntax tree, and no semantic features, then the binding process is an unnecessary // overhead. This functions allows us to set all the parents, without all the expense of // binding. - var stack = [rootNode]; - while (stack.length) { - var parent = stack.pop(); - bindParentToChildren(parent, gatherChildren(parent)); - } - return; - function gatherChildren(node) { - var children = []; - forEachChild(node, function (n) { children.unshift(n); }); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal - return children; - } - function bindParentToChildren(parent, children) { - for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { - var child = children_1[_i]; - if (child.parent === parent) - continue; // already bound, assume subtree is bound - child.parent = parent; - stack.push(child); - if (ts.hasJSDocNodes(child)) { - for (var _a = 0, _b = child.jsDoc; _a < _b.length; _a++) { - var jsDoc = _b[_a]; - jsDoc.parent = child; - stack.push(jsDoc); - } + forEachChildRecursively(rootNode, bindParentToChild); + function bindParentToChild(child, parent) { + child.parent = parent; + if (ts.hasJSDocNodes(child)) { + for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) { + var doc = _a[_i]; + bindParentToChild(doc, child); + forEachChildRecursively(doc, bindParentToChild); } } } @@ -19452,8 +20028,11 @@ var ts; function reScanSlashToken() { return currentToken = scanner.reScanSlashToken(); } - function reScanTemplateToken() { - return currentToken = scanner.reScanTemplateToken(); + function reScanTemplateToken(isTaggedTemplate) { + return currentToken = scanner.reScanTemplateToken(isTaggedTemplate); + } + function reScanTemplateHeadOrNoSubstitutionTemplate() { + return currentToken = scanner.reScanTemplateHeadOrNoSubstitutionTemplate(); } function reScanLessThanToken() { return currentToken = scanner.reScanLessThanToken(); @@ -19618,7 +20197,7 @@ var ts; } function createNodeWithJSDoc(kind, pos) { var node = createNode(kind, pos); - if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */) { + if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */ && (kind !== 226 /* ExpressionStatement */ || token() !== 20 /* OpenParenToken */)) { addJSDocComment(node); } return node; @@ -20473,24 +21052,24 @@ var ts; } return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } - function parseTemplateExpression() { + function parseTemplateExpression(isTaggedTemplate) { var template = createNode(211 /* TemplateExpression */); - template.head = parseTemplateHead(); + template.head = parseTemplateHead(isTaggedTemplate); ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); var list = []; var listPos = getNodePos(); do { - list.push(parseTemplateSpan()); + list.push(parseTemplateSpan(isTaggedTemplate)); } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */); template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } - function parseTemplateSpan() { + function parseTemplateSpan(isTaggedTemplate) { var span = createNode(221 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; if (token() === 19 /* CloseBraceToken */) { - reScanTemplateToken(); + reScanTemplateToken(isTaggedTemplate); literal = parseTemplateMiddleOrTemplateTail(); } else { @@ -20502,7 +21081,10 @@ var ts; function parseLiteralNode() { return parseLiteralLikeNode(token()); } - function parseTemplateHead() { + function parseTemplateHead(isTaggedTemplate) { + if (isTaggedTemplate) { + reScanTemplateHeadOrNoSubstitutionTemplate(); + } var fragment = parseLiteralLikeNode(token()); ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind"); return fragment; @@ -20540,6 +21122,9 @@ var ts; if (node.kind === 8 /* NumericLiteral */) { node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */; } + if (ts.isTemplateLiteralKind(node.kind)) { + node.templateFlags = scanner.getTokenFlags() & 2048 /* ContainsInvalidEscape */; + } nextToken(); finishNode(node); return node; @@ -22401,7 +22986,11 @@ var ts; parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); } else { - parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); + // We want the error span to cover only 'Foo.Bar' in < Foo.Bar > + // or to cover only 'Foo' in < Foo > + var tag = openingTag.tagName; + var start = ts.skipTrivia(sourceText, tag.pos); + parseErrorAt(start, tag.end, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); } return undefined; case 30 /* LessThanSlashToken */: @@ -22585,12 +23174,33 @@ var ts; return token() === 28 /* QuestionDotToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate); } + function tryReparseOptionalChain(node) { + if (node.flags & 32 /* OptionalChain */) { + return true; + } + // check for an optional chain in a non-null expression + if (ts.isNonNullExpression(node)) { + var expr = node.expression; + while (ts.isNonNullExpression(expr) && !(expr.flags & 32 /* OptionalChain */)) { + expr = expr.expression; + } + if (expr.flags & 32 /* OptionalChain */) { + // this is part of an optional chain. Walk down from `node` to `expression` and set the flag. + while (ts.isNonNullExpression(node)) { + node.flags |= 32 /* OptionalChain */; + node = node.expression; + } + return true; + } + } + return false; + } function parsePropertyAccessExpressionRest(expression, questionDotToken) { var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.questionDotToken = questionDotToken; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true); - if (questionDotToken || expression.flags & 32 /* OptionalChain */) { + if (questionDotToken || tryReparseOptionalChain(expression)) { propertyAccess.flags |= 32 /* OptionalChain */; if (ts.isPrivateIdentifier(propertyAccess.name)) { parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers); @@ -22613,7 +23223,7 @@ var ts; indexedAccess.argumentExpression = argument; } parseExpected(23 /* CloseBracketToken */); - if (questionDotToken || expression.flags & 32 /* OptionalChain */) { + if (questionDotToken || tryReparseOptionalChain(expression)) { indexedAccess.flags |= 32 /* OptionalChain */; } return finishNode(indexedAccess); @@ -22661,8 +23271,8 @@ var ts; tagExpression.questionDotToken = questionDotToken; tagExpression.typeArguments = typeArguments; tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */ - ? parseLiteralNode() - : parseTemplateExpression(); + ? (reScanTemplateHeadOrNoSubstitutionTemplate(), parseLiteralNode()) + : parseTemplateExpression(/*isTaggedTemplate*/ true); if (questionDotToken || tag.flags & 32 /* OptionalChain */) { tagExpression.flags |= 32 /* OptionalChain */; } @@ -22689,7 +23299,7 @@ var ts; callExpr.questionDotToken = questionDotToken; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); - if (questionDotToken || expression.flags & 32 /* OptionalChain */) { + if (questionDotToken || tryReparseOptionalChain(expression)) { callExpr.flags |= 32 /* OptionalChain */; } expression = finishNode(callExpr); @@ -22701,7 +23311,7 @@ var ts; callExpr.expression = expression; callExpr.questionDotToken = questionDotToken; callExpr.arguments = parseArgumentList(); - if (questionDotToken || expression.flags & 32 /* OptionalChain */) { + if (questionDotToken || tryReparseOptionalChain(expression)) { callExpr.flags |= 32 /* OptionalChain */; } expression = finishNode(callExpr); @@ -22823,7 +23433,7 @@ var ts; } break; case 15 /* TemplateHead */: - return parseTemplateExpression(); + return parseTemplateExpression(/* isTaggedTemplate */ false); } return parseIdentifier(ts.Diagnostics.Expression_expected); } @@ -22905,12 +23515,18 @@ var ts; } function parseObjectLiteralExpression() { var node = createNode(193 /* ObjectLiteralExpression */); + var openBracePosition = scanner.getTokenPos(); parseExpected(18 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; } node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); - parseExpected(19 /* CloseBraceToken */); + if (!parseExpected(19 /* CloseBraceToken */)) { + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (lastError && lastError.code === ts.Diagnostics._0_expected.code) { + ts.addRelatedInfo(lastError, ts.createFileDiagnostic(sourceFile, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)); + } + } return finishNode(node); } function parseFunctionExpression() { @@ -22968,9 +23584,12 @@ var ts; var node = createNode(197 /* NewExpression */, fullStart); node.expression = expression; node.typeArguments = typeArguments; - if (node.typeArguments || token() === 20 /* OpenParenToken */) { + if (token() === 20 /* OpenParenToken */) { node.arguments = parseArgumentList(); } + else if (node.typeArguments) { + parseErrorAt(fullStart, scanner.getStartPos(), ts.Diagnostics.A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list); + } return finishNode(node); } // STATEMENTS @@ -23209,7 +23828,7 @@ var ts; // Avoiding having to do the lookahead for a labeled statement by just trying to parse // out an expression, seeing if it is identifier and then seeing if it is followed by // a colon. - var node = createNodeWithJSDoc(0 /* Unknown */); + var node = createNodeWithJSDoc(token() === 75 /* Identifier */ ? 0 /* Unknown */ : 226 /* ExpressionStatement */); var expression = allowInAnd(parseExpression); if (expression.kind === 75 /* Identifier */ && parseOptional(58 /* ColonToken */)) { node.kind = 238 /* LabeledStatement */; @@ -24584,25 +25203,28 @@ var ts; case "author": tag = parseAuthorTag(start, tagName, margin); break; + case "implements": + tag = parseImplementsTag(start, tagName); + break; case "augments": case "extends": tag = parseAugmentsTag(start, tagName); break; case "class": case "constructor": - tag = parseSimpleTag(start, 309 /* JSDocClassTag */, tagName); + tag = parseSimpleTag(start, 310 /* JSDocClassTag */, tagName); break; case "public": - tag = parseSimpleTag(start, 310 /* JSDocPublicTag */, tagName); + tag = parseSimpleTag(start, 311 /* JSDocPublicTag */, tagName); break; case "private": - tag = parseSimpleTag(start, 311 /* JSDocPrivateTag */, tagName); + tag = parseSimpleTag(start, 312 /* JSDocPrivateTag */, tagName); break; case "protected": - tag = parseSimpleTag(start, 312 /* JSDocProtectedTag */, tagName); + tag = parseSimpleTag(start, 313 /* JSDocProtectedTag */, tagName); break; case "readonly": - tag = parseSimpleTag(start, 313 /* JSDocReadonlyTag */, tagName); + tag = parseSimpleTag(start, 314 /* JSDocReadonlyTag */, tagName); break; case "this": tag = parseThisTag(start, tagName); @@ -24654,10 +25276,12 @@ var ts; comments.push(text); indent += text.length; } - if (initialMargin) { + if (initialMargin !== undefined) { // jump straight to saving comments if there is some initial indentation - pushComment(initialMargin); - state = 2 /* SavingComments */; + if (initialMargin !== "") { + pushComment(initialMargin); + } + state = 1 /* SawAsterisk */; } var tok = token(); loop: while (true) { @@ -24798,8 +25422,8 @@ var ts; typeExpression = tryParseTypeExpression(); } var result = target === 1 /* Property */ ? - createNode(322 /* JSDocPropertyTag */, start) : - createNode(316 /* JSDocParameterTag */, start); + createNode(323 /* JSDocPropertyTag */, start) : + createNode(317 /* JSDocParameterTag */, start); var comment = parseTagComments(indent + scanner.getStartPos() - start); var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { @@ -24822,7 +25446,7 @@ var ts; var start_3 = scanner.getStartPos(); var children = void 0; while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) { - if (child.kind === 316 /* JSDocParameterTag */ || child.kind === 322 /* JSDocPropertyTag */) { + if (child.kind === 317 /* JSDocParameterTag */ || child.kind === 323 /* JSDocPropertyTag */) { children = ts.append(children, child); } } @@ -24841,7 +25465,7 @@ var ts; if (ts.some(tags, ts.isJSDocReturnTag)) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(317 /* JSDocReturnTag */, start); + var result = createNode(318 /* JSDocReturnTag */, start); result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); @@ -24850,13 +25474,13 @@ var ts; if (ts.some(tags, ts.isJSDocTypeTag)) { parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(319 /* JSDocTypeTag */, start); + var result = createNode(320 /* JSDocTypeTag */, start); result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); return finishNode(result); } function parseAuthorTag(start, tagName, indent) { - var result = createNode(308 /* JSDocAuthorTag */, start); + var result = createNode(309 /* JSDocAuthorTag */, start); result.tagName = tagName; var authorInfoWithEmail = tryParse(function () { return tryParseAuthorNameAndEmail(); }); if (!authorInfoWithEmail) { @@ -24909,6 +25533,12 @@ var ts; return comments.length === 0 ? undefined : comments.join(""); } } + function parseImplementsTag(start, tagName) { + var result = createNode(308 /* JSDocImplementsTag */, start); + result.tagName = tagName; + result.class = parseExpressionWithTypeArgumentsForAugments(); + return finishNode(result); + } function parseAugmentsTag(start, tagName) { var result = createNode(307 /* JSDocAugmentsTag */, start); result.tagName = tagName; @@ -24942,14 +25572,14 @@ var ts; return finishNode(tag); } function parseThisTag(start, tagName) { - var tag = createNode(318 /* JSDocThisTag */, start); + var tag = createNode(319 /* JSDocThisTag */, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); return finishNode(tag); } function parseEnumTag(start, tagName) { - var tag = createNode(315 /* JSDocEnumTag */, start); + var tag = createNode(316 /* JSDocEnumTag */, start); tag.tagName = tagName; tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); skipWhitespace(); @@ -24958,7 +25588,7 @@ var ts; function parseTypedefTag(start, tagName, indent) { var typeExpression = tryParseTypeExpression(); skipWhitespaceOrAsterisk(); - var typedefTag = createNode(321 /* JSDocTypedefTag */, start); + var typedefTag = createNode(322 /* JSDocTypedefTag */, start); typedefTag.tagName = tagName; typedefTag.fullName = parseJSDocTypeNameWithNamespace(); typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); @@ -24974,7 +25604,7 @@ var ts; if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start); } - if (child.kind === 319 /* JSDocTypeTag */) { + if (child.kind === 320 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -25020,7 +25650,7 @@ var ts; return typeNameOrNamespaceName; } function parseCallbackTag(start, tagName, indent) { - var callbackTag = createNode(314 /* JSDocCallbackTag */, start); + var callbackTag = createNode(315 /* JSDocCallbackTag */, start); callbackTag.tagName = tagName; callbackTag.fullName = parseJSDocTypeNameWithNamespace(); callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); @@ -25035,7 +25665,7 @@ var ts; var returnTag = tryParse(function () { if (parseOptionalJsdoc(59 /* AtToken */)) { var tag = parseTag(indent); - if (tag && tag.kind === 317 /* JSDocReturnTag */) { + if (tag && tag.kind === 318 /* JSDocReturnTag */) { return tag; } } @@ -25080,7 +25710,7 @@ var ts; case 59 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target, indent); - if (child && (child.kind === 316 /* JSDocParameterTag */ || child.kind === 322 /* JSDocPropertyTag */) && + if (child && (child.kind === 317 /* JSDocParameterTag */ || child.kind === 323 /* JSDocPropertyTag */) && target !== 4 /* CallbackParameter */ && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; @@ -25147,10 +25777,10 @@ var ts; var typeParameter = createNode(155 /* TypeParameter */); typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); finishNode(typeParameter); - skipWhitespace(); + skipWhitespaceOrAsterisk(); typeParameters.push(typeParameter); } while (parseOptionalJsdoc(27 /* CommaToken */)); - var result = createNode(320 /* JSDocTemplateTag */, start); + var result = createNode(321 /* JSDocTemplateTag */, start); result.tagName = tagName; result.constraint = constraint; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); @@ -25269,9 +25899,51 @@ var ts; // will immediately bail out of walking any subtrees when we can see that their parents // are already correct. var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind); + result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks); return result; } IncrementalParser.updateSourceFile = updateSourceFile; + function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) { + if (!oldDirectives) + return newDirectives; + var commentDirectives; + var addedNewlyScannedDirectives = false; + for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) { + var directive = oldDirectives_1[_i]; + var range = directive.range, type = directive.type; + // Range before the change + if (range.end < changeStart) { + commentDirectives = ts.append(commentDirectives, directive); + } + else if (range.pos > changeRangeOldEnd) { + addNewlyScannedDirectives(); + // Node is entirely past the change range. We need to move both its pos and + // end, forward or backward appropriately. + var updatedDirective = { + range: { pos: range.pos + delta, end: range.end + delta }, + type: type + }; + commentDirectives = ts.append(commentDirectives, updatedDirective); + if (aggressiveChecks) { + ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end)); + } + } + // Ignore ranges that fall in change range + } + addNewlyScannedDirectives(); + return commentDirectives; + function addNewlyScannedDirectives() { + if (addedNewlyScannedDirectives) + return; + addedNewlyScannedDirectives = true; + if (!commentDirectives) { + commentDirectives = newDirectives; + } + else if (newDirectives) { + commentDirectives.push.apply(commentDirectives, newDirectives); + } + } + } function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { if (isArray) { visitArray(element); @@ -25957,7 +26629,9 @@ var 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.es2020.bigint.d.ts"] + ["esnext.bigint", "lib.es2020.bigint.d.ts"], + ["esnext.string", "lib.esnext.string.d.ts"], + ["esnext.promise", "lib.esnext.promise.d.ts"] ]; /** * An array of supported "lib" reference file names used to determine the order for inclusion @@ -26979,7 +27653,8 @@ var ts; target: 1 /* ES5 */, strict: true, esModuleInterop: true, - forceConsistentCasingInFileNames: true + forceConsistentCasingInFileNames: true, + skipLibCheck: true }; /* @internal */ function convertEnableAutoDiscoveryToEnable(typeAcquisition) { @@ -27038,6 +27713,7 @@ var ts; createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : createDiagnostics(diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption); } + /*@internal*/ function parseCommandLineWorker(diagnostics, commandLine, readFile) { var options = {}; var watchOptions; @@ -27080,9 +27756,9 @@ var ts; } } function parseResponseFile(fileName) { - var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName); - if (!text) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName)); + var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); })); + if (!ts.isString(text)) { + errors.push(text); return; } var args = []; @@ -27114,50 +27790,78 @@ var ts; parseStrings(args); } } + ts.parseCommandLineWorker = parseCommandLineWorker; function parseOptionValue(args, i, diagnostics, opt, options, errors) { if (opt.isTSConfigOnly) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); + var optValue = args[i]; + if (optValue === "null") { + options[opt.name] = undefined; + i++; + } + else if (opt.type === "boolean") { + if (optValue === "false") { + options[opt.name] = false; + i++; + } + else { + if (optValue === "true") + i++; + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line, opt.name)); + } + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line, opt.name)); + if (optValue && !ts.startsWith(optValue, "-")) + i++; + } } else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt))); } - switch (opt.type) { - case "number": - options[opt.name] = parseInt(args[i]); - i++; - break; - case "boolean": - // boolean flag has optional value true, false, others - var optValue = args[i]; - options[opt.name] = optValue !== "false"; - // consume next argument as boolean flag value - if (optValue === "false" || optValue === "true") { + if (args[i] !== "null") { + switch (opt.type) { + case "number": + options[opt.name] = parseInt(args[i]); i++; - } - break; - case "string": - options[opt.name] = args[i] || ""; - i++; - break; - case "list": - var result = parseListTypeOption(opt, args[i], errors); - options[opt.name] = result || []; - if (result) { + break; + case "boolean": + // boolean flag has optional value true, false, others + var optValue = args[i]; + options[opt.name] = optValue !== "false"; + // consume next argument as boolean flag value + if (optValue === "false" || optValue === "true") { + i++; + } + break; + case "string": + options[opt.name] = args[i] || ""; i++; - } - break; - // If not a primitive, the possible types are specified in what is effectively a map of options. - default: - options[opt.name] = parseCustomTypeOption(opt, args[i], errors); - i++; - break; + break; + case "list": + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } + break; + // If not a primitive, the possible types are specified in what is effectively a map of options. + default: + options[opt.name] = parseCustomTypeOption(opt, args[i], errors); + i++; + break; + } + } + else { + options[opt.name] = undefined; + i++; } } return i; } - var compilerOptionsDidYouMeanDiagnostics = { + /*@internal*/ + ts.compilerOptionsDidYouMeanDiagnostics = { getOptionsNameMap: getOptionsNameMap, optionDeclarations: ts.optionDeclarations, unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0, @@ -27165,7 +27869,7 @@ var ts; optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument }; function parseCommandLine(commandLine, readFile) { - return parseCommandLineWorker(compilerOptionsDidYouMeanDiagnostics, commandLine, readFile); + return parseCommandLineWorker(ts.compilerOptionsDidYouMeanDiagnostics, commandLine, readFile); } ts.parseCommandLine = parseCommandLine; /** @internal */ @@ -27234,19 +27938,10 @@ var ts; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ - function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend) { - var configFileText; - try { - configFileText = host.readFile(configFileName); - } - catch (e) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - if (!configFileText) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); - host.onUnRecoverableConfigFileDiagnostic(error); + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) { + var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); }); + if (!ts.isString(configFileText)) { + host.onUnRecoverableConfigFileDiagnostic(configFileText); return undefined; } var result = ts.parseJsonText(configFileName, configFileText); @@ -27255,8 +27950,7 @@ var ts; result.resolvedPath = result.path; result.originalFileName = result.fileName; return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd), - /*resolutionStack*/ undefined, - /*extraFileExtension*/ undefined, extendedConfigCache, watchOptionsToExtend); + /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend); } ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; /** @@ -27290,6 +27984,7 @@ var ts; return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; } ts.readJsonConfigFile = readJsonConfigFile; + /*@internal*/ function tryReadFile(fileName, readFile) { var text; try { @@ -27298,8 +27993,9 @@ var ts; catch (e) { return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); } - return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text; } + ts.tryReadFile = tryReadFile; function commandLineOptionsToMap(options) { return ts.arrayToMap(options, getOptionName); } @@ -27342,7 +28038,7 @@ var ts; name: "compilerOptions", type: "object", elementOptions: getCommandLineCompilerOptionsMap(), - extraKeyDiagnostics: compilerOptionsDidYouMeanDiagnostics, + extraKeyDiagnostics: ts.compilerOptionsDidYouMeanDiagnostics, }, { name: "watchOptions", @@ -27438,7 +28134,7 @@ var ts; if (!isDoubleQuotedString(element.name)) { errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - var textOfKey = ts.getTextOfPropertyName(element.name); + var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name); var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey); var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined; if (keyText && extraKeyDiagnostics && !option) { @@ -27754,15 +28450,12 @@ var ts; // Serialize all options and their descriptions var marginLength = 0; var seenKnownKeys = 0; - var nameColumn = []; - var descriptionColumn = []; + var entries = []; categorizedOptions.forEach(function (options, category) { - if (nameColumn.length !== 0) { - nameColumn.push(""); - descriptionColumn.push(""); + if (entries.length !== 0) { + entries.push({ value: "" }); } - nameColumn.push("/* " + category + " */"); - descriptionColumn.push(""); + entries.push({ value: "/* " + category + " */" }); for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { var option = options_1[_i]; var optionName = void 0; @@ -27772,8 +28465,10 @@ var ts; else { optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; } - nameColumn.push(optionName); - descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); + entries.push({ + value: optionName, + description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */" + }); marginLength = Math.max(optionName.length, marginLength); } }); @@ -27782,11 +28477,13 @@ var ts; var result = []; result.push("{"); result.push(tab + "\"compilerOptions\": {"); + result.push("" + tab + tab + "/* " + ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file) + " */"); + result.push(""); // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < nameColumn.length; i++) { - var optionName = nameColumn[i]; - var description = descriptionColumn[i]; - result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); + for (var _a = 0, entries_3 = entries; _a < entries_3.length; _a++) { + var entry = entries_3[_a]; + var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b; + result.push(value && "" + tab + tab + value + (description && (makePadding(marginLength - value.length + 2) + description))); } if (fileNames.length) { result.push(tab + "},"); @@ -27820,7 +28517,7 @@ var ts; } ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths; function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) { - if (option) { + if (option && !isNullOrUndefined(value)) { if (option.type === "list") { var values = value; if (option.element.isFilePath && values.length) { @@ -28241,7 +28938,7 @@ var ts; } function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = getDefaultCompilerOptions(configFileName); - convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, compilerOptionsDidYouMeanDiagnostics, errors); + convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, ts.compilerOptionsDidYouMeanDiagnostics, errors); if (configFileName) { options.configFilePath = ts.normalizeSlashes(configFileName); } @@ -28727,7 +29424,12 @@ var ts; ts.Debug.assert(ts.extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } - function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, resultFromCache) { + var _a; + if (resultFromCache) { + (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations); + return resultFromCache; + } return { resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId }, failedLookupLocations: failedLookupLocations @@ -29419,15 +30121,12 @@ var ts; } ts.nodeModuleNameResolver = nodeModuleNameResolver; function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) { + var _a, _b; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); }); - if (result && result.value) { - var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; - return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); - } - return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + return createResolvedModuleWithFailedLookupLocations((_a = result === null || result === void 0 ? void 0 : result.value) === null || _a === void 0 ? void 0 : _a.resolved, (_b = result === null || result === void 0 ? void 0 : result.value) === null || _b === void 0 ? void 0 : _b.isExternalLibraryImport, failedLookupLocations, state.resultFromCache); function tryResolve(extensions) { var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); }; var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); @@ -29864,13 +30563,12 @@ var ts; } ts.unmangleScopedPackageName = unmangleScopedPackageName; function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) { - var _a; var result = cache && cache.get(containingDirectory); if (result) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - (_a = state.failedLookupLocations).push.apply(_a, result.failedLookupLocations); + state.resultFromCache = result; return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } @@ -29881,7 +30579,7 @@ var ts; var containingDirectory = ts.getDirectoryPath(containingFile); var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); // No originalPath because classic resolution doesn't resolve realPath - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, state.resultFromCache); function tryResolve(extensions) { var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { @@ -29926,7 +30624,7 @@ var ts; var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations }; var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); - return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache); } ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; /** @@ -30219,16 +30917,7 @@ var ts; symbol.constEnumOnlyModule = false; } if (symbolFlags & 111551 /* Value */) { - setValueDeclaration(symbol, node); - } - } - function setValueDeclaration(symbol, node) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (ts.isAssignmentDeclaration(valueDeclaration) && !ts.isAssignmentDeclaration(node)) || - (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules and assignment declarations - symbol.valueDeclaration = node; + ts.setValueDeclaration(symbol, node); } } // Should not be called on a declaration with a computed property name, @@ -30307,7 +30996,7 @@ var ts; } } function getDisplayName(node) { - return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.assertDefined(getDeclarationName(node))); + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.checkDefined(getDeclarationName(node))); } /** * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. @@ -30319,7 +31008,7 @@ var ts; */ function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = ts.hasModifier(node, 512 /* Default */); + var isDefaultExport = ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default"; // The exported symbol for an export default function/class node is always named "default" var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node); var symbol; @@ -30708,9 +31397,12 @@ var ts; case 196 /* CallExpression */: bindCallExpressionFlow(node); break; - case 321 /* JSDocTypedefTag */: - case 314 /* JSDocCallbackTag */: - case 315 /* JSDocEnumTag */: + case 218 /* NonNullExpression */: + bindNonNullExpressionFlow(node); + break; + case 322 /* JSDocTypedefTag */: + case 315 /* JSDocCallbackTag */: + case 316 /* JSDocEnumTag */: bindJSDocTypeAlias(node); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime @@ -30817,9 +31509,12 @@ var ts; function createLoopLabel() { return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined }); } + function createReduceLabel(target, antecedents, antecedent) { + return initFlowNode({ flags: 1024 /* ReduceLabel */, target: target, antecedents: antecedents, antecedent: antecedent }); + } function setFlowNodeReferenced(flow) { // On first reference we set the Referenced flag, thereafter we set the Shared flag - flow.flags |= flow.flags & 1024 /* Referenced */ ? 2048 /* Shared */ : 1024 /* Referenced */; + flow.flags |= flow.flags & 2048 /* Referenced */ ? 4096 /* Shared */ : 2048 /* Referenced */; } function addAntecedent(label, antecedent) { if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { @@ -31050,35 +31745,36 @@ var ts; } } function bindTryStatement(node) { - var preFinallyLabel = createBranchLabel(); // We conservatively assume that *any* code in the try block can cause an exception, but we only need // to track code that causes mutations (because only mutations widen the possible control flow type of - // a variable). The currentExceptionTarget is the target label for control flows that result from - // exceptions. We add all mutation flow nodes as antecedents of this label such that we can analyze them - // as possible antecedents of the start of catch or finally blocks. Furthermore, we add the current - // control flow to represent exceptions that occur before any mutations. + // a variable). The exceptionLabel is the target label for control flows that result from exceptions. + // We add all mutation flow nodes as antecedents of this label such that we can analyze them as possible + // antecedents of the start of catch or finally blocks. Furthermore, we add the current control flow to + // represent exceptions that occur before any mutations. var saveReturnTarget = currentReturnTarget; var saveExceptionTarget = currentExceptionTarget; - currentReturnTarget = createBranchLabel(); - currentExceptionTarget = node.catchClause ? createBranchLabel() : currentReturnTarget; - addAntecedent(currentExceptionTarget, currentFlow); + var normalExitLabel = createBranchLabel(); + var returnLabel = createBranchLabel(); + var exceptionLabel = createBranchLabel(); + if (node.finallyBlock) { + currentReturnTarget = returnLabel; + } + addAntecedent(exceptionLabel, currentFlow); + currentExceptionTarget = exceptionLabel; bind(node.tryBlock); - addAntecedent(preFinallyLabel, currentFlow); - var flowAfterTry = currentFlow; - var flowAfterCatch = unreachableFlow; + addAntecedent(normalExitLabel, currentFlow); if (node.catchClause) { // Start of catch clause is the target of exceptions from try block. - currentFlow = finishFlowLabel(currentExceptionTarget); + currentFlow = finishFlowLabel(exceptionLabel); // The currentExceptionTarget now represents control flows from exceptions in the catch clause. // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block // acts like a second try block. - currentExceptionTarget = currentReturnTarget; - addAntecedent(currentExceptionTarget, currentFlow); + exceptionLabel = createBranchLabel(); + addAntecedent(exceptionLabel, currentFlow); + currentExceptionTarget = exceptionLabel; bind(node.catchClause); - addAntecedent(preFinallyLabel, currentFlow); - flowAfterCatch = currentFlow; + addAntecedent(normalExitLabel, currentFlow); } - var exceptionTarget = finishFlowLabel(currentExceptionTarget); currentReturnTarget = saveReturnTarget; currentExceptionTarget = saveExceptionTarget; if (node.finallyBlock) { @@ -31091,35 +31787,33 @@ var ts; // When analyzing a control flow graph that starts inside a finally block we want to consider all // five possibilities above. However, when analyzing a control flow graph that starts outside (past) // the finally block, we only want to consider the first two (if we're past a finally block then it - // must have completed normally). To make this possible, we inject two extra nodes into the control - // flow graph: An after-finally with an antecedent of the control flow at the end of the finally - // block, and a pre-finally with an antecedent that represents all exceptional control flows. The - // 'lock' property of the pre-finally references the after-finally, and the after-finally has a - // boolean 'locked' property that we set to true when analyzing a control flow that contained the - // the after-finally node. When the lock associated with a pre-finally is locked, the antecedent of - // the pre-finally (i.e. the exceptional control flows) are skipped. - var preFinallyFlow = initFlowNode({ flags: 4096 /* PreFinally */, antecedent: exceptionTarget, lock: {} }); - addAntecedent(preFinallyLabel, preFinallyFlow); - currentFlow = finishFlowLabel(preFinallyLabel); + // must have completed normally). Likewise, when analyzing a control flow graph from return statements + // in try or catch blocks in an IIFE, we only want to consider the third. To make this possible, we + // inject a ReduceLabel node into the control flow graph. This node contains an alternate reduced + // set of antecedents for the pre-finally label. As control flow analysis passes by a ReduceLabel + // node, the pre-finally label is temporarily switched to the reduced antecedent set. + var finallyLabel = createBranchLabel(); + finallyLabel.antecedents = ts.concatenate(ts.concatenate(normalExitLabel.antecedents, exceptionLabel.antecedents), returnLabel.antecedents); + currentFlow = finallyLabel; bind(node.finallyBlock); - // If the end of the finally block is reachable, but the end of the try and catch blocks are not, - // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should - // result in an unreachable current control flow. - if (!(currentFlow.flags & 1 /* Unreachable */)) { - if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { - currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow - ? reportedUnreachableFlow - : unreachableFlow; - } + if (currentFlow.flags & 1 /* Unreachable */) { + // If the end of the finally block is unreachable, the end of the entire try statement is unreachable. + currentFlow = unreachableFlow; } - if (!(currentFlow.flags & 1 /* Unreachable */)) { - var afterFinallyFlow = initFlowNode({ flags: 8192 /* AfterFinally */, antecedent: currentFlow }); - preFinallyFlow.lock = afterFinallyFlow; - currentFlow = afterFinallyFlow; + else { + // If we have an IIFE return target and return statements in the try or catch blocks, add a control + // flow that goes back through the finally block and back through only the return statements. + if (currentReturnTarget && returnLabel.antecedents) { + addAntecedent(currentReturnTarget, createReduceLabel(finallyLabel, returnLabel.antecedents, currentFlow)); + } + // If the end of the finally block is reachable, but the end of the try and catch blocks are not, + // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should + // result in an unreachable current control flow. + currentFlow = normalExitLabel.antecedents ? createReduceLabel(finallyLabel, normalExitLabel.antecedents, currentFlow) : unreachableFlow; } } else { - currentFlow = finishFlowLabel(preFinallyLabel); + currentFlow = finishFlowLabel(normalExitLabel); } } function bindSwitchStatement(node) { @@ -31460,7 +32154,7 @@ var ts; } function bindJSDocTypeAlias(node) { node.tagName.parent = node; - if (node.kind !== 315 /* JSDocEnumTag */ && node.fullName) { + if (node.kind !== 316 /* JSDocEnumTag */ && node.fullName) { setParentPointers(node, node.fullName); } } @@ -31479,15 +32173,17 @@ var ts; } } function bindOptionalChainRest(node) { - bind(node.questionDotToken); switch (node.kind) { case 194 /* PropertyAccessExpression */: + bind(node.questionDotToken); bind(node.name); break; case 195 /* ElementAccessExpression */: + bind(node.questionDotToken); bind(node.argumentExpression); break; case 196 /* CallExpression */: + bind(node.questionDotToken); bindEach(node.typeArguments); bindEach(node.arguments); break; @@ -31505,7 +32201,7 @@ var ts; // and build it's CFA graph as if it were the first condition (`a && ...`). Then we bind the rest // of the node as part of the "true" branch, and continue to do so as we ascend back up to the outermost // chain node. We then treat the entire node as the right side of the expression. - var preChainLabel = node.questionDotToken ? createBranchLabel() : undefined; + var preChainLabel = ts.isOptionalChainRoot(node) ? createBranchLabel() : undefined; bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget); if (preChainLabel) { currentFlow = finishFlowLabel(preChainLabel); @@ -31526,6 +32222,14 @@ var ts; bindOptionalChain(node, currentTrueTarget, currentFalseTarget); } } + function bindNonNullExpressionFlow(node) { + if (ts.isOptionalChain(node)) { + bindOptionalChainFlow(node); + } + else { + bindEachChild(node); + } + } function bindAccessExpressionFlow(node) { if (ts.isOptionalChain(node)) { bindOptionalChainFlow(node); @@ -31676,8 +32380,8 @@ var ts; case 201 /* FunctionExpression */: case 202 /* ArrowFunction */: case 300 /* JSDocFunctionType */: - case 321 /* JSDocTypedefTag */: - case 314 /* JSDocCallbackTag */: + case 322 /* JSDocTypedefTag */: + case 315 /* JSDocCallbackTag */: case 247 /* TypeAliasDeclaration */: case 186 /* MappedType */: // All the children of these container types are never visible through another @@ -31882,7 +32586,9 @@ var ts; container = declName.parent.expression.name; break; case 5 /* Property */: - container = ts.isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name : declName.parent.expression; + container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file + : ts.isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name + : declName.parent.expression; break; case 0 /* None */: return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration"); @@ -32297,7 +33003,7 @@ var ts; case 304 /* JSDocTypeLiteral */: case 186 /* MappedType */: return bindAnonymousTypeWorker(node); - case 309 /* JSDocClassTag */: + case 310 /* JSDocClassTag */: return bindJSDocClassTag(node); case 193 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); @@ -32365,7 +33071,7 @@ var ts; // falls through case 250 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); - case 316 /* JSDocParameterTag */: + case 317 /* JSDocParameterTag */: if (node.parent.kind === 305 /* JSDocSignature */) { return bindParameter(node); } @@ -32373,15 +33079,15 @@ var ts; break; } // falls through - case 322 /* JSDocPropertyTag */: + case 323 /* JSDocPropertyTag */: var propTag = node; var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 299 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 321 /* JSDocTypedefTag */: - case 314 /* JSDocCallbackTag */: - case 315 /* JSDocEnumTag */: + case 322 /* JSDocTypedefTag */: + case 315 /* JSDocCallbackTag */: + case 316 /* JSDocEnumTag */: return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); } } @@ -32423,7 +33129,7 @@ var ts; var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); if (node.isExportEquals) { // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. - setValueDeclaration(symbol, node); + ts.setValueDeclaration(symbol, node); } } } @@ -32525,7 +33231,7 @@ var ts; ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); - setValueDeclaration(symbol, node); + ts.setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -32665,15 +33371,13 @@ var ts; // util.property = function ... bindExportsPropertyAssignment(node); } + else if (ts.hasDynamicName(node)) { + bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */); + var sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototype*/ false, /*containerIsClass*/ false); + addLateBoundAssignmentDeclarationToSymbol(node, sym); + } else { - if (ts.hasDynamicName(node)) { - bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */); - var sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototype*/ false, /*containerIsClass*/ false); - addLateBoundAssignmentDeclarationToSymbol(node, sym); - } - else { - bindStaticPropertyAssignment(ts.cast(node.left, ts.isBindableStaticAccessExpression)); - } + bindStaticPropertyAssignment(ts.cast(node.left, ts.isBindableStaticNameExpression)); } } /** @@ -32681,6 +33385,7 @@ var ts; * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y; */ function bindStaticPropertyAssignment(node) { + ts.Debug.assert(!ts.isIdentifier(node)); node.expression.parent = node; bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false, /*containerIsClass*/ false); } @@ -32891,7 +33596,7 @@ var ts; } } function bindParameter(node) { - if (node.kind === 316 /* JSDocParameterTag */ && container.kind !== 305 /* JSDocSignature */) { + if (node.kind === 317 /* JSDocParameterTag */ && container.kind !== 305 /* JSDocSignature */) { return; } if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) { @@ -33151,6 +33856,9 @@ var ts; return computePropertyAccess(node, subtreeFlags); case 195 /* ElementAccessExpression */: return computeElementAccess(node, subtreeFlags); + case 267 /* JsxSelfClosingElement */: + case 268 /* JsxOpeningElement */: + return computeJsxOpeningLikeElement(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); } @@ -33193,6 +33901,14 @@ var ts; node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */; } + function computeJsxOpeningLikeElement(node, subtreeFlags) { + var transformFlags = subtreeFlags | 2 /* AssertJsx */; + if (node.typeArguments) { + transformFlags |= 1 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536870912 /* NodeExcludes */; + } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; @@ -33608,7 +34324,7 @@ var ts; break; case 199 /* TypeAssertionExpression */: case 217 /* AsExpression */: - case 325 /* PartiallyEmittedExpression */: + case 326 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. transformFlags |= 1 /* AssertTypeScript */; excludeFlags = 536870912 /* OuterExpressionExcludes */; @@ -33627,8 +34343,6 @@ var ts; transformFlags |= 1 /* AssertTypeScript */; break; case 266 /* JsxElement */: - case 267 /* JsxSelfClosingElement */: - case 268 /* JsxOpeningElement */: case 11 /* JsxText */: case 269 /* JsxClosingElement */: case 270 /* JsxFragment */: @@ -33645,8 +34359,18 @@ var ts; case 15 /* TemplateHead */: case 16 /* TemplateMiddle */: case 17 /* TemplateTail */: - case 211 /* TemplateExpression */: + if (node.templateFlags) { + transformFlags |= 32 /* AssertES2018 */; + break; + } + // falls through case 198 /* TaggedTemplateExpression */: + if (ts.hasInvalidEscape(node.template)) { + transformFlags |= 32 /* AssertES2018 */; + break; + } + // falls through + case 211 /* TemplateExpression */: case 282 /* ShorthandPropertyAssignment */: case 120 /* StaticKeyword */: case 219 /* MetaProperty */: @@ -33873,7 +34597,7 @@ var ts; return 536879104 /* BindingPatternExcludes */; case 199 /* TypeAssertionExpression */: case 217 /* AsExpression */: - case 325 /* PartiallyEmittedExpression */: + case 326 /* PartiallyEmittedExpression */: case 200 /* ParenthesizedExpression */: case 102 /* SuperKeyword */: return 536870912 /* OuterExpressionExcludes */; @@ -34103,7 +34827,9 @@ var ts; var WideningKind; (function (WideningKind) { WideningKind[WideningKind["Normal"] = 0] = "Normal"; - WideningKind[WideningKind["GeneratorYield"] = 1] = "GeneratorYield"; + WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn"; + WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext"; + WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield"; })(WideningKind || (WideningKind = {})); var TypeFacts; (function (TypeFacts) { @@ -34239,6 +34965,8 @@ var ts; IntersectionState[IntersectionState["None"] = 0] = "None"; IntersectionState[IntersectionState["Source"] = 1] = "Source"; IntersectionState[IntersectionState["Target"] = 2] = "Target"; + IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck"; + IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck"; })(IntersectionState || (IntersectionState = {})); var MappedTypeModifiers; (function (MappedTypeModifiers) { @@ -34281,6 +35009,11 @@ var ts; DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; })(DeclarationSpaces || (DeclarationSpaces = {})); + function SymbolLinks() { + } + function NodeLinks() { + this.flags = 0; + } function getNodeId(node) { if (!node.id) { node.id = nextNodeId; @@ -34334,12 +35067,12 @@ var ts; var typeCount = 0; var symbolCount = 0; var enumCount = 0; + var totalInstantiationCount = 0; var instantiationCount = 0; var instantiationDepth = 0; var constraintDepth = 0; var currentNode; var emptySymbols = ts.createSymbolTable(); - var identityMapper = ts.identity; var arrayVariances = [1 /* Covariant */]; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -34376,6 +35109,7 @@ var ts; getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, getTypeCount: function () { return typeCount; }, + getInstantiationCount: function () { return totalInstantiationCount; }, getRelationCacheSizes: function () { return ({ assignable: assignableRelation.size, identity: identityRelation.size, @@ -34443,7 +35177,8 @@ var ts; }, getSymbolAtLocation: function (node) { node = ts.getParseTreeNode(node); - return node ? getSymbolAtLocation(node) : undefined; + // set ignoreErrors: true because any lookups invoked by the API shouldn't cause any new errors + return node ? getSymbolAtLocation(node, /*ignoreErrors*/ true) : undefined; }, getShorthandAssignmentValueSymbol: function (node) { node = ts.getParseTreeNode(node); @@ -34583,9 +35318,7 @@ var ts; }, getApparentType: getApparentType, getUnionType: getUnionType, - isTypeAssignableTo: function (source, target) { - return isTypeAssignableTo(source, target); - }, + isTypeAssignableTo: isTypeAssignableTo, createAnonymousType: createAnonymousType, createSignature: createSignature, createSymbol: createSymbol, @@ -34625,6 +35358,9 @@ var ts; getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); }, getAccessibleSymbolChain: getAccessibleSymbolChain, getTypePredicateOfSignature: getTypePredicateOfSignature, + resolveExternalModuleName: function (moduleSpecifier) { + return resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true); + }, resolveExternalModuleSymbol: resolveExternalModuleSymbol, tryGetThisTypeAt: function (node, includeGlobalThis) { node = ts.getParseTreeNode(node); @@ -34731,6 +35467,8 @@ var ts; var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType; var numberOrBigIntType = getUnionType([numberType, bigintType]); + var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t; }); + var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; }); var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */; @@ -34908,6 +35646,7 @@ var ts; if (jsxPragma) { var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); + ts.visitNode(file.localJsxFactory, markAsSynthetic); if (file.localJsxFactory) { return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText; } @@ -34918,6 +35657,7 @@ var ts; _jsxNamespace = "React"; if (compilerOptions.jsxFactory) { _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + ts.visitNode(_jsxFactoryEntity, markAsSynthetic); if (_jsxFactoryEntity) { _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText; } @@ -34926,7 +35666,15 @@ var ts; _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace); } } + if (!_jsxFactoryEntity) { + _jsxFactoryEntity = ts.createQualifiedName(ts.createIdentifier(ts.unescapeLeadingUnderscores(_jsxNamespace)), "createElement"); + } return _jsxNamespace; + function markAsSynthetic(node) { + node.pos = -1; + node.end = -1; + return ts.visitEachChild(node, markAsSynthetic, ts.nullTransformationContext); + } } function getEmitResolver(sourceFile, cancellationToken) { // Ensure we have all the type information in place for this file so that all the @@ -35063,12 +35811,8 @@ var ts; target.constEnumOnlyModule = false; } target.flags |= source.flags; - if (source.valueDeclaration && - (!target.valueDeclaration || - ts.isAssignmentDeclaration(target.valueDeclaration) && !ts.isAssignmentDeclaration(source.valueDeclaration) || - ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { - // other kinds of value declarations take precedence over modules and assignment declarations - target.valueDeclaration = source.valueDeclaration; + if (source.valueDeclaration) { + ts.setValueDeclaration(target, source.valueDeclaration); } ts.addRange(target.declarations, source.declarations); if (source.members) { @@ -35126,24 +35870,32 @@ var ts; function addDuplicateLocations(locs, symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.pushIfUnique(locs, (ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(decl) : ts.getNameOfDeclaration(decl)) || decl); + ts.pushIfUnique(locs, decl); } } } function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations); + addDuplicateDeclarationError(node, message, symbolName, source.declarations); }); } - function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNodes) { + function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) { + var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node; var err = lookupOrIssueError(errorNode, message, symbolName); + var _loop_6 = function (relatedNode) { + var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode; + if (adjustedNode === errorNode) + return "continue"; + err.relatedInformation = err.relatedInformation || []; + var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName); + var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here); + if (ts.length(err.relatedInformation) >= 5 || ts.some(err.relatedInformation, function (r) { return ts.compareDiagnostics(r, followOnMessage) === 0 /* EqualTo */ || ts.compareDiagnostics(r, leadingMessage) === 0 /* EqualTo */; })) + return "continue"; + ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage); + }; for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) { var relatedNode = _a[_i]; - err.relatedInformation = err.relatedInformation || []; - if (ts.length(err.relatedInformation) >= 5) - continue; - 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)); + _loop_6(relatedNode); } } function combineSymbolTables(first, second) { @@ -35164,6 +35916,7 @@ var ts; }); } function mergeModuleAugmentation(moduleName) { + var _a, _b; var moduleAugmentation = moduleName.parent; if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { // this is a combined symbol for multiple augmentations within the same file. @@ -35202,6 +35955,16 @@ var ts; patternAmbientModuleAugmentations.set(moduleName.text, merged); } else { + if (((_a = mainModule_1.exports) === null || _a === void 0 ? void 0 : _a.get("__export" /* ExportStar */)) && ((_b = moduleAugmentation.symbol.exports) === null || _b === void 0 ? void 0 : _b.size)) { + // We may need to merge the module augmentation's exports into the target symbols of the resolved exports + var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */); + for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) { + var _d = _c[_i], key = _d[0], value = _d[1]; + if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) { + mergeSymbol(resolvedExports.get(key), value); + } + } + } mergeSymbol(mainModule_1, moduleAugmentation.symbol); } } @@ -35230,18 +35993,18 @@ var ts; if (symbol.flags & 33554432 /* Transient */) return symbol; var id = getSymbolId(symbol); - return symbolLinks[id] || (symbolLinks[id] = {}); + return symbolLinks[id] || (symbolLinks[id] = new SymbolLinks()); } function getNodeLinks(node) { var nodeId = getNodeId(node); - return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks()); } function isGlobalSourceFile(node) { return node.kind === 290 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { - var symbol = symbols.get(name); + var symbol = getMergedSymbol(symbols.get(name)); if (symbol) { ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { @@ -35277,6 +36040,7 @@ var ts; function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); + var declContainer = ts.getEnclosingBlockScopeContainer(declaration); if (declarationFile !== useFile) { if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || (!compilerOptions.outFile && !compilerOptions.out) || @@ -35318,11 +36082,10 @@ var ts; return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false); } else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) { - var container_3 = ts.getEnclosingBlockScopeContainer(declaration.parent); // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields && ts.getContainingClass(declaration) === ts.getContainingClass(usage) - && isUsedInFunctionOrInstanceProperty(usage, declaration, container_3)); + && isUsedInFunctionOrInstanceProperty(usage, declaration)); } return true; } @@ -35344,40 +36107,42 @@ var ts; if (usage.kind === 259 /* ExportAssignment */ && usage.isExportEquals) { return true; } - var container = ts.getEnclosingBlockScopeContainer(declaration); - if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage)) { + if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) { return true; } - if (isUsedInFunctionOrInstanceProperty(usage, declaration, container)) { - if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields) { - return (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent)) && - !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields + && ts.getContainingClass(declaration) + && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) { + return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true); } else { return true; } } return false; + function usageInTypeDeclaration() { + return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); }); + } function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { - var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { case 225 /* VariableStatement */: case 230 /* ForStatement */: case 232 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) - if (isSameScopeDescendentOf(usage, declaration, container)) { + if (isSameScopeDescendentOf(usage, declaration, declContainer)) { return true; } break; } // ForIn/ForOf case - use site should not be used in expression part var grandparent = declaration.parent.parent; - return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer); } - function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { + function isUsedInFunctionOrInstanceProperty(usage, declaration) { return !!ts.findAncestor(usage, function (current) { - if (current === container) { + if (current === declContainer) { return "quit"; } if (ts.isFunctionLike(current)) { @@ -35439,6 +36204,61 @@ var ts; return ancestorChangingReferenceScope === undefined; } } + function useOuterVariableScopeInParameter(result, location, lastLocation) { + var target = ts.getEmitScriptTarget(compilerOptions); + var functionLocation = location; + if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body + // - static field in a class expression + // - optional chaining pre-es2020 + // - nullish coalesce pre-es2020 + // - spread assignment in binding pattern pre-es2017 + if (target >= 2 /* ES2015 */) { + var links = getNodeLinks(functionLocation); + if (links.declarationRequiresScopeChange === undefined) { + links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false; + } + return !links.declarationRequiresScopeChange; + } + } + return false; + function requiresScopeChange(node) { + return requiresScopeChangeWorker(node.name) + || !!node.initializer && requiresScopeChangeWorker(node.initializer); + } + function requiresScopeChangeWorker(node) { + switch (node.kind) { + case 202 /* ArrowFunction */: + case 201 /* FunctionExpression */: + case 244 /* FunctionDeclaration */: + case 162 /* Constructor */: + // do not descend into these + return false; + case 161 /* MethodDeclaration */: + case 163 /* GetAccessor */: + case 164 /* SetAccessor */: + case 281 /* PropertyAssignment */: + return requiresScopeChangeWorker(node.name); + case 159 /* PropertyDeclaration */: + // static properties in classes introduce temporary variables + if (ts.hasStaticModifier(node)) { + return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields; + } + return requiresScopeChangeWorker(node.name); + default: + // null coalesce and optional chain pre-es2020 produce temporary variables + if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) { + return target < 7 /* ES2020 */; + } + if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) { + return target < 4 /* ES2017 */; + } + if (ts.isTypeNode(node)) + return false; + return ts.forEachChild(node, requiresScopeChangeWorker) || false; + } + } + } /** * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with @@ -35456,7 +36276,7 @@ var ts; var lastLocation; var lastSelfReferenceLocation; var propertyWithInvalidInitializer; - var associatedDeclarationForContainingInitializer; + var associatedDeclarationForContainingInitializerOrBindingName; var withinDeferredContext = false; var errorLocation = location; var grandparent; @@ -35484,9 +36304,7 @@ var ts; } if (meaning & result.flags & 3 /* Variable */) { // expression inside parameter will lookup as normal variable scope when targeting es2015+ - var functionLocation = location; - if (compilerOptions.target && compilerOptions.target >= 2 /* ES2015 */ && ts.isParameter(lastLocation) && - functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) { + if (useOuterVariableScopeInParameter(result, location, lastLocation)) { useResult = false; } else if (result.flags & 1 /* FunctionScopedVariable */) { @@ -35700,22 +36518,28 @@ var ts; location = location.parent; } break; - case 321 /* JSDocTypedefTag */: - case 314 /* JSDocCallbackTag */: - case 315 /* JSDocEnumTag */: + case 322 /* JSDocTypedefTag */: + case 315 /* JSDocCallbackTag */: + case 316 /* JSDocEnumTag */: // js type aliases do not resolve names from their host, so skip past it location = ts.getJSDocHost(location); break; case 156 /* Parameter */: - if (lastLocation && lastLocation === location.initializer) { - associatedDeclarationForContainingInitializer = location; + if (lastLocation && (lastLocation === location.initializer || + lastLocation === location.name && ts.isBindingPattern(lastLocation))) { + if (!associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; + } } break; case 191 /* BindingElement */: - if (lastLocation && lastLocation === location.initializer) { + if (lastLocation && (lastLocation === location.initializer || + lastLocation === location.name && ts.isBindingPattern(lastLocation))) { var root = ts.getRootDeclaration(location); if (root.kind === 156 /* Parameter */) { - associatedDeclarationForContainingInitializer = location; + if (!associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; + } } } break; @@ -35815,17 +36639,17 @@ var ts; errorOrSuggestion(!compilerOptions.allowUmdGlobalAccess, errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); } } - // If we're in a parameter initializer, we can't reference the values of the parameter whose initializer we're within or parameters to the right - if (result && associatedDeclarationForContainingInitializer && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) { + // If we're in a parameter initializer or binding name, we can't reference the values of the parameter whose initializer we're within or parameters to the right + if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) { var candidate = getMergedSymbol(getLateBoundSymbol(result)); - var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializer); + var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName); // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself - if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializer)) { - error(errorLocation, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(associatedDeclarationForContainingInitializer.name)); + if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) { + error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name)); } // And it cannot refer to any declarations which come after it - else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializer.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) { - error(errorLocation, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializer.name), ts.declarationNameToString(errorLocation)); + else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) { + error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation)); } } if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) { @@ -35838,10 +36662,11 @@ var ts; if (!ts.isValidTypeOnlyAliasUseSite(useSite)) { var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(symbol); if (typeOnlyDeclaration) { - var message = typeOnlyDeclaration.kind === 263 /* ExportSpecifier */ + var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration); + var message = isExport ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type; - var relatedMessage = typeOnlyDeclaration.kind === 263 /* ExportSpecifier */ + var relatedMessage = isExport ? ts.Diagnostics._0_was_exported_here : ts.Diagnostics._0_was_imported_here; var unescapedName = ts.unescapeLeadingUnderscores(name); @@ -35975,7 +36800,7 @@ var ts; if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) { var symbol = resolveSymbol(resolveName(errorLocation, name, ~788968 /* Type */ & 111551 /* 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)); + error(errorLocation, ts.Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here_Did_you_mean_typeof_0, ts.unescapeLeadingUnderscores(name)); return true; } } @@ -36143,10 +36968,11 @@ var ts; function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) { if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false)) { var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfNode(node)); - var message = typeOnlyDeclaration.kind === 263 /* ExportSpecifier */ + var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration); + var message = isExport ? ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type : ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type; - var relatedMessage = typeOnlyDeclaration.kind === 263 /* ExportSpecifier */ + var relatedMessage = isExport ? ts.Diagnostics._0_was_exported_here : ts.Diagnostics._0_was_imported_here; // Non-null assertion is safe because the optionality comes from ImportClause, @@ -36219,12 +37045,7 @@ var ts; ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); } else { - if (moduleSymbol.exports && moduleSymbol.exports.has(node.symbol.escapedName)) { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); - } - else { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); - } + reportNonDefaultExport(moduleSymbol, node); } } else if (hasSyntheticDefault) { @@ -36237,6 +37058,25 @@ var ts; return exportDefaultSymbol; } } + function reportNonDefaultExport(moduleSymbol, node) { + var _a, _b; + if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); + } + else { + var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */); + if (exportStar) { + var defaultExport = ts.find(exportStar.declarations, function (decl) { + var _a, _b; + return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier && ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */))); + }); + if (defaultExport) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default)); + } + } + } + } function getTargetOfNamespaceImport(node, dontResolveAlias) { var moduleSpecifier = node.parent.parent.moduleSpecifier; var immediate = resolveExternalModuleName(node, moduleSpecifier); @@ -36306,8 +37146,8 @@ var ts; } } function getExternalModuleMember(node, specifier, dontResolveAlias) { - if (dontResolveAlias === void 0) { dontResolveAlias = false; } var _a; + if (dontResolveAlias === void 0) { dontResolveAlias = false; } var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217 var name = specifier.propertyName || specifier.name; var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop); @@ -36353,7 +37193,7 @@ var ts; error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); } else { - reportNonExportedMember(name, declarationName, moduleSymbol, moduleName); + reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName); } } } @@ -36361,25 +37201,48 @@ var ts; } } } - function reportNonExportedMember(name, declarationName, moduleSymbol, moduleName) { + function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) { var _a; var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText); var exports = moduleSymbol.exports; if (localSymbol) { - var exportedSymbol = exports && !exports.has("export=" /* ExportEquals */) - ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) - : undefined; - var diagnostic = exportedSymbol - ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) - : error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); - ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { - return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); - }))); + var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */); + if (exportedEqualsSymbol) { + getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) : + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } + else { + var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined; + var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) : + error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName); + ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) { + return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName); + }))); + } } else { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); } } + function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) { + if (moduleKind >= ts.ModuleKind.ES2015) { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName); + } + else { + if (ts.isInJSFile(node)) { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName); + } + else { + var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import : + ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import; + error(name, message, declarationName, declarationName, moduleName); + } + } + } function getTargetOfImportSpecifier(node, dontResolveAlias) { var resolved = getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false); @@ -36398,7 +37261,7 @@ var ts; return resolved; } function getTargetOfExportAssignment(node, dontResolveAlias) { - var expression = (ts.isExportAssignment(node) ? node.expression : node.right); + var expression = ts.isExportAssignment(node) ? node.expression : node.right; var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias); markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false); return resolved; @@ -36491,6 +37354,13 @@ var ts; } return links.target; } + function tryResolveAlias(symbol) { + var links = getSymbolLinks(symbol); + if (links.target !== resolvingSymbol) { + return resolveAlias(symbol); + } + return undefined; + } /** * Marks a symbol as type-only if its declaration is syntactically type-only. * If it is not itself marked type-only, but resolves to a type-only alias @@ -36619,11 +37489,11 @@ var ts; var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0); var symbol; if (name.kind === 75 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); - var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; - symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); + var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); + var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; + symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true)); if (!symbol) { - return symbolFromJSPrototype; + return getMergedSymbol(symbolFromJSPrototype); } } else if (name.kind === 153 /* QualifiedName */ || name.kind === 194 /* PropertyAccessExpression */) { @@ -36651,7 +37521,7 @@ var ts; } } } - symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning)); if (!symbol) { if (!ignoreErrors) { error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); @@ -36663,7 +37533,7 @@ var ts; throw ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); - if (ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 259 /* ExportAssignment */)) { + if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 259 /* ExportAssignment */)) { markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true); } return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); @@ -36706,8 +37576,8 @@ var ts; return getDeclarationOfJSPrototypeContainer(symbol); } } - var sig = ts.getHostSignatureFromJSDocHost(host); - if (sig) { + var sig = ts.getEffectiveJSDocHost(node); + if (sig && ts.isFunctionLike(sig)) { var symbol = getSymbolOfNode(sig); return symbol && symbol.valueDeclaration; } @@ -36742,7 +37612,7 @@ var ts; } } function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { - return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0); + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations); } function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { if (isForAugmentation === void 0) { isForAugmentation = false; } @@ -36851,7 +37721,7 @@ var ts; return getPackagesSet().has(ts.getTypesPackageName(packageName)); } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { - if (moduleSymbol) { + if (moduleSymbol === null || moduleSymbol === void 0 ? void 0 : moduleSymbol.exports) { var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias); var exported = getCommonJsExportEquals(getMergedSymbol(exportEquals), getMergedSymbol(moduleSymbol)); return getMergedSymbol(exported) || moduleSymbol; @@ -37127,11 +37997,14 @@ var ts; } return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); function fileSymbolIfFileSymbolExportEqualsContainer(d) { - var fileSymbol = getExternalModuleContainer(d); - var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); - return exported && container && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined; + return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container); } } + function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined; + } function getAliasForSymbolInContainer(container, symbol) { if (container === getParentOfSymbol(symbol)) { // fast path, `symbol` is either already the alias or isn't aliased @@ -37251,7 +38124,7 @@ var ts; } function forEachSymbolTableInScope(enclosingDeclaration, callback) { var result; - var _loop_6 = function (location) { + var _loop_7 = function (location) { // Locals of a source file are not in scope (because they get merged into the global symbol table) if (location.locals && !isGlobalSourceFile(location)) { if (result = callback(location.locals)) { @@ -37297,7 +38170,7 @@ var ts; } }; for (var location = enclosingDeclaration; location; location = location.parent) { - var state_2 = _loop_6(location); + var state_2 = _loop_7(location); if (typeof state_2 === "object") return state_2.value; } @@ -37486,7 +38359,7 @@ var ts; // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, // we'd like to make that connection here - potentially causing us to paint the declaration's visibility, and therefore the literal. - var firstDecl = ts.first(symbol.declarations); + var firstDecl = !!ts.length(symbol.declarations) && ts.first(symbol.declarations); if (!ts.length(containers) && meaning & 111551 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) { if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { containers = [getSymbolOfNode(firstDecl.parent)]; @@ -37681,7 +38554,7 @@ var ts; var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); var result = writer.getText(); - var maxLength = noTruncation ? undefined : ts.defaultMaximumTruncationLength * 2; + var maxLength = noTruncation ? ts.noTruncationMaximumTruncationLength * 2 : ts.defaultMaximumTruncationLength * 2; if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } @@ -37701,7 +38574,7 @@ var ts; } function toNodeBuilderFlags(flags) { if (flags === void 0) { flags = 0 /* None */; } - return flags & 277904747 /* NodeBuilderFlagsMask */; + return flags & 814775659 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { return { @@ -37740,10 +38613,15 @@ var ts; flags: flags || 0 /* None */, // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? { - getCommonSourceDirectory: host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, + getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, getSourceFiles: function () { return host.getSourceFiles(); }, - getCurrentDirectory: ts.maybeBind(host, host.getCurrentDirectory), + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks), + useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), + redirectTargetsMap: host.redirectTargetsMap, + getProjectReferenceRedirect: function (fileName) { return host.getProjectReferenceRedirect(fileName); }, + isSourceOfProjectReferenceRedirect: function (fileName) { return host.isSourceOfProjectReferenceRedirect(fileName); }, + fileExists: function (fileName) { return host.fileExists(fileName); }, } : undefined }, encounteredError: false, visitedTypes: undefined, @@ -37757,7 +38635,7 @@ var ts; function checkTruncationLength(context) { if (context.truncating) return context.truncating; - return context.truncating = !(context.flags & 1 /* NoTruncation */) && context.approximateLength > ts.defaultMaximumTruncationLength; + return context.truncating = context.approximateLength > ((context.flags & 1 /* NoTruncation */) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength); } function typeToTypeNodeHelper(type, context) { if (cancellationToken && cancellationToken.throwIfCancellationRequested) { @@ -37766,8 +38644,15 @@ var ts; var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; context.flags &= ~8388608 /* InTypeAlias */; if (!type) { - context.encounteredError = true; - return undefined; // TODO: GH#18217 + if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { + context.encounteredError = true; + return undefined; // TODO: GH#18217 + } + context.approximateLength += 3; + return ts.createKeywordTypeNode(125 /* AnyKeyword */); + } + if (!(context.flags & 536870912 /* NoTypeReduction */)) { + type = getReducedType(type); } if (type.flags & 1 /* Any */) { context.approximateLength += 3; @@ -37943,7 +38828,7 @@ var ts; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } if (type.flags & 33554432 /* Substitution */) { - return typeToTypeNodeHelper(type.typeVariable, context); + return typeToTypeNodeHelper(type.baseType, context); } return ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { @@ -38117,14 +39002,14 @@ var ts; var i = 0; var resultType = void 0; if (outerTypeParameters) { - var length_1 = outerTypeParameters.length; - while (i < length_1) { + var length_2 = outerTypeParameters.length; + while (i < length_2) { // Find group of type arguments for type parameters with the same declaring container. var start = i; var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { @@ -38291,7 +39176,7 @@ var ts; propertyTypeNode = createElidedInformationPlaceholder(context); } else { - propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(125 /* AnyKeyword */); + propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.createKeywordTypeNode(125 /* AnyKeyword */); } context.flags = savedFlags; var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined; @@ -38303,8 +39188,8 @@ var ts; typeElements.push(preserveCommentsOn(propertySignature)); } function preserveCommentsOn(node) { - if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 322 /* JSDocPropertyTag */; })) { - var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 322 /* JSDocPropertyTag */; }); + if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 323 /* JSDocPropertyTag */; })) { + var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 323 /* JSDocPropertyTag */; }); var commentText = d.comment; if (commentText) { ts.setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]); @@ -38331,28 +39216,63 @@ var ts; ]; } } - var result = []; + var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */); + /** Map from type reference identifier text to [type, index in `result` where the type node is] */ + var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined; + var result_3 = []; var i = 0; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; i++; if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { - result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + result_3.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode_1) { - result.push(typeNode_1); + result_3.push(typeNode_1); } break; } context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { - result.push(typeNode); + result_3.push(typeNode); + if (seenNames && ts.isIdentifierTypeReference(typeNode)) { + seenNames.add(typeNode.typeName.escapedText, [type, result_3.length - 1]); + } } } - return result; + if (seenNames) { + // To avoid printing types like `[Foo, Foo]` or `Bar & Bar` where + // occurrences of the same name actually come from different + // namespaces, go through the single-identifier type reference nodes + // we just generated, and see if any names were generated more than + // once while referring to different types. If so, regenerate the + // type node for each entry by that name with the + // `UseFullyQualifiedType` flag enabled. + var saveContextFlags = context.flags; + context.flags |= 64 /* UseFullyQualifiedType */; + seenNames.forEach(function (types) { + if (!ts.arrayIsHomogeneous(types, function (_a, _b) { + var a = _a[0]; + var b = _b[0]; + return typesAreSameReference(a, b); + })) { + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var _a = types_2[_i], type = _a[0], resultIndex = _a[1]; + result_3[resultIndex] = typeToTypeNodeHelper(type, context); + } + } + }); + context.flags = saveContextFlags; + } + return result_3; } } + function typesAreSameReference(a, b) { + return a === b + || !!a.symbol && a.symbol === b.symbol + || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol; + } function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) { var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 143 /* StringKeyword */ : 140 /* NumberKeyword */); @@ -38370,7 +39290,7 @@ var ts; return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } - function signatureToSignatureDeclarationHelper(signature, kind, context) { + function signatureToSignatureDeclarationHelper(signature, kind, context, privateSymbolVisitor, bundledImports) { var suppressAny = context.flags & 256 /* SuppressAnyReturnType */; if (suppressAny) context.flags &= ~256 /* SuppressAnyReturnType */; // suppress only toplevel `any`s @@ -38382,7 +39302,7 @@ var ts; else { typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); } - var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */); }); + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */, privateSymbolVisitor, bundledImports); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -38402,7 +39322,7 @@ var ts; else { var returnType = getReturnTypeOfSignature(signature); if (returnType && !(suppressAny && isTypeAny(returnType))) { - returnTypeNode = typeToTypeNodeHelper(returnType, context); + returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, privateSymbolVisitor, bundledImports); } else if (!suppressAny) { returnTypeNode = ts.createKeywordTypeNode(125 /* AnyKeyword */); @@ -38425,16 +39345,16 @@ var ts; var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } - function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { + function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) { var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 156 /* Parameter */); if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) { - parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 316 /* JSDocParameterTag */); + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 317 /* JSDocParameterTag */); } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { parameterType = getOptionalType(parameterType); } - var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); + var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* RestParameter */; var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; @@ -38485,7 +39405,7 @@ var ts; var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) { - chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); + chain = ts.Debug.checkDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } else { @@ -38579,10 +39499,10 @@ var ts; var typeParameterNodes; if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) { var parentSymbol = symbol; - var nextSymbol = chain[index + 1]; - if (ts.getCheckFlags(nextSymbol) & 1 /* Instantiated */) { + var nextSymbol_1 = chain[index + 1]; + if (ts.getCheckFlags(nextSymbol_1) & 1 /* Instantiated */) { var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); - typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context); + typeParameterNodes = mapToTypeNodes(ts.map(params, function (t) { return getMappedType(t, nextSymbol_1.mapper); }), context); } else { typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); @@ -38601,6 +39521,12 @@ var ts; } function getSpecifierForModuleSymbol(symbol, context) { var file = ts.getDeclarationOfKind(symbol, 290 /* SourceFile */); + if (!file) { + var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); }); + if (equivalentFileSymbol) { + file = ts.getDeclarationOfKind(equivalentFileSymbol, 290 /* SourceFile */); + } + } if (file && file.moduleName !== undefined) { // Use the amd name if it is available return file.moduleName; @@ -38637,7 +39563,7 @@ var ts; // specifier preference var moduleResolverHost = context.tracker.moduleResolverHost; var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions; - specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, host.getSourceFiles(), { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }, host.redirectTargetsMap)); + specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" })); links.specifierCache = links.specifierCache || ts.createMap(); links.specifierCache.set(contextFile.path, specifier); } @@ -38739,8 +39665,15 @@ var ts; return identifier; } } - function typeParameterShadowsNameInScope(escapedName, context) { - return !!resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false); + function typeParameterShadowsNameInScope(escapedName, context, type) { + var result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false); + if (result) { + if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) { + return false; + } + return true; + } + return false; } function typeParameterToName(type, context) { if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) { @@ -38757,7 +39690,7 @@ var ts; var rawtext = result.escapedText; var i = 0; var text = rawtext; - while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context)) { + while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context, type)) { i++; text = rawtext + "_" + i; } @@ -38878,7 +39811,7 @@ var ts; } } function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) { - return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) ? +name : name, !!singleQuote); + return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) && +name >= 0 ? +name : name, !!singleQuote); } function cloneNodeBuilderContext(context) { var initial = __assign({}, context); @@ -38905,6 +39838,179 @@ var ts; } return initial; } + function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) { + return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; })); }); + } + function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) { + return !(ts.getObjectFlags(type) & 4 /* Reference */) || !ts.isTypeReferenceNode(existing) || ts.length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters); + } + /** + * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag + * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym` + */ + function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) { + if (type !== errorType && enclosingDeclaration) { + var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration); + if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { + // try to reuse the existing annotation + var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); + if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { + var result_4 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled); + if (result_4) { + return result_4; + } + } + } + } + var oldFlags = context.flags; + if (type.flags & 8192 /* UniqueESSymbol */ && + type.symbol === symbol) { + context.flags |= 1048576 /* AllowUniqueESSymbolType */; + } + var result = typeToTypeNodeHelper(type, context); + context.flags = oldFlags; + return result; + } + function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) { + if (type !== errorType && context.enclosingDeclaration) { + var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) { + var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled); + if (result) { + return result; + } + } + } + return typeToTypeNodeHelper(type, context); + } + function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) { + if (cancellationToken && cancellationToken.throwIfCancellationRequested) { + cancellationToken.throwIfCancellationRequested(); + } + var hadError = false; + var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols); + if (hadError) { + return undefined; + } + return transformed === existing ? ts.getMutableClone(existing) : transformed; + function visitExistingNodeTreeSymbols(node) { + var _a, _b; + // We don't _actually_ support jsdoc namepath types, emit `any` instead + if (ts.isJSDocAllType(node) || node.kind === 302 /* JSDocNamepathType */) { + return ts.createKeywordTypeNode(125 /* AnyKeyword */); + } + if (ts.isJSDocUnknownType(node)) { + return ts.createKeywordTypeNode(148 /* UnknownKeyword */); + } + if (ts.isJSDocNullableType(node)) { + return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]); + } + if (ts.isJSDocOptionalType(node)) { + return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]); + } + if (ts.isJSDocNonNullableType(node)) { + return ts.visitNode(node.type, visitExistingNodeTreeSymbols); + } + if (ts.isJSDocVariadicType(node)) { + return ts.createArrayTypeNode(ts.visitNode(node.type, visitExistingNodeTreeSymbols)); + } + if (ts.isJSDocTypeLiteral(node)) { + return ts.createTypeLiteralNode(ts.map(node.jsDocPropertyTags, function (t) { + var name = ts.isIdentifier(t.name) ? t.name : t.name.right; + var typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode(node), name.escapedText); + var overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode(t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : undefined; + return ts.createPropertySignature( + /*modifiers*/ undefined, name, t.typeExpression && ts.isJSDocOptionalType(t.typeExpression.type) ? ts.createToken(57 /* QuestionToken */) : undefined, overrideTypeNode || (t.typeExpression && ts.visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols)) || ts.createKeywordTypeNode(125 /* AnyKeyword */), + /*initializer*/ undefined); + })); + } + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") { + return ts.setOriginalNode(ts.createKeywordTypeNode(125 /* AnyKeyword */), node); + } + if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { + return ts.createTypeLiteralNode([ts.createIndexSignature( + /*decorators*/ undefined, + /*modifiers*/ undefined, [ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotdotdotToken*/ undefined, "x", + /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); + } + if (ts.isJSDocFunctionType(node)) { + if (ts.isJSDocConstructSignature(node)) { + var newTypeNode_1; + return ts.createConstructorTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), + /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols)); + } + else { + return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), + /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols)); + } + } + if (ts.isTypeReferenceNode(node) && ts.isInJSDoc(node) && (getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */, /*ignoreErrors*/ true))) { + return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node); + } + if (ts.isLiteralImportTypeNode(node)) { + return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); + } + if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { + var leftmost = ts.getFirstIdentifier(node); + if (ts.isInJSFile(node) && (ts.isExportsIdentifier(leftmost) || ts.isModuleExportsAccessExpression(leftmost.parent) || (ts.isQualifiedName(leftmost.parent) && ts.isModuleIdentifier(leftmost.parent.left) && ts.isExportsIdentifier(leftmost.parent.right)))) { + hadError = true; + return node; + } + var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); + if (sym) { + if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) { + hadError = true; + } + else { + (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.trackSymbol) === null || _b === void 0 ? void 0 : _b.call(_a, sym, context.enclosingDeclaration, 67108863 /* All */); + includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym); + } + if (ts.isIdentifier(node)) { + var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.getMutableClone(node); + name.symbol = sym; // for quickinfo, which uses identifier symbol information + return ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */); + } + } + } + return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext); + function getEffectiveDotDotDotForParameter(p) { + return p.dotDotDotToken || (p.type && ts.isJSDocVariadicType(p.type) ? ts.createToken(25 /* DotDotDotToken */) : undefined); + } + function rewriteModuleSpecifier(parent, lit) { + if (bundled) { + if (context.tracker && context.tracker.moduleResolverHost) { + var targetFile = getExternalModuleFileFromDeclaration(parent); + if (targetFile) { + var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames); + var resolverHost = { + getCanonicalFileName: getCanonicalFileName, + getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); }, + getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); } + }; + var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile); + return ts.createLiteral(newName); + } + } + } + else { + if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) { + var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined); + if (moduleSym) { + context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym); + } + } + } + return lit; + } + } + } function symbolTableToDeclarationStatements(symbolTable, context, bundled) { var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.createProperty, 161 /* MethodDeclaration */, /*useAcessors*/ true); var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type, initializer) { return ts.createPropertySignature(mods, name, question, type, initializer); }, 160 /* MethodSignature */, /*useAcessors*/ false); @@ -38999,7 +40105,7 @@ var ts; if (ts.length(reexports) > 1) { var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; }); if (groups.length !== reexports.length) { - var _loop_7 = function (group_1) { + var _loop_8 = function (group_1) { if (group_1.length > 1) { // remove group members from statements and then merge group members and add back to statements statements = __spreadArrays(ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), [ @@ -39011,7 +40117,7 @@ var ts; }; for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) { var group_1 = groups_1[_i]; - _loop_7(group_1); + _loop_8(group_1); } } } @@ -39119,7 +40225,7 @@ var ts; function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) { var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName); var isDefault = symbol.escapedName === "default" /* Default */; - if (ts.isStringANonContextualKeyword(symbolName) && !isDefault) { + if (!(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) { // Oh no. We cannot use this symbol's name as it's name... It's likely some jsdoc had an invalid name like `export` or `default` :( context.encounteredError = true; // TODO: Issue error via symbol tracker? @@ -39154,7 +40260,7 @@ var ts; serializeEnum(symbol, symbolName, modifierFlags); } if (symbol.flags & 32 /* Class */) { - if (symbol.flags & 4 /* Property */) { + if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) { // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members, // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today. @@ -39194,7 +40300,7 @@ var ts; function includePrivateSymbol(symbol) { if (ts.some(symbol.declarations, ts.isParameterDeclaration)) return; - ts.Debug.assertDefined(deferredPrivates); + ts.Debug.assertIsDefined(deferredPrivates); getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol deferredPrivates.set("" + getSymbolId(symbol), symbol); } @@ -39255,7 +40361,7 @@ var ts; /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags); } function getNamespaceMembersForSerialization(symbol) { - return !symbol.exports ? [] : ts.filter(ts.arrayFrom((symbol.exports).values()), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember); } function isTypeOnlyNamespace(symbol) { return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); }); @@ -39274,13 +40380,19 @@ var ts; serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */))); } if (ts.length(mergedMembers)) { + var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration); var localName = getInternalSymbolName(symbol, symbolName); var nsBody = ts.createModuleBlock([ts.createExportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) { + /*modifiers*/ undefined, ts.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) { + var _a, _b; var name = ts.unescapeLeadingUnderscores(s.escapedName); var localName = getInternalSymbolName(s, name); var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s); + if (containingFile_1 && (aliasDecl ? containingFile_1 !== ts.getSourceFileOfNode(aliasDecl) : !ts.some(s.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile_1; }))) { + (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportNonlocalAugmentation) === null || _b === void 0 ? void 0 : _b.call(_a, containingFile_1, symbol, s); + return undefined; + } var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true); includePrivateSymbol(target || s); var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName; @@ -39325,7 +40437,7 @@ var ts; textRange = textRange.parent.parent; } var statement = ts.setTextRange(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(name, serializeTypeForDeclaration(type, symbol)) + ts.createVariableDeclaration(name, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled)) ], flags)), textRange); addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags); if (name !== localName && !isPrivate) { @@ -39362,13 +40474,14 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; // Each overload becomes a separate function declaration, in order - var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context); + var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context, includePrivateSymbol, bundled); decl.name = ts.createIdentifier(localName); - addResult(ts.setTextRange(decl, sig.declaration), modifierFlags); + // for expressions assigned to `var`s, use the `var` as the text range + addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags); } // Module symbol emit will take care of module-y members, provided it has exports if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) { - var props = ts.filter(getPropertiesOfType(type), function (p) { return !((p.flags & 4194304 /* Prototype */) || (p.escapedName === "prototype")); }); + var props = ts.filter(getPropertiesOfType(type), isNamespaceMember); serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true); } } @@ -39421,24 +40534,32 @@ var ts; addResult(fakespace, modifierFlags); // namespaces can never be default exported } } + function isNamespaceMember(p) { + return !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && ts.isClassLike(p.valueDeclaration.parent)); + } function serializeAsClass(symbol, localName, modifierFlags) { var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); }); var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseTypes = getBaseTypes(classType); + var implementsTypes = getImplementsTypes(classType); var staticType = getTypeOfSymbol(symbol); var staticBaseType = getBaseConstructorTypeOfClass(staticType); - var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.createHeritageClause(90 /* ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))]; - var symbolProps = getPropertiesOfType(classType); + var heritageClauses = __spreadArrays(!ts.length(baseTypes) ? [] : [ts.createHeritageClause(90 /* ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], !ts.length(implementsTypes) ? [] : [ts.createHeritageClause(113 /* ImplementsKeyword */, ts.map(implementsTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))]); + var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType)); var publicSymbolProps = ts.filter(symbolProps, function (s) { + // `valueDeclaration` could be undefined if inherited from + // a union/intersection base type, but inherited properties + // don't matter here. var valueDecl = s.valueDeclaration; - ts.Debug.assertDefined(valueDecl); - return !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); + return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name)); }); var hasPrivateIdentifier = ts.some(symbolProps, function (s) { + // `valueDeclaration` could be undefined if inherited from + // a union/intersection base type, but inherited properties + // don't matter here. var valueDecl = s.valueDeclaration; - ts.Debug.assertDefined(valueDecl); - return ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); + return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name); }); // Boil down all private properties into a single one. var privateProperties = hasPrivateIdentifier ? @@ -39451,9 +40572,7 @@ var ts; ts.emptyArray; var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ false, baseTypes[0]); }); // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics - var staticMembers = symbol.flags & (16 /* Function */ | 512 /* ValueModule */) - ? [] - : ts.flatMap(ts.filter(getPropertiesOfType(staticType), function (p) { return !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype"; }), function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ true, staticBaseType); }); + var staticMembers = ts.flatMap(ts.filter(getPropertiesOfType(staticType), function (p) { return !(p.flags & 4194304 /* Prototype */) && p.escapedName !== "prototype" && !isNamespaceMember(p); }), function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ true, staticBaseType); }); var constructors = serializeSignatures(1 /* Construct */, staticType, baseTypes[0], 162 /* Constructor */); for (var _i = 0, constructors_1 = constructors; _i < constructors_1.length; _i++) { var c = constructors_1[_i]; @@ -39585,7 +40704,7 @@ var ts; if (referenced || target) { includePrivateSymbol(referenced || target); } - // We disable the context's symbol traker for the duration of this name serialization + // We disable the context's symbol tracker for the duration of this name serialization // as, by virtue of being here, the name is required to print something, and we don't want to // issue a visibility error on it. Only anonymous classes that an alias points at _would_ issue // a visibility error here (as they're not visible within any scope), but we want to hoist them @@ -39621,14 +40740,14 @@ var ts; var varName = getUnusedName(name, symbol); // We have to use `getWidenedType` here since the object within a json file is unwidened within the file // (Unwidened types can only exist in expression contexts and should never be serialized) - var typeToSerialize = getWidenedType(getTypeOfSymbol(symbol)); + var typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol))); if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) { // If there are no index signatures and `typeToSerialize` is an object type, emit as a namespace instead of a const serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignment ? 0 /* None */ : 1 /* Export */); } else { var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(varName, serializeTypeForDeclaration(typeToSerialize, symbol)) + ts.createVariableDeclaration(varName, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled)) ], 2 /* Const */)); addResult(statement, name === varName ? 1 /* Export */ : 0 /* None */); } @@ -39652,7 +40771,7 @@ var ts; !getIndexInfoOfType(typeToSerialize, 1 /* Number */) && !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) && !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK - !getDeclarationWithTypeAnnotation(hostSymbol) && + !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) && !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) && !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) && !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) && @@ -39667,13 +40786,14 @@ var ts; // need to be merged namespace members return []; } - if (p.flags & 4194304 /* Prototype */ || (baseType && getPropertyOfType(baseType, p.escapedName) - && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) - && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */) - && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) { + if (p.flags & 4194304 /* Prototype */ || + (baseType && getPropertyOfType(baseType, p.escapedName) + && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p) + && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */) + && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) { return []; } - var flag = modifierFlags | (isStatic ? 32 /* Static */ : 0); + var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0); var name = getPropertyNameNodeForSymbol(p, context); var firstPropertyLikeDecl = ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression)); if (p.flags & 98304 /* Accessor */ && useAccessors) { @@ -39684,13 +40804,13 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "arg", - /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p))], + /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl)); } if (p.flags & 32768 /* GetAccessor */) { var isPrivate_1 = modifierFlags & 8 /* Private */; result.push(ts.setTextRange(ts.createGetAccessor( - /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p), + /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl)); } return result; @@ -39699,7 +40819,7 @@ var ts; // If this happens, we assume the accessor takes priority, as it imposes more constraints else if (p.flags & (4 /* Property */ | 3 /* Variable */)) { return ts.setTextRange(createProperty( - /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(getTypeOfSymbol(p), p), + /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl); @@ -39736,115 +40856,6 @@ var ts; function serializePropertySymbolForInterface(p, baseType) { return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ false, baseType); } - function getDeclarationWithTypeAnnotation(symbol) { - return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; }); }); - } - /** - * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag - * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym` - */ - function serializeTypeForDeclaration(type, symbol) { - var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol); - if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) { - // try to reuse the existing annotation - var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation); - var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols); - return transformed === existing ? ts.getMutableClone(existing) : transformed; - } - var oldFlags = context.flags; - if (type.flags & 8192 /* UniqueESSymbol */ && - type.symbol === symbol) { - context.flags |= 1048576 /* AllowUniqueESSymbolType */; - } - var result = typeToTypeNodeHelper(type, context); - context.flags = oldFlags; - return result; - function visitExistingNodeTreeSymbols(node) { - if (ts.isJSDocAllType(node)) { - return ts.createKeywordTypeNode(125 /* AnyKeyword */); - } - if (ts.isJSDocUnknownType(node)) { - return ts.createKeywordTypeNode(148 /* UnknownKeyword */); - } - if (ts.isJSDocNullableType(node)) { - return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]); - } - if (ts.isJSDocOptionalType(node)) { - return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]); - } - if (ts.isJSDocNonNullableType(node)) { - return ts.visitNode(node.type, visitExistingNodeTreeSymbols); - } - if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) { - return ts.createTypeLiteralNode([ts.createIndexSignature( - /*decorators*/ undefined, - /*modifiers*/ undefined, [ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotdotdotToken*/ undefined, "x", - /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]); - } - if (ts.isJSDocFunctionType(node)) { - if (ts.isJSDocConstructSignature(node)) { - var newTypeNode_1; - return ts.createConstructorTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, p.dotDotDotToken, p.name || p.dotDotDotToken ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), - /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols)); - } - else { - return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, p.dotDotDotToken, p.name || p.dotDotDotToken ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), - /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols)); - } - } - if (ts.isLiteralImportTypeNode(node)) { - return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); - } - if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = ts.getFirstIdentifier(node); - var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); - if (sym) { - includePrivateSymbol(sym); - if (ts.isIdentifier(node) && sym.flags & 262144 /* TypeParameter */) { - var name = typeParameterToName(getDeclaredTypeOfSymbol(sym), context); - if (ts.idText(name) !== ts.idText(node)) { - return name; - } - return node; - } - } - } - return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext); - } - function rewriteModuleSpecifier(parent, lit) { - if (bundled) { - if (context.tracker && context.tracker.moduleResolverHost) { - var targetFile = getExternalModuleFileFromDeclaration(parent); - if (targetFile) { - var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames); - var resolverHost = { - getCanonicalFileName: getCanonicalFileName, - getCurrentDirectory: context.tracker.moduleResolverHost.getCurrentDirectory ? function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); } : function () { return ""; }, - getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); } - }; - var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile); - return ts.createLiteral(newName); - } - } - } - else { - if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) { - var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined); - if (moduleSym) { - context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym); - } - } - } - return lit; - } - } function serializeSignatures(kind, input, baseType, outputKind) { var signatures = getSignaturesOfType(input, kind); if (kind === 1 /* Construct */) { @@ -40138,9 +41149,9 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 314 /* JSDocCallbackTag */: - case 321 /* JSDocTypedefTag */: - case 315 /* JSDocEnumTag */: + case 315 /* JSDocCallbackTag */: + case 322 /* JSDocTypedefTag */: + case 316 /* JSDocEnumTag */: // 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)); @@ -40276,8 +41287,8 @@ var ts; var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { // A cycle was found - var length_2 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_2; i++) { + var length_3 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_3; i++) { resolutionResults[i] = false; } return false; @@ -40366,9 +41377,6 @@ var ts; var symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } - function isComputedNonLiteralName(name) { - return name.kind === 154 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteralLike(name.expression); - } function getRestType(source, properties, symbol) { source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); }); if (source.flags & 131072 /* Never */) { @@ -40473,9 +41481,14 @@ var ts; if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } + // Filter `undefined` from the type we check against if the parent has an initializer and that initializer is not possibly `undefined` + else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */)) { + parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */); + } var type; if (pattern.kind === 189 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { + parentType = getReducedType(parentType); if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); return errorType; @@ -40566,7 +41579,7 @@ var ts; // [Symbol.iterator] or next). This may be because we accessed properties from anyType, // or it may have led to an error inside getElementTypeOfIterable. var forOfStatement = declaration.parent.parent; - return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; + return checkRightHandSideOfForOf(forOfStatement) || anyType; } if (ts.isBindingPattern(declaration.parent)) { return getTypeForBindingElement(declaration); @@ -40777,28 +41790,55 @@ var ts; } return anyType; } + if (containsSameNamedThisProperty(expression.left, expression.right)) { + return anyType; + } var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & 524288 /* Object */ && kind === 2 /* ModuleExports */ && symbol.escapedName === "export=" /* ExportEquals */) { - var exportedType_1 = resolveStructuredTypeMembers(type); + var exportedType = resolveStructuredTypeMembers(type); var members_4 = ts.createSymbolTable(); - ts.copyEntries(exportedType_1.members, members_4); + ts.copyEntries(exportedType.members, members_4); if (resolvedSymbol && !resolvedSymbol.exports) { resolvedSymbol.exports = ts.createSymbolTable(); } (resolvedSymbol || symbol).exports.forEach(function (s, name) { - if (members_4.has(name)) { - var exportedMember = exportedType_1.members.get(name); - var union = createSymbol(s.flags | exportedMember.flags, name); - union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); - members_4.set(name, union); + var _a; + var exportedMember = members_4.get(name); + if (exportedMember && exportedMember !== s) { + if (s.flags & 111551 /* Value */) { + // If the member has an additional value-like declaration, union the types from the two declarations, + // but issue an error if they occurred in two different files. The purpose is to support a JS file with + // a pattern like: + // + // module.exports = { a: true }; + // module.exports.a = 3; + // + // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation + // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because + // it's unclear what that's supposed to mean, so it's probably a mistake. + if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) { + var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName); + var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration; + ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName)); + ts.addRelatedInfo(error(exportedMemberName, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(s.valueDeclaration, ts.Diagnostics._0_was_also_declared_here, unescapedName)); + } + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + union.valueDeclaration = exportedMember.valueDeclaration; + union.declarations = ts.concatenate(exportedMember.declarations, s.declarations); + members_4.set(name, union); + } + else { + members_4.set(name, mergeSymbol(s, exportedMember)); + } } else { members_4.set(name, s); } }); - var result = createAnonymousType(exportedType_1.symbol, members_4, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + var result = createAnonymousType(exportedType.symbol, members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo); result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag return result; } @@ -40808,6 +41848,11 @@ var ts; } return type; } + function containsSameNamedThisProperty(thisProperty, expression) { + return ts.isPropertyAccessExpression(thisProperty) + && thisProperty.expression.kind === 104 /* ThisKeyword */ + && ts.forEachChildRecursively(expression, function (n) { return isMatchingReference(thisProperty, n); }); + } function isDeclarationInConstructor(expression) { var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. @@ -41183,7 +42228,7 @@ var ts; var links = getSymbolLinks(symbol); var originalLinks = links; if (!links.type) { - var jsDeclaration = ts.getDeclarationOfExpando(symbol.valueDeclaration); + var jsDeclaration = symbol.valueDeclaration && ts.getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { var merged = mergeJSSymbols(symbol, getSymbolOfNode(jsDeclaration)); if (merged) { @@ -41200,9 +42245,9 @@ var ts; if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { return anyType; } - else if (declaration.kind === 209 /* BinaryExpression */ || + else if (declaration && (declaration.kind === 209 /* BinaryExpression */ || ts.isAccessExpression(declaration) && - declaration.parent.kind === 209 /* BinaryExpression */) { + declaration.parent.kind === 209 /* BinaryExpression */)) { return getWidenedTypeForAssignmentDeclaration(symbol); } else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) { @@ -41280,20 +42325,24 @@ var ts; function getTypeOfSymbolWithDeferredType(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - ts.Debug.assertDefined(links.deferralParent); - ts.Debug.assertDefined(links.deferralConstituents); + ts.Debug.assertIsDefined(links.deferralParent); + ts.Debug.assertIsDefined(links.deferralConstituents); links.type = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralConstituents) : getIntersectionType(links.deferralConstituents); } return links.type; } function getTypeOfSymbol(symbol) { - if (ts.getCheckFlags(symbol) & 65536 /* DeferredType */) { + var checkFlags = ts.getCheckFlags(symbol); + if (checkFlags & 65536 /* DeferredType */) { return getTypeOfSymbolWithDeferredType(symbol); } - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + if (checkFlags & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } - if (ts.getCheckFlags(symbol) & 8192 /* ReverseMapped */) { + if (checkFlags & 262144 /* Mapped */) { + return getTypeOfMappedSymbol(symbol); + } + if (checkFlags & 8192 /* ReverseMapped */) { return getTypeOfReverseMappedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -41364,6 +42413,7 @@ var ts; return undefined; } switch (node.kind) { + case 225 /* VariableStatement */: case 245 /* ClassDeclaration */: case 214 /* ClassExpression */: case 246 /* InterfaceDeclaration */: @@ -41378,10 +42428,10 @@ var ts; case 201 /* FunctionExpression */: case 202 /* ArrowFunction */: case 247 /* TypeAliasDeclaration */: - case 320 /* JSDocTemplateTag */: - case 321 /* JSDocTypedefTag */: - case 315 /* JSDocEnumTag */: - case 314 /* JSDocCallbackTag */: + case 321 /* JSDocTemplateTag */: + case 322 /* JSDocTypedefTag */: + case 316 /* JSDocEnumTag */: + case 315 /* JSDocCallbackTag */: case 186 /* MappedType */: case 180 /* ConditionalType */: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); @@ -41391,6 +42441,9 @@ var ts; else if (node.kind === 180 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } + else if (node.kind === 225 /* VariableStatement */ && !ts.isInJSFile(node)) { + break; + } var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */ || node.kind === 246 /* InterfaceDeclaration */ || isJSConstructor(node)) && @@ -41512,6 +42565,28 @@ var ts; } return type.resolvedBaseConstructorType; } + function getImplementsTypes(type) { + var resolvedImplementsTypes = ts.emptyArray; + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration); + if (!implementsTypeNodes) + continue; + for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) { + var node = implementsTypeNodes_1[_b]; + var implementsType = getTypeFromTypeNode(node); + if (implementsType !== errorType) { + if (resolvedImplementsTypes === ts.emptyArray) { + resolvedImplementsTypes = [implementsType]; + } + else { + resolvedImplementsTypes.push(implementsType); + } + } + } + } + return resolvedImplementsTypes; + } function getBaseTypes(type) { if (!type.resolvedBaseTypes) { if (type.objectFlags & 8 /* Tuple */) { @@ -41564,11 +42639,14 @@ var ts; if (baseType === errorType) { return type.resolvedBaseTypes = ts.emptyArray; } - if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(baseType)); + var reducedBaseType = getReducedType(baseType); + if (!isValidBaseType(reducedBaseType)) { + var elaboration = elaborateNeverIntersection(/*errorInfo*/ undefined, baseType); + var diagnostic = ts.chainDiagnosticMessages(elaboration, ts.Diagnostics.Base_constructor_return_type_0_is_not_an_object_type_or_intersection_of_object_types_with_statically_known_members, typeToString(reducedBaseType)); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(baseTypeNode.expression, diagnostic)); return type.resolvedBaseTypes = ts.emptyArray; } - if (type === baseType || hasBaseType(baseType, type)) { + if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) { error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); return type.resolvedBaseTypes = ts.emptyArray; } @@ -41579,7 +42657,7 @@ var ts; // partial instantiation of the members without the base types fully resolved type.members = undefined; } - return type.resolvedBaseTypes = [baseType]; + return type.resolvedBaseTypes = [reducedBaseType]; } function areAllOuterTypeParametersApplied(type) { // An unapplied type parameter has its symbol still the same as the matching argument symbol. @@ -41602,8 +42680,8 @@ var ts; } // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed? // There's no reason a `T` should be allowed while a `Readonly` should not. - return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || - !!(type.flags & 2097152 /* Intersection */) && ts.every(type.types, isValidBaseType); + return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || + type.flags & 2097152 /* Intersection */ && ts.every(type.types, isValidBaseType)); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; @@ -41612,7 +42690,7 @@ var ts; if (declaration.kind === 246 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; - var baseType = getTypeFromTypeNode(node); + var baseType = getReducedType(getTypeFromTypeNode(node)); if (baseType !== errorType) { if (isValidBaseType(baseType)) { if (type !== baseType && !hasBaseType(baseType, type)) { @@ -41707,7 +42785,7 @@ var ts; if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { return errorType; } - var declaration = ts.Debug.assertDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found"); + var declaration = ts.Debug.checkDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found"); var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; @@ -42222,7 +43300,6 @@ var ts; var stringIndexInfo; var numberIndexInfo; if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { - mapper = identityMapper; members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties); callSignatures = source.declaredCallSignatures; constructSignatures = source.declaredConstructSignatures; @@ -42439,7 +43516,7 @@ var ts; // signatures from the type, whose ordering would be non-obvious) var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0]; var results = masterList.slice(); - var _loop_8 = function (signatures) { + var _loop_9 = function (signatures) { if (signatures !== masterList) { var signature_1 = signatures[0]; ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); @@ -42451,7 +43528,7 @@ var ts; }; for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) { var signatures = signatureLists_1[_b]; - var state_3 = _loop_8(signatures); + var state_3 = _loop_9(signatures); if (state_3 === "break") break; } @@ -42515,9 +43592,9 @@ var ts; function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; - for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { - var type = types_2[_i]; - var indexInfo = getIndexInfoOfType(type, kind); + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var type = types_3[_i]; + var indexInfo = getIndexInfoOfType(getApparentType(type), kind); if (!indexInfo) { return undefined; } @@ -42575,7 +43652,7 @@ var ts; var types = type.types; var mixinFlags = findMixins(types); var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; }); - var _loop_9 = function (i) { + var _loop_10 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -42598,19 +43675,19 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_9(i); + _loop_10(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, stringIndexInfo, numberIndexInfo); } function appendSignatures(signatures, newSignatures) { - var _loop_10 = function (sig) { + var _loop_11 = function (sig) { if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical); })) { signatures = ts.append(signatures, sig); } }; for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) { var sig = newSignatures_1[_i]; - _loop_10(sig); + _loop_11(sig); } return signatures; } @@ -42726,8 +43803,7 @@ var ts; var checkType = type.checkType; var constraint = getLowerBoundOfKeyType(checkType); if (constraint !== checkType) { - var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); - return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + return getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper)); } } return type; @@ -42776,8 +43852,7 @@ var ts; // Create a mapper from T to the current iteration type constituent. Then, if the // mapped type is itself an instantiated type, combine the iteration mapper with the // instantiation mapper. - var templateMapper = combineTypeMappers(type.mapper, createTypeMapper([typeParameter], [t])); - var propType = instantiateType(templateType, templateMapper); + var templateMapper = appendTypeMapping(type.mapper, typeParameter, t); // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. if (isTypeUsableAsPropertyName(t)) { @@ -42787,13 +43862,10 @@ var ts; !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */); var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ || !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp)); - var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, isReadonly ? 8 /* Readonly */ : 0); - // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the - // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks - // mode, if the underlying property is optional we remove 'undefined' from the type. - prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : - strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : - propType; + var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */; + var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0)); + prop.mappedType = type; + prop.mapper = templateMapper; if (modifiersProp) { prop.syntheticOrigin = modifiersProp; prop.declarations = modifiersProp.declarations; @@ -42801,14 +43873,39 @@ var ts; prop.nameType = t; members.set(propName, prop); } - else if (t.flags & (1 /* Any */ | 4 /* String */)) { - stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); - } - else if (t.flags & (8 /* Number */ | 32 /* Enum */)) { - numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + else if (t.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 32 /* Enum */)) { + var propType = instantiateType(templateType, templateMapper); + if (t.flags & (1 /* Any */ | 4 /* String */)) { + stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } + else { + numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } } } } + function getTypeOfMappedSymbol(symbol) { + if (!symbol.type) { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return errorType; + } + var templateType = getTemplateTypeFromMappedType(symbol.mappedType.target || symbol.mappedType); + var propType = instantiateType(templateType, symbol.mapper); + // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the + // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks + // mode, if the underlying property is optional we remove 'undefined' from the type. + var type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) : + symbol.checkFlags & 524288 /* StripOptional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : + propType; + if (!popTypeResolution()) { + error(currentNode, ts.Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(symbol.mappedType)); + type = errorType; + } + symbol.type = type; + symbol.mapper = undefined; + } + return symbol.type; + } function getTypeParameterFromMappedType(type) { return type.typeParameter || (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); @@ -42820,7 +43917,7 @@ var ts; function getTemplateTypeFromMappedType(type) { return type.templateType || (type.templateType = type.declaration.type ? - instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper || identityMapper) : + instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper) : errorType); } function getConstraintDeclarationForMappedType(type) { @@ -42837,7 +43934,7 @@ var ts; // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves // 'keyof T' to a literal union type and we can't recover T from that type. - type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper); + type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper); } else { // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, @@ -42846,7 +43943,7 @@ var ts; var declaredType = getTypeFromMappedTypeNode(type.declaration); var constraint = getConstraintTypeFromMappedType(declaredType); var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : unknownType; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper) : unknownType; } } return type.modifiersType; @@ -42933,8 +44030,8 @@ var ts; } } // The properties of a union type are those that are present in all constituent types, so - // we only need to check the properties of the first type - if (type.flags & 1048576 /* Union */) { + // we only need to check the properties of the first type without index signature + if (type.flags & 1048576 /* Union */ && !getIndexInfoOfType(current, 0 /* String */) && !getIndexInfoOfType(current, 1 /* Number */)) { break; } } @@ -42943,7 +44040,7 @@ var ts; return type.resolvedProperties; } function getPropertiesOfType(type) { - type = getApparentType(type); + type = getReducedApparentType(type); return type.flags & 3145728 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); @@ -42963,8 +44060,8 @@ var ts; return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); - for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { - var memberType = types_3[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var memberType = types_4[_i]; for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) { var escapedName = _b[_a].escapedName; if (!props.has(escapedName)) { @@ -43035,8 +44132,7 @@ var ts; var simplified = getSimplifiedType(type.checkType, /*writing*/ false); var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint && constraint !== type.checkType) { - var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); - var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + var instantiated = getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper)); if (!(instantiated.flags & 131072 /* Never */)) { return instantiated; } @@ -43053,8 +44149,8 @@ var ts; function getEffectiveConstraintOfIntersection(types, targetIsUnion) { var constraints; var hasDisjointDomainType = false; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var t = types_4[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var t = types_5[_i]; if (t.flags & 63176704 /* Instantiable */) { // We keep following constraints as long as we have an instantiable type that is known // not to be circular or infinite (hence we stop on index access types). @@ -43079,8 +44175,8 @@ var ts; if (hasDisjointDomainType) { // We add any types belong to one of the disjoint domains because they might cause the final // intersection operation to reduce the union constraints. - for (var _a = 0, types_5 = types; _a < types_5.length; _a++) { - var t = types_5[_a]; + for (var _a = 0, types_6 = types; _a < types_6.length; _a++) { + var t = types_6[_a]; if (t.flags & 67238908 /* DisjointDomains */) { constraints = ts.append(constraints, t); } @@ -43166,8 +44262,8 @@ var ts; if (t.flags & 3145728 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; - for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { - var type_2 = types_6[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var type_2 = types_7[_i]; var baseType = getBaseConstraint(type_2); if (baseType) { baseTypes.push(baseType); @@ -43253,8 +44349,7 @@ var ts; if (typeVariable) { var constraint = getConstraintOfTypeParameter(typeVariable); if (constraint && (isArrayType(constraint) || isTupleType(constraint))) { - var mapper = makeUnaryTypeMapper(typeVariable, constraint); - return instantiateType(type, combineTypeMappers(mapper, type.mapper)); + return instantiateType(type, prependTypeMapping(typeVariable, constraint, type.mapper)); } } return type; @@ -43262,7 +44357,7 @@ var ts; /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the - * type itself. Note that the apparent type of a union type is the union type itself. + * type itself. */ function getApparentType(type) { var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type; @@ -43270,7 +44365,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 >= 99 /* ESNext */) : + t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ES2020 */) : t.flags & 528 /* BooleanLike */ ? globalBooleanType : t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType : @@ -43278,11 +44373,18 @@ var ts; t.flags & 2 /* Unknown */ && !strictNullChecks ? emptyObjectType : t; } + function getReducedApparentType(type) { + // Since getApparentType may return a non-reduced union or intersection type, we need to perform + // type reduction both before and after obtaining the apparent type. For example, given a type parameter + // 'T extends A | B', the type 'T & X' becomes 'A & X | B & X' after obtaining the apparent type, and + // that type may need futher reduction to remove empty intersections. + return getReducedType(getApparentType(getReducedType(type))); + } function createUnionOrIntersectionProperty(containingType, name) { - var propSet = ts.createMap(); + var singleProp; + var propSet; var indexTypes; var isUnion = containingType.flags & 1048576 /* Union */; - var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */; var syntheticFlag = 4 /* SyntheticMethod */; @@ -43290,19 +44392,28 @@ var ts; for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var current = _a[_i]; var type = getApparentType(current); - if (type !== errorType) { + if (!(type === errorType || type.flags & 131072 /* Never */)) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; - if (prop && !(modifiers & excludeModifiers)) { + if (prop) { if (isUnion) { optionalFlag |= (prop.flags & 16777216 /* Optional */); } else { optionalFlag &= prop.flags; } - var id = "" + getSymbolId(prop); - if (!propSet.has(id)) { - propSet.set(id, prop); + if (!singleProp) { + singleProp = prop; + } + else if (prop !== singleProp) { + if (!propSet) { + propSet = ts.createMap(); + propSet.set("" + getSymbolId(singleProp), singleProp); + } + var id = "" + getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) | @@ -43329,13 +44440,15 @@ var ts; } } } - if (!propSet.size) { + if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */)) { + // No property was found, or, in a union, a property has a private or protected declaration in one + // constituent, but is missing or has a different declaration in another constituent. return undefined; } - var props = ts.arrayFrom(propSet.values()); - if (props.length === 1 && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { - return props[0]; + if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) { + return singleProp; } + var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp]; var declarations; var firstType; var nameType; @@ -43347,7 +44460,7 @@ var ts; if (!firstValueDeclaration) { firstValueDeclaration = prop.valueDeclaration; } - else if (prop.valueDeclaration !== firstValueDeclaration) { + else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) { hasNonUniformValueDeclaration = true; } declarations = ts.addRange(declarations, prop.declarations); @@ -43362,6 +44475,9 @@ var ts; if (isLiteralType(type)) { checkFlags |= 128 /* HasLiteralType */; } + if (type.flags & 131072 /* Never */) { + checkFlags |= 131072 /* HasNeverType */; + } propTypes.push(type); } ts.addRange(propTypes, indexTypes); @@ -43408,6 +44524,63 @@ var ts; // We need to filter out partial properties in union types return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined; } + /** + * Return the reduced form of the given type. For a union type, it is a union of the normalized constituent types. + * For an intersection of types containing one or more mututally exclusive discriminant properties, it is 'never'. + * For all other types, it is simply the type itself. Discriminant properties are considered mutually exclusive when + * no constituent property has type 'never', but the intersection of the constituent property types is 'never'. + */ + function getReducedType(type) { + if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) { + return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type)); + } + else if (type.flags & 2097152 /* Intersection */) { + if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) { + type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ | + (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0); + } + return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type; + } + return type; + } + function getReducedUnionType(unionType) { + var reducedTypes = ts.sameMap(unionType.types, getReducedType); + if (reducedTypes === unionType.types) { + return unionType; + } + var reduced = getUnionType(reducedTypes); + if (reduced.flags & 1048576 /* Union */) { + reduced.resolvedReducedType = reduced; + } + return reduced; + } + function isNeverReducedProperty(prop) { + return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop); + } + function isDiscriminantWithNeverType(prop) { + // Return true for a synthetic non-optional property with non-uniform types, where at least one is + // a literal type and none is never, that reduces to never. + return !(prop.flags & 16777216 /* Optional */) && + (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ && + !!(getTypeOfSymbol(prop).flags & 131072 /* Never */); + } + function isConflictingPrivateProperty(prop) { + // Return true for a synthetic property with multiple declarations, at least one of which is private. + return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */); + } + function elaborateNeverIntersection(errorInfo, type) { + if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) { + var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType); + if (neverProp) { + return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_has_conflicting_types_in_some_constituents, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(neverProp)); + } + var privateProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty); + if (privateProp) { + return ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_intersection_0_was_reduced_to_never_because_property_1_exists_in_multiple_constituents_and_is_private_in_some, typeToString(type, /*enclosingDeclaration*/ undefined, 536870912 /* NoTypeReduction */), symbolToString(privateProp)); + } + } + return errorInfo; + } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from @@ -43417,7 +44590,7 @@ var ts; * @param name a name of property to look up in a given type */ function getPropertyOfType(type, name) { - type = getApparentType(type); + type = getReducedApparentType(type); if (type.flags & 524288 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); @@ -43453,7 +44626,7 @@ var ts; * maps primitive types and type parameters are to their apparent types. */ function getSignaturesOfType(type, kind) { - return getSignaturesOfStructuredType(getApparentType(type), kind); + return getSignaturesOfStructuredType(getReducedApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { if (type.flags & 3670016 /* StructuredType */) { @@ -43468,12 +44641,12 @@ var ts; // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and // maps primitive types and type parameters are to their apparent types. function getIndexInfoOfType(type, kind) { - return getIndexInfoOfStructuredType(getApparentType(type), kind); + return getIndexInfoOfStructuredType(getReducedApparentType(type), kind); } // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and // maps primitive types and type parameters are to their apparent types. function getIndexTypeOfType(type, kind) { - return getIndexTypeOfStructuredType(getApparentType(type), kind); + return getIndexTypeOfStructuredType(getReducedApparentType(type), kind); } function getImplicitIndexTypeOfType(type, kind) { if (isObjectTypeWithInferableIndex(type)) { @@ -43488,7 +44661,7 @@ var ts; ts.append(propTypes, getIndexTypeOfType(type, 1 /* Number */)); } if (propTypes.length) { - return getUnionType(propTypes, 2 /* Subtype */); + return getUnionType(propTypes); } } return undefined; @@ -43537,7 +44710,7 @@ var ts; var signature = getSignatureFromDeclaration(node.parent); var parameterIndex = node.parent.parameters.indexOf(node); ts.Debug.assert(parameterIndex >= 0); - return parameterIndex >= getMinArgumentCount(signature); + return parameterIndex >= getMinArgumentCount(signature, /*strongArityForUntypedJS*/ true); } var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); if (iife) { @@ -43612,6 +44785,9 @@ var ts; ts.isValueSignatureDeclaration(declaration) && !ts.hasJSDocParameterTags(declaration) && !ts.getJSDocType(declaration); + if (isUntypedSignatureInJSFile) { + flags |= 16 /* IsUntypedSignatureInJSFile */; + } // If this is a JSDoc construct signature, then skip the first parameter in the // parameter list. The first parameter represents the return type of the construct // signature. @@ -43638,7 +44814,6 @@ var ts; var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || param.initializer || param.questionToken || param.dotDotDotToken || iife && parameters.length > iife.arguments.length && !type || - isUntypedSignatureInJSFile || isJSDocOptionalParameter(param); if (!isOptionalParameter_1) { minArgumentCount = parameters.length; @@ -43691,7 +44866,10 @@ var ts; return true; } function getSignatureOfTypeTag(node) { - var typeTag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined; + // should be attached to a function declaration or expression + if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node))) + return undefined; + var typeTag = ts.getJSDocTypeTag(node); var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -44036,8 +45214,18 @@ var ts; } else { var constraintDeclaration = getConstraintDeclaration(typeParameter); - typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) : - getInferredTypeParameterConstraint(typeParameter) || noConstraintType; + if (!constraintDeclaration) { + typeParameter.constraint = getInferredTypeParameterConstraint(typeParameter) || noConstraintType; + } + else { + var type = getTypeFromTypeNode(constraintDeclaration); + if (type.flags & 1 /* Any */ && type !== errorType) { // Allow errorType to propegate to keep downstream errors suppressed + // use keyofConstraintType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was), + // use unknown otherwise + type = constraintDeclaration.parent.parent.kind === 186 /* MappedType */ ? keyofConstraintType : unknownType; + } + typeParameter.constraint = type; + } } } return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; @@ -44050,12 +45238,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_3 = types.length; + var length_4 = types.length; var i = 0; - while (i < length_3) { + while (i < length_4) { var startId = types[i].id; var count = 1; - while (i + count < length_3 && types[i + count].id === startId + count) { + while (i + count < length_4 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -44076,8 +45264,8 @@ var ts; // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types, excludeKinds) { var result = 0; - 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]; if (!(type.flags & excludeKinds)) { result |= ts.getObjectFlags(type); } @@ -44168,7 +45356,7 @@ var ts; return errorType; } } - if (node.kind === 169 /* TypeReference */ && isAliasedType(node)) { + if (node.kind === 169 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) { return createDeferredTypeReference(type, node, /*mapper*/ undefined); } // In a type reference, the outer type parameters of the referenced class or interface are automatically @@ -44246,9 +45434,7 @@ var ts; // Get type from reference to named type that cannot be generic (enum or type parameter) var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { - return checkNoTypeArguments(node, symbol) ? - res.flags & 262144 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : - errorType; + return checkNoTypeArguments(node, symbol) ? getRegularTypeOfLiteralType(res) : errorType; } if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) { var jsdocType = getTypeFromJSDocValueReference(node, symbol); @@ -44294,17 +45480,17 @@ var ts; } return links.resolvedJSDocType; } - function getSubstitutionType(typeVariable, substitute) { - if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === typeVariable) { - return typeVariable; + function getSubstitutionType(baseType, substitute) { + if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === baseType) { + return baseType; } - var id = getTypeId(typeVariable) + ">" + getTypeId(substitute); + var id = getTypeId(baseType) + ">" + getTypeId(substitute); var cached = substitutionTypes.get(id); if (cached) { return cached; } var result = createType(33554432 /* Substitution */); - result.typeVariable = typeVariable; + result.baseType = baseType; result.substitute = substitute; substitutionTypes.set(id, result); return result; @@ -44312,24 +45498,24 @@ var ts; function isUnaryTupleTypeNode(node) { return node.kind === 175 /* TupleType */ && node.elementTypes.length === 1; } - function getImpliedConstraint(typeVariable, checkNode, extendsNode) { - return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : - getActualTypeVariable(getTypeFromTypeNode(checkNode)) === typeVariable ? getTypeFromTypeNode(extendsNode) : + function getImpliedConstraint(type, checkNode, extendsNode) { + return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : + getActualTypeVariable(getTypeFromTypeNode(checkNode)) === type ? getTypeFromTypeNode(extendsNode) : undefined; } - function getConstrainedTypeVariable(typeVariable, node) { + function getConditionalFlowTypeOfType(type, node) { var constraints; while (node && !ts.isStatement(node) && node.kind !== 303 /* JSDocComment */) { var parent = node.parent; if (parent.kind === 180 /* ConditionalType */ && node === parent.trueType) { - var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); + var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); } } node = parent; } - return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; + return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type; } function isJSDocTypeReference(node) { return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 169 /* TypeReference */ || node.kind === 188 /* ImportType */); @@ -44393,6 +45579,11 @@ var ts; function getTypeFromTypeReference(node) { var links = getNodeLinks(node); if (!links.resolvedType) { + // handle LS queries on the `const` in `x as const` by resolving to the type of `x` + if (ts.isConstTypeReference(node) && ts.isAssertionExpression(node.parent)) { + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = checkExpressionCached(node.parent.expression); + } var symbol = void 0; var type = void 0; var meaning = 788968 /* Type */; @@ -44571,10 +45762,17 @@ var ts; var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 176 /* OptionalType */ && n !== restElement; }) + 1; return getTupleTypeOfArity(node.elementTypes.length, minLength, !!restElement, readonly, /*associatedNames*/ undefined); } + // Return true if the given type reference node is directly aliased or if it needs to be deferred + // because it is possibly contained in a circular chain of eagerly resolved types. + function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) { + return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 174 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) : + node.kind === 175 /* TupleType */ ? ts.some(node.elementTypes, mayResolveTypeAlias) : + hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias)); + } // Return true when the given node is transitively contained in type constructs that eagerly // resolve their constituent types. We include SyntaxKind.TypeReference because type arguments // of type aliases are eagerly resolved. - function isAliasedType(node) { + function isResolvedByTypeAlias(node) { var parent = node.parent; switch (parent.kind) { case 182 /* ParenthesizedType */: @@ -44584,12 +45782,44 @@ var ts; case 185 /* IndexedAccessType */: case 180 /* ConditionalType */: case 184 /* TypeOperator */: - return isAliasedType(parent); + case 174 /* ArrayType */: + case 175 /* TupleType */: + return isResolvedByTypeAlias(parent); case 247 /* TypeAliasDeclaration */: return true; } return false; } + // Return true if resolving the given node (i.e. getTypeFromTypeNode) possibly causes resolution + // of a type alias. + function mayResolveTypeAlias(node) { + switch (node.kind) { + case 169 /* TypeReference */: + return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node.typeName, 788968 /* Type */).flags & 524288 /* TypeAlias */); + case 172 /* TypeQuery */: + return true; + case 184 /* TypeOperator */: + return node.operator !== 147 /* UniqueKeyword */ && mayResolveTypeAlias(node.type); + case 182 /* ParenthesizedType */: + case 176 /* OptionalType */: + case 299 /* JSDocOptionalType */: + case 297 /* JSDocNullableType */: + case 298 /* JSDocNonNullableType */: + case 294 /* JSDocTypeExpression */: + return mayResolveTypeAlias(node.type); + case 177 /* RestType */: + return node.type.kind !== 174 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType); + case 178 /* UnionType */: + case 179 /* IntersectionType */: + return ts.some(node.types, mayResolveTypeAlias); + case 185 /* IndexedAccessType */: + return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType); + case 180 /* ConditionalType */: + return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) || + mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType); + } + return false; + } function getTypeFromArrayOrTupleTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -44597,7 +45827,7 @@ var ts; if (target === emptyGenericType) { links.resolvedType = emptyObjectType; } - else if (isAliasedType(node)) { + else if (isDeferredTypeReferenceNode(node)) { links.resolvedType = node.kind === 175 /* TupleType */ && node.elementTypes.length === 0 ? target : createDeferredTypeReference(target, node, /*mapper*/ undefined); } @@ -44713,14 +45943,14 @@ var ts; } // We ignore 'never' types in unions if (!(flags & 131072 /* Never */)) { - includes |= flags & 68943871 /* IncludesMask */; + includes |= flags & 71041023 /* IncludesMask */; if (flags & 66846720 /* StructuredOrInstantiable */) includes |= 262144 /* IncludesStructuredOrInstantiable */; if (type === wildcardType) - includes |= 4194304 /* IncludesWildcard */; + includes |= 8388608 /* IncludesWildcard */; if (!strictNullChecks && flags & 98304 /* Nullable */) { if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */)) - includes |= 2097152 /* IncludesNonWideningType */; + includes |= 4194304 /* IncludesNonWideningType */; } else { var len = typeSet.length; @@ -44735,8 +45965,8 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToUnion(typeSet, includes, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var type = types_9[_i]; includes = addTypeToUnion(typeSet, includes, type); } return includes; @@ -44765,8 +45995,8 @@ var ts; while (i > 0) { i--; var source = types[i]; - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var target = types_9[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var target = types_10[_i]; if (source !== target) { if (count === 100000) { // After 100000 subtype checks we estimate the remaining amount of work by assuming the @@ -44826,7 +46056,7 @@ var ts; var includes = addTypesToUnion(typeSet, 0, types); if (unionReduction !== 0 /* None */) { if (includes & 3 /* AnyOrUnknown */) { - return includes & 1 /* Any */ ? includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; + return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; } switch (unionReduction) { case 1 /* Literal */: @@ -44841,12 +46071,14 @@ var ts; break; } if (typeSet.length === 0) { - return includes & 65536 /* Null */ ? includes & 2097152 /* IncludesNonWideningType */ ? nullType : nullWideningType : - includes & 32768 /* Undefined */ ? includes & 2097152 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType : + return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType : + includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType : neverType; } } - return getUnionTypeFromSortedList(typeSet, includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */, aliasSymbol, aliasTypeArguments); + var objectFlags = (includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) | + (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0); + return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -44918,15 +46150,15 @@ var ts; return addTypesToIntersection(typeSet, includes, type.types); } if (isEmptyAnonymousObjectType(type)) { - if (!(includes & 8388608 /* IncludesEmptyObject */)) { - includes |= 8388608 /* IncludesEmptyObject */; + if (!(includes & 16777216 /* IncludesEmptyObject */)) { + includes |= 16777216 /* IncludesEmptyObject */; typeSet.set(type.id.toString(), type); } } else { if (flags & 3 /* AnyOrUnknown */) { if (type === wildcardType) - includes |= 4194304 /* IncludesWildcard */; + includes |= 8388608 /* IncludesWildcard */; } else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !typeSet.has(type.id.toString())) { if (type.flags & 109440 /* Unit */ && includes & 109440 /* Unit */) { @@ -44936,15 +46168,15 @@ var ts; } typeSet.set(type.id.toString(), type); } - includes |= flags & 68943871 /* IncludesMask */; + includes |= flags & 71041023 /* IncludesMask */; } return includes; } // 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_10 = types; _i < types_10.length; _i++) { - var type = types_10[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var type = types_11[_i]; includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type)); } return includes; @@ -45069,7 +46301,7 @@ var ts; // a void-like type and a type known to be non-void-like, or // a non-primitive type and a type known to be primitive. if (includes & 131072 /* Never */ || - strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 8388608 /* IncludesEmptyObject */) || + strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) || includes & 67108864 /* NonPrimitive */ && includes & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) || includes & 132 /* StringLike */ && includes & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) || includes & 296 /* NumberLike */ && includes & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) || @@ -45079,7 +46311,7 @@ var ts; return neverType; } if (includes & 1 /* Any */) { - return includes & 4194304 /* IncludesWildcard */ ? wildcardType : anyType; + return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType; } if (!strictNullChecks && includes & 98304 /* Nullable */) { return includes & 32768 /* Undefined */ ? undefinedType : nullType; @@ -45090,7 +46322,7 @@ var ts; includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) { removeRedundantPrimitiveTypes(typeSet, includes); } - if (includes & 8388608 /* IncludesEmptyObject */ && includes & 524288 /* Object */) { + if (includes & 16777216 /* IncludesEmptyObject */ && includes & 524288 /* Object */) { ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType)); } if (typeSet.length === 0) { @@ -45195,6 +46427,7 @@ var ts; } function getIndexType(type, stringsOnly, noIndexSignatures) { if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } + type = getReducedType(type); return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) : maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : @@ -45427,10 +46660,24 @@ var ts; accessNode; } function isGenericObjectType(type) { - return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 131072 /* GenericMappedType */); + if (type.flags & 3145728 /* UnionOrIntersection */) { + if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) { + type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ | + (ts.some(type.types, isGenericObjectType) ? 8388608 /* IsGenericObjectType */ : 0); + } + return !!(type.objectFlags & 8388608 /* IsGenericObjectType */); + } + return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type); } function isGenericIndexType(type) { - return maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */); + if (type.flags & 3145728 /* UnionOrIntersection */) { + if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) { + type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ | + (ts.some(type.types, isGenericIndexType) ? 33554432 /* IsGenericIndexType */ : 0); + } + return !!(type.objectFlags & 33554432 /* IsGenericIndexType */); + } + return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */)); } function isThisTypeParameter(type) { return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType); @@ -45570,7 +46817,7 @@ var ts; // In the following we resolve T[K] to the type of the property in T selected by K. // We treat boolean as different from other unions to improve errors; // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. - var apparentObjectType = getApparentType(objectType); + var apparentObjectType = getReducedApparentType(objectType); if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; var wasMissingProp = false; @@ -45605,7 +46852,7 @@ var ts; links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ && resolved.objectType === objectType && resolved.indexType === indexType ? - getConstrainedTypeVariable(resolved, node) : resolved; + getConditionalFlowTypeOfType(resolved, node) : resolved; } return links.resolvedType; } @@ -45625,7 +46872,7 @@ var ts; } function getActualTypeVariable(type) { if (type.flags & 33554432 /* Substitution */) { - return type.typeVariable; + return type.baseType; } if (type.flags & 8388608 /* IndexedAccess */ && (type.objectType.flags & 33554432 /* Substitution */ || type.indexType.flags & 33554432 /* Substitution */)) { @@ -45634,65 +46881,89 @@ var ts; return type; } function getConditionalType(root, mapper) { - var checkType = instantiateType(root.checkType, mapper); - var extendsType = instantiateType(root.extendsType, mapper); - if (checkType === wildcardType || extendsType === wildcardType) { - return wildcardType; + var result; + var extraTypes; + var _loop_12 = function () { + var checkType = instantiateType(root.checkType, mapper); + var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType); + var extendsType = instantiateType(root.extendsType, mapper); + if (checkType === wildcardType || extendsType === wildcardType) { + return { value: wildcardType }; + } + var combinedMapper = void 0; + if (root.inferTypeParameters) { + var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); + // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type + // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to + // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint + // so in those cases we refain from performing inference and retain the uninfered type parameter + if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) { + // We don't want inferences from constraints as they may cause us to eagerly resolve the + // conditional type instead of deferring resolution. Also, we always want strict function + // types rules (i.e. proper contravariance) for inferences. + inferTypes(context.inferences, checkType, extendsType, 128 /* NoConstraints */ | 256 /* AlwaysStrict */); + } + combinedMapper = mergeTypeMappers(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 && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) { + // 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 instantiations will be and we can just return the false branch type. + if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) { + // Return union of trueType and falseType for 'any' since it matches anything + if (checkType.flags & 1 /* Any */) { + (extraTypes || (extraTypes = [])).push(instantiateTypeWithoutDepthIncrease(root.trueType, combinedMapper || mapper)); + } + // If falseType is an immediately nested conditional type that isn't distributive or has an + // identical checkType, switch to that type and loop. + var falseType_1 = root.falseType; + if (falseType_1.flags & 16777216 /* Conditional */) { + var newRoot = falseType_1.root; + if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) { + root = newRoot; + return "continue"; + } + } + result = instantiateTypeWithoutDepthIncrease(falseType_1, mapper); + return "break"; + } + // 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 + // that has no constraint. This ensures that, for example, the type + // type Foo = T extends { x: string } ? string : number + // doesn't immediately resolve to 'string' instead of being deferred. + if (inferredExtendsType.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) { + result = instantiateTypeWithoutDepthIncrease(root.trueType, combinedMapper || mapper); + return "break"; + } + } + // Return a deferred type for a check that is neither definitely true nor definitely false + var erasedCheckType = getActualTypeVariable(checkType); + result = createType(16777216 /* Conditional */); + result.root = root; + result.checkType = erasedCheckType; + result.extendsType = extendsType; + result.mapper = mapper; + result.combinedMapper = combinedMapper; + result.aliasSymbol = root.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 + return "break"; + }; + // We loop here for an immediately nested conditional type in the false position, effectively treating + // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for + // purposes of resolution. This means such types aren't subject to the instatiation depth limiter. + while (true) { + var state_4 = _loop_12(); + if (typeof state_4 === "object") + return state_4.value; + if (state_4 === "break") + break; } - var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */); - var combinedMapper; - if (root.inferTypeParameters) { - var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); - // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type - // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to - // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint - // so in those cases we refain from performing inference and retain the uninfered type parameter - if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) { - // We don't want inferences from constraints as they may cause us to eagerly resolve the - // conditional type instead of deferring resolution. Also, we always want strict function - // types rules (i.e. proper contravariance) for inferences. - inferTypes(context.inferences, checkType, extendsType, 128 /* NoConstraints */ | 256 /* AlwaysStrict */); - } - 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 */ | 131072 /* GenericMappedType */)) { - if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) { - return instantiateType(root.trueType, combinedMapper || mapper); - } - // 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 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 instantiations will be and we can just return the false branch type. - if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) { - return instantiateType(root.falseType, mapper); - } - // 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 - // that has no constraint. This ensures that, for example, the type - // type Foo = T extends { x: string } ? string : number - // doesn't immediately resolve to 'string' instead of being deferred. - if (isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) { - return instantiateType(root.trueType, combinedMapper || mapper); - } - } - // Return a deferred type for a check that is neither definitely true nor definitely false - var erasedCheckType = getActualTypeVariable(checkType); - var result = createType(16777216 /* Conditional */); - result.root = root; - result.checkType = erasedCheckType; - result.extendsType = extendsType; - result.mapper = mapper; - result.combinedMapper = combinedMapper; - result.aliasSymbol = root.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 - return result; + return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result; } function getTrueTypeFromConditionalType(type) { return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); @@ -46044,7 +47315,7 @@ var ts; } function getRegularTypeOfLiteralType(type) { return type.flags & 2944 /* Literal */ ? type.regularType : - type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)))) : type; } function isFreshLiteralType(type) { @@ -46122,6 +47393,9 @@ var ts; return links.resolvedType; } function getTypeFromTypeNode(node) { + return getConditionalFlowTypeOfType(getTypeFromTypeNodeWorker(node), node); + } + function getTypeFromTypeNodeWorker(node) { switch (node.kind) { case 125 /* AnyKeyword */: case 295 /* JSDocAllType */: @@ -46235,27 +47509,41 @@ var ts; function instantiateSignatures(signatures, mapper) { return instantiateList(signatures, mapper, instantiateSignature); } - function makeUnaryTypeMapper(source, target) { - return function (t) { return t === source ? target : t; }; + function createTypeMapper(sources, targets) { + return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : makeArrayTypeMapper(sources, targets); } - function makeBinaryTypeMapper(source1, target1, source2, target2) { - return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; + function getMappedType(type, mapper) { + switch (mapper.kind) { + case 0 /* Simple */: + return type === mapper.source ? mapper.target : type; + case 1 /* Array */: + var sources = mapper.sources; + var targets = mapper.targets; + for (var i = 0; i < sources.length; i++) { + if (type === sources[i]) { + return targets ? targets[i] : anyType; + } + } + return type; + case 2 /* Function */: + return mapper.func(type); + case 3 /* Composite */: + case 4 /* Merged */: + var t1 = getMappedType(type, mapper.mapper1); + return t1 !== type && mapper.kind === 3 /* Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2); + } + } + function makeUnaryTypeMapper(source, target) { + return { kind: 0 /* Simple */, source: source, target: target }; } function makeArrayTypeMapper(sources, targets) { - return function (t) { - for (var i = 0; i < sources.length; i++) { - if (t === sources[i]) { - return targets ? targets[i] : anyType; - } - } - return t; - }; + return { kind: 1 /* Array */, sources: sources, targets: targets }; } - function createTypeMapper(sources, targets) { - ts.Debug.assert(targets === undefined || sources.length === targets.length); - return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : - sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : - makeArrayTypeMapper(sources, targets); + function makeFunctionTypeMapper(func) { + return { kind: 2 /* Function */, func: func }; + } + function makeCompositeTypeMapper(kind, mapper1, mapper2) { + return { kind: kind, mapper1: mapper1, mapper2: mapper2 }; } function createTypeEraser(sources) { return createTypeMapper(sources, /*targets*/ undefined); @@ -46265,29 +47553,25 @@ var ts; * This is used during inference when instantiating type parameter defaults. */ function createBackreferenceMapper(context, index) { - return function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; }; + return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; }); } function combineTypeMappers(mapper1, mapper2) { - if (!mapper1) - return mapper2; - if (!mapper2) - return mapper1; - return function (t) { return instantiateType(mapper1(t), mapper2); }; + return mapper1 ? makeCompositeTypeMapper(3 /* Composite */, mapper1, mapper2) : mapper2; } - function createReplacementMapper(source, target, baseMapper) { - return function (t) { return t === source ? target : baseMapper(t); }; + function mergeTypeMappers(mapper1, mapper2) { + return mapper1 ? makeCompositeTypeMapper(4 /* Merged */, mapper1, mapper2) : mapper2; } - function permissiveMapper(type) { - return type.flags & 262144 /* TypeParameter */ ? wildcardType : type; + function prependTypeMapping(source, target, mapper) { + return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, makeUnaryTypeMapper(source, target), mapper); + } + function appendTypeMapping(mapper, source, target) { + return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, mapper, makeUnaryTypeMapper(source, target)); } function getRestrictiveTypeParameter(tp) { return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol), tp.restrictiveInstantiation.constraint = unknownType, tp.restrictiveInstantiation); } - function restrictiveMapper(type) { - return type.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(type) : type; - } function cloneTypeParameter(typeParameter) { var result = createTypeParameter(typeParameter.symbol); result.target = typeParameter; @@ -46321,7 +47605,7 @@ var ts; } function instantiateSymbol(symbol, mapper) { var links = getSymbolLinks(symbol); - if (links.type && !maybeTypeOfKind(links.type, 524288 /* Object */ | 63176704 /* Instantiable */)) { + if (links.type && !couldContainTypeVariables(links.type)) { // If the type of the symbol is already resolved, and if that type could not possibly // be affected by instantiation, simply return the symbol itself. return symbol; @@ -46387,7 +47671,8 @@ var ts; // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the // mapper to the type parameters to produce the effective list of type arguments, and compute the // instantiation cache key from the type IDs of the type arguments. - var typeArguments = ts.map(typeParameters, combineTypeMappers(type.mapper, mapper)); + var combinedMapper_1 = combineTypeMappers(type.mapper, mapper); + var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); }); var id = getTypeListId(typeArguments); var result = links.instantiations.get(id); if (!result) { @@ -46426,7 +47711,7 @@ var ts; return !!tp.isThisType; case 75 /* Identifier */: return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && - getTypeFromTypeNode(node) === tp; + getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality case 172 /* TypeQuery */: return true; } @@ -46458,9 +47743,9 @@ var ts; if (typeVariable) { var mappedTypeVariable = instantiateType(typeVariable, mapper); if (typeVariable !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { + return mapType(getReducedType(mappedTypeVariable), function (t) { if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) { - var replacementMapper = createReplacementMapper(typeVariable, t, mapper); + var replacementMapper = prependTypeMapping(typeVariable, t, mapper); return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) : isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) : instantiateAnonymousType(type, replacementMapper); @@ -46493,10 +47778,10 @@ var ts; createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, newReadonly, tupleType.target.associatedNames); } function instantiateMappedTypeTemplate(type, key, isOptional, mapper) { - var templateMapper = combineTypeMappers(mapper, createTypeMapper([getTypeParameterFromMappedType(type)], [key])); + var templateMapper = appendTypeMapping(mapper, getTypeParameterFromMappedType(type), key); var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper); var modifiers = getMappedTypeModifiers(type); - return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : + return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) : strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) : propType; } @@ -46523,7 +47808,7 @@ var ts; // We are instantiating a conditional type that has one or more type parameters in scope. Apply the // mapper to the type parameters to produce the effective list of type arguments, and compute the // instantiation cache key from the type IDs of the type arguments. - var typeArguments = ts.map(root.outerTypeParameters, mapper); + var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); }); var id = getTypeListId(typeArguments); var result = root.instantiations.get(id); if (!result) { @@ -46541,15 +47826,15 @@ var ts; // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y). if (root.isDistributive) { var checkType_1 = root.checkType; - var instantiatedType = mapper(checkType_1); + var instantiatedType = getMappedType(checkType_1, mapper); if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) { - return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); + return mapType(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); }); } } return getConditionalType(root, mapper); } function instantiateType(type, mapper) { - if (!type || !mapper || mapper === identityMapper) { + if (!type || !mapper) { return type; } if (instantiationDepth === 50 || instantiationCount >= 5000000) { @@ -46559,16 +47844,27 @@ var ts; error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); return errorType; } + totalInstantiationCount++; instantiationCount++; instantiationDepth++; var result = instantiateTypeWorker(type, mapper); instantiationDepth--; return result; } + /** + * This can be used to avoid the penalty on instantiation depth for types which result from immediate + * simplification. It essentially removes the depth increase done in `instantiateType`. + */ + function instantiateTypeWithoutDepthIncrease(type, mapper) { + instantiationDepth--; + var result = instantiateType(type, mapper); + instantiationDepth++; + return result; + } function instantiateTypeWorker(type, mapper) { var flags = type.flags; if (flags & 262144 /* TypeParameter */) { - return mapper(type); + return getMappedType(type, mapper); } if (flags & 524288 /* Object */) { var objectFlags = type.objectFlags; @@ -46592,15 +47888,17 @@ var ts; } return type; } - if (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */)) { + if ((flags & 2097152 /* Intersection */) || (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */))) { + if (!couldContainTypeVariables(type)) { + return type; + } var types = type.types; var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; - } - if (flags & 2097152 /* Intersection */) { - var types = type.types; - var newTypes = instantiateTypes(types, mapper); - return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; + return newTypes === types + ? type + : (flags & 2097152 /* Intersection */) + ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) + : getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); } if (flags & 4194304 /* Index */) { return getIndexType(instantiateType(type.type, mapper)); @@ -46612,7 +47910,7 @@ var ts; return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); } if (flags & 33554432 /* Substitution */) { - var maybeVariable = instantiateType(type.typeVariable, mapper); + var maybeVariable = instantiateType(type.baseType, mapper); if (maybeVariable.flags & 8650752 /* TypeVariable */) { return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper)); } @@ -46712,7 +48010,7 @@ var ts; } function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body); + return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -46885,6 +48183,13 @@ var ts; if (target.symbol && ts.length(target.symbol.declarations)) { ts.addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], ts.createDiagnosticForNode(target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature)); } + if ((ts.getFunctionFlags(node) & 2 /* Async */) === 0 + // exclude cases where source itself is promisy - this way we don't make a suggestion when relating + // an IPromise and a Promise that are slightly different + && !getTypeOfPropertyOfType(sourceReturn, "then") + && checkTypeRelatedTo(createPromiseType(sourceReturn), targetReturn, relation, /*errorNode*/ undefined)) { + ts.addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], ts.createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async)); + } return true; } } @@ -46902,6 +48207,15 @@ var ts; } } } + function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) { + next.contextualType = sourcePropType; + try { + return checkExpressionForMutableLocation(next, 1 /* Contextual */, sourcePropType); + } + finally { + next.contextualType = undefined; + } + } /** * For every element returned from the iterator, checks that element to issue an error on a property of that element's type * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` @@ -46925,7 +48239,7 @@ var ts; // Issue error on the prop itself, since the prop couldn't elaborate the error var resultObj = errorOutputContainer || {}; // Use the expression type, if available - var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; + var specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType; var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType @@ -47142,11 +48456,20 @@ var ts; return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer); } // recreate a tuple from the elements, if possible - var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true); - if (isTupleLikeType(tupleizedType)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation, containingMessageChain, errorOutputContainer); + // Since we're re-doing the expression type, we need to reapply the contextual type + var oldContext = node.contextualType; + node.contextualType = target; + try { + var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true); + node.contextualType = oldContext; + if (isTupleLikeType(tupleizedType)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation, containingMessageChain, errorOutputContainer); + } + return false; + } + finally { + node.contextualType = oldContext; } - return false; } function generateObjectLiteralElements(node) { var _i, _a, prop, type, _b; @@ -47179,7 +48502,7 @@ var ts; case 3: _c.sent(); return [3 /*break*/, 7]; - case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; + case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: ts.isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; case 5: _c.sent(); return [3 /*break*/, 7]; @@ -47492,11 +48815,19 @@ var ts; if (isFreshLiteralType(target)) { target = target.regularType; } - if (source === target || - relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || - relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + if (source === target) { return true; } + if (relation !== identityRelation) { + if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation)) { + return true; + } + } + else { + if (!(source.flags & 3145728 /* UnionOrIntersection */) && !(target.flags & 3145728 /* UnionOrIntersection */) && + source.flags !== target.flags && !(source.flags & 66584576 /* Substructure */)) + return false; + } if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { var related = relation.get(getRelationKey(source, target, 0 /* None */, relation)); if (related !== undefined) { @@ -47512,11 +48843,18 @@ var ts; return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName); } function getNormalizedType(type, writing) { - return isFreshLiteralType(type) ? type.regularType : - ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) : - type.flags & 33554432 /* Substitution */ ? writing ? type.typeVariable : type.substitute : - type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : - type; + while (true) { + var t = isFreshLiteralType(type) ? type.regularType : + ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) : + type.flags & 3145728 /* UnionOrIntersection */ ? getReducedType(type) : + type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute : + type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : + type; + if (t === type) + break; + type = t; + } + return type; } /** * Checks if 'source' is related to 'target' (e.g.: is a assignable to). @@ -47542,13 +48880,14 @@ var ts; var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid var lastSkippedInfo; var incompatibleStack = []; + var inPropertyCheck = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); if (incompatibleStack.length) { reportIncompatibleStack(); } if (overflow) { - var diag = error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); if (errorOutputContainer) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); } @@ -47729,8 +49068,15 @@ var ts; if (incompatibleStack.length) reportIncompatibleStack(); var _a = getTypeNamesForErrorDisplay(source, target), sourceType = _a[0], targetType = _a[1]; - if (target.flags & 262144 /* TypeParameter */ && target.immediateBaseConstraint !== undefined && isTypeAssignableTo(source, target.immediateBaseConstraint)) { - reportError(ts.Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2, sourceType, targetType, typeToString(target.immediateBaseConstraint)); + if (target.flags & 262144 /* TypeParameter */) { + var constraint = getBaseConstraintOfType(target); + var constraintElab = constraint && isTypeAssignableTo(source, constraint); + if (constraintElab) { + reportError(ts.Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2, sourceType, targetType, typeToString(constraint)); + } + else { + reportError(ts.Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, sourceType); + } } if (!message) { if (relation === comparableRelation) { @@ -47798,12 +49144,34 @@ var ts; function isRelatedTo(originalSource, originalTarget, reportErrors, headMessage, intersectionState) { if (reportErrors === void 0) { reportErrors = false; } if (intersectionState === void 0) { intersectionState = 0 /* None */; } + // Before normalization: if `source` is type an object type, and `target` is primitive, + // skip all the checks we don't need and just return `isSimpleTypeRelatedTo` result + if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 131068 /* Primitive */) { + if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { + return -1 /* True */; + } + reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */)); + return 0 /* False */; + } // Normalize the source and target types: Turn fresh literal types into regular literal types, // turn deferred type references into regular type references, simplify indexed access and // conditional types, and resolve substitution types to either the substitution (on the source // side) or the type variable (on the target side). var source = getNormalizedType(originalSource, /*writing*/ false); var target = getNormalizedType(originalTarget, /*writing*/ true); + if (source === target) + return -1 /* True */; + if (relation === identityRelation) { + return isIdenticalTo(source, target); + } + // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common, + // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself, + // as we break down the _target_ union first, _then_ get the source constraint - so for every + // member of the target, we attempt to find a match in the source. This avoids that in cases where + // the target is exactly the constraint. + if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) { + return -1 /* True */; + } // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. // If so, reporting the `null` and `undefined` in the type is hardly useful. // First, see if we're even relating an object type to a union. @@ -47817,15 +49185,11 @@ var ts; target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) { var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */); if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) { + if (source === nullStrippedTarget) + return -1 /* True */; target = nullStrippedTarget; } } - // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases - if (source === target) - return -1 /* True */; - if (relation === identityRelation) { - return isIdenticalTo(source, target); - } if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; @@ -47865,7 +49229,7 @@ var ts; if (source.flags & 1048576 /* Union */) { result = relation === comparableRelation ? someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */)); + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState); } else { if (target.flags & 1048576 /* Union */) { @@ -47873,12 +49237,6 @@ var ts; } else if (target.flags & 2097152 /* Intersection */) { result = typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */); - if (result && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks)) { - // Validate against excess props using the original `source` - if (!propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */)) { - return 0 /* False */; - } - } } else if (source.flags & 2097152 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. @@ -47926,59 +49284,85 @@ var ts; } } } - if (!result && reportErrors) { - source = originalSource.aliasSymbol ? originalSource : source; - target = originalTarget.aliasSymbol ? originalTarget : target; - var maybeSuppress = overrideNextErrorInfo > 0; - if (maybeSuppress) { - overrideNextErrorInfo--; - } - if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { - var currentError = errorInfo; - tryElaborateArrayLikeErrors(source, target, reportErrors); - if (errorInfo !== currentError) { - maybeSuppress = !!errorInfo; + // For certain combinations involving intersections and optional, excess, or mismatched properties we need + // an extra property check where the intersection is viewed as a single object. The following are motivating + // examples that all should be errors, but aren't without this extra property check: + // + // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property + // + // declare let wrong: { a: { y: string } }; + // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type + // + // function foo(x: { a?: string }, y: T & { a: boolean }) { + // x = y; // Mismatched property in source intersection + // } + // + // We suppress recursive intersection property checks because they can generate lots of work when relating + // recursive intersections that are structurally similar but not exactly identical. See #37854. + if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || + isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) { + inPropertyCheck = true; + result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */); + inPropertyCheck = false; + } + reportErrorResults(source, target, result, isComparingJsxAttributes); + return result; + function reportErrorResults(source, target, result, isComparingJsxAttributes) { + if (!result && reportErrors) { + source = originalSource.aliasSymbol ? originalSource : source; + target = originalTarget.aliasSymbol ? originalTarget : target; + var maybeSuppress = overrideNextErrorInfo > 0; + if (maybeSuppress) { + overrideNextErrorInfo--; } - } - if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { - tryElaborateErrorsForPrimitivesAndObjects(source, target); - } - else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { - reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); - } - else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { - var targetTypes = target.types; - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); - var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); - if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && - (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { - // do not report top error + if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { + var currentError = errorInfo; + tryElaborateArrayLikeErrors(source, target, reportErrors); + if (errorInfo !== currentError) { + maybeSuppress = !!errorInfo; + } + } + if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { + var targetTypes = target.types; + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); + var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); + if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && + (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { + // do not report top error + return result; + } + } + else { + errorInfo = elaborateNeverIntersection(errorInfo, originalTarget); + } + if (!headMessage && maybeSuppress) { + lastSkippedInfo = [source, target]; + // Used by, eg, missing property checking to replace the top-level message with a more informative one return result; } + reportRelationError(headMessage, source, target); } - if (!headMessage && maybeSuppress) { - lastSkippedInfo = [source, target]; - // Used by, eg, missing property checking to replace the top-level message with a more informative one - return result; - } - reportRelationError(headMessage, source, target); } - return result; } function isIdenticalTo(source, target) { - var result; var flags = source.flags & target.flags; - if (flags & 524288 /* Object */ || flags & 8388608 /* IndexedAccess */ || flags & 16777216 /* Conditional */ || flags & 4194304 /* Index */ || flags & 33554432 /* Substitution */) { - return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */); + if (!(flags & 66584576 /* Substructure */)) { + return 0 /* False */; } - if (flags & (1048576 /* Union */ | 2097152 /* Intersection */)) { - if (result = eachTypeRelatedToSomeType(source, target)) { - if (result &= eachTypeRelatedToSomeType(target, source)) { - return result; - } + if (flags & 3145728 /* UnionOrIntersection */) { + var result_5 = eachTypeRelatedToSomeType(source, target); + if (result_5) { + result_5 &= eachTypeRelatedToSomeType(target, source); } + return result_5; } - return 0 /* False */; + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */); } function getTypeOfPropertyInTypes(types, name) { var appendPropType = function (propTypes, type) { @@ -48004,8 +49388,8 @@ var ts; reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target); checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget]; } - var _loop_11 = function (prop) { - if (shouldCheckAsExcessProperty(prop, source.symbol)) { + var _loop_13 = function (prop) { + if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // Report error in terms of object types in the target as those are the only ones @@ -48060,9 +49444,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_4 = _loop_11(prop); - if (typeof state_4 === "object") - return state_4.value; + var state_5 = _loop_13(prop); + if (typeof state_5 === "object") + return state_5.value; } return false; } @@ -48127,12 +49511,20 @@ var ts; } return 0 /* False */; } - function eachTypeRelatedToType(source, target, reportErrors) { + function eachTypeRelatedToType(source, target, reportErrors, intersectionState) { var result = -1 /* True */; var sourceTypes = source.types; - for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { - var sourceType = sourceTypes_2[_i]; - var related = isRelatedTo(sourceType, target, reportErrors); + for (var i = 0; i < sourceTypes.length; i++) { + var sourceType = sourceTypes[i]; + if (target.flags & 1048576 /* Union */ && target.types.length === sourceTypes.length) { + // many unions are mappings of one another; in such cases, simply comparing members at the same index can shortcut the comparison + var related_1 = isRelatedTo(sourceType, target.types[i], /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState); + if (related_1) { + result &= related_1; + continue; + } + } + var related = isRelatedTo(sourceType, target, reportErrors, /*headMessage*/ undefined, intersectionState); if (!related) { return 0 /* False */; } @@ -48208,7 +49600,7 @@ var ts; if (overflow) { return 0 /* False */; } - var id = getRelationKey(source, target, intersectionState, relation); + var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0), relation); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) { @@ -48220,10 +49612,10 @@ var ts; // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component var saved = entry & 24 /* ReportsMask */; if (saved & 8 /* ReportsUnmeasurable */) { - instantiateType(source, reportUnmeasurableMarkers); + instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers)); } if (saved & 16 /* ReportsUnreliable */) { - instantiateType(source, reportUnreliableMarkers); + instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)); } } return entry & 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; @@ -48290,26 +49682,29 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { + if (intersectionState & 4 /* PropertyCheck */) { + return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */); + } var flags = source.flags & target.flags; if (relation === identityRelation && !(flags & 524288 /* Object */)) { if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_3 = 0 /* False */; + var result_6 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_3 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_3 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_3; + if (result_6 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_6; } } } if (flags & 16777216 /* Conditional */) { 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)) { - return result_3; + if (result_6 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_6 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_6; } } } @@ -48486,6 +49881,8 @@ var ts; } } else { + // conditionals aren't related to one another via distributive constraint as it is much too inaccurate and allows way + // more assignments than are desirable (since it maps the source check type to its constraint, it loses information) var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); if (distributiveConstraint) { if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { @@ -48493,12 +49890,14 @@ var ts; return result; } } - var defaultConstraint = getDefaultConstraintOfConditionalType(source); - if (defaultConstraint) { - if (result = isRelatedTo(defaultConstraint, target, reportErrors)) { - resetErrorInfo(saveErrorInfo); - return result; - } + } + // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O` + // when `O` is a conditional (`never` is trivially aissgnable to `O`, as is `O`!). + var defaultConstraint = getDefaultConstraintOfConditionalType(source); + if (defaultConstraint) { + if (result = isRelatedTo(defaultConstraint, target, reportErrors)) { + resetErrorInfo(saveErrorInfo); + return result; } } } @@ -48590,9 +49989,9 @@ var ts; if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { - var result_4 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); - if (result_4) { - return result_4; + var result_7 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); + if (result_7) { + return result_7; } } } @@ -48659,12 +50058,12 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_5; + var result_8; var targetConstraint = getConstraintTypeFromMappedType(target); - var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers); - if (result_5 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { + var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers)); + if (result_8 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_5 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_8 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -48712,11 +50111,11 @@ var ts; // constituents of 'target'. If any combination does not have a match then 'source' is not relatable. var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes); var matchingTypes = []; - var _loop_12 = function (combination) { + var _loop_14 = function (combination) { var hasMatch = false; outer: for (var _i = 0, _a = target.types; _i < _a.length; _i++) { var type = _a[_i]; - var _loop_13 = function (i) { + var _loop_15 = function (i) { var sourceProperty = sourcePropertiesFiltered[i]; var targetProperty = getPropertyOfType(type, sourceProperty.escapedName); if (!targetProperty) @@ -48724,7 +50123,7 @@ var ts; if (sourceProperty === targetProperty) return "continue"; // We compare the source property to the target in the context of a single discriminant type. - var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */); + var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */, /*skipOptional*/ strictNullChecks || relation === comparableRelation); // If the target property could not be found, or if the properties were not related, // then this constituent is not a match. if (!related) { @@ -48732,8 +50131,8 @@ var ts; } }; for (var i = 0; i < sourcePropertiesFiltered.length; i++) { - var state_6 = _loop_13(i); - switch (state_6) { + var state_7 = _loop_15(i); + switch (state_7) { case "continue-outer": continue outer; } } @@ -48746,9 +50145,9 @@ var ts; }; for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) { var combination = discriminantCombinations_1[_a]; - var state_5 = _loop_12(combination); - if (typeof state_5 === "object") - return state_5.value; + var state_6 = _loop_14(combination); + if (typeof state_6 === "object") + return state_6.value; } // Compare the remaining non-discriminant properties of each match. var result = -1 /* True */; @@ -48795,10 +50194,10 @@ var ts; if (ts.getCheckFlags(targetProp) & 65536 /* DeferredType */ && !getSymbolLinks(targetProp).type) { // Rather than resolving (and normalizing) the type, relate constituent-by-constituent without performing normalization or seconadary passes var links = getSymbolLinks(targetProp); - ts.Debug.assertDefined(links.deferralParent); - ts.Debug.assertDefined(links.deferralConstituents); + ts.Debug.assertIsDefined(links.deferralParent); + ts.Debug.assertIsDefined(links.deferralConstituents); var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */); - var result_6 = unionParent ? 0 /* False */ : -1 /* True */; + var result_9 = unionParent ? 0 /* False */ : -1 /* True */; var targetTypes = links.deferralConstituents; for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) { var targetType = targetTypes_3[_i]; @@ -48808,7 +50207,7 @@ var ts; // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - result_6 &= related; + result_9 &= related; } else { if (related) { @@ -48816,34 +50215,27 @@ var ts; } } } - if (unionParent && !result_6 && targetIsOptional) { - result_6 = isRelatedTo(source, undefinedType); + if (unionParent && !result_9 && targetIsOptional) { + result_9 = isRelatedTo(source, undefinedType); } - if (unionParent && !result_6 && reportErrors) { + if (unionParent && !result_9 && reportErrors) { // The easiest way to get the right errors here is to un-defer (which may be costly) // If it turns out this is too costly too often, we can replicate the error handling logic within // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union // type on which to hand discriminable properties, which we are expressly trying to avoid here) return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors); } - return result_6; + return result_9; } else { return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState); } } - function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) { + function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) { var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { - var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; - if (ts.getCheckFlags(sourceProp) & 1024 /* ContainsPrivate */ && hasDifferingDeclarations) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); - } - return 0 /* False */; - } - if (hasDifferingDeclarations) { + if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); @@ -48878,7 +50270,7 @@ var ts; return 0 /* False */; } // When checking for comparability, be more lenient with optional properties. - if (relation !== comparableRelation && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { + if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. @@ -48899,6 +50291,7 @@ var ts; if (unmatchedProperty.valueDeclaration && ts.isNamedDeclaration(unmatchedProperty.valueDeclaration) && ts.isPrivateIdentifier(unmatchedProperty.valueDeclaration.name) + && source.symbol && source.symbol.flags & 32 /* Class */) { var privateIdentifierDescription = unmatchedProperty.valueDeclaration.name.escapedText; var symbolTableKey = ts.getSymbolNameForPrivateIdentifier(source.symbol, privateIdentifierDescription); @@ -49002,7 +50395,7 @@ var ts; if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) { var sourceProp = getPropertyOfType(source, name); if (sourceProp && sourceProp !== targetProp) { - var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState); + var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation); if (!related) { return 0 /* False */; } @@ -49128,7 +50521,7 @@ var ts; * See signatureAssignableTo, compareSignaturesIdentical */ function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) { - return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedTo, reportUnreliableMarkers); + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedTo, makeFunctionTypeMapper(reportUnreliableMarkers)); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -49250,18 +50643,22 @@ var ts; } function getBestMatchingType(source, target, isRelatedTo) { if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; } - return findMatchingDiscriminantType(source, target, isRelatedTo) || + return findMatchingDiscriminantType(source, target, isRelatedTo, /*skipPartial*/ true) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || findBestTypeForInvokable(source, target) || findMostOverlappyType(source, target); } - function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue) { + function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) { // undefined=unknown, true=discriminated, false=not discriminated // The state of each type progresses from left to right. Discriminated types stop at 'true'. var discriminable = target.types.map(function (_) { return undefined; }); for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) { var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1]; + var targetProp = getUnionOrIntersectionProperty(target, propertyName); + if (skipPartial && targetProp && ts.getCheckFlags(targetProp) & 16 /* ReadPartial */) { + continue; + } var i = 0; for (var _b = 0, _c = target.types; _b < _c.length; _b++) { var type = _c[_b]; @@ -49332,7 +50729,7 @@ var ts; // The emptyArray singleton is used to signal a recursive invocation. cache.variances = ts.emptyArray; variances = []; - var _loop_14 = function (tp) { + var _loop_16 = function (tp) { var unmeasurable = false; var unreliable = false; var oldHandler = outofbandVarianceMarkerHandler; @@ -49364,7 +50761,7 @@ var ts; }; for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { var tp = typeParameters_1[_i]; - _loop_14(tp); + _loop_16(tp); } cache.variances = variances; } @@ -49647,8 +51044,8 @@ var ts; } function literalTypesWithSameBaseType(types) { var commonBaseType; - 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]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -49776,7 +51173,7 @@ var ts; } /** * Check if a Type was written as a tuple type literal. - * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. + * Prefer using isTupleLikeType() unless the use of `elementTypes`/`getTypeArguments` is required. */ function isTupleType(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); @@ -49797,8 +51194,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var t = types_13[_i]; result |= getFalsyFlags(t); } return result; @@ -50169,7 +51566,7 @@ var ts; case 201 /* FunctionExpression */: case 202 /* ArrowFunction */: if (noImplicitAny && !declaration.name) { - if (wideningKind === 1 /* GeneratorYield */) { + if (wideningKind === 3 /* GeneratorYield */) { error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString); } else { @@ -50178,7 +51575,7 @@ var ts; return; } diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage : - wideningKind === 1 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : + wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; case 186 /* MappedType */: @@ -50192,7 +51589,7 @@ var ts; errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type, wideningKind) { - if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) { + if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type, wideningKind); @@ -50243,8 +51640,8 @@ var ts; signature: signature, flags: flags, compareTypes: compareTypes, - mapper: function (t) { return mapToInferredType(context, t, /*fix*/ true); }, - nonFixingMapper: function (t) { return mapToInferredType(context, t, /*fix*/ false); }, + mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ true); }), + nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ false); }), }; return context; } @@ -50306,17 +51703,18 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - return !!(type.flags & 63176704 /* Instantiable */ || + if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) { + return !!(objectFlags & 134217728 /* CouldContainTypeVariables */); + } + var result = !!(type.flags & 63176704 /* Instantiable */ || objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */) || - type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && couldUnionOrIntersectionContainTypeVariables(type)); - } - function couldUnionOrIntersectionContainTypeVariables(type) { - if (type.couldContainTypeVariables === undefined) { - type.couldContainTypeVariables = ts.some(type.types, couldContainTypeVariables); + type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && ts.some(type.types, couldContainTypeVariables)); + if (type.flags & 3899393 /* ObjectFlagsType */) { + type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0); } - return type.couldContainTypeVariables; + return result; } function isTypeParameterAtTopLevel(type, typeParameter) { return !!(type === typeParameter || @@ -50471,7 +51869,7 @@ var ts; function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) { if (priority === void 0) { priority = 0; } if (contravariant === void 0) { contravariant = false; } - var symbolStack; + var symbolOrTypeStack; var visited; var bivariant = false; var propagationType; @@ -50652,12 +52050,13 @@ var ts; 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 _e = 0, sourceTypes_2 = sourceTypes; _e < sourceTypes_2.length; _e++) { + var sourceType = sourceTypes_2[_e]; inferFromTypes(sourceType, target); } } else { + source = getReducedType(source); if (!(priority & 128 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) { var apparentSource = getApparentType(source); // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type. @@ -50760,8 +52159,8 @@ var ts; } function getSingleTypeVariableFromIntersectionTypes(types) { var typeVariable; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var type = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var type = types_14[_i]; var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); if (!t || typeVariable && t !== typeVariable) { return undefined; @@ -50906,15 +52305,15 @@ var ts; // its symbol with the instance side which would lead to false positives. var isNonConstructorObject = target.flags & 524288 /* Object */ && !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); - var symbol = isNonConstructorObject ? target.symbol : undefined; - if (symbol) { - if (ts.contains(symbolStack, symbol)) { + var symbolOrType = isNonConstructorObject ? isTupleType(target) ? target.target : target.symbol : undefined; + if (symbolOrType) { + if (ts.contains(symbolOrTypeStack, symbolOrType)) { inferencePriority = -1 /* Circularity */; return; } - (symbolStack || (symbolStack = [])).push(symbol); + (symbolOrTypeStack || (symbolOrTypeStack = [])).push(symbolOrType); inferFromObjectTypesWorker(source, target); - symbolStack.pop(); + symbolOrTypeStack.pop(); } else { inferFromObjectTypesWorker(source, target); @@ -50940,6 +52339,32 @@ var ts; } // Infer from the members of source and target only if the two types are possibly related if (!typesDefinitelyUnrelated(source, target)) { + if (isArrayType(source) || isTupleType(source)) { + if (isTupleType(target)) { + var sourceLength = isTupleType(source) ? getLengthOfTupleType(source) : 0; + var targetLength = getLengthOfTupleType(target); + 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++) { + inferFromTypes(i < sourceLength ? getTypeArguments(source)[i] : sourceRestType, getTypeArguments(target)[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? getTypeArguments(source).slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + return; + } + if (isArrayType(target)) { + inferFromIndexTypes(source, target); + return; + } + } inferFromProperties(source, target); inferFromSignatures(source, target, 0 /* Call */); inferFromSignatures(source, target, 1 /* Construct */); @@ -50947,32 +52372,6 @@ var ts; } } function inferFromProperties(source, target) { - if (isArrayType(source) || isTupleType(source)) { - if (isTupleType(target)) { - var sourceLength = isTupleType(source) ? getLengthOfTupleType(source) : 0; - var targetLength = getLengthOfTupleType(target); - 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++) { - inferFromTypes(i < sourceLength ? getTypeArguments(source)[i] : sourceRestType, getTypeArguments(target)[i]); - } - if (targetRestType) { - var types = fixedLength < sourceLength ? getTypeArguments(source).slice(fixedLength, sourceLength) : []; - if (sourceRestType) { - types.push(sourceRestType); - } - if (types.length) { - inferFromTypes(getUnionType(types), targetRestType); - } - } - return; - } - if (isArrayType(target)) { - inferFromIndexTypes(source, target); - return; - } - } var properties = getPropertiesOfObjectType(target); for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { var targetProp = properties_3[_i]; @@ -50990,7 +52389,7 @@ var ts; var len = sourceLen < targetLen ? sourceLen : targetLen; var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */); for (var i = 0; i < len; i++) { - inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); + inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters); } } function inferFromSignature(source, target, skipParameters) { @@ -51025,7 +52424,7 @@ var ts; } } function isTypeOrBaseIdenticalTo(s, t) { - return isTypeIdenticalTo(s, t) || !!(s.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) && isTypeIdenticalTo(getBaseTypeOfLiteralType(s), t); + return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */); } function isTypeCloselyMatchedBy(s, t) { return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol || @@ -51106,7 +52505,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, index), context.nonFixingMapper)); + inferredType = instantiateType(defaultType, mergeTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper)); } } } @@ -51243,6 +52642,12 @@ var ts; } return false; } + // Given a source x, check if target matches x or is an && operation with an operand that matches x. + function containsTruthyCheck(source, target) { + return isMatchingReference(source, target) || + (target.kind === 209 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && + (containsTruthyCheck(source, target.left) || containsTruthyCheck(source, target.right))); + } function getAccessedPropertyName(access) { return access.kind === 194 /* PropertyAccessExpression */ ? access.name.escapedText : ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : @@ -51280,9 +52685,6 @@ var ts; } return false; } - function isSyntheticThisPropertyAccess(expr) { - return ts.isAccessExpression(expr) && expr.expression.kind === 104 /* ThisKeyword */ && !!(expr.expression.flags & 8 /* Synthesized */); - } function findDiscriminantProperties(sourceProperties, target) { var result; for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { @@ -51358,8 +52760,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; result |= getTypeFacts(t); } return result; @@ -51427,6 +52829,9 @@ var ts; if (flags & 67108864 /* NonPrimitive */) { return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */; } + if (flags & 131072 /* Never */) { + return 0 /* None */; + } if (flags & 63176704 /* Instantiable */) { return getTypeFacts(getBaseConstraintOfType(type) || unknownType); } @@ -51492,7 +52897,7 @@ var ts; case 231 /* ForInStatement */: return stringType; case 232 /* ForOfStatement */: - return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType; + return checkRightHandSideOfForOf(parent) || errorType; case 209 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); case 203 /* DeleteExpression */: @@ -51533,7 +52938,7 @@ var ts; return stringType; } if (node.parent.parent.kind === 232 /* ForOfStatement */) { - return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType; + return checkRightHandSideOfForOf(node.parent.parent) || errorType; } return errorType; } @@ -51586,9 +52991,7 @@ var ts; } return links.switchTypes; } - // Get the types from all cases in a switch on `typeof`. An - // `undefined` element denotes an explicit `default` clause. - function getSwitchClauseTypeOfWitnesses(switchStatement) { + function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) { var witnesses = []; for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { var clause = _a[_i]; @@ -51599,7 +53002,8 @@ var ts; } return ts.emptyArray; } - witnesses.push(/*explicitDefaultStatement*/ undefined); + if (retainDefault) + witnesses.push(/*explicitDefaultStatement*/ undefined); } return witnesses; } @@ -51636,7 +53040,7 @@ var ts; var filtered = ts.filter(types, f); return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags); } - return f(type) ? type : neverType; + return type.flags & 131072 /* Never */ || f(type) ? type : neverType; } function countTypes(type) { return type.flags & 1048576 /* Union */ ? type.types.length : 1; @@ -51728,8 +53132,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - 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 (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -51766,20 +53170,31 @@ var ts; return isLengthPushOrUnshift || isElementAssignment; } function isDeclarationWithExplicitTypeAnnotation(declaration) { - return !!(declaration && (declaration.kind === 242 /* VariableDeclaration */ || declaration.kind === 156 /* Parameter */ || + return (declaration.kind === 242 /* VariableDeclaration */ || declaration.kind === 156 /* Parameter */ || declaration.kind === 159 /* PropertyDeclaration */ || declaration.kind === 158 /* PropertySignature */) && - ts.getEffectiveTypeAnnotationNode(declaration)); + !!ts.getEffectiveTypeAnnotationNode(declaration); } function getExplicitTypeOfSymbol(symbol, diagnostic) { if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 512 /* ValueModule */)) { return getTypeOfSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { - if (isDeclarationWithExplicitTypeAnnotation(symbol.valueDeclaration)) { - return getTypeOfSymbol(symbol); - } - if (diagnostic && symbol.valueDeclaration) { - ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(symbol.valueDeclaration, ts.Diagnostics._0_needs_an_explicit_type_annotation, symbolToString(symbol))); + var declaration = symbol.valueDeclaration; + if (declaration) { + if (isDeclarationWithExplicitTypeAnnotation(declaration)) { + return getTypeOfSymbol(symbol); + } + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) { + var statement = declaration.parent.parent; + var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined); + if (expressionType) { + var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */; + return checkIteratedTypeOrElementType(use, expressionType, undefinedType, /*errorNode*/ undefined); + } + } + if (diagnostic) { + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_needs_an_explicit_type_annotation, symbolToString(symbol))); + } } } } @@ -51852,14 +53267,11 @@ var ts; diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis)); } function isReachableFlowNode(flow) { - var result = isReachableFlowNodeWorker(flow, /*skipCacheCheck*/ false); + var result = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ false); lastFlowNode = flow; lastFlowNodeReachable = result; return result; } - function isUnlockedReachableFlowNode(flow) { - return !(flow.flags & 4096 /* PreFinally */ && flow.lock.locked) && isReachableFlowNodeWorker(flow, /*skipCacheCheck*/ false); - } function isFalseExpression(expr) { var node = ts.skipParentheses(expr); return node.kind === 91 /* FalseKeyword */ || node.kind === 209 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || @@ -51871,15 +53283,15 @@ var ts; return lastFlowNodeReachable; } var flags = flow.flags; - if (flags & 2048 /* Shared */) { + if (flags & 4096 /* Shared */) { if (!noCacheCheck) { var id = getFlowNodeId(flow); var reachable = flowNodeReachable[id]; - return reachable !== undefined ? reachable : (flowNodeReachable[id] = isReachableFlowNodeWorker(flow, /*skipCacheCheck*/ true)); + return reachable !== undefined ? reachable : (flowNodeReachable[id] = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ true)); } noCacheCheck = false; } - if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */ | 4096 /* PreFinally */)) { + if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */)) { flow = flow.antecedent; } else if (flags & 512 /* Call */) { @@ -51900,7 +53312,7 @@ var ts; } else if (flags & 4 /* BranchLabel */) { // A branching point is reachable if any branch is reachable. - return ts.some(flow.antecedents, isUnlockedReachableFlowNode); + return ts.some(flow.antecedents, function (f) { return isReachableFlowNodeWorker(f, /*noCacheCheck*/ false); }); } else if (flags & 8 /* LoopLabel */) { // A loop is reachable if the control flow path that leads to the top is reachable. @@ -51914,12 +53326,14 @@ var ts; } flow = flow.antecedent; } - else if (flags & 8192 /* AfterFinally */) { - // Cache is unreliable once we start locking nodes + else if (flags & 1024 /* ReduceLabel */) { + // Cache is unreliable once we start adjusting labels lastFlowNode = undefined; - flow.locked = true; - var result = isReachableFlowNodeWorker(flow.antecedent, /*skipCacheCheck*/ false); - flow.locked = false; + var target = flow.target; + var saveAntecedents = target.antecedents; + target.antecedents = flow.antecedents; + var result = isReachableFlowNodeWorker(flow.antecedent, /*noCacheCheck*/ false); + target.antecedents = saveAntecedents; return result; } else { @@ -51969,7 +53383,7 @@ var ts; flowDepth++; while (true) { var flags = flow.flags; - if (flags & 2048 /* Shared */) { + if (flags & 4096 /* Shared */) { // We cache results of flow type resolution for shared nodes that were previously visited in // the same getFlowTypeOfReference invocation. A node is considered shared when it is the // antecedent of more than one node. @@ -51981,19 +53395,7 @@ var ts; } } var type = void 0; - if (flags & 8192 /* AfterFinally */) { - // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement - flow.locked = true; - type = getTypeAtFlowNode(flow.antecedent); - flow.locked = false; - } - else if (flags & 4096 /* PreFinally */) { - // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel - // so here just redirect to antecedent - flow = flow.antecedent; - continue; - } - else if (flags & 16 /* Assignment */) { + if (flags & 16 /* Assignment */) { type = getTypeAtFlowAssignment(flow); if (!type) { flow = flow.antecedent; @@ -52029,6 +53431,13 @@ var ts; continue; } } + else if (flags & 1024 /* ReduceLabel */) { + var target = flow.target; + var saveAntecedents = target.antecedents; + target.antecedents = flow.antecedents; + type = getTypeAtFlowNode(flow.antecedent); + target.antecedents = saveAntecedents; + } else if (flags & 2 /* Start */) { // Check if we should continue with the control flow of the containing function. var container = flow.node; @@ -52047,7 +53456,7 @@ var ts; // simply return the non-auto declared type to reduce follow-on errors. type = convertAutoToAny(declaredType); } - if (flags & 2048 /* Shared */) { + if (flags & 4096 /* Shared */) { // Record visited node and the associated type in the cache. sharedFlowNodes[sharedFlowCount] = flow; sharedFlowTypes[sharedFlowCount] = type; @@ -52133,7 +53542,7 @@ var ts; var predicate = getTypePredicateOfSignature(signature); if (predicate && (predicate.kind === 2 /* AssertsThis */ || predicate.kind === 3 /* AssertsIdentifier */)) { var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); + var type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType)); var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) : predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type; @@ -52231,12 +53640,6 @@ var ts; var bypassFlow; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; - if (antecedent.flags & 4096 /* PreFinally */ && antecedent.lock.locked) { - // if flow correspond to branch from pre-try to finally and this branch is locked - this means that - // we initially have started following the flow outside the finally block. - // in this case we should ignore this branch. - continue; - } if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.clauseStart === antecedent.clauseEnd) { // The antecedent is the bypass branch of a potentially exhaustive switch statement. bypassFlow = antecedent; @@ -52458,6 +53861,12 @@ var ts; if (isMatchingReferenceDiscriminant(right_1, declaredType)) { return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); } + if (isMatchingConstructorReference(left_1)) { + return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue); + } + if (isMatchingConstructorReference(right_1)) { + return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue); + } break; case 98 /* InstanceOfKeyword */: return narrowTypeByInstanceof(type, expr, assumeTrue); @@ -52531,7 +53940,7 @@ var ts; } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); - return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; }); } return type; } @@ -52545,24 +53954,27 @@ var ts; if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - // 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; } if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } + if (assumeTrue && type.flags & 2 /* Unknown */ && literal.text === "object") { + // The pattern x && typeof x === 'object', where x is of type unknown, narrows x to type object. We don't + // need to check for the reverse typeof x === 'object' && x since that already narrows correctly. + if (typeOfExpr.parent.parent.kind === 209 /* BinaryExpression */) { + var expr = typeOfExpr.parent.parent; + if (expr.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && expr.right === typeOfExpr.parent && containsTruthyCheck(reference, expr.left)) { + return nonPrimitiveType; + } + } + return getUnionType([nonPrimitiveType, nullType]); + } var facts = assumeTrue ? typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ : typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */; return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); function narrowTypeForTypeof(type) { - if (type.flags & 2 /* Unknown */ && literal.text === "object") { - return getUnionType([nonPrimitiveType, nullType]); - } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. @@ -52654,7 +54066,7 @@ var ts; }; } function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) { - var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, /*retainDefault*/ true); if (!switchWitnesses.length) { return type; } @@ -52717,22 +54129,57 @@ var ts; } return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts); } + function isMatchingConstructorReference(expr) { + return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" || + ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") && + isMatchingReference(reference, expr.expression); + } + function narrowTypeByConstructor(type, operator, identifier, assumeTrue) { + // Do not narrow when checking inequality. + if (assumeTrue ? (operator !== 34 /* EqualsEqualsToken */ && operator !== 36 /* EqualsEqualsEqualsToken */) : (operator !== 35 /* ExclamationEqualsToken */ && operator !== 37 /* ExclamationEqualsEqualsToken */)) { + return type; + } + // Get the type of the constructor identifier expression, if it is not a function then do not narrow. + var identifierType = getTypeOfExpression(identifier); + if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) { + return type; + } + // Get the prototype property of the type identifier so we can find out its type. + var prototypeProperty = getPropertyOfType(identifierType, "prototype"); + if (!prototypeProperty) { + return type; + } + // Get the type of the prototype, if it is undefined, or the global `Object` or `Function` types then do not narrow. + var prototypeType = getTypeOfSymbol(prototypeProperty); + var candidate = !isTypeAny(prototypeType) ? prototypeType : undefined; + if (!candidate || candidate === globalObjectType || candidate === globalFunctionType) { + return type; + } + // If the type that is being narrowed is `any` then just return the `candidate` type since every type is a subtype of `any`. + if (isTypeAny(type)) { + return candidate; + } + // Filter out types that are not considered to be "constructed by" the `candidate` type. + return filterType(type, function (t) { return isConstructedBy(t, candidate); }); + function isConstructedBy(source, target) { + // If either the source or target type are a class type then we need to check that they are the same exact type. + // This is because you may have a class `A` that defines some set of properties, and another class `B` + // that defines the same set of properties as class `A`, in that case they are structurally the same + // type, but when you do something like `instanceOfA.constructor === B` it will return false. + if (source.flags & 524288 /* Object */ && ts.getObjectFlags(source) & 1 /* Class */ || + target.flags & 524288 /* Object */ && ts.getObjectFlags(target) & 1 /* Class */) { + return source.symbol === target.symbol; + } + // For all other types just check that the `source` type is a subtype of the `target` type. + return isTypeSubtypeOf(source, target); + } + } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - // 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; } // Check that right operand is a function type with a prototype property @@ -52803,10 +54250,10 @@ var ts; } if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { - return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); } - if (containsMatchingReference(reference, predicateArgument)) { - return declaredType; + if (isMatchingReferenceDiscriminant(predicateArgument, declaredType)) { + return narrowTypeByDiscriminant(type, predicateArgument, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); }); } } } @@ -52916,12 +54363,19 @@ var ts; } /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ function removeOptionalityFromDeclaredType(declaredType, declaration) { - var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 156 /* Parameter */ && - declaration.initializer && - getFalsyFlags(declaredType) & 32768 /* Undefined */ && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */); - return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType; + if (pushTypeResolution(declaration.symbol, 2 /* DeclaredType */)) { + var annotationIncludesUndefined = strictNullChecks && + declaration.kind === 156 /* Parameter */ && + declaration.initializer && + getFalsyFlags(declaredType) & 32768 /* Undefined */ && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */); + popTypeResolution(); + return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType; + } + else { + reportCircularityError(declaration.symbol); + return declaredType; + } } function isConstraintPosition(node) { var parent = node.parent; @@ -53292,7 +54746,7 @@ var ts; break; case 159 /* PropertyDeclaration */: case 158 /* PropertySignature */: - if (ts.hasModifier(container, 32 /* Static */)) { + if (ts.hasModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } @@ -53337,7 +54791,9 @@ var ts; var classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { var classType = getDeclaredTypeOfSymbol(classSymbol).thisType; - return getFlowTypeOfReference(node, classType); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl @@ -53764,7 +55220,7 @@ var ts; var name = declaration.propertyName || declaration.name; var parentType = getContextualTypeForVariableLikeDeclaration(parent) || parent.kind !== 191 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent); - if (parentType && !ts.isBindingPattern(name) && !isComputedNonLiteralName(name)) { + if (parentType && !ts.isBindingPattern(name) && !ts.isComputedNonLiteralName(name)) { var nameType = getLiteralTypeFromPropertyName(name); if (isTypeUsableAsPropertyName(nameType)) { var text = getPropertyNameFromType(nameType); @@ -53803,7 +55259,7 @@ var ts; var contextualReturnType = getContextualReturnType(func); if (contextualReturnType) { if (functionFlags & 2 /* Async */) { // Async function - var contextualAwaitedType = getAwaitedTypeOfPromise(contextualReturnType); + var contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeOfPromise); return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]); } return contextualReturnType; // Regular function @@ -54457,8 +55913,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var current = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var current = types_17[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -54494,58 +55950,73 @@ var ts; function checkArrayLiteral(node, checkMode, forceTuple) { var elements = node.elements; var elementCount = elements.length; - var hasNonEndingSpreadElement = false; var elementTypes = []; - var inDestructuringPattern = ts.isAssignmentTarget(node); + var hasEndingSpreadElement = false; + var hasNonEndingSpreadElement = false; var contextualType = getApparentTypeOfContextualType(node); + var inDestructuringPattern = ts.isAssignmentTarget(node); var inConstContext = isConstContext(node); - for (var index = 0; index < elementCount; index++) { - var e = elements[index]; - if (inDestructuringPattern && e.kind === 213 /* SpreadElement */) { - // Given the following situation: - // var c: {}; - // [...c] = ["", 0]; - // - // c is represented in the tree as a spread element in an array literal. - // But c really functions as a rest element, and its purpose is to provide - // a contextual type for the right hand side of the assignment. Therefore, - // instead of calling checkExpression on "...c", which will give an error - // if c is not iterable/array-like, we need to act as if we are trying to - // get the contextual element type from it. So we do something similar to - // getContextualTypeForElementExpression, which will crucially not error - // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode, forceTuple); - var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || - getIteratedTypeOrElementType(65 /* Destructuring */, restArrayType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false); - if (restElementType) { - elementTypes.push(restElementType); + for (var i = 0; i < elementCount; i++) { + var e = elements[i]; + var spread = e.kind === 213 /* SpreadElement */ && e.expression; + var spreadType = spread && checkExpression(spread, checkMode, forceTuple); + if (spreadType && isTupleType(spreadType)) { + elementTypes.push.apply(elementTypes, getTypeArguments(spreadType)); + if (spreadType.target.hasRestElement) { + if (i === elementCount - 1) + hasEndingSpreadElement = true; + else + hasNonEndingSpreadElement = true; } } else { - var elementContextualType = getContextualTypeForElementExpression(contextualType, index); - var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); - elementTypes.push(type); - } - if (index < elementCount - 1 && e.kind === 213 /* SpreadElement */) { - hasNonEndingSpreadElement = true; + if (inDestructuringPattern && spreadType) { + // Given the following situation: + // var c: {}; + // [...c] = ["", 0]; + // + // c is represented in the tree as a spread element in an array literal. + // But c really functions as a rest element, and its purpose is to provide + // a contextual type for the right hand side of the assignment. Therefore, + // instead of calling checkExpression on "...c", which will give an error + // if c is not iterable/array-like, we need to act as if we are trying to + // get the contextual element type from it. So we do something similar to + // getContextualTypeForElementExpression, which will crucially not error + // if there is no index type / iterated type. + var restElementType = getIndexTypeOfType(spreadType, 1 /* Number */) || + getIteratedTypeOrElementType(65 /* Destructuring */, spreadType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false); + if (restElementType) { + elementTypes.push(restElementType); + } + } + else { + var elementContextualType = getContextualTypeForElementExpression(contextualType, elementTypes.length); + var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple); + elementTypes.push(type); + } + if (spread) { // tuples are done above, so these are only arrays + if (i === elementCount - 1) + hasEndingSpreadElement = true; + else + hasNonEndingSpreadElement = true; + } } } if (!hasNonEndingSpreadElement) { - var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 213 /* SpreadElement */; - var minLength = elementCount - (hasRestElement ? 1 : 0); + var minLength = elementTypes.length - (hasEndingSpreadElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". var tupleResult = void 0; if (inDestructuringPattern && minLength > 0) { - var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); + var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasEndingSpreadElement)); type.pattern = node; return type; } - else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, inConstContext)) { + else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasEndingSpreadElement, elementTypes.length, inConstContext)) { return createArrayLiteralType(tupleResult); } else if (forceTuple) { - return createArrayLiteralType(createTupleType(elementTypes, minLength, hasRestElement)); + return createArrayLiteralType(createTupleType(elementTypes, minLength, hasEndingSpreadElement)); } } return createArrayLiteralType(createArrayType(elementTypes.length ? @@ -54658,7 +56129,8 @@ var ts; var inDestructuringPattern = ts.isAssignmentTarget(node); // Grammar checking checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable; + var allPropertiesTable = strictNullChecks ? ts.createSymbolTable() : undefined; + var propertiesTable = ts.createSymbolTable(); var propertiesArray = []; var spread = emptyObjectType; var contextualType = getApparentTypeOfContextualType(node); @@ -54673,7 +56145,15 @@ var ts; var patternWithComputedProperties = false; var hasComputedStringProperty = false; var hasComputedNumberProperty = false; - propertiesTable = ts.createSymbolTable(); + // Spreads may cause an early bail; ensure computed names are always checked (this is cached) + // As otherwise they may not be checked until exports for the type at this position are retrieved, + // which may never occur. + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var elem = _a[_i]; + if (elem.name && ts.isComputedPropertyName(elem.name) && !ts.isWellKnownSymbolSyntactically(elem.name)) { + checkComputedPropertyName(elem.name); + } + } var offset = 0; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; @@ -54732,6 +56212,7 @@ var ts; prop.type = type; prop.target = member; member = prop; + allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop); } else if (memberDecl.kind === 283 /* SpreadAssignment */) { if (languageVersion < 2 /* ES2015 */) { @@ -54744,11 +56225,14 @@ var ts; hasComputedStringProperty = false; hasComputedNumberProperty = false; } - var type = checkExpression(memberDecl.expression); + var type = getReducedType(checkExpression(memberDecl.expression)); if (!isValidSpreadType(type)) { error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); return errorType; } + if (allPropertiesTable) { + checkSpreadPropOverrides(type, allPropertiesTable, memberDecl); + } spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext); offset = i + 1; continue; @@ -54782,10 +56266,12 @@ var ts; } // If object literal is contextually typed by the implied type of a binding pattern, augment the result // type with those properties for which the binding pattern specifies a default value. - if (contextualTypeHasPattern) { - for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { - var prop = _a[_i]; - if (!propertiesTable.get(prop.escapedName) && !(spread && getPropertyOfType(spread, prop.escapedName))) { + // If the object literal is spread into another object literal, skip this step and let the top-level object + // literal handle it instead. + if (contextualTypeHasPattern && node.parent.kind !== 283 /* SpreadAssignment */) { + for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) { if (!(prop.flags & 16777216 /* Optional */)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } @@ -54836,6 +56322,7 @@ var ts; } function checkJsxSelfClosingElementDeferred(node) { checkJsxOpeningLikeElementOrOpeningFragment(node); + resolveUntypedCall(node); // ensure type arguments and parameters are typechecked, even if there is an arity error } function checkJsxSelfClosingElement(node, _checkMode) { checkNodeDeferred(node); @@ -54896,6 +56383,7 @@ var ts; */ function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { var attributes = openingLikeElement.attributes; + var allAttributesTable = strictNullChecks ? ts.createSymbolTable() : undefined; var attributesTable = ts.createSymbolTable(); var spread = emptyJsxObjectType; var hasSpreadAnyType = false; @@ -54918,6 +56406,7 @@ var ts; attributeSymbol.type = exprType; attributeSymbol.target = member; attributesTable.set(attributeSymbol.escapedName, attributeSymbol); + allAttributesTable === null || allAttributesTable === void 0 ? void 0 : allAttributesTable.set(attributeSymbol.escapedName, attributeSymbol); if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { explicitlySpecifyChildrenAttribute = true; } @@ -54928,12 +56417,15 @@ var ts; spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false); attributesTable = ts.createSymbolTable(); } - var exprType = checkExpressionCached(attributeDecl.expression, checkMode); + var exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode)); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false); + if (allAttributesTable) { + checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl); + } } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -55009,6 +56501,17 @@ var ts; } return childrenTypes; } + function checkSpreadPropOverrides(type, props, spread) { + for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { + var right = _a[_i]; + var left = props.get(right.escapedName); + var rightType = getTypeOfSymbol(right); + if (left && !maybeTypeOfKind(rightType, 98304 /* Nullable */) && !(maybeTypeOfKind(rightType, 3 /* AnyOrUnknown */) && right.flags & 16777216 /* Optional */)) { + var diagnostic = error(left.valueDeclaration, ts.Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, ts.unescapeLeadingUnderscores(left.escapedName)); + ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(spread, ts.Diagnostics.This_spread_always_overwrites_this_property)); + } + } + } /** * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element. * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used) @@ -55184,14 +56687,14 @@ var ts; if (refKind === 1 /* Function */) { var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement); if (sfcReturnConstraint) { - checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); } } else if (refKind === 0 /* Component */) { var classConstraint = getJsxElementClassTypeAt(openingLikeElement); if (classConstraint) { - // Issue an error if this return type isn't assignable to JSX.ElementClass or JSX.Element, failing that - checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + // Issue an error if this return type isn't assignable to JSX.ElementClass, failing that + checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); } } else { // Mixed @@ -55201,7 +56704,11 @@ var ts; return; } var combined = getUnionType([sfcReturnConstraint, classConstraint]); - checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain); + } + function generateInitialErrorChain() { + var componentName = ts.getTextOfNode(openingLikeElement.tagName); + return ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName); } } /** @@ -55282,8 +56789,9 @@ var ts; } } if (isNodeOpeningLikeElement) { - var sig = getResolvedSignature(node); - checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); + var jsxOpeningLikeNode = node; + var sig = getResolvedSignature(jsxOpeningLikeNode); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode); } } /** @@ -55367,11 +56875,6 @@ var ts; function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 153 /* QualifiedName */ ? node.right : node.kind === 188 /* ImportType */ ? node : node.name; - if (ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */) { - // Synthetic property with private constituent property - error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); - return false; - } if (isSuper) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or @@ -55445,7 +56948,7 @@ var ts; return false; } var thisType = getTypeFromTypeNode(thisParameter.type); - enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); + enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType).target; } // No further restrictions for static properties if (flags & 32 /* Static */) { @@ -55801,7 +57304,7 @@ var ts; relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); } else { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); } } } @@ -55888,7 +57391,19 @@ var ts; return ts.getSpellingSuggestion(name, symbols, getCandidateName); function getCandidateName(candidate) { var candidateName = ts.symbolName(candidate); - return !ts.startsWith(candidateName, "\"") && candidate.flags & meaning ? candidateName : undefined; + if (ts.startsWith(candidateName, "\"")) { + return undefined; + } + if (candidate.flags & meaning) { + return candidateName; + } + if (candidate.flags & 2097152 /* Alias */) { + var alias = tryResolveAlias(candidate); + if (alias && alias.flags & meaning) { + return candidateName; + } + } + return undefined; } } function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { @@ -55901,7 +57416,7 @@ var ts; if (!hasPrivateModifier && !hasPrivateIdentifier) { return; } - if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { + if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) { return; } if (isThisAccess) { @@ -56403,8 +57918,83 @@ var ts; // can be specified by users through attributes property. var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode); - return checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes, + return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer); + function checkTagNameDoesNotExpectTooManyArguments() { + var _a; + var tagType = ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node) && !isJsxIntrinsicIdentifier(node.tagName) ? checkExpression(node.tagName) : undefined; + if (!tagType) { + return true; + } + var tagCallSignatures = getSignaturesOfType(tagType, 0 /* Call */); + if (!ts.length(tagCallSignatures)) { + return true; + } + var factory = getJsxFactoryEntity(node); + if (!factory) { + return true; + } + var factorySymbol = resolveEntityName(factory, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, node); + if (!factorySymbol) { + return true; + } + var factoryType = getTypeOfSymbol(factorySymbol); + var callSignatures = getSignaturesOfType(factoryType, 0 /* Call */); + if (!ts.length(callSignatures)) { + return true; + } + var hasFirstParamSignatures = false; + var maxParamCount = 0; + // Check that _some_ first parameter expects a FC-like thing, and that some overload of the SFC expects an acceptable number of arguments + for (var _i = 0, callSignatures_1 = callSignatures; _i < callSignatures_1.length; _i++) { + var sig = callSignatures_1[_i]; + var firstparam = getTypeAtPosition(sig, 0); + var signaturesOfParam = getSignaturesOfType(firstparam, 0 /* Call */); + if (!ts.length(signaturesOfParam)) + continue; + for (var _b = 0, signaturesOfParam_1 = signaturesOfParam; _b < signaturesOfParam_1.length; _b++) { + var paramSig = signaturesOfParam_1[_b]; + hasFirstParamSignatures = true; + if (hasEffectiveRestParameter(paramSig)) { + return true; // some signature has a rest param, so function components can have an arbitrary number of arguments + } + var paramCount = getParameterCount(paramSig); + if (paramCount > maxParamCount) { + maxParamCount = paramCount; + } + } + } + if (!hasFirstParamSignatures) { + // Not a single signature had a first parameter which expected a signature - for back compat, and + // to guard against generic factories which won't have signatures directly, do not error + return true; + } + var absoluteMinArgCount = Infinity; + for (var _c = 0, tagCallSignatures_1 = tagCallSignatures; _c < tagCallSignatures_1.length; _c++) { + var tagSig = tagCallSignatures_1[_c]; + var tagRequiredArgCount = getMinArgumentCount(tagSig); + if (tagRequiredArgCount < absoluteMinArgCount) { + absoluteMinArgCount = tagRequiredArgCount; + } + } + if (absoluteMinArgCount <= maxParamCount) { + return true; // some signature accepts the number of arguments the function component provides + } + if (reportErrors) { + var diag = ts.createDiagnosticForNode(node.tagName, ts.Diagnostics.Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3, ts.entityNameToString(node.tagName), absoluteMinArgCount, ts.entityNameToString(factory), maxParamCount); + var tagNameDeclaration = (_a = getSymbolAtLocation(node.tagName)) === null || _a === void 0 ? void 0 : _a.valueDeclaration; + if (tagNameDeclaration) { + ts.addRelatedInfo(diag, ts.createDiagnosticForNode(tagNameDeclaration, ts.Diagnostics._0_is_declared_here, ts.entityNameToString(node.tagName))); + } + if (errorOutputContainer && errorOutputContainer.skipLogging) { + (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag); + } + if (!errorOutputContainer.skipLogging) { + diagnostics.add(diag); + } + } + return false; + } } function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors, containingMessageChain) { var errorOutputContainer = { errors: undefined, skipLogging: true }; @@ -56616,8 +58206,8 @@ var ts; } function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) { if (ts.isCallExpression(node)) { - var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_4 = _a.length; - return ts.createFileDiagnostic(sourceFile, start, length_4, message, arg0, arg1, arg2, arg3); + var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_5 = _a.length; + return ts.createFileDiagnostic(sourceFile, start, length_5, message, arg0, arg1, arg2, arg3); } else { return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3); @@ -56833,7 +58423,7 @@ var ts; var min_3 = Number.MAX_VALUE; var minIndex = 0; var i_1 = 0; - var _loop_15 = function (c) { + var _loop_17 = function (c) { var chain_2 = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Overload_0_of_1_2_gave_the_following_error, i_1 + 1, candidates.length, signatureToString(c)); }; var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2); if (diags_2) { @@ -56851,15 +58441,15 @@ var ts; }; for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) { var c = candidatesForArgumentError_1[_a]; - _loop_15(c); + _loop_17(c); } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); var chain = ts.chainDiagnosticMessages(ts.map(diags_3, function (d) { return typeof d.messageText === "string" ? d : d.messageText; }), ts.Diagnostics.No_overload_matches_this_call); var related = ts.flatMap(diags_3, function (d) { return d.relatedInformation; }); if (ts.every(diags_3, function (d) { return d.start === diags_3[0].start && d.length === diags_3[0].length && d.file === diags_3[0].file; })) { - var _b = diags_3[0], file = _b.file, start = _b.start, length_5 = _b.length; - diagnostics.add({ file: file, start: start, length: length_5, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related }); + var _b = diags_3[0], file = _b.file, start = _b.start, length_6 = _b.length; + diagnostics.add({ file: file, start: start, length: length_6, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related }); } else { diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, chain, related)); @@ -56885,7 +58475,7 @@ var ts; } } } - return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); + return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } candidatesForArgumentError = undefined; @@ -56967,9 +58557,9 @@ var ts; } } // 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) { ts.Debug.assert(candidates.length > 0); // Else should not have called this. + checkNodeDeferred(node); // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine. // Don't do this if there is a `candidatesOutArray`, // because then we want the chosen best candidate to be one of the overloads, not a combination. @@ -56985,7 +58575,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_16 = function (i) { + var _loop_18 = function (i) { var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : i < s.parameters.length ? s.parameters[i] : undefined; }); @@ -56993,7 +58583,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_16(i); + _loop_18(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); var flags = 0 /* None */; @@ -57144,7 +58734,7 @@ var ts; if (node.arguments.length === 1) { var text = ts.getSourceFileOfNode(node).text; if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { - relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.Are_you_missing_a_semicolon); } } invocationError(node.expression, apparentType, 0 /* Call */, relatedInformation); @@ -57328,8 +58918,8 @@ var ts; if (apparentType.flags & 1048576 /* Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var constituent = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var constituent = types_18[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -57383,9 +58973,9 @@ var ts; ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo)); } if (ts.isCallExpression(errorTarget.parent)) { - var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_6 = _b.length; + var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_7 = _b.length; diagnostic.start = start; - diagnostic.length = length_6; + diagnostic.length = length_7; } diagnostics.add(diagnostic); invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic); @@ -57854,8 +59444,14 @@ var ts; } return targetType; } + function checkNonNullChain(node) { + var leftType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(leftType, node.expression); + return propagateOptionalTypeMarker(getNonNullableType(nonOptionalType), node, nonOptionalType !== leftType); + } function checkNonNullAssertion(node) { - return getNonNullableType(checkExpression(node.expression)); + return node.flags & 32 /* OptionalChain */ ? checkNonNullChain(node) : + getNonNullableType(checkExpression(node.expression)); } function checkMetaProperty(node) { checkGrammarMetaProperty(node); @@ -57966,7 +59562,7 @@ var ts; } return length; } - function getMinArgumentCount(signature) { + function getMinArgumentCount(signature, strongArityForUntypedJS) { if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); if (isTupleType(restType)) { @@ -57976,6 +59572,9 @@ var ts; } } } + if (!strongArityForUntypedJS && signature.flags & 16 /* IsUntypedSignatureInJSFile */) { + return 0; + } return signature.minArgumentCount; } function hasEffectiveRestParameter(signature) { @@ -57994,7 +59593,7 @@ var ts; } function getNonArrayRestType(signature) { var restType = getEffectiveRestType(signature); - return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : undefined; + return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072 /* Never */) === 0 ? restType : undefined; } function getTypeOfFirstParameterOfSignature(signature) { return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); @@ -58177,18 +59776,16 @@ var ts; returnType = getUnionType(types, 2 /* Subtype */); } if (returnType || yieldType || nextType) { - var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); - if (!contextualSignature) { - if (yieldType) - reportErrorsFromWidening(func, yieldType, 1 /* GeneratorYield */); - if (returnType) - reportErrorsFromWidening(func, returnType); - if (nextType) - reportErrorsFromWidening(func, nextType); - } + if (yieldType) + reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */); + if (returnType) + reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */); + if (nextType) + reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */); if (returnType && isUnitType(returnType) || yieldType && isUnitType(yieldType) || nextType && isUnitType(nextType)) { + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); var contextualType = !contextualSignature ? undefined : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType : instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func); @@ -58326,8 +59923,7 @@ var ts; function computeExhaustiveSwitchStatement(node) { if (node.expression.kind === 204 /* TypeOfExpression */) { var operandType = getTypeOfExpression(node.expression.expression); - // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. - var witnesses = getSwitchClauseTypeOfWitnesses(node); + var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); // notEqualFacts states that the type of the switched value is not equal to every type in the switch. var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); var type_3 = getBaseConstraintOfType(operandType) || operandType; @@ -58407,7 +60003,7 @@ var ts; return; } var functionFlags = ts.getFunctionFlags(func); - var type = returnType && getReturnOrPromisedType(returnType, functionFlags); + var type = returnType && unwrapReturnType(returnType, functionFlags); // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. if (type && maybeTypeOfKind(type, 1 /* Any */ | 16384 /* Void */)) { return; @@ -58516,13 +60112,6 @@ var ts; } } } - function getReturnOrPromisedType(type, functionFlags) { - var isGenerator = !!(functionFlags & 1 /* Generator */); - var isAsync = !!(functionFlags & 2 /* Async */); - return type && isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsync) || errorType : - type && isAsync ? getAwaitedType(type) || errorType : - type; - } function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); @@ -58547,7 +60136,7 @@ var ts; // check assignability of the awaited type of the expression body against the promised type of // its return type annotation. var exprType = checkExpression(node.body); - var returnOrPromisedType = getReturnOrPromisedType(returnType, functionFlags); + var returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags); if (returnOrPromisedType) { if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -58660,7 +60249,7 @@ var ts; } function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) { // References are combinations of identifiers, parentheses, and property accesses. - var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); + var node = ts.skipOuterExpressions(expr, 6 /* Assertions */ | 1 /* Parentheses */); if (node.kind !== 75 /* Identifier */ && !ts.isAccessExpression(node)) { error(expr, invalidReferenceMessage); return false; @@ -58678,6 +60267,7 @@ var ts; error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); return booleanType; } + // eslint-disable-next-line if (expr.kind === 194 /* PropertyAccessExpression */ && ts.isPrivateIdentifier(expr.name)) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier); } @@ -58825,13 +60415,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 & ~131072 /* GenericMappedType */ || kind & 131072 /* GenericMappedType */ && isGenericMappedType(type)) { + if (type.flags & kind) { return true; } if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var t = types_19[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -59416,8 +61006,8 @@ var ts; var name = prop.escapedName; var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false); if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { - grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); - return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop); + addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol); } } } @@ -59598,7 +61188,8 @@ var ts; return getContextualIterationType(2 /* Next */, func) || anyType; } function checkConditionalExpression(node, checkMode) { - checkTruthinessExpression(node.condition); + var type = checkTruthinessExpression(node.condition); + checkTestingKnownTruthyCallableType(node.condition, node.whenTrue, type); var type1 = checkExpression(node.whenTrue, checkMode); var type2 = checkExpression(node.whenFalse, checkMode); return getUnionType([type1, type2], 2 /* Subtype */); @@ -60161,6 +61752,9 @@ var ts; if (!(func.kind === 162 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } + if (func.kind === 162 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") { + error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name); + } } if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); @@ -60175,10 +61769,13 @@ var ts; if (func.kind === 202 /* ArrowFunction */) { error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter); } + if (func.kind === 163 /* GetAccessor */ || func.kind === 164 /* SetAccessor */) { + error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters); + } } // 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), anyReadonlyArrayType)) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -60580,8 +62177,9 @@ var ts; // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || - ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }); + var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) && + (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || + ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); })); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { @@ -61041,7 +62639,7 @@ var ts; // entirely unable to merge - a more helpful message like "Class declaration cannot implement overload list" // might be warranted. :shrug: ts.forEach(declarations, function (declaration) { - addDuplicateDeclarationError(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), ts.filter(declarations, function (d) { return d !== declaration; })); + addDuplicateDeclarationError(declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), declarations); }); } // Abstract methods can't have an implementation -- in particular, they don't need one. @@ -61129,9 +62727,9 @@ var ts; case 247 /* TypeAliasDeclaration */: // A jsdoc typedef and callback are, by definition, type aliases. // falls through - case 321 /* JSDocTypedefTag */: - case 314 /* JSDocCallbackTag */: - case 315 /* JSDocEnumTag */: + case 322 /* JSDocTypedefTag */: + case 315 /* JSDocCallbackTag */: + case 316 /* JSDocEnumTag */: return 2 /* ExportType */; case 249 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ @@ -61154,10 +62752,10 @@ var ts; case 253 /* ImportEqualsDeclaration */: case 256 /* NamespaceImport */: case 255 /* ImportClause */: - var result_7 = 0 /* None */; + var result_10 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_7 |= getDeclarationSpaces(d); }); - return result_7; + ts.forEach(target.declarations, function (d) { result_10 |= getDeclarationSpaces(d); }); + return result_10; case 242 /* VariableDeclaration */: case 191 /* BindingElement */: case 244 /* FunctionDeclaration */: @@ -61184,9 +62782,9 @@ var ts; * @param type The type of the promise. * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. */ - function getPromisedTypeOfPromise(promise, errorNode) { + function getPromisedTypeOfPromise(type, errorNode) { // - // { // promise + // { // type // then( // thenFunction // onfulfilled: ( // onfulfilledParameterType // value: T // valueParameterType @@ -61194,17 +62792,17 @@ var ts; // ): any; // } // - if (isTypeAny(promise)) { + if (isTypeAny(type)) { return undefined; } - var typeAsPromise = promise; + var typeAsPromise = type; if (typeAsPromise.promisedTypeOfPromise) { return typeAsPromise.promisedTypeOfPromise; } - if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) { - return typeAsPromise.promisedTypeOfPromise = getTypeArguments(promise)[0]; + if (isReferenceToType(type, getGlobalPromiseType(/*reportErrors*/ false))) { + return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0]; } - var thenFunction = getTypeOfPropertyOfType(promise, "then"); // TODO: GH#18217 + var thenFunction = getTypeOfPropertyOfType(type, "then"); // TODO: GH#18217 if (isTypeAny(thenFunction)) { return undefined; } @@ -61239,28 +62837,44 @@ var ts; var awaitedType = getAwaitedType(type, errorNode, diagnosticMessage, arg0); return awaitedType || errorType; } + /** + * Determines whether a type has a callable `then` member. + */ + function isThenableType(type) { + var thenFunction = getTypeOfPropertyOfType(type, "then"); + return !!thenFunction && getSignaturesOfType(getTypeWithFacts(thenFunction, 2097152 /* NEUndefinedOrNull */), 0 /* Call */).length > 0; + } + /** + * Gets the "awaited type" of a type. + * + * The "awaited type" of an expression is its "promised type" if the expression is a + * Promise-like type; otherwise, it is the type of the expression. If the "promised + * type" is itself a Promise-like, the "promised type" is recursively unwrapped until a + * non-promise type is found. + * + * This is used to reflect the runtime behavior of the `await` keyword. + */ function getAwaitedType(type, errorNode, diagnosticMessage, arg0) { + if (isTypeAny(type)) { + return type; + } var typeAsAwaitable = type; if (typeAsAwaitable.awaitedTypeOfType) { return typeAsAwaitable.awaitedTypeOfType; } - if (isTypeAny(type)) { - return typeAsAwaitable.awaitedTypeOfType = type; - } - if (type.flags & 1048576 /* Union */) { - var types = void 0; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var constituentType = _a[_i]; - types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage, arg0)); - } - if (!types) { - return undefined; - } - return typeAsAwaitable.awaitedTypeOfType = getUnionType(types); + // For a union, get a union of the awaited types of each constituent. + // + return typeAsAwaitable.awaitedTypeOfType = + mapType(type, errorNode ? function (constituentType) { return getAwaitedTypeWorker(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeWorker); + } + function getAwaitedTypeWorker(type, errorNode, diagnosticMessage, arg0) { + var typeAsAwaitable = type; + if (typeAsAwaitable.awaitedTypeOfType) { + return typeAsAwaitable.awaitedTypeOfType; } var promisedType = getPromisedTypeOfPromise(type); if (promisedType) { - if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { + if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) { // Verify that we don't have a bad actor in the form of a promise whose // promised type is the same as the promise type, or a mutually recursive // promise. If so, we return undefined as we cannot guess the shape. If this @@ -61274,6 +62888,7 @@ var ts; // onfulfilled: (value: BadPromise) => any, // onrejected: (error: any) => any): BadPromise; // } + // // The above interface will pass the PromiseLike check, and return a // promised type of `BadPromise`. Since this is a self reference, we // don't want to keep recursing ad infinitum. @@ -61310,8 +62925,8 @@ var ts; } // The type was not a promise, so it could not be unwrapped any further. // As long as the type does not have a callable "then" property, it is - // safe to return the type; otherwise, an error will be reported in - // the call to getNonThenableType and we will return undefined. + // safe to return the type; otherwise, an error is reported and we return + // undefined. // // An example of a non-promise "thenable" might be: // @@ -61323,8 +62938,7 @@ var ts; // of a runtime problem. If the user wants to return this value from an async // function, they would need to wrap it in some other value. If they want it to // be treated as a promise, they can cast to . - var thenFunction = getTypeOfPropertyOfType(type, "then"); - if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) { + if (isThenableType(type)) { if (errorNode) { if (!diagnosticMessage) return ts.Debug.fail(); @@ -61515,8 +63129,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 182 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -61669,15 +63283,24 @@ var ts; } } } + function checkJSDocPropertyTag(node) { + checkSourceElement(node.typeExpression); + } function checkJSDocFunctionType(node) { if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) { reportImplicitAny(node, anyType); } checkSignatureDeclaration(node); } + function checkJSDocImplementsTag(node) { + var classLike = ts.getEffectiveJSDocHost(node); + if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); + } + } function checkJSDocAugmentsTag(node) { - var classLike = ts.getJSDocHost(node); - if (!ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { + var classLike = ts.getEffectiveJSDocHost(node); + if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) { error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } @@ -61847,7 +63470,9 @@ var ts; break; } var symbol = getSymbolOfNode(member); - if (!symbol.isReferenced && (ts.hasModifier(member, 8 /* Private */) || ts.isNamedDeclaration(member) && ts.isPrivateIdentifier(member.name))) { + if (!symbol.isReferenced + && (ts.hasModifier(member, 8 /* Private */) || ts.isNamedDeclaration(member) && ts.isPrivateIdentifier(member.name)) + && !(member.flags & 8388608 /* Ambient */)) { addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; @@ -61894,7 +63519,7 @@ var ts; ? ts.rangeOfNode(parent) // Include the `<>` in the error message : ts.rangeOfTypeParameters(parent.typeParameters); - var only = typeParameters.length === 1; + var only = parent.typeParameters.length === 1; var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused; var arg0 = only ? name : undefined; addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0)); @@ -61921,6 +63546,16 @@ var ts; function tryGetRootParameterDeclaration(node) { return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); } + function isValidUnusedLocalDeclaration(declaration) { + if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + return !!ts.findAncestor(declaration.parent, function (ancestor) { + return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false : + ts.isForOfStatement(ancestor) ? true : "quit"; + }); + } + return ts.isAmbientModule(declaration) || + (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name); + } function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. var unusedImports = ts.createMap(); @@ -61934,8 +63569,7 @@ var ts; } for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (ts.isAmbientModule(declaration) || - (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + if (isValidUnusedLocalDeclaration(declaration)) { continue; } if (isImportedDeclaration(declaration)) { @@ -62412,21 +64046,21 @@ var ts; // Grammar checking checkGrammarStatementInAmbientContext(node); var type = checkTruthinessExpression(node.expression); - checkTestingKnownTruthyCallableType(node, type); + checkTestingKnownTruthyCallableType(node.expression, node.thenStatement, type); checkSourceElement(node.thenStatement); if (node.thenStatement.kind === 224 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); } - function checkTestingKnownTruthyCallableType(ifStatement, type) { + function checkTestingKnownTruthyCallableType(condExpr, body, type) { if (!strictNullChecks) { return; } - var testedNode = ts.isIdentifier(ifStatement.expression) - ? ifStatement.expression - : ts.isPropertyAccessExpression(ifStatement.expression) - ? ifStatement.expression.name + var testedNode = ts.isIdentifier(condExpr) + ? condExpr + : ts.isPropertyAccessExpression(condExpr) + ? condExpr.name : undefined; if (!testedNode) { return; @@ -62448,17 +64082,39 @@ var ts; if (!testedFunctionSymbol) { return; } - var functionIsUsedInBody = ts.forEachChild(ifStatement.thenStatement, function check(childNode) { + var functionIsUsedInBody = ts.forEachChild(body, function check(childNode) { if (ts.isIdentifier(childNode)) { var childSymbol = getSymbolAtLocation(childNode); - if (childSymbol && childSymbol.id === testedFunctionSymbol.id) { - return true; + if (childSymbol && childSymbol === testedFunctionSymbol) { + // If the test was a simple identifier, the above check is sufficient + if (ts.isIdentifier(condExpr)) { + return true; + } + // Otherwise we need to ensure the symbol is called on the same target + var testedExpression = testedNode.parent; + var childExpression = childNode.parent; + while (testedExpression && childExpression) { + if (ts.isIdentifier(testedExpression) && ts.isIdentifier(childExpression) || + testedExpression.kind === 104 /* ThisKeyword */ && childExpression.kind === 104 /* ThisKeyword */) { + return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression); + } + if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) { + if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) { + return false; + } + childExpression = childExpression.expression; + testedExpression = testedExpression.expression; + } + else { + return false; + } + } } } return ts.forEachChild(childNode, check); }); if (!functionIsUsedInBody) { - error(ifStatement.expression, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead); + error(condExpr, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead); } } function checkDoStatement(node) { @@ -62529,7 +64185,7 @@ var ts; } else { var varExpr = node.initializer; - var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); + var iteratedType = checkRightHandSideOfForOf(node); // There may be a destructuring assignment on the left side if (varExpr.kind === 192 /* ArrayLiteralExpression */ || varExpr.kind === 193 /* ObjectLiteralExpression */) { // iteratedType may be undefined. In this case, we still want to check the structure of @@ -62606,10 +64262,9 @@ var ts; checkVariableDeclaration(decl); } } - function checkRightHandSideOfForOf(rhsExpression, awaitModifier) { - var expressionType = checkNonNullExpression(rhsExpression); - var use = awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */; - return checkIteratedTypeOrElementType(use, expressionType, undefinedType, rhsExpression); + function checkRightHandSideOfForOf(statement) { + var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */; + return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression); } function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) { if (isTypeAny(inputType)) { @@ -63225,10 +64880,11 @@ var ts; // TODO: Check that target label is valid } function unwrapReturnType(returnType, functionFlags) { + var _a, _b; var isGenerator = !!(functionFlags & 1 /* Generator */); var isAsync = !!(functionFlags & 2 /* Async */); - return isGenerator ? getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync) || errorType : - isAsync ? getPromisedTypeOfPromise(returnType) || errorType : + return isGenerator ? (_a = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync)) !== null && _a !== void 0 ? _a : errorType : + isAsync ? (_b = getAwaitedType(returnType)) !== null && _b !== void 0 ? _b : errorType : returnType; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { @@ -63236,6 +64892,7 @@ var ts; return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */); } function checkReturnStatement(node) { + var _a; // Grammar checking if (checkGrammarStatementInAmbientContext(node)) { return; @@ -63261,7 +64918,7 @@ var ts; } } else if (getReturnTypeFromAnnotation(func)) { - var unwrappedReturnType = unwrapReturnType(returnType, functionFlags); + var unwrappedReturnType = (_a = unwrapReturnType(returnType, functionFlags)) !== null && _a !== void 0 ? _a : returnType; var unwrappedExprType = functionFlags & 2 /* Async */ ? checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) : exprType; @@ -63442,6 +65099,9 @@ var ts; } var propDeclaration = prop.valueDeclaration; var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration); + if (name && ts.isPrivateIdentifier(name)) { + return; + } // index is numeric and property name is not valid numeric literal if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) { return; @@ -63693,7 +65353,7 @@ var ts; checkKindsOfPropertyMemberOverrides(type, baseType_1); } } - var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); + var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node); if (implementedTypeNodes) { for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { var typeRefNode = implementedTypeNodes_1[_b]; @@ -63702,7 +65362,7 @@ var ts; } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { - var t = getTypeFromTypeNode(typeRefNode); + var t = getReducedType(getTypeFromTypeNode(typeRefNode)); if (t !== errorType) { if (isValidBaseType(t)) { var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? @@ -63729,7 +65389,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_17 = function (member) { + var _loop_19 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -63748,7 +65408,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_17(member); + _loop_19(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -63907,6 +65567,25 @@ var ts; } } } + function getNonInterhitedProperties(type, baseTypes, properties) { + if (!ts.length(baseTypes)) { + return properties; + } + var seen = ts.createUnderscoreEscapedMap(); + ts.forEach(properties, function (p) { seen.set(p.escapedName, p); }); + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; + var properties_5 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) { + var prop = properties_4[_a]; + var existing = seen.get(prop.escapedName); + if (existing && !isPropertyIdenticalTo(existing, prop)) { + seen.delete(prop.escapedName); + } + } + } + return ts.arrayFrom(seen.values()); + } function checkInheritedPropertiesAreIdentical(type, typeNode) { var baseTypes = getBaseTypes(type); if (baseTypes.length < 2) { @@ -63915,11 +65594,11 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); }); var ok = true; - for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { - var base = baseTypes_2[_i]; + for (var _i = 0, baseTypes_3 = baseTypes; _i < baseTypes_3.length; _i++) { + var base = baseTypes_3[_i]; var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { - var prop = properties_4[_a]; + for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) { + var prop = properties_6[_a]; var existing = seen.get(prop.escapedName); if (!existing) { seen.set(prop.escapedName, { prop: prop, containingType: base }); @@ -64037,7 +65716,7 @@ var ts; } } function computeMemberValue(member, autoValue) { - if (isComputedNonLiteralName(member.name)) { + if (ts.isComputedNonLiteralName(member.name)) { error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums); } else { @@ -64088,7 +65767,13 @@ var ts; } else { // Only here do we need to check that the initializer is assignable to the enum type. - checkTypeAssignableTo(checkExpression(initializer), getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + var source = checkExpression(initializer); + if (!isTypeAssignableToKind(source, 296 /* NumberLike */)) { + error(initializer, ts.Diagnostics.Only_numeric_enums_can_have_computed_members_but_this_expression_has_type_0_If_you_do_not_need_exhaustiveness_checks_consider_using_an_object_literal_instead, typeToString(source)); + } + else { + checkTypeAssignableTo(source, getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined); + } } return value; function evaluate(expr) { @@ -64171,6 +65856,9 @@ var ts; error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); return 0; } + else { + error(expr, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(memberSymbol)); + } } return undefined; } @@ -64444,7 +66132,7 @@ var ts; return false; } if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { - // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration + // we have already reported errors on top level imports/exports in external module augmentations in checkModuleDeclaration // no need to do this again. if (!isTopLevelInExternalModuleAugmentation(node)) { // TypeScript 1.0 spec (April 2013): 12.1.6 @@ -64563,16 +66251,15 @@ var ts; if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } + if (node.moduleSpecifier && node.exportClause && ts.isNamedExports(node.exportClause) && ts.length(node.exportClause.elements) && languageVersion === 0 /* ES3 */) { + checkExternalEmitHelpers(node, 1048576 /* CreateBinding */); + } + checkGrammarExportDeclaration(node); if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { - if (node.exportClause) { + if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) { // export { x, y } // export { x, y } from "foo" - if (ts.isNamedExports(node.exportClause)) { - ts.forEach(node.exportClause.elements, checkExportSpecifier); - } - else if (!ts.isNamespaceExport(node.exportClause)) { - checkImportBinding(node.exportClause); - } + ts.forEach(node.exportClause.elements, checkExportSpecifier); var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 250 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 8388608 /* Ambient */; @@ -64586,12 +66273,23 @@ var ts; if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } + else if (node.exportClause) { + checkAliasSymbol(node.exportClause); + } if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) { checkExternalEmitHelpers(node, 65536 /* ExportStar */); } } } } + function checkGrammarExportDeclaration(node) { + var _a; + var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 261 /* NamedExports */; + if (isTypeOnlyExportStar) { + grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type); + } + return !isTypeOnlyExportStar; + } function checkGrammarModuleElementContext(node, errorMessage) { var isInAppropriateContext = node.parent.kind === 290 /* SourceFile */ || node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 249 /* ModuleDeclaration */; if (!isInAppropriateContext) { @@ -64828,16 +66526,20 @@ var ts; return checkImportType(node); case 307 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 321 /* JSDocTypedefTag */: - case 314 /* JSDocCallbackTag */: - case 315 /* JSDocEnumTag */: + case 308 /* JSDocImplementsTag */: + return checkJSDocImplementsTag(node); + case 322 /* JSDocTypedefTag */: + case 315 /* JSDocCallbackTag */: + case 316 /* JSDocEnumTag */: return checkJSDocTypeAliasTag(node); - case 320 /* JSDocTemplateTag */: + case 321 /* JSDocTemplateTag */: return checkJSDocTemplateTag(node); - case 319 /* JSDocTypeTag */: + case 320 /* JSDocTypeTag */: return checkJSDocTypeTag(node); - case 316 /* JSDocParameterTag */: + case 317 /* JSDocParameterTag */: return checkJSDocParameterTag(node); + case 323 /* JSDocPropertyTag */: + return checkJSDocPropertyTag(node); case 300 /* JSDocFunctionType */: checkJSDocFunctionType(node); // falls through @@ -65015,6 +66717,16 @@ var ts; currentNode = node; instantiationCount = 0; switch (node.kind) { + case 196 /* CallExpression */: + case 197 /* NewExpression */: + case 198 /* TaggedTemplateExpression */: + case 157 /* Decorator */: + case 268 /* JsxOpeningElement */: + // These node kinds are deferred checked when overload resolution fails + // To save on work, we ensure the arguments are checked just once, in + // a deferred way + resolveUntypedCall(node); + break; case 201 /* FunctionExpression */: case 202 /* ArrowFunction */: case 161 /* MethodDeclaration */: @@ -65400,10 +67112,10 @@ var ts; return entityNameSymbol; } } - if (name.parent.kind === 316 /* JSDocParameterTag */) { + if (name.parent.kind === 317 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(name.parent); } - if (name.parent.kind === 155 /* TypeParameter */ && name.parent.parent.kind === 320 /* JSDocTemplateTag */) { + if (name.parent.kind === 155 /* TypeParameter */ && name.parent.parent.kind === 321 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(name.parent); return typeParameter && typeParameter.symbol; @@ -65444,7 +67156,7 @@ var ts; // Do we want to return undefined here? return undefined; } - function getSymbolAtLocation(node) { + function getSymbolAtLocation(node, ignoreErrors) { if (node.kind === 290 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } @@ -65517,7 +67229,7 @@ var ts; ((node.parent.kind === 254 /* ImportDeclaration */ || node.parent.kind === 260 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { - return resolveExternalModuleName(node, node); + return resolveExternalModuleName(node, node, ignoreErrors); } if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { return getSymbolOfNode(parent); @@ -65537,9 +67249,9 @@ var ts; case 80 /* ClassKeyword */: return getSymbolOfNode(node.parent); case 188 /* ImportType */: - return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; + return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined; case 89 /* ExportKeyword */: - return ts.isExportAssignment(node.parent) ? ts.Debug.assertDefined(node.parent.symbol) : undefined; + return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined; default: return undefined; } @@ -65621,7 +67333,7 @@ var ts; // for ( { a } of elems) { // } if (expr.parent.kind === 232 /* ForOfStatement */) { - var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); + var iteratedType = checkRightHandSideOfForOf(expr.parent); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from "for" initializer @@ -66186,6 +67898,9 @@ var ts; var type = getTypeOfSymbol(getSymbolOfNode(node)); return literalTypeToNode(type, node, tracker); } + function getJsxFactoryEntity(location) { + return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; + } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope // to avoid scope pollution @@ -66199,9 +67914,11 @@ var ts; return; } var file = host.getSourceFile(resolvedDirective.resolvedFileName); - // Add the transitive closure of path references loaded by this file (as long as they are not) - // part of an existing type reference. - addReferencedFilesToTypeDirective(file, key); + if (file) { + // Add the transitive closure of path references loaded by this file (as long as they are not) + // part of an existing type reference. + addReferencedFilesToTypeDirective(file, key); + } }); } return { @@ -66256,7 +67973,7 @@ var ts; var symbol = node && getSymbolOfNode(node); return !!(symbol && ts.getCheckFlags(symbol) & 4096 /* Late */); }, - getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, + getJsxFactoryEntity: getJsxFactoryEntity, getAllAccessorDeclarations: function (accessor) { accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 var otherKind = accessor.kind === 164 /* SetAccessor */ ? 163 /* GetAccessor */ : 164 /* SetAccessor */; @@ -66286,8 +68003,34 @@ var ts; return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled); } return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled); - } + }, + isImportRequiredByAugmentation: isImportRequiredByAugmentation, }; + function isImportRequiredByAugmentation(node) { + var file = ts.getSourceFileOfNode(node); + if (!file.symbol) + return false; + var importTarget = getExternalModuleFileFromDeclaration(node); + if (!importTarget) + return false; + if (importTarget === file) + return false; + var exports = getExportsOfModule(file.symbol); + for (var _i = 0, _a = ts.arrayFrom(exports.values()); _i < _a.length; _i++) { + var s = _a[_i]; + if (s.mergeId) { + var merged = getMergedSymbol(s); + for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) { + var d = _c[_b]; + var declFile = ts.getSourceFileOfNode(d); + if (declFile === importTarget) { + return true; + } + } + } + } + return false; + } function isInHeritageClause(node) { return node.parent && node.parent.kind === 216 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 279 /* HeritageClause */; } @@ -66522,7 +68265,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1 /* FirstEmitHelper */; helper <= 524288 /* LastEmitHelper */; helper <<= 1) { + for (var helper = 1 /* FirstEmitHelper */; helper <= 1048576 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 111551 /* Value */); @@ -66558,6 +68301,7 @@ var ts; case 131072 /* MakeTemplateObject */: return "__makeTemplateObject"; case 262144 /* ClassPrivateFieldGet */: return "__classPrivateFieldGet"; case 524288 /* ClassPrivateFieldSet */: return "__classPrivateFieldSet"; + case 1048576 /* CreateBinding */: return "__createBinding"; default: return ts.Debug.fail("Unrecognized helper"); } } @@ -66961,6 +68705,7 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); } } + checkGrammarForDisallowedTrailingComma(node.parameters, ts.Diagnostics.An_index_signature_cannot_have_a_trailing_comma); if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } @@ -67329,7 +69074,7 @@ var ts; if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } - var parameter = ts.Debug.assertDefined(ts.getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion."); + var parameter = ts.Debug.checkDefined(ts.getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion."); if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); } @@ -67968,13 +69713,13 @@ var ts; return type; } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly - function findMatchingDiscriminantType(source, target, isRelatedTo) { + function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) { if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) { var sourceProperties = getPropertiesOfType(source); if (sourceProperties) { var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target); if (sourcePropertiesFiltered) { - return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo); + return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo, /*defaultValue*/ undefined, skipPartial); } } } @@ -68984,10 +70729,8 @@ var ts; } ts.createPropertyAccess = createPropertyAccess; function updatePropertyAccess(node, expression, name) { - if (ts.isOptionalChain(node) && ts.isIdentifier(node.name) && ts.isIdentifier(name)) { - // Not sure why this cast was necessary: the previous line should already establish that node.name is an identifier - var theNode = node; - return updatePropertyAccessChain(theNode, expression, node.questionDotToken, name); + if (ts.isPropertyAccessChain(node)) { + return updatePropertyAccessChain(node, expression, node.questionDotToken, ts.cast(name, ts.isIdentifier)); } // Because we are updating existed propertyAccess we want to inherit its emitFlags // instead of using the default from createPropertyAccess @@ -69350,7 +71093,7 @@ var ts; } var token = rawTextScanner.scan(); if (token === 23 /* CloseBracketToken */) { - token = rawTextScanner.reScanTemplateToken(); + token = rawTextScanner.reScanTemplateToken(/* isTaggedTemplate */ false); } if (rawTextScanner.isUnterminated()) { rawTextScanner.setText(undefined); @@ -69412,9 +71155,11 @@ var ts; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { + var asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; + expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; var node = createSynthesizedNode(212 /* YieldExpression */); - node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; - node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; + node.asteriskToken = asteriskToken; + node.expression = expression && ts.parenthesizeExpressionForList(expression); return node; } ts.createYield = createYield; @@ -69497,11 +71242,28 @@ var ts; } ts.createNonNullExpression = createNonNullExpression; function updateNonNullExpression(node, expression) { + if (ts.isNonNullChain(node)) { + return updateNonNullChain(node, expression); + } return node.expression !== expression ? updateNode(createNonNullExpression(expression), node) : node; } ts.updateNonNullExpression = updateNonNullExpression; + function createNonNullChain(expression) { + var node = createSynthesizedNode(218 /* NonNullExpression */); + node.flags |= 32 /* OptionalChain */; + node.expression = ts.parenthesizeForAccess(expression); + return node; + } + ts.createNonNullChain = createNonNullChain; + function updateNonNullChain(node, expression) { + ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead."); + return node.expression !== expression + ? updateNode(createNonNullChain(expression), node) + : node; + } + ts.updateNonNullChain = updateNonNullChain; function createMetaProperty(keywordToken, name) { var node = createSynthesizedNode(219 /* MetaProperty */); node.keywordToken = keywordToken; @@ -69868,6 +71630,26 @@ var ts; : node; } ts.updateFunctionDeclaration = updateFunctionDeclaration; + /* @internal */ + function updateFunctionLikeBody(declaration, body) { + switch (declaration.kind) { + case 244 /* FunctionDeclaration */: + return createFunctionDeclaration(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 161 /* MethodDeclaration */: + return createMethod(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.questionToken, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 163 /* GetAccessor */: + return createGetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, declaration.type, body); + case 164 /* SetAccessor */: + return createSetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, body); + case 162 /* Constructor */: + return createConstructor(declaration.decorators, declaration.modifiers, declaration.parameters, body); + case 201 /* FunctionExpression */: + return createFunctionExpression(declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body); + case 202 /* ArrowFunction */: + return createArrowFunction(declaration.modifiers, declaration.typeParameters, declaration.parameters, declaration.type, declaration.equalsGreaterThanToken, body); + } + } + ts.updateFunctionLikeBody = updateFunctionLikeBody; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { var node = createSynthesizedNode(245 /* ClassDeclaration */); node.decorators = asNodeArray(decorators); @@ -70201,7 +71983,7 @@ var ts; ts.createJSDocTypeExpression = createJSDocTypeExpression; /* @internal */ function createJSDocTypeTag(typeExpression, comment) { - var tag = createJSDocTag(319 /* JSDocTypeTag */, "type"); + var tag = createJSDocTag(320 /* JSDocTypeTag */, "type"); tag.typeExpression = typeExpression; tag.comment = comment; return tag; @@ -70209,7 +71991,7 @@ var ts; ts.createJSDocTypeTag = createJSDocTypeTag; /* @internal */ function createJSDocReturnTag(typeExpression, comment) { - var tag = createJSDocTag(317 /* JSDocReturnTag */, "returns"); + var tag = createJSDocTag(318 /* JSDocReturnTag */, "returns"); tag.typeExpression = typeExpression; tag.comment = comment; return tag; @@ -70217,14 +71999,14 @@ var ts; ts.createJSDocReturnTag = createJSDocReturnTag; /** @internal */ function createJSDocThisTag(typeExpression) { - var tag = createJSDocTag(318 /* JSDocThisTag */, "this"); + var tag = createJSDocTag(319 /* JSDocThisTag */, "this"); tag.typeExpression = typeExpression; return tag; } ts.createJSDocThisTag = createJSDocThisTag; /* @internal */ function createJSDocParamTag(name, isBracketed, typeExpression, comment) { - var tag = createJSDocTag(316 /* JSDocParameterTag */, "param"); + var tag = createJSDocTag(317 /* JSDocParameterTag */, "param"); tag.typeExpression = typeExpression; tag.name = name; tag.isBracketed = isBracketed; @@ -70233,6 +72015,11 @@ var ts; } ts.createJSDocParamTag = createJSDocParamTag; /* @internal */ + function createJSDocClassTag() { + return createJSDocTag(310 /* JSDocClassTag */, "class"); + } + ts.createJSDocClassTag = createJSDocClassTag; + /* @internal */ function createJSDocComment(comment, tags) { var node = createSynthesizedNode(303 /* JSDocComment */); node.comment = comment; @@ -70599,7 +72386,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(324 /* NotEmittedStatement */); + var node = createSynthesizedNode(325 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -70611,7 +72398,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(328 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(329 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -70623,7 +72410,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(327 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(328 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -70638,7 +72425,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(325 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(326 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -70654,7 +72441,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 === 326 /* CommaListExpression */) { + if (node.kind === 327 /* CommaListExpression */) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) { @@ -70664,7 +72451,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(326 /* CommaListExpression */); + var node = createSynthesizedNode(327 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -70677,7 +72464,7 @@ var ts; ts.updateCommaList = updateCommaList; /* @internal */ function createSyntheticReferenceExpression(expression, thisArg) { - var node = createSynthesizedNode(329 /* SyntheticReferenceExpression */); + var node = createSynthesizedNode(330 /* SyntheticReferenceExpression */); node.expression = expression; node.thisArg = thisArg; return node; @@ -70723,6 +72510,8 @@ var ts; ts.importDefaultHelper, ts.classPrivateFieldGetHelper, ts.classPrivateFieldSetHelper, + ts.createBindingHelper, + ts.setModuleDefaultHelper ], function (helper) { return helper.name; })); } function createUnparsedSource() { @@ -70751,7 +72540,7 @@ var ts; stripInternal = mapTextOrStripInternal; bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts; if (node.oldFileOfCurrentEmit) { - parseOldFileOfCurrentEmit(node, ts.Debug.assertDefined(bundleFileInfo)); + parseOldFileOfCurrentEmit(node, ts.Debug.checkDefined(bundleFileInfo)); return node; } } @@ -70916,13 +72705,13 @@ var ts; }; node.javascriptPath = declarationTextOrJavascriptPath; node.javascriptMapPath = javascriptMapPath; - node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath); + node.declarationPath = ts.Debug.checkDefined(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)); } }, + declarationText: { get: function () { return definedTextGetter_1(ts.Debug.checkDefined(javascriptMapTextOrDeclarationPath)); } }, declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } }, buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } } }); @@ -71249,6 +73038,12 @@ var ts; return node; } ts.moveSyntheticComments = moveSyntheticComments; + /** @internal */ + function ignoreSourceNewlines(node) { + getOrCreateEmitNode(node).flags |= 134217728 /* IgnoreSourceNewlines */; + return node; + } + ts.ignoreSourceNewlines = ignoreSourceNewlines; /** * Gets the constant value to emit for an expression. */ @@ -71400,11 +73195,14 @@ var ts; enableEmitNotification: ts.noop, enableSubstitution: ts.noop, endLexicalEnvironment: ts.returnUndefined, - getCompilerOptions: ts.notImplemented, + getCompilerOptions: function () { return ({}); }, getEmitHost: ts.notImplemented, getEmitResolver: ts.notImplemented, + setLexicalEnvironmentFlags: ts.noop, + getLexicalEnvironmentFlags: function () { return 0; }, hoistFunctionDeclaration: ts.noop, hoistVariableDeclaration: ts.noop, + addInitializationStatement: ts.noop, isEmitNotificationEnabled: ts.notImplemented, isSubstitutionEnabled: ts.notImplemented, onEmitNode: ts.noop, @@ -71577,10 +73375,10 @@ var ts; name: "typescript:spread", importName: "__spread", scoped: false, + dependencies: [ts.readHelper], 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(ts.readHelper); context.requestEmitHelper(ts.spreadHelper); return ts.setTextRange(ts.createCall(getUnscopedHelperName("__spread"), /*typeArguments*/ undefined, argumentList), location); @@ -71660,7 +73458,7 @@ var ts; } function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { if (cacheIdentifiers === void 0) { cacheIdentifiers = false; } - var callee = skipOuterExpressions(expression, 7 /* All */); + var callee = skipOuterExpressions(expression, 15 /* All */); var thisArg; var target; if (ts.isSuperProperty(callee)) { @@ -71767,7 +73565,7 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_5 = []; + var properties_7 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, /*asteriskToken*/ undefined, @@ -71778,7 +73576,7 @@ var ts; ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_5.push(getter); + properties_7.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, @@ -71790,15 +73588,15 @@ var ts; ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_5.push(setter); + properties_7.push(setter); } - properties_5.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); - properties_5.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_7.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue())); + properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_5, multiLine) + ts.createObjectLiteral(properties_7, multiLine) ]), /*location*/ firstAccessor); return ts.aggregateTransformFlags(expression); @@ -72021,11 +73819,12 @@ var ts; return statementOffset; } ts.addStandardPrologue = addStandardPrologue; - function addCustomPrologue(target, source, statementOffset, visitor) { + function addCustomPrologue(target, source, statementOffset, visitor, filter) { + if (filter === void 0) { filter = ts.returnTrue; } var numStatements = source.length; while (statementOffset !== undefined && statementOffset < numStatements) { var statement = source[statementOffset]; - if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { + if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */ && filter(statement)) { ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -72364,7 +74163,7 @@ var ts; if (kind === 201 /* FunctionExpression */ || kind === 202 /* ArrowFunction */) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); - return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); + return recreateOuterExpressions(expression, mutableCall, 8 /* PartiallyEmittedExpressions */); } } var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; @@ -72440,7 +74239,7 @@ var ts; case 195 /* ElementAccessExpression */: case 194 /* PropertyAccessExpression */: case 218 /* NonNullExpression */: - case 325 /* PartiallyEmittedExpression */: + case 326 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -72457,54 +74256,44 @@ var ts; ts.parenthesizeConciseBody = parenthesizeConciseBody; function isCommaSequence(node) { return node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ || - node.kind === 326 /* CommaListExpression */; + node.kind === 327 /* CommaListExpression */; } ts.isCommaSequence = isCommaSequence; var OuterExpressionKinds; (function (OuterExpressionKinds) { OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses"; - OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 2] = "Assertions"; - OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions"; - OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All"; + OuterExpressionKinds[OuterExpressionKinds["TypeAssertions"] = 2] = "TypeAssertions"; + OuterExpressionKinds[OuterExpressionKinds["NonNullAssertions"] = 4] = "NonNullAssertions"; + OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 8] = "PartiallyEmittedExpressions"; + OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 6] = "Assertions"; + OuterExpressionKinds[OuterExpressionKinds["All"] = 15] = "All"; })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); function isOuterExpression(node, kinds) { - if (kinds === void 0) { kinds = 7 /* All */; } + if (kinds === void 0) { kinds = 15 /* All */; } switch (node.kind) { case 200 /* ParenthesizedExpression */: return (kinds & 1 /* Parentheses */) !== 0; case 199 /* TypeAssertionExpression */: case 217 /* AsExpression */: + return (kinds & 2 /* TypeAssertions */) !== 0; case 218 /* NonNullExpression */: - return (kinds & 2 /* Assertions */) !== 0; - case 325 /* PartiallyEmittedExpression */: - return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; + return (kinds & 4 /* NonNullAssertions */) !== 0; + case 326 /* PartiallyEmittedExpression */: + return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0; } return false; } ts.isOuterExpression = isOuterExpression; function skipOuterExpressions(node, kinds) { - if (kinds === void 0) { kinds = 7 /* All */; } - var previousNode; - do { - previousNode = node; - if (kinds & 1 /* Parentheses */) { - node = ts.skipParentheses(node); - } - if (kinds & 2 /* Assertions */) { - node = skipAssertions(node); - } - if (kinds & 4 /* PartiallyEmittedExpressions */) { - node = ts.skipPartiallyEmittedExpressions(node); - } - } while (previousNode !== node); + if (kinds === void 0) { kinds = 15 /* All */; } + while (isOuterExpression(node, kinds)) { + node = node.expression; + } return node; } ts.skipOuterExpressions = skipOuterExpressions; function skipAssertions(node) { - while (ts.isAssertionExpression(node) || node.kind === 218 /* NonNullExpression */) { - node = node.expression; - } - return node; + return skipOuterExpressions(node, 6 /* Assertions */); } ts.skipAssertions = skipAssertions; function updateOuterExpression(outerExpression, expression) { @@ -72513,7 +74302,7 @@ var ts; case 199 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); case 217 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); case 218 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 325 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 326 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -72539,7 +74328,7 @@ var ts; && !ts.some(ts.getSyntheticTrailingComments(node)); } function recreateOuterExpressions(outerExpression, innerExpression, kinds) { - if (kinds === void 0) { kinds = 7 /* All */; } + if (kinds === void 0) { kinds = 15 /* All */; } if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) { return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression)); } @@ -72881,9 +74670,7 @@ var ts; } var target = getTargetOfBindingOrAssignmentElement(bindingElement); if (target && ts.isPropertyName(target)) { - return ts.isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression) - ? target.expression - : target; + return target; } } ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement; @@ -73075,18 +74862,70 @@ var ts; return ts.mergeLexicalEnvironment(statements, context.endLexicalEnvironment()); } ts.visitLexicalEnvironment = visitLexicalEnvironment; - /** - * Starts a new lexical environment and visits a parameter list, suspending the lexical - * environment upon completion. - */ function visitParameterList(nodes, visitor, context, nodesVisitor) { if (nodesVisitor === void 0) { nodesVisitor = visitNodes; } + var updated; context.startLexicalEnvironment(); - var updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + if (nodes) { + context.setLexicalEnvironmentFlags(1 /* InParameters */, true); + updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration); + // As of ES2015, any runtime execution of that occurs in for a parameter (such as evaluating an + // initializer or a binding pattern), occurs in its own lexical scope. As a result, any expression + // that we might transform that introduces a temporary variable would fail as the temporary variable + // exists in a different lexical scope. To address this, we move any binding patterns and initializers + // in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list + // when the emit target is greater than ES2015. + if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ && + ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) { + updated = addDefaultValueAssignmentsIfNeeded(updated, context); + } + context.setLexicalEnvironmentFlags(1 /* InParameters */, false); + } context.suspendLexicalEnvironment(); return updated; } ts.visitParameterList = visitParameterList; + function addDefaultValueAssignmentsIfNeeded(parameters, context) { + var result; + for (var i = 0; i < parameters.length; i++) { + var parameter = parameters[i]; + var updated = addDefaultValueAssignmentIfNeeded(parameter, context); + if (result || updated !== parameter) { + if (!result) + result = parameters.slice(0, i); + result[i] = updated; + } + } + if (result) { + return ts.setTextRange(ts.createNodeArray(result, parameters.hasTrailingComma), parameters); + } + return parameters; + } + function addDefaultValueAssignmentIfNeeded(parameter, context) { + // A rest parameter cannot have a binding pattern or an initializer, + // so let's just ignore it. + return parameter.dotDotDotToken ? parameter : + ts.isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) : + parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) : + parameter; + } + function addDefaultValueAssignmentForBindingPattern(parameter, context) { + context.addInitializationStatement(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(parameter.name, parameter.type, parameter.initializer ? + ts.createConditional(ts.createStrictEquality(ts.getGeneratedNameForNode(parameter), ts.createVoidZero()), parameter.initializer, ts.getGeneratedNameForNode(parameter)) : + ts.getGeneratedNameForNode(parameter)), + ]))); + return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, ts.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, + /*initializer*/ undefined); + } + function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) { + context.addInitializationStatement(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 */)) + ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */))); + return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, + /*initializer*/ undefined); + } function visitFunctionBody(node, visitor, context) { context.resumeLexicalEnvironment(); var updated = visitNode(node, visitor, ts.isConciseBody); @@ -73202,17 +75041,17 @@ var ts; return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); case 194 /* PropertyAccessExpression */: if (node.flags & 32 /* OptionalChain */) { - return ts.updatePropertyAccessChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, visitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier)); + return ts.updatePropertyAccessChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier)); } return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifierOrPrivateIdentifier)); case 195 /* ElementAccessExpression */: if (node.flags & 32 /* OptionalChain */) { - return ts.updateElementAccessChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, visitor, ts.isToken), visitNode(node.argumentExpression, visitor, ts.isExpression)); + return ts.updateElementAccessChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, tokenVisitor, ts.isToken), visitNode(node.argumentExpression, visitor, ts.isExpression)); } return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); case 196 /* CallExpression */: if (node.flags & 32 /* OptionalChain */) { - return ts.updateCallChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, visitor, ts.isToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); + return ts.updateCallChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); } return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); case 197 /* NewExpression */: @@ -73226,7 +75065,7 @@ var ts; case 201 /* FunctionExpression */: return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 202 /* ArrowFunction */: - return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, tokenVisitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); case 203 /* DeleteExpression */: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); case 204 /* TypeOfExpression */: @@ -73240,9 +75079,9 @@ var ts; case 208 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); case 209 /* BinaryExpression */: - return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); + return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, tokenVisitor, ts.isToken)); case 210 /* ConditionalExpression */: - return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); + return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, tokenVisitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); case 211 /* TemplateExpression */: return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); case 212 /* YieldExpression */: @@ -73280,7 +75119,7 @@ var ts; case 231 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 232 /* ForOfStatement */: - return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateForOf(node, visitNode(node.awaitModifier, tokenVisitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 233 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); case 234 /* BreakStatement */: @@ -73386,9 +75225,9 @@ var ts; case 290 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 325 /* PartiallyEmittedExpression */: + case 326 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 326 /* CommaListExpression */: + case 327 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -73445,7 +75284,7 @@ var ts; case 224 /* EmptyStatement */: case 215 /* OmittedExpression */: case 241 /* DebuggerStatement */: - case 324 /* NotEmittedStatement */: + case 325 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names @@ -73829,10 +75668,10 @@ var ts; result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 325 /* PartiallyEmittedExpression */: + case 326 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 326 /* CommaListExpression */: + case 327 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -73841,13 +75680,93 @@ var ts; return result; } ts.reduceEachChild = reduceEachChild; + function findSpanEnd(array, test, start) { + var i = start; + while (i < array.length && test(array[i])) { + i++; + } + return i; + } function mergeLexicalEnvironment(statements, declarations) { if (!ts.some(declarations)) { return statements; } - return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements) - : ts.insertStatementsAfterStandardPrologue(statements, declarations); + // When we merge new lexical statements into an existing statement list, we merge them in the following manner: + // + // Given: + // + // | Left | Right | + // |------------------------------------|-------------------------------------| + // | [standard prologues (left)] | [standard prologues (right)] | + // | [hoisted functions (left)] | [hoisted functions (right)] | + // | [hoisted variables (left)] | [hoisted variables (right)] | + // | [lexical init statements (left)] | [lexical init statements (right)] | + // | [other statements (left)] | | + // + // The resulting statement list will be: + // + // | Result | + // |-------------------------------------| + // | [standard prologues (right)] | + // | [standard prologues (left)] | + // | [hoisted functions (right)] | + // | [hoisted functions (left)] | + // | [hoisted variables (right)] | + // | [hoisted variables (left)] | + // | [lexical init statements (right)] | + // | [lexical init statements (left)] | + // | [other statements (left)] | + // + // NOTE: It is expected that new lexical init statements must be evaluated before existing lexical init statements, + // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state. + // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom + var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0); + var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd); + var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd); + // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom + var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0); + var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd); + var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd); + var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd); + ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues"); + // splice prologues from the right into the left. We do this in reverse order + // so that we don't need to recompute the index on the left when we insert items. + var left = ts.isNodeArray(statements) ? statements.slice() : statements; + // splice other custom prologues from right into left + if (rightCustomPrologueEnd > rightHoistedVariablesEnd) { + left.splice.apply(left, __spreadArrays([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd))); + } + // splice hoisted variables from right into left + if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) { + left.splice.apply(left, __spreadArrays([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd))); + } + // splice hoisted functions from right into left + if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) { + left.splice.apply(left, __spreadArrays([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd))); + } + // splice standard prologues from right into left (that are not already in left) + if (rightStandardPrologueEnd > 0) { + if (leftStandardPrologueEnd === 0) { + left.splice.apply(left, __spreadArrays([0, 0], declarations.slice(0, rightStandardPrologueEnd))); + } + else { + var leftPrologues = ts.createMap(); + for (var i = 0; i < leftStandardPrologueEnd; i++) { + var leftPrologue = statements[i]; + leftPrologues.set(leftPrologue.expression.text, true); + } + for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) { + var rightPrologue = declarations[i]; + if (!leftPrologues.has(rightPrologue.expression.text)) { + left.unshift(rightPrologue); + } + } + } + } + if (ts.isNodeArray(statements)) { + return ts.setTextRange(ts.createNodeArray(left, statements.hasTrailingComma), statements); + } + return statements; } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -74981,9 +76900,6 @@ var ts; } return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression(); function emitExpression(expression) { - // NOTE: this completely disables source maps, but aligns with the behavior of - // `emitAssignment` in the old emitter. - ts.setEmitFlags(expression, 64 /* NoNestedSourceMaps */); ts.aggregateTransformFlags(expression); expressions = ts.append(expressions, expression); } @@ -75088,9 +77004,6 @@ var ts; /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value); variable.original = original; ts.setTextRange(variable, location); - if (ts.isIdentifier(name)) { - ts.setEmitFlags(variable, 64 /* NoNestedSourceMaps */); - } ts.aggregateTransformFlags(variable); declarations.push(variable); } @@ -75389,6 +77302,99 @@ var ts; })(ts || (ts = {})); /*@internal*/ var ts; +(function (ts) { + var ProcessLevel; + (function (ProcessLevel) { + ProcessLevel[ProcessLevel["LiftRestriction"] = 0] = "LiftRestriction"; + ProcessLevel[ProcessLevel["All"] = 1] = "All"; + })(ProcessLevel = ts.ProcessLevel || (ts.ProcessLevel = {})); + function processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, level) { + // Visit the tag expression + var tag = ts.visitNode(node.tag, visitor, ts.isExpression); + // Build up the template arguments and the raw and cooked strings for the template. + // We start out with 'undefined' for the first argument and revisit later + // to avoid walking over the template string twice and shifting all our arguments over after the fact. + var templateArguments = [undefined]; + var cookedStrings = []; + var rawStrings = []; + var template = node.template; + if (level === ProcessLevel.LiftRestriction && !ts.hasInvalidEscape(template)) + return node; + if (ts.isNoSubstitutionTemplateLiteral(template)) { + cookedStrings.push(createTemplateCooked(template)); + rawStrings.push(getRawLiteral(template, currentSourceFile)); + } + else { + cookedStrings.push(createTemplateCooked(template.head)); + rawStrings.push(getRawLiteral(template.head, currentSourceFile)); + for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { + var templateSpan = _a[_i]; + cookedStrings.push(createTemplateCooked(templateSpan.literal)); + rawStrings.push(getRawLiteral(templateSpan.literal, currentSourceFile)); + templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); + } + } + var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings)); + // Create a variable to cache the template object if we're in a module. + // Do not do this in the global scope, as any variable we currently generate could conflict with + // variables from outside of the current compilation. In the future, we can revisit this behavior. + if (ts.isExternalModule(currentSourceFile)) { + var tempVar = ts.createUniqueName("templateObject"); + recordTaggedTemplateString(tempVar); + templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall)); + } + else { + templateArguments[0] = helperCall; + } + return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments); + } + ts.processTaggedTemplateExpression = processTaggedTemplateExpression; + function createTemplateCooked(template) { + return template.templateFlags ? ts.createIdentifier("undefined") : ts.createLiteral(template.text); + } + /** + * Creates an ES5 compatible literal from an ES6 template literal. + * + * @param node The ES6 template literal. + */ + function getRawLiteral(node, currentSourceFile) { + // Find original source text, since we need to emit the raw strings of the tagged template. + // The raw strings contain the (escaped) strings of what the user wrote. + // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". + var text = node.rawText; + if (text === undefined) { + text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); + // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), + // thus we need to remove those characters. + // First template piece starts with "`", others with "}" + // Last template piece ends with "`", others with "${" + var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */; + text = text.substring(1, text.length - (isLast ? 1 : 2)); + } + // Newline normalization: + // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's + // and LineTerminatorSequences are normalized to for both TV and TRV. + text = text.replace(/\r\n?/g, "\n"); + return ts.setTextRange(ts.createLiteral(text), node); + } + function createTemplateObjectHelper(context, cooked, raw) { + context.requestEmitHelper(ts.templateObjectHelper); + return ts.createCall(ts.getUnscopedHelperName("__makeTemplateObject"), + /*typeArguments*/ undefined, [ + cooked, + raw + ]); + } + ts.templateObjectHelper = { + name: "typescript:makeTemplateObject", + importName: "__makeTemplateObject", + scoped: false, + priority: 0, + text: "\n var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n };" + }; +})(ts || (ts = {})); +/*@internal*/ +var ts; (function (ts) { /** * Indicates whether to emit type metadata in the new format. @@ -75413,10 +77419,9 @@ var ts; ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass"; - ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; - ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 7] = "UseImmediatelyInvokedFunctionExpression"; ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported"; })(ClassFacts || (ClassFacts = {})); function transformTypeScript(context) { @@ -75852,6 +77857,10 @@ var ts; case 253 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); + case 267 /* JsxSelfClosingElement */: + return visitJsxSelfClosingElement(node); + case 268 /* JsxOpeningElement */: + return visitJsxJsxOpeningElement(node); default: // node contains some other TypeScript syntax return ts.visitEachChild(node, visitor, context); @@ -75899,8 +77908,6 @@ var ts; facts |= 32 /* IsDefaultExternalExport */; else if (isNamedExternalModuleExport(node)) facts |= 16 /* IsNamedExternalExport */; - if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */)) - facts |= 128 /* UseImmediatelyInvokedFunctionExpression */; return facts; } function hasTypeScriptClassSyntax(node) { @@ -75918,7 +77925,7 @@ var ts; } var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true); var facts = getClassFacts(node, staticProperties); - if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { + if (facts & 7 /* UseImmediatelyInvokedFunctionExpression */) { context.startLexicalEnvironment(); } var name = node.name || (facts & 5 /* NeedsName */ ? ts.getGeneratedNameForNode(node) : undefined); @@ -75930,7 +77937,7 @@ var ts; addClassElementDecorationStatements(statements, node, /*isStatic*/ false); addClassElementDecorationStatements(statements, node, /*isStatic*/ true); addConstructorDecorationStatement(statements, node); - if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { + if (facts & 7 /* UseImmediatelyInvokedFunctionExpression */) { // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the // 'es2015' transformer can properly nest static initializers and decorators. The result // looks something like: @@ -75956,11 +77963,16 @@ var ts; ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); + // Class comment is already added by the ES2015 transform when targeting ES5 or below. + // Only add if targetting ES2015+ to prevent duplicates + if (languageVersion > 1 /* ES5 */) { + ts.addSyntheticLeadingComment(iife, 3 /* MultiLineCommentTrivia */, "* @class "); + } var varStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), /*type*/ undefined, iife) - ])); + ], languageVersion > 1 /* ES5 */ ? 1 /* Let */ : undefined)); ts.setOriginalNode(varStatement, node); ts.setCommentRange(varStatement, node); ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node)); @@ -75973,7 +77985,7 @@ var ts; if (facts & 8 /* IsExportOfNamespace */) { addExportMemberAssignment(statements, node); } - else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) { + else if (facts & 7 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) { if (facts & 32 /* IsDefaultExternalExport */) { statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); } @@ -76000,7 +78012,7 @@ var ts; // ${members} // } // we do not emit modifiers on the declaration if we are emitting an IIFE - var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */) + var modifiers = !(facts & 7 /* UseImmediatelyInvokedFunctionExpression */) ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) : undefined; var classDeclaration = ts.createClassDeclaration( @@ -76740,6 +78752,17 @@ var ts; case 183 /* ThisType */: case 188 /* ImportType */: break; + // handle JSDoc types from an invalid parse + case 295 /* JSDocAllType */: + case 296 /* JSDocUnknownType */: + case 300 /* JSDocFunctionType */: + case 301 /* JSDocVariadicType */: + case 302 /* JSDocNamepathType */: + break; + case 297 /* JSDocNullableType */: + case 298 /* JSDocNonNullableType */: + case 299 /* JSDocOptionalType */: + return serializeTypeNode(node.type); default: return ts.Debug.failBadSyntaxKind(node); } @@ -76749,8 +78772,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_20 = types; _i < types_20.length; _i++) { - var typeNode = types_20[_i]; + for (var _i = 0, types_21 = types; _i < types_21.length; _i++) { + var typeNode = types_21[_i]; while (typeNode.kind === 182 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -77186,7 +79209,7 @@ var ts; /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } function visitParenthesizedExpression(node) { - var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */); + var innerExpression = ts.skipOuterExpressions(node.expression, ~6 /* Assertions */); if (ts.isAssertionExpression(innerExpression)) { // Make sure we consider all nested cast expressions, e.g.: // (-A).x; @@ -77233,6 +79256,14 @@ var ts; return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression)); } + function visitJsxSelfClosingElement(node) { + return ts.updateJsxSelfClosingElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), + /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes)); + } + function visitJsxJsxOpeningElement(node) { + return ts.updateJsxOpeningElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), + /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes)); + } /** * Determines whether to emit an enum declaration. * @@ -77555,24 +79586,25 @@ var ts; startLexicalEnvironment(); var statementsLocation; var blockLocation; - var body = node.body; - if (body.kind === 250 /* ModuleBlock */) { - saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); - statementsLocation = body.statements; - blockLocation = body; - } - else { - var result = visitModuleDeclaration(body); - if (result) { - if (ts.isArray(result)) { - ts.addRange(statements, result); - } - else { - statements.push(result); - } + if (node.body) { + if (node.body.kind === 250 /* ModuleBlock */) { + saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); + statementsLocation = node.body.statements; + blockLocation = node.body; + } + else { + var result = visitModuleDeclaration(node.body); + if (result) { + if (ts.isArray(result)) { + ts.addRange(statements, result); + } + else { + statements.push(result); + } + } + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; - statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; @@ -77602,7 +79634,7 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (body.kind !== 250 /* ModuleBlock */) { + if (!node.body || node.body.kind !== 250 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; @@ -77699,16 +79731,18 @@ var ts; if (node.isTypeOnly) { return undefined; } - if (!node.exportClause) { - // Elide a star export if the module it references does not export a value. - return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) { + // never elide `export from ` declarations - + // they should be kept for sideffects/untyped exports, even when the + // type checker doesn't know about any exports + return node; } if (!resolver.isValueAliasDeclaration(node)) { // Elide the export declaration if it does not export a value. return undefined; } // Elide the export declaration if all of its named exports are elided. - var exportClause = ts.visitNode(node.exportClause, visitNamedExportBindings, ts.isNamedImportBindings); + var exportClause = ts.visitNode(node.exportClause, visitNamedExportBindings, ts.isNamedExportBindings); return exportClause ? ts.updateExportDeclaration(node, /*decorators*/ undefined, @@ -78477,7 +80511,7 @@ var ts; /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { if (isDecoratedClassDeclaration) { - ts.Debug.assertDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration."); + ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration."); // Write any pending expressions from elided or moved computed property names if (pendingStatements && pendingExpressions && ts.some(pendingExpressions)) { pendingStatements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); @@ -78553,7 +80587,7 @@ var ts; } return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor( /*decorators*/ undefined, - /*modifiers*/ undefined, parameters, body), constructor || node), constructor)); + /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields; @@ -78619,8 +80653,8 @@ var ts; * @param receiver The receiver on which each property should be assigned. */ function addPropertyStatements(statements, properties, receiver) { - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var property = properties_6[_i]; + for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) { + var property = properties_8[_i]; var expression = transformProperty(property, receiver); if (!expression) { continue; @@ -78640,8 +80674,8 @@ var ts; */ function generateInitializedPropertyExpressions(properties, receiver) { var expressions = []; - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var property = properties_7[_i]; + for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) { + var property = properties_9[_i]; var expression = transformProperty(property, receiver); if (!expression) { continue; @@ -79551,6 +81585,30 @@ var ts; /** Enables substitutions for async methods with `super` calls. */ ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {})); + // Facts we track as we traverse the tree + var HierarchyFacts; + (function (HierarchyFacts) { + HierarchyFacts[HierarchyFacts["None"] = 0] = "None"; + // + // Ancestor facts + // + HierarchyFacts[HierarchyFacts["HasLexicalThis"] = 1] = "HasLexicalThis"; + HierarchyFacts[HierarchyFacts["IterationContainer"] = 2] = "IterationContainer"; + // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below. + // + // Ancestor masks + // + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 3] = "AncestorFactsMask"; + HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 1] = "SourceFileIncludes"; + HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 2] = "SourceFileExcludes"; + HierarchyFacts[HierarchyFacts["StrictModeSourceFileIncludes"] = 0] = "StrictModeSourceFileIncludes"; + HierarchyFacts[HierarchyFacts["ClassOrFunctionIncludes"] = 1] = "ClassOrFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ClassOrFunctionExcludes"] = 2] = "ClassOrFunctionExcludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 0] = "ArrowFunctionIncludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 2] = "ArrowFunctionExcludes"; + HierarchyFacts[HierarchyFacts["IterationStatementIncludes"] = 2] = "IterationStatementIncludes"; + HierarchyFacts[HierarchyFacts["IterationStatementExcludes"] = 0] = "IterationStatementExcludes"; + })(HierarchyFacts || (HierarchyFacts = {})); function transformES2018(context) { var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -79564,7 +81622,9 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; - var hasLexicalThis; + var hierarchyFacts = 0; + var currentSourceFile; + var taggedTemplateStringDeclarations; /** Keeps track of property names accessed on super (`super.x`) within async functions. */ var capturedSuperProperties; /** Whether the async function contains an element access on super (`super[x]`). */ @@ -79572,14 +81632,39 @@ var ts; /** A set of node IDs for generated super accessors. */ var substitutedSuperAccessors = []; return ts.chainBundle(transformSourceFile); + function affectsSubtree(excludeFacts, includeFacts) { + return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts); + } + /** + * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification. + * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree. + * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree. + */ + function enterSubtree(excludeFacts, includeFacts) { + var ancestorFacts = hierarchyFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */; + return ancestorFacts; + } + /** + * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's + * subtree. + * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree. + */ + function exitSubtree(ancestorFacts) { + hierarchyFacts = ancestorFacts; + } + function recordTaggedTemplateString(temp) { + taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp)); + } function transformSourceFile(node) { if (node.isDeclarationFile) { return node; } - exportedVariableStatement = false; - hasLexicalThis = !ts.isEffectiveStrictModeSourceFile(node, compilerOptions); - var visited = ts.visitEachChild(node, visitor, context); + currentSourceFile = node; + var visited = visitSourceFile(node); ts.addEmitHelpers(visited, context.readEmitHelpers()); + currentSourceFile = undefined; + taggedTemplateStringDeclarations = undefined; return visited; } function visitor(node) { @@ -79594,11 +81679,11 @@ var ts; } return node; } - function doWithLexicalThis(cb, value) { - if (!hasLexicalThis) { - hasLexicalThis = true; + function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) { + if (affectsSubtree(excludeFacts, includeFacts)) { + var ancestorFacts = enterSubtree(excludeFacts, includeFacts); var result = cb(value); - hasLexicalThis = false; + exitSubtree(ancestorFacts); return result; } return cb(value); @@ -79629,32 +81714,38 @@ var ts; return visitVariableStatement(node); case 242 /* VariableDeclaration */: return visitVariableDeclaration(node); + case 228 /* DoStatement */: + case 229 /* WhileStatement */: + case 231 /* ForInStatement */: + return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); case 232 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); case 230 /* ForStatement */: - return visitForStatement(node); + return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); case 205 /* VoidExpression */: return visitVoidExpression(node); case 162 /* Constructor */: - return doWithLexicalThis(visitConstructorDeclaration, node); + return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 161 /* MethodDeclaration */: - return doWithLexicalThis(visitMethodDeclaration, node); + return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 163 /* GetAccessor */: - return doWithLexicalThis(visitGetAccessorDeclaration, node); + return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 164 /* SetAccessor */: - return doWithLexicalThis(visitSetAccessorDeclaration, node); + return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 244 /* FunctionDeclaration */: - return doWithLexicalThis(visitFunctionDeclaration, node); + return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 201 /* FunctionExpression */: - return doWithLexicalThis(visitFunctionExpression, node); + return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); case 202 /* ArrowFunction */: - return visitArrowFunction(node); + return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */); case 156 /* Parameter */: return visitParameter(node); case 226 /* ExpressionStatement */: return visitExpressionStatement(node); case 200 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, noDestructuringValue); + case 198 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); case 194 /* PropertyAccessExpression */: if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 102 /* SuperKeyword */) { capturedSuperProperties.set(node.name.escapedText, true); @@ -79667,7 +81758,7 @@ var ts; return ts.visitEachChild(node, visitor, context); case 245 /* ClassDeclaration */: case 214 /* ClassExpression */: - return doWithLexicalThis(visitDefault, node); + return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */); default: return ts.visitEachChild(node, visitor, context); } @@ -79703,7 +81794,7 @@ var ts; if (statement.kind === 232 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } - return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); + return ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node); } return ts.visitEachChild(node, visitor, context); } @@ -79777,6 +81868,22 @@ var ts; function visitParenthesizedExpression(node, noDestructuringValue) { return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); } + function visitSourceFile(node) { + var ancestorFacts = enterSubtree(2 /* SourceFileExcludes */, ts.isEffectiveStrictModeSourceFile(node, compilerOptions) ? + 0 /* StrictModeSourceFileIncludes */ : + 1 /* SourceFileIncludes */); + exportedVariableStatement = false; + var visited = ts.visitEachChild(node, visitor, context); + var statement = ts.concatenate(visited.statements, taggedTemplateStringDeclarations && [ + ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)) + ]); + var result = ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements)); + exitSubtree(ancestorFacts); + return result; + } + function visitTaggedTemplateExpression(node) { + return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction); + } /** * Visits a BinaryExpression that contains a destructuring assignment. * @@ -79853,15 +81960,15 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { + var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */); if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } - if (node.awaitModifier) { - return transformForAwaitOfStatement(node, outermostLabeledStatement); - } - else { - return ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); - } + var result = node.awaitModifier ? + transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) : + ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement); + exitSubtree(ancestorFacts); + return result; } function transformForOfStatementWithObjectRest(node) { var initializerWithoutParens = ts.skipParentheses(node.initializer); @@ -79909,7 +82016,7 @@ var ts; ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression)) : ts.createAwait(expression); } - function transformForAwaitOfStatement(node, outermostLabeledStatement) { + function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -79923,9 +82030,13 @@ var ts; var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); + // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration + var initializer = ancestorFacts & 2 /* IterationContainer */ ? + ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), callValues]) : + callValues; var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression), ts.createVariableDeclaration(result) ]), node.expression), 2097152 /* NoHoisting */), /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), @@ -80055,7 +82166,7 @@ var ts; /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), /*typeParameters*/ undefined, /*parameters*/ [], - /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), hasLexicalThis)); + /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */))); // 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 */); @@ -80263,13 +82374,13 @@ var ts; name: "typescript:asyncGenerator", importName: "__asyncGenerator", scoped: false, + dependencies: [ts.awaitHelper], 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, hasLexicalThis) { - context.requestEmitHelper(ts.awaitHelper); context.requestEmitHelper(ts.asyncGeneratorHelper); // Mark this node as originally an async function - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */; return ts.createCall(ts.getUnscopedHelperName("__asyncGenerator"), /*typeArguments*/ undefined, [ hasLexicalThis ? ts.createThis() : ts.createVoidZero(), @@ -80281,10 +82392,10 @@ var ts; name: "typescript:asyncDelegator", importName: "__asyncDelegator", scoped: false, + dependencies: [ts.awaitHelper], 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(ts.awaitHelper); context.requestEmitHelper(ts.asyncDelegator); return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__asyncDelegator"), /*typeArguments*/ undefined, [expression]), location); @@ -80370,9 +82481,11 @@ var ts; } } function flattenChain(chain) { + ts.Debug.assertNotNode(chain, ts.isNonNullChain); var links = [chain]; while (!chain.questionDotToken && !ts.isTaggedTemplateExpression(chain)) { - chain = ts.cast(chain.expression, ts.isOptionalChain); + chain = ts.cast(ts.skipPartiallyEmittedExpressions(chain.expression), ts.isOptionalChain); + ts.Debug.assertNotNode(chain, ts.isNonNullChain); links.unshift(chain); } return { expression: chain.expression, chain: links }; @@ -80398,6 +82511,7 @@ var ts; if (shouldCaptureInTempVariable(expression)) { thisArg = ts.createTempVariable(hoistVariableDeclaration); expression = ts.createAssignment(thisArg, expression); + // if (inParameterInitializer) tempVariableInParameter = true; } else { thisArg = expression; @@ -80433,6 +82547,7 @@ var ts; if (shouldCaptureInTempVariable(leftExpression)) { capturedLeft = ts.createTempVariable(hoistVariableDeclaration); leftExpression = ts.createAssignment(capturedLeft, leftExpression); + // if (inParameterInitializer) tempVariableInParameter = true; } var rightExpression = capturedLeft; var thisArg; @@ -80445,6 +82560,7 @@ var ts; if (shouldCaptureInTempVariable(rightExpression)) { thisArg = ts.createTempVariable(hoistVariableDeclaration); rightExpression = ts.createAssignment(thisArg, rightExpression); + // if (inParameterInitializer) tempVariableInParameter = true; } else { thisArg = rightExpression; @@ -80480,6 +82596,7 @@ var ts; if (shouldCaptureInTempVariable(left)) { right = ts.createTempVariable(hoistVariableDeclaration); left = ts.createAssignment(right, left); + // if (inParameterInitializer) tempVariableInParameter = true; } return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression)); } @@ -82276,7 +84393,7 @@ var ts; ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); properties.push(setter); } - properties.push(ts.createPropertyAssignment("enumerable", ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue())); + properties.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue())); var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ target, @@ -82406,6 +84523,8 @@ var ts; // 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(prologue, body.statements, /*ensureUseStrict*/ false); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedFunction); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedVariableStatement); } multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine; multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine; @@ -82531,10 +84650,15 @@ var ts; } return ts.visitEachChild(node, visitor, context); } + function isVariableStatementOfTypeScriptClassWrapper(node) { + return node.declarationList.declarations.length === 1 + && !!node.declarationList.declarations[0].initializer + && !!(ts.getEmitFlags(node.declarationList.declarations[0].initializer) & 33554432 /* TypeScriptClassWrapper */); + } function visitVariableStatement(node) { var ancestorFacts = enterSubtree(0 /* None */, ts.hasModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */); var updated; - if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0) { + if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0 && !isVariableStatementOfTypeScriptClassWrapper(node)) { // we are inside a converted loop - hoist variable declarations var assignments = void 0; for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -83686,7 +85810,11 @@ var ts; // The class statements are the statements generated by visiting the first statement with initializer of the // body (1), while all other statements are added to remainingStatements (2) var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; }; + // visit the class body statements outside of any converted loop body. + var savedConvertedLoopState = convertedLoopState; + convertedLoopState = undefined; var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); + convertedLoopState = savedConvertedLoopState; var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement); @@ -83943,67 +86071,7 @@ var ts; * @param node A TaggedTemplateExpression node. */ function visitTaggedTemplateExpression(node) { - // Visit the tag expression - var tag = ts.visitNode(node.tag, visitor, ts.isExpression); - // Build up the template arguments and the raw and cooked strings for the template. - // We start out with 'undefined' for the first argument and revisit later - // to avoid walking over the template string twice and shifting all our arguments over after the fact. - var templateArguments = [undefined]; - var cookedStrings = []; - var rawStrings = []; - var template = node.template; - if (ts.isNoSubstitutionTemplateLiteral(template)) { - cookedStrings.push(ts.createLiteral(template.text)); - rawStrings.push(getRawLiteral(template)); - } - else { - cookedStrings.push(ts.createLiteral(template.head.text)); - rawStrings.push(getRawLiteral(template.head)); - for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) { - var templateSpan = _a[_i]; - cookedStrings.push(ts.createLiteral(templateSpan.literal.text)); - rawStrings.push(getRawLiteral(templateSpan.literal)); - templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression)); - } - } - var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings)); - // Create a variable to cache the template object if we're in a module. - // Do not do this in the global scope, as any variable we currently generate could conflict with - // variables from outside of the current compilation. In the future, we can revisit this behavior. - if (ts.isExternalModule(currentSourceFile)) { - var tempVar = ts.createUniqueName("templateObject"); - recordTaggedTemplateString(tempVar); - templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall)); - } - else { - templateArguments[0] = helperCall; - } - return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments); - } - /** - * Creates an ES5 compatible literal from an ES6 template literal. - * - * @param node The ES6 template literal. - */ - function getRawLiteral(node) { - // Find original source text, since we need to emit the raw strings of the tagged template. - // The raw strings contain the (escaped) strings of what the user wrote. - // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". - var text = node.rawText; - if (text === undefined) { - text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); - // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), - // thus we need to remove those characters. - // First template piece starts with "`", others with "}" - // Last template piece ends with "`", others with "${" - var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */; - text = text.substring(1, text.length - (isLast ? 1 : 2)); - } - // Newline normalization: - // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's - // and LineTerminatorSequences are normalized to for both TV and TRV. - text = text.replace(/\r\n?/g, "\n"); - return ts.setTextRange(ts.createLiteral(text), node); + return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.All); } /** * Visits a TemplateExpression node. @@ -84296,14 +86364,6 @@ var ts; ts.createFileLevelUniqueName("_super") ]); } - function createTemplateObjectHelper(context, cooked, raw) { - context.requestEmitHelper(ts.templateObjectHelper); - return ts.createCall(ts.getUnscopedHelperName("__makeTemplateObject"), - /*typeArguments*/ undefined, [ - cooked, - raw - ]); - } ts.extendsHelper = { name: "typescript:extends", importName: "__extends", @@ -84311,13 +86371,6 @@ var ts; 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 })();" }; - ts.templateObjectHelper = { - name: "typescript:makeTemplateObject", - importName: "__makeTemplateObject", - scoped: false, - priority: 0, - text: "\n var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n };" - }; })(ts || (ts = {})); /*@internal*/ var ts; @@ -87135,16 +89188,14 @@ var ts; if (shouldEmitUnderscoreUnderscoreESModule()) { ts.append(statements, createUnderscoreUnderscoreESModule()); } + if (ts.length(currentModuleInfo.exportedNames)) { + ts.append(statements, ts.createExpressionStatement(ts.reduceLeft(currentModuleInfo.exportedNames, function (prev, nextId) { return ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(ts.idText(nextId))), prev); }, ts.createVoidZero()))); + } 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.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 - // we need to inform the emitter to add the __export helper. - ts.addEmitHelper(updated, exportStarHelper); - } ts.addEmitHelpers(updated, context.readEmitHelpers()); return updated; } @@ -87354,6 +89405,9 @@ var ts; if (shouldEmitUnderscoreUnderscoreESModule()) { ts.append(statements, createUnderscoreUnderscoreESModule()); } + if (ts.length(currentModuleInfo.exportedNames)) { + ts.append(statements, ts.createExpressionStatement(ts.reduceLeft(currentModuleInfo.exportedNames, function (prev, nextId) { return ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(ts.idText(nextId))), prev); }, ts.createVoidZero()))); + } // Visit each statement of the module body. ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); if (moduleKind === ts.ModuleKind.AMD) { @@ -87366,11 +89420,6 @@ var ts; // and merge any new lexical declarations. ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); - if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { - // If we have any `export * from ...` declarations - // we need to inform the emitter to add the __export helper. - ts.addEmitHelper(body, exportStarHelper); - } if (needUMDDynamicImportHelper) { ts.addEmitHelper(body, dynamicImportUMDHelper); } @@ -87427,9 +89476,9 @@ var ts; return visitFunctionDeclaration(node); case 245 /* ClassDeclaration */: return visitClassDeclaration(node); - case 327 /* MergeDeclarationMarker */: + case 328 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 328 /* EndOfDeclarationMarker */: + case 329 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return ts.visitEachChild(node, moduleExpressionElementVisitor, context); @@ -87787,8 +89836,13 @@ var ts; } for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; - var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); - statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier), specifier)); + if (languageVersion === 0 /* ES3 */) { + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createCreateBindingHelper(context, generatedName, ts.createLiteral(specifier.propertyName || specifier.name), specifier.propertyName ? ts.createLiteral(specifier.name) : undefined)), specifier), specifier)); + } + else { + var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); + statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue, /* location */ undefined, /* liveBinding */ true)), specifier), specifier)); + } } return ts.singleOrMany(statements); } @@ -87891,7 +89945,6 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { var modifiers = void 0; // If we're exporting these variables, then these just become assignments to 'exports.x'. - // We only want to emit assignments for variables with initializers. for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var variable = _a[_i]; if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) { @@ -87952,7 +90005,7 @@ var ts; } else { return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), - /*location*/ node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor)); + /*location*/ node.name), node.initializer ? ts.visitNode(node.initializer, moduleExpressionElementVisitor) : ts.createVoidZero()); } } /** @@ -88030,7 +90083,7 @@ var ts; case 257 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; - statements = appendExportsOfDeclaration(statements, importBinding); + statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true); } break; } @@ -88127,13 +90180,13 @@ var ts; * appended. * @param decl The declaration to export. */ - function appendExportsOfDeclaration(statements, decl) { + function appendExportsOfDeclaration(statements, decl, liveBinding) { var name = ts.getDeclarationName(decl); var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { var exportSpecifier = exportSpecifiers_1[_i]; - statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name); + statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /* allowComments */ undefined, liveBinding); } } return statements; @@ -88150,8 +90203,8 @@ var ts; * @param location The location to use for source maps and comments for the export. * @param allowComments Whether to allow comments on the export. */ - function appendExportStatement(statements, exportName, expression, location, allowComments) { - statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments)); + function appendExportStatement(statements, exportName, expression, location, allowComments, liveBinding) { + statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding)); return statements; } function createUnderscoreUnderscoreESModule() { @@ -88180,8 +90233,8 @@ var ts; * @param location The location to use for source maps and comments for the export. * @param allowComments An optional value indicating whether to emit comments for the statement. */ - function createExportStatement(name, value, location, allowComments) { - var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value)), location); + function createExportStatement(name, value, location, allowComments, liveBinding) { + var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value, /* location */ undefined, liveBinding)), location); ts.startOnNewLine(statement); if (!allowComments) { ts.setEmitFlags(statement, 1536 /* NoComments */); @@ -88195,8 +90248,22 @@ var ts; * @param value The exported value. * @param location The location to use for source maps and comments for the export. */ - function createExportExpression(name, value, location) { - return ts.setTextRange(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location); + function createExportExpression(name, value, location, liveBinding) { + return ts.setTextRange(liveBinding && languageVersion !== 0 /* ES3 */ ? ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral(name), + ts.createObjectLiteral([ + ts.createPropertyAssignment("enumerable", ts.createLiteral(/*value*/ true)), + ts.createPropertyAssignment("get", ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ [], + /*type*/ undefined, ts.createBlock([ts.createReturn(value)]))) + ]) + ]) : ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location); } // // Modifier Visitors @@ -88421,17 +90488,36 @@ var ts; } } ts.transformModule = transformModule; + ts.createBindingHelper = { + name: "typescript:commonjscreatebinding", + importName: "__createBinding", + scoped: false, + priority: 1, + text: "\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));" + }; + function createCreateBindingHelper(context, module, inputName, outputName) { + context.requestEmitHelper(ts.createBindingHelper); + return ts.createCall(ts.getUnscopedHelperName("__createBinding"), /*typeArguments*/ undefined, __spreadArrays([ts.createIdentifier("exports"), module, inputName], (outputName ? [outputName] : []))); + } + ts.setModuleDefaultHelper = { + name: "typescript:commonjscreatevalue", + importName: "__setModuleDefault", + scoped: false, + priority: 1, + text: "\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});" + }; // emit output for the __export helper function var exportStarHelper = { name: "typescript:export-star", - scoped: true, - text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" + importName: "__exportStar", + scoped: false, + dependencies: [ts.createBindingHelper], + priority: 2, + text: "\n var __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);\n };" }; function createExportStarHelper(context, module) { - var compilerOptions = context.getCompilerOptions(); - return compilerOptions.importHelpers - ? ts.createCall(ts.getUnscopedHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")]) - : ts.createCall(ts.createIdentifier("__export"), /*typeArguments*/ undefined, [module]); + context.requestEmitHelper(exportStarHelper); + return ts.createCall(ts.getUnscopedHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")]); } // emit helper for dynamic import var dynamicImportUMDHelper = { @@ -88444,7 +90530,9 @@ var ts; name: "typescript:commonjsimportstar", importName: "__importStar", 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};" + dependencies: [ts.createBindingHelper, ts.setModuleDefaultHelper], + priority: 2, + 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)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};" }; // emit helper for `import Name from "foo"` ts.importDefaultHelper = { @@ -88908,7 +90996,7 @@ var ts; return ts.singleOrMany(statements); } function visitExportDeclaration(node) { - ts.Debug.assertDefined(node); + ts.Debug.assertIsDefined(node); return undefined; } /** @@ -89404,9 +91492,9 @@ var ts; return visitCatchClause(node); case 223 /* Block */: return visitBlock(node); - case 327 /* MergeDeclarationMarker */: + case 328 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 328 /* EndOfDeclarationMarker */: + case 329 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -90549,7 +92637,8 @@ var ts; reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError, moduleResolverHost: host, trackReferencedAmbientModule: trackReferencedAmbientModule, - trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode + trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode, + reportNonlocalAugmentation: reportNonlocalAugmentation }; var errorNameNode; var currentSourceFile; @@ -90640,6 +92729,14 @@ var ts; context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier)); } } + function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) { + var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; }); + var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; }); + for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) { + var augmentations = augmentingDeclarations_1[_i]; + context.addDiagnostic(ts.addRelatedInfo(ts.createDiagnosticForNode(augmentations, ts.Diagnostics.Declaration_augments_declaration_in_another_file_This_cannot_be_serialized), ts.createDiagnosticForNode(primaryDeclaration, ts.Diagnostics.This_is_the_declaration_being_augmented_Consider_moving_the_augmenting_declaration_into_the_same_file))); + } + } function transformDeclarationsForJS(sourceFile, bundled) { var oldDiag = getSymbolAccessibilityDiagnostic; getSymbolAccessibilityDiagnostic = function (s) { return ({ @@ -90778,8 +92875,8 @@ var ts; declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } if (declFileName) { - var specifier = ts.moduleSpecifiers.getModuleSpecifier(__assign(__assign({}, options), { baseUrl: options.baseUrl && ts.toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }), currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, host.getSourceFiles(), - /*preferences*/ undefined, host.redirectTargetsMap); + var specifier = ts.moduleSpecifiers.getModuleSpecifier(__assign(__assign({}, options), { baseUrl: options.baseUrl && ts.toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }), currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, + /*preferences*/ undefined); if (!ts.pathIsRelative(specifier)) { // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration // via a non-relative name, emit a type reference directive to that non-relative name, rather than @@ -90794,7 +92891,7 @@ var ts; } // omit references to files from node_modules (npm may disambiguate module // references when installing this package, making the path is unreliable). - if (ts.startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + if (ts.startsWith(fileName, "node_modules/") || ts.pathContainsNodeModules(fileName)) { return; } references.push({ pos: -1, end: -1, fileName: fileName }); @@ -91067,6 +93164,12 @@ var ts; return ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); } + // Augmentation of export depends on import + if (resolver.isImportRequiredByAugmentation(decl)) { + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, + /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } // Nothing visible } function transformAndReplaceLatePaintedStatements(statements) { @@ -91900,11 +94003,15 @@ 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(330 /* Count */); + var enabledSyntaxKindFeatures = new Array(331 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; + var lexicalEnvironmentStatements; + var lexicalEnvironmentFlags = 0 /* None */; var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; + var lexicalEnvironmentStatementsStack = []; + var lexicalEnvironmentFlagsStack = []; var lexicalEnvironmentStackOffset = 0; var lexicalEnvironmentSuspended = false; var emitHelpers; @@ -91922,8 +94029,11 @@ var ts; suspendLexicalEnvironment: suspendLexicalEnvironment, resumeLexicalEnvironment: resumeLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, + setLexicalEnvironmentFlags: setLexicalEnvironmentFlags, + getLexicalEnvironmentFlags: getLexicalEnvironmentFlags, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, + addInitializationStatement: addInitializationStatement, requestEmitHelper: requestEmitHelper, readEmitHelpers: readEmitHelpers, enableSubstitution: enableSubstitution, @@ -92053,6 +94163,9 @@ var ts; else { lexicalEnvironmentVariableDeclarations.push(decl); } + if (lexicalEnvironmentFlags & 1 /* InParameters */) { + lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */; + } } /** * Records a hoisted function declaration within a lexical environment. @@ -92060,6 +94173,7 @@ var ts; function hoistFunctionDeclaration(func) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.setEmitFlags(func, 1048576 /* CustomPrologue */); if (!lexicalEnvironmentFunctionDeclarations) { lexicalEnvironmentFunctionDeclarations = [func]; } @@ -92067,6 +94181,20 @@ var ts; lexicalEnvironmentFunctionDeclarations.push(func); } } + /** + * Adds an initialization statement to the top of the lexical environment. + */ + function addInitializationStatement(node) { + ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); + ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); + ts.setEmitFlags(node, 1048576 /* CustomPrologue */); + if (!lexicalEnvironmentStatements) { + lexicalEnvironmentStatements = [node]; + } + else { + lexicalEnvironmentStatements.push(node); + } + } /** * Starts a new lexical environment. Any existing hoisted variable or function declarations * are pushed onto a stack, and the related storage variables are reset. @@ -92081,9 +94209,13 @@ var ts; // transformation. lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations; lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations; + lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements; + lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags; lexicalEnvironmentStackOffset++; lexicalEnvironmentVariableDeclarations = undefined; lexicalEnvironmentFunctionDeclarations = undefined; + lexicalEnvironmentStatements = undefined; + lexicalEnvironmentFlags = 0 /* None */; } /** Suspends the current lexical environment, usually after visiting a parameter list. */ function suspendLexicalEnvironment() { @@ -92108,7 +94240,9 @@ var ts; ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended."); var statements; - if (lexicalEnvironmentVariableDeclarations || lexicalEnvironmentFunctionDeclarations) { + if (lexicalEnvironmentVariableDeclarations || + lexicalEnvironmentFunctionDeclarations || + lexicalEnvironmentStatements) { if (lexicalEnvironmentFunctionDeclarations) { statements = __spreadArrays(lexicalEnvironmentFunctionDeclarations); } @@ -92123,21 +94257,47 @@ var ts; statements.push(statement); } } + if (lexicalEnvironmentStatements) { + if (!statements) { + statements = __spreadArrays(lexicalEnvironmentStatements); + } + else { + statements = __spreadArrays(statements, lexicalEnvironmentStatements); + } + } } // Restore the previous lexical environment. lexicalEnvironmentStackOffset--; lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset]; lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset]; + lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset]; if (lexicalEnvironmentStackOffset === 0) { lexicalEnvironmentVariableDeclarationsStack = []; lexicalEnvironmentFunctionDeclarationsStack = []; + lexicalEnvironmentStatementsStack = []; + lexicalEnvironmentFlagsStack = []; } return statements; } + function setLexicalEnvironmentFlags(flags, value) { + lexicalEnvironmentFlags = value ? + lexicalEnvironmentFlags | flags : + lexicalEnvironmentFlags & ~flags; + } + function getLexicalEnvironmentFlags() { + return lexicalEnvironmentFlags; + } function requestEmitHelper(helper) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed."); ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper."); + if (helper.dependencies) { + for (var _i = 0, _a = helper.dependencies; _i < _a.length; _i++) { + var h = _a[_i]; + requestEmitHelper(h); + } + } emitHelpers = ts.append(emitHelpers, helper); } function readEmitHelpers() { @@ -92301,7 +94461,7 @@ var ts; } ts.getOutputExtension = getOutputExtension; function rootDirOfOptions(configFile) { - return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.assertDefined(configFile.options.configFilePath)); + return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.checkDefined(configFile.options.configFilePath)); } function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) { return outputDir ? @@ -92323,7 +94483,7 @@ var ts; 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 */ ? + return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ? outputFileName : undefined; } @@ -92398,7 +94558,7 @@ var ts; 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"); + return ts.Debug.checkDefined(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]; @@ -92686,7 +94846,7 @@ var ts; var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText); return "data:application/json;base64," + base64SourceMapText; } - var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.assertDefined(sourceMapFilePath))); + var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.checkDefined(sourceMapFilePath))); if (mapOptions.mapRoot) { var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot); if (sourceFile) { @@ -92761,6 +94921,7 @@ var ts; getSymbolOfExternalModuleSpecifier: ts.notImplemented, isBindingCapturedByNode: ts.notImplemented, getDeclarationStatementsForSourceFile: ts.notImplemented, + isImportRequiredByAugmentation: ts.notImplemented, }; function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) { var sourceFiles = bundle.sourceFiles.map(function (fileName) { @@ -92770,7 +94931,7 @@ var ts; sourceFile.statements = ts.createNodeArray(); return sourceFile; }); - var jsBundle = ts.Debug.assertDefined(bundle.js); + var jsBundle = ts.Debug.checkDefined(bundle.js); ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) { var sourceFile = sourceFiles[prologueInfo.file]; sourceFile.text = prologueInfo.text; @@ -92787,10 +94948,10 @@ var ts; /*@internal*/ function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) { 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)); + var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath)); if (!buildInfoText) return buildInfoPath; - var jsFileText = host.readFile(ts.Debug.assertDefined(jsFilePath)); + var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath)); if (!jsFileText) return jsFilePath; var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath); @@ -92827,6 +94988,7 @@ var ts; getLibFileFromReference: ts.notImplemented, isSourceFileFromExternalLibrary: ts.returnFalse, getResolvedProjectReferenceToRedirect: ts.returnUndefined, + getProjectReferenceRedirect: ts.returnUndefined, isSourceOfProjectReferenceRedirect: ts.returnFalse, writeFile: function (name, text, writeByteOrderMark) { switch (name) { @@ -92866,7 +95028,6 @@ var ts; 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, getSourceFileFromReference: ts.returnUndefined, @@ -92901,12 +95062,13 @@ var ts; var tempFlags; // TempFlags for the current name generation scope. var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes. var reservedNames; // TempFlags to reserve in nested name generation scopes. + var preserveSourceNewlines = printerOptions.preserveSourceNewlines; // Can be overridden inside nodes with the `IgnoreSourceNewlines` emit flag. var writer; var ownWriter; // Reusable `EmitTextWriter` for basic printing. var write = writeBase; var isOwnFileEmit; var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined; - var relativeToBuildInfo = bundleFileInfo ? ts.Debug.assertDefined(printerOptions.relativeToBuildInfo) : undefined; + var relativeToBuildInfo = bundleFileInfo ? ts.Debug.checkDefined(printerOptions.relativeToBuildInfo) : undefined; var recordInternalSection = printerOptions.recordInternalSection; var sourceFileTextPos = 0; var sourceFileTextKind = "text" /* Text */; @@ -93183,14 +95345,19 @@ var ts; function pipelineEmit(emitHint, node) { var savedLastNode = lastNode; var savedLastSubstitution = lastSubstitution; + var savedPreserveSourceNewlines = preserveSourceNewlines; lastNode = node; lastSubstitution = undefined; + if (preserveSourceNewlines && !!(ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) { + preserveSourceNewlines = false; + } var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node); pipelinePhase(emitHint, node); ts.Debug.assert(lastNode === node); var substitute = lastSubstitution; lastNode = savedLastNode; lastSubstitution = savedLastSubstitution; + preserveSourceNewlines = savedPreserveSourceNewlines; return substitute || node; } function getPipelinePhase(phase, emitHint, node) { @@ -93500,27 +95667,28 @@ var ts; case 284 /* EnumMember */: return emitEnumMember(node); // JSDoc nodes (only used in codefixes currently) - case 316 /* JSDocParameterTag */: - case 322 /* JSDocPropertyTag */: + case 317 /* JSDocParameterTag */: + case 323 /* JSDocPropertyTag */: return emitJSDocPropertyLikeTag(node); - case 317 /* JSDocReturnTag */: - case 319 /* JSDocTypeTag */: - case 318 /* JSDocThisTag */: - case 315 /* JSDocEnumTag */: + case 318 /* JSDocReturnTag */: + case 320 /* JSDocTypeTag */: + case 319 /* JSDocThisTag */: + case 316 /* JSDocEnumTag */: return emitJSDocSimpleTypedTag(node); + case 308 /* JSDocImplementsTag */: case 307 /* JSDocAugmentsTag */: - return emitJSDocAugmentsTag(node); - case 320 /* JSDocTemplateTag */: + return emitJSDocHeritageTag(node); + case 321 /* JSDocTemplateTag */: return emitJSDocTemplateTag(node); - case 321 /* JSDocTypedefTag */: + case 322 /* JSDocTypedefTag */: return emitJSDocTypedefTag(node); - case 314 /* JSDocCallbackTag */: + case 315 /* JSDocCallbackTag */: return emitJSDocCallbackTag(node); case 305 /* JSDocSignature */: return emitJSDocSignature(node); case 304 /* JSDocTypeLiteral */: return emitJSDocTypeLiteral(node); - case 309 /* JSDocClassTag */: + case 310 /* JSDocClassTag */: case 306 /* JSDocTag */: return emitJSDocSimpleTag(node); case 303 /* JSDocComment */: @@ -93622,9 +95790,9 @@ var ts; case 270 /* JsxFragment */: return emitJsxFragment(node); // Transformation nodes - case 325 /* PartiallyEmittedExpression */: + case 326 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 326 /* CommaListExpression */: + case 327 /* CommaListExpression */: return emitCommaList(node); } } @@ -94175,10 +96343,10 @@ var ts; } function emitPropertyAccessExpression(node) { var expression = ts.cast(emitExpression(node.expression), ts.isExpression); - var token = ts.getDotOrQuestionDotToken(node); - var indentBeforeDot = needsIndentation(node, node.expression, token); - var indentAfterDot = needsIndentation(node, token, node.name); - increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false); + var token = node.questionDotToken || ts.createNode(24 /* DotToken */, node.expression.end, node.name.pos); + var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token); + var linesAfterDot = getLinesBetweenNodes(node, token, node.name); + writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false); var shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ && mayNeedDotDotForPropertyAccess(expression) && !writer.hasTrailingComment() && @@ -94186,10 +96354,15 @@ var ts; if (shouldEmitDotDot) { writePunctuation("."); } - emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node); - increaseIndentIf(indentAfterDot, /*writeSpaceIfNotIndenting*/ false); + if (node.questionDotToken) { + emit(token); + } + else { + emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node); + } + writeLinesAndIndent(linesAfterDot, /*writeSpaceIfNotIndenting*/ false); emit(node.name); - decreaseIndentIf(indentBeforeDot, indentAfterDot); + decreaseIndentIf(linesBeforeDot, linesAfterDot); } // 1..toString is a valid property access, emit a dot after the literal // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal @@ -94244,7 +96417,10 @@ var ts; } function emitParenthesizedExpression(node) { var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node); + var indented = writeLineSeparatorsAndIndentBefore(node.expression, node); emitExpression(node.expression); + writeLineSeparatorsAfter(node.expression, node); + decreaseIndentIf(indented); emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { @@ -94336,20 +96512,20 @@ var ts; } case 1 /* EmitRight */: { var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */; - var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); - var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); - increaseIndentIf(indentBeforeOperator, isCommaOperator); + var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); + var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); + writeLinesAndIndent(linesBeforeOperator, isCommaOperator); emitLeadingCommentsOfPosition(node.operatorToken.pos); writeTokenNode(node.operatorToken, node.operatorToken.kind === 97 /* InKeyword */ ? writeKeyword : writeOperator); emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts - increaseIndentIf(indentAfterOperator, /*writeSpaceIfNotIndenting*/ true); + writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true); maybePipelineEmitExpression(node.right); break; } case 2 /* FinishEmit */: { - var indentBeforeOperator = needsIndentation(node, node.left, node.operatorToken); - var indentAfterOperator = needsIndentation(node, node.operatorToken, node.right); - decreaseIndentIf(indentBeforeOperator, indentAfterOperator); + var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken); + var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right); + decreaseIndentIf(linesBeforeOperator, linesAfterOperator); stackIndex--; break; } @@ -94385,21 +96561,21 @@ var ts; } } function emitConditionalExpression(node) { - var indentBeforeQuestion = needsIndentation(node, node.condition, node.questionToken); - var indentAfterQuestion = needsIndentation(node, node.questionToken, node.whenTrue); - var indentBeforeColon = needsIndentation(node, node.whenTrue, node.colonToken); - var indentAfterColon = needsIndentation(node, node.colonToken, node.whenFalse); + var linesBeforeQuestion = getLinesBetweenNodes(node, node.condition, node.questionToken); + var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue); + var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken); + var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse); emitExpression(node.condition); - increaseIndentIf(indentBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); + writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true); emit(node.questionToken); - increaseIndentIf(indentAfterQuestion, /*writeSpaceIfNotIndenting*/ true); + writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.whenTrue); - decreaseIndentIf(indentBeforeQuestion, indentAfterQuestion); - increaseIndentIf(indentBeforeColon, /*writeSpaceIfNotIndenting*/ true); + decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion); + writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true); emit(node.colonToken); - increaseIndentIf(indentAfterColon, /*writeSpaceIfNotIndenting*/ true); + writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true); emitExpression(node.whenFalse); - decreaseIndentIf(indentBeforeColon, indentAfterColon); + decreaseIndentIf(linesBeforeColon, linesAfterColon); } function emitTemplateExpression(node) { emit(node.head); @@ -94740,14 +96916,14 @@ var ts; if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) { return false; } - if (shouldWriteLeadingLineTerminator(body, body.statements, 2 /* PreserveLines */) - || shouldWriteClosingLineTerminator(body, body.statements, 2 /* PreserveLines */)) { + if (getLeadingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */) + || getClosingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)) { return false; } var previousStatement; for (var _a = 0, _b = body.statements; _a < _b.length; _a++) { var statement = _b[_a]; - if (shouldWriteSeparatingLineTerminator(previousStatement, statement, 2 /* PreserveLines */)) { + if (getSeparatingLineTerminatorCount(previousStatement, statement, 2 /* PreserveLines */) > 0) { return false; } previousStatement = statement; @@ -95040,12 +97216,15 @@ var ts; function emitJsxOpeningElementOrFragment(node) { writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { + var indented = writeLineSeparatorsAndIndentBefore(node.tagName, node); emitJsxTagName(node.tagName); emitTypeArguments(node, node.typeArguments); if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); } emit(node.attributes); + writeLineSeparatorsAfter(node.attributes, node); + decreaseIndentIf(indented); } writePunctuation(">"); } @@ -95195,7 +97374,7 @@ var ts; } } if (node.tags) { - if (node.tags.length === 1 && node.tags[0].kind === 319 /* JSDocTypeTag */ && !node.comment) { + if (node.tags.length === 1 && node.tags[0].kind === 320 /* JSDocTypeTag */ && !node.comment) { writeSpace(); emit(node.tags[0]); } @@ -95211,7 +97390,7 @@ var ts; emitJSDocTypeExpression(tag.typeExpression); emitJSDocComment(tag.comment); } - function emitJSDocAugmentsTag(tag) { + function emitJSDocHeritageTag(tag) { emitJSDocTagName(tag.tagName); writeSpace(); writePunctuation("{"); @@ -95382,8 +97561,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { - var directive = types_21[_d]; + for (var _d = 0, types_22 = types; _d < types_22.length; _d++) { + var directive = types_22[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -95610,7 +97789,7 @@ var ts; } } function emitDecorators(parentNode, decorators) { - emitList(parentNode, decorators, 49153 /* Decorators */); + emitList(parentNode, decorators, 2146305 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { emitList(parentNode, typeArguments, 53776 /* TypeArguments */); @@ -95709,7 +97888,7 @@ var ts; } if (isEmpty) { // Write a line terminator if the parent node was multi-line - if (format & 1 /* MultiLine */) { + if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && ts.rangeIsOnSingleLine(parentNode, currentSourceFile))) { writeLine(); } else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) { @@ -95720,8 +97899,9 @@ var ts; // Write the opening line terminator or leading whitespace. var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; - if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217 - writeLine(); + var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217 + if (leadingLineTerminatorCount) { + writeLine(leadingLineTerminatorCount); shouldEmitInterveningComments = false; } else if (format & 256 /* SpaceBetweenBraces */) { @@ -95756,14 +97936,15 @@ var ts; writeDelimiter(format); recordBundleFileInternalSectionEnd(previousSourceFileTextKind); // Write either a line terminator or whitespace to separate the elements. - if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { + var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format); + if (separatingLineTerminatorCount > 0) { // If a synthesized node in a single-line list starts on a new // line, we should increase the indent. if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) { increaseIndent(); shouldDecreaseIndentAfterEmit = true; } - writeLine(); + writeLine(separatingLineTerminatorCount); shouldEmitInterveningComments = false; } else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) { @@ -95808,10 +97989,11 @@ var ts; } recordBundleFileInternalSectionEnd(previousSourceFileTextKind); // Write the closing line terminator or closing whitespace. - if (shouldWriteClosingLineTerminator(parentNode, children, format)) { - writeLine(); + var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format); + if (closingLineTerminatorCount) { + writeLine(closingLineTerminatorCount); } - else if (format & 256 /* SpaceBetweenBraces */) { + else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) { writeSpace(); } } @@ -95863,8 +98045,11 @@ var ts; function writeProperty(s) { writer.writeProperty(s); } - function writeLine() { - writer.writeLine(); + function writeLine(count) { + if (count === void 0) { count = 1; } + for (var i = 0; i < count; i++) { + writer.writeLine(i > 0); + } } function increaseIndent() { writer.increaseIndent(); @@ -95911,10 +98096,10 @@ var ts; } } } - function increaseIndentIf(value, writeSpaceIfNotIndenting) { - if (value) { + function writeLinesAndIndent(lineCount, writeSpaceIfNotIndenting) { + if (lineCount) { increaseIndent(); - writeLine(); + writeLine(lineCount); } else if (writeSpaceIfNotIndenting) { writeSpace(); @@ -95932,69 +98117,113 @@ var ts; decreaseIndent(); } } - function shouldWriteLeadingLineTerminator(parentNode, children, format) { - if (format & 1 /* MultiLine */) { - return true; - } - if (format & 2 /* PreserveLines */) { + function getLeadingLineTerminatorCount(parentNode, children, format) { + if (format & 2 /* PreserveLines */ || preserveSourceNewlines) { if (format & 65536 /* PreferNewLine */) { - return true; + return 1; } - var firstChild = children[0]; - if (firstChild === undefined) { - return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + var firstChild_1 = children[0]; + if (firstChild_1 === undefined) { + return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } - else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(firstChild)) { - return synthesizedNodeStartsOnNewLine(firstChild, format); + if (firstChild_1.kind === 11 /* JsxText */) { + // JsxText will be written with its leading whitespace, so don't add more manually. + return 0; } - else { - return !ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild, currentSourceFile); + if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || firstChild_1.parent === parentNode)) { + if (preserveSourceNewlines) { + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); }); + } + return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1; + } + if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) { + return 1; } } - else { - return false; - } + return format & 1 /* MultiLine */ ? 1 : 0; } - function shouldWriteSeparatingLineTerminator(previousNode, nextNode, format) { - if (format & 1 /* MultiLine */) { - return true; - } - else if (format & 2 /* PreserveLines */) { + function getSeparatingLineTerminatorCount(previousNode, nextNode, format) { + if (format & 2 /* PreserveLines */ || preserveSourceNewlines) { if (previousNode === undefined || nextNode === undefined) { - return false; + return 0; } - else if (ts.nodeIsSynthesized(previousNode) || ts.nodeIsSynthesized(nextNode)) { - return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format); + if (nextNode.kind === 11 /* JsxText */) { + // JsxText will be written with its leading whitespace, so don't add more manually. + return 0; } - else { - return !ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile); + else if (!ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode) && previousNode.parent === nextNode.parent) { + if (preserveSourceNewlines) { + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); }); + } + return ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1; + } + else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) { + return 1; } } - else { - return ts.getStartsOnNewLine(nextNode); + else if (ts.getStartsOnNewLine(nextNode)) { + return 1; } + return format & 1 /* MultiLine */ ? 1 : 0; } - function shouldWriteClosingLineTerminator(parentNode, children, format) { - if (format & 1 /* MultiLine */) { - return (format & 131072 /* NoTrailingNewLine */) === 0; - } - else if (format & 2 /* PreserveLines */) { + function getClosingLineTerminatorCount(parentNode, children, format) { + if (format & 2 /* PreserveLines */ || preserveSourceNewlines) { if (format & 65536 /* PreferNewLine */) { - return true; + return 1; } - var lastChild = ts.lastOrUndefined(children); - if (lastChild === undefined) { - return !ts.rangeIsOnSingleLine(parentNode, currentSourceFile); + var lastChild_1 = ts.lastOrUndefined(children); + if (lastChild_1 === undefined) { + return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1; } - else if (ts.positionIsSynthesized(parentNode.pos) || ts.nodeIsSynthesized(lastChild)) { - return synthesizedNodeStartsOnNewLine(lastChild, format); + if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild_1) && (!lastChild_1.parent || lastChild_1.parent === parentNode)) { + if (preserveSourceNewlines) { + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, parentNode.end, currentSourceFile, includeComments); }); + } + return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild_1, currentSourceFile) ? 0 : 1; } - else { - return !ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile); + if (synthesizedNodeStartsOnNewLine(lastChild_1, format)) { + return 1; } } - else { - return false; + if (format & 1 /* MultiLine */ && !(format & 131072 /* NoTrailingNewLine */)) { + return 1; + } + return 0; + } + function getEffectiveLines(getLineDifference) { + // If 'preserveSourceNewlines' is disabled, we should never call this function + // because it could be more expensive than alternative approximations. + ts.Debug.assert(!!preserveSourceNewlines); + // We start by measuring the line difference from a position to its adjacent comments, + // so that this is counted as a one-line difference, not two: + // + // node1; + // // NODE2 COMMENT + // node2; + var lines = getLineDifference(/*includeComments*/ true); + if (lines === 0) { + // However, if the line difference considering comments was 0, we might have this: + // + // node1; // NODE2 COMMENT + // node2; + // + // in which case we should be ignoring node2's comment, so this too is counted as + // a one-line difference, not zero. + return getLineDifference(/*includeComments*/ false); + } + return lines; + } + function writeLineSeparatorsAndIndentBefore(node, parent) { + var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */); + if (leadingNewlines) { + writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false); + } + return !!leadingNewlines; + } + function writeLineSeparatorsAfter(node, parent) { + var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* None */); + if (trailingNewlines) { + writeLine(trailingNewlines); } } function synthesizedNodeStartsOnNewLine(node, format) { @@ -96007,21 +98236,24 @@ var ts; } return (format & 65536 /* PreferNewLine */) !== 0; } - function needsIndentation(parent, node1, node2) { + function getLinesBetweenNodes(parent, node1, node2) { if (ts.getEmitFlags(parent) & 131072 /* NoIndentation */) { - return false; + return 0; } parent = skipSynthesizedParentheses(parent); node1 = skipSynthesizedParentheses(node1); node2 = skipSynthesizedParentheses(node2); // Always use a newline for synthesized code if the synthesizer desires it. if (ts.getStartsOnNewLine(node2)) { - return true; + return 1; } - return !ts.nodeIsSynthesized(parent) - && !ts.nodeIsSynthesized(node1) - && !ts.nodeIsSynthesized(node2) - && !ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile); + if (!ts.nodeIsSynthesized(parent) && !ts.nodeIsSynthesized(node1) && !ts.nodeIsSynthesized(node2)) { + if (preserveSourceNewlines) { + return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(node1, node2, currentSourceFile, includeComments); }); + } + return ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile) ? 0 : 1; + } + return 0; } function isEmptyBlock(block) { return block.statements.length === 0 @@ -96430,7 +98662,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 !== 324 /* NotEmittedStatement */; + var isEmittedNode = node.kind !== 325 /* 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 */; @@ -96713,7 +98945,7 @@ var ts; 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 !== 324 /* NotEmittedStatement */ + if (node.kind !== 325 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 && pos >= 0) { emitSourcePos(source, skipSourceTrivia(source, pos)); @@ -96726,7 +98958,7 @@ var ts; else { pipelinePhase(hint, node); } - if (node.kind !== 324 /* NotEmittedStatement */ + if (node.kind !== 325 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 && end >= 0) { emitSourcePos(source, end); @@ -97186,7 +99418,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; function findConfigFile(searchPath, fileExists, configName) { if (configName === void 0) { configName = "tsconfig.json"; } return ts.forEachAncestorDirectory(searchPath, function (ancestor) { @@ -97511,12 +99742,6 @@ var ts; return formatStyle + text + resetEscapeSequence; } ts.formatColorAndReset = formatColorAndReset; - function padLeft(s, length) { - while (s.length < length) { - s = " " + s; - } - return s; - } function formatCodeSpan(file, start, length, indent, squiggleColor, host) { var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character; @@ -97532,7 +99757,7 @@ var ts; // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, // so we'll skip ahead to the second-to-last line. if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - context += indent + formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + context += indent + formatColorAndReset(ts.padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); i = lastLine - 1; } var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); @@ -97541,10 +99766,10 @@ var ts; lineContent = lineContent.replace(/\s+$/g, ""); // trim from end lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces // Output the gutter and the actual contents of the line. - context += indent + formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; context += lineContent + host.getNewLine(); // Output the gutter and the error span for the line using tildes. - context += indent + formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += indent + formatColorAndReset(ts.padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; context += squiggleColor; if (i === firstLine) { // If we're on the last line, then limit it to the last character of the last line. @@ -97596,11 +99821,11 @@ var ts; if (diagnostic.relatedInformation) { output += host.getNewLine(); for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { - var _c = _b[_a], file = _c.file, start = _c.start, length_7 = _c.length, messageText = _c.messageText; + var _c = _b[_a], file = _c.file, start = _c.start, length_8 = _c.length, messageText = _c.messageText; if (file) { output += host.getNewLine(); output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 - output += formatCodeSpan(file, start, length_7, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_8, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 } output += host.getNewLine(); output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); @@ -97703,7 +99928,7 @@ var ts; hasInvalidatedResolution(sourceFile.path); } function sourceFileVersionUptoDate(sourceFile) { - return sourceFile.version === getSourceVersion(sourceFile.resolvedPath); + return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName); } function projectReferenceUptoDate(oldRef, newRef, index) { if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) { @@ -97762,6 +99987,7 @@ var ts; }; } function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { + var _a; var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217 var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; var oldProgram = createProgramOptions.oldProgram; @@ -97808,10 +100034,10 @@ var ts; var hasEmitBlockingDiagnostics = ts.createMap(); var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; - var resolveModuleNamesWorker; + var actualResolveModuleNamesWorker; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames, redirectedReference, options).map(function (resolved) { + actualResolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.checkEachDefined(moduleNames), containingFile, reusedNames, redirectedReference, options).map(function (resolved) { // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. if (!resolved || resolved.extension !== undefined) { return resolved; @@ -97824,15 +100050,15 @@ var ts; else { moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options); var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217 - resolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; + actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); }; } - var resolveTypeReferenceDirectiveNamesWorker; + var actualResolveTypeReferenceDirectiveNamesWorker; if (host.resolveTypeReferenceDirectives) { - resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); }; + actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); }; } else { var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217 - resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.assertEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; + actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); }; } // Map from a stringified PackageId to the source file with that id. // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile). @@ -97858,7 +100084,16 @@ var ts; var projectReferenceRedirects; var mapFromFileToProjectReferenceRedirects; var mapFromToProjectReferenceRedirectSource; - var useSourceOfProjectReferenceRedirect = !!host.useSourceOfProjectReferenceRedirect && host.useSourceOfProjectReferenceRedirect(); + var useSourceOfProjectReferenceRedirect = !!((_a = host.useSourceOfProjectReferenceRedirect) === null || _a === void 0 ? void 0 : _a.call(host)) && + !options.disableSourceOfProjectReferenceRedirect; + var _b = updateHostForUseSourceOfProjectReferenceRedirect({ + compilerHost: host, + useSourceOfProjectReferenceRedirect: useSourceOfProjectReferenceRedirect, + toPath: toPath, + getResolvedProjectReferences: getResolvedProjectReferences, + getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect, + forEachResolvedProjectReference: forEachResolvedProjectReference + }), onProgramCreateComplete = _b.onProgramCreateComplete, fileExists = _b.fileExists; var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`. @@ -97871,12 +100106,6 @@ var ts; if (!resolvedProjectReferences) { resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); } - if (host.setResolvedProjectReferenceCallbacks) { - host.setResolvedProjectReferenceCallbacks({ - getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect, - forEachResolvedProjectReference: forEachResolvedProjectReference - }); - } if (rootNames.length) { for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) { var parsedRef = resolvedProjectReferences_1[_i]; @@ -97885,8 +100114,8 @@ var ts; var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out; if (useSourceOfProjectReferenceRedirect) { if (out || ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) { - for (var _a = 0, _b = parsedRef.commandLine.fileNames; _a < _b.length; _a++) { - var fileName = _b[_a]; + for (var _c = 0, _d = parsedRef.commandLine.fileNames; _c < _d.length; _c++) { + var fileName = _d[_c]; processSourceFile(fileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } } @@ -97896,8 +100125,8 @@ var ts; processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) { - for (var _c = 0, _d = parsedRef.commandLine.fileNames; _c < _d.length; _c++) { - var fileName = _d[_c]; + for (var _e = 0, _f = parsedRef.commandLine.fileNames; _e < _f.length; _e++) { + var fileName = _f[_e]; if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) { processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); } @@ -97949,8 +100178,8 @@ var ts; // not part of the new program. if (oldProgram && host.onReleaseOldSourceFile) { var oldSourceFiles = oldProgram.getSourceFiles(); - for (var _e = 0, oldSourceFiles_1 = oldSourceFiles; _e < oldSourceFiles_1.length; _e++) { - var oldSourceFile = oldSourceFiles_1[_e]; + for (var _g = 0, oldSourceFiles_1 = oldSourceFiles; _g < oldSourceFiles_1.length; _g++) { + var oldSourceFile = oldSourceFiles_1[_g]; var newFile = getSourceFileByPath(oldSourceFile.resolvedPath); if (shouldCreateNewSourceFile || !newFile || // old file wasnt redirect but new file is @@ -97993,6 +100222,7 @@ var ts; getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, + getInstantiationCount: function () { return getDiagnosticsProducingTypeChecker().getInstantiationCount(); }, getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, @@ -98014,12 +100244,29 @@ var ts; forEachResolvedProjectReference: forEachResolvedProjectReference, isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect, emitBuildInfo: emitBuildInfo, - getProbableSymlinks: getProbableSymlinks + fileExists: fileExists, + getProbableSymlinks: getProbableSymlinks, + useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, }; + onProgramCreateComplete(); verifyCompilerOptions(); ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); return program; + function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames, redirectedReference) { + ts.performance.mark("beforeResolveModule"); + var result = actualResolveModuleNamesWorker(moduleNames, containingFile, reusedNames, redirectedReference); + ts.performance.mark("afterResolveModule"); + ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule"); + return result; + } + function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, redirectedReference) { + ts.performance.mark("beforeResolveTypeReference"); + var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, redirectedReference); + ts.performance.mark("afterResolveTypeReference"); + ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference"); + return result; + } function compareDefaultLibFiles(a, b) { return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b)); } @@ -98093,13 +100340,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_8 = []; + var result_11 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_8.push(resolvedModule); + result_11.push(resolvedModule); } - return result_8; + return result_11; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -98247,12 +100494,6 @@ var ts; } if (projectReferences) { resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile); - if (host.setResolvedProjectReferenceCallbacks) { - host.setResolvedProjectReferenceCallbacks({ - getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect, - forEachResolvedProjectReference: forEachResolvedProjectReference - }); - } } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; @@ -98447,11 +100688,26 @@ var ts; return oldProgram.structureIsReused = 2 /* Completely */; } function getEmitHost(writeFileCallback) { - return __assign(__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, + return { + 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, getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect, + getProjectReferenceRedirect: getProjectReferenceRedirect, isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect, - getProbableSymlinks: getProbableSymlinks, 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) { + getProbableSymlinks: getProbableSymlinks, + 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)) @@ -98460,7 +100716,12 @@ 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(); }, getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); }, getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); }, redirectTargetsMap: redirectTargetsMap }); + }, + useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); }, + getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); }, + getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); }, + redirectTargetsMap: redirectTargetsMap, + }; } function emitBuildInfo(writeFileCallback) { ts.Debug.assert(!options.out && !options.outFile); @@ -98576,19 +100837,19 @@ var ts; } var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - var diagnostics; - for (var _i = 0, _a = [fileProcessingDiagnosticsInFile, programDiagnosticsInFile]; _i < _a.length; _i++) { - var diags = _a[_i]; - if (diags) { - for (var _b = 0, diags_4 = diags; _b < diags_4.length; _b++) { - var diag = diags_4[_b]; - if (shouldReportDiagnostic(diag)) { - diagnostics = ts.append(diagnostics, diag); - } - } - } + return getMergedProgramDiagnostics(sourceFile, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); + } + function getMergedProgramDiagnostics(sourceFile) { + var _a; + var allDiagnostics = []; + for (var _i = 1; _i < arguments.length; _i++) { + allDiagnostics[_i - 1] = arguments[_i]; } - return diagnostics || ts.emptyArray; + var flatDiagnostics = ts.flatten(allDiagnostics); + if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) { + return flatDiagnostics; + } + return getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics).diagnostics; } function getDeclarationDiagnostics(sourceFile, cancellationToken) { var options = program.getCompilerOptions(); @@ -98652,57 +100913,74 @@ var ts; sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */); var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; - var diagnostics; - for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { - var diags = _a[_i]; - if (diags) { - for (var _b = 0, diags_5 = diags; _b < diags_5.length; _b++) { - var diag = diags_5[_b]; - if (shouldReportDiagnostic(diag)) { - diagnostics = ts.append(diagnostics, diag); - } - } - } - } - return diagnostics || ts.emptyArray; + return getMergedBindAndCheckDiagnostics(sourceFile, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined); }); } + function getMergedBindAndCheckDiagnostics(sourceFile) { + var _a; + var allDiagnostics = []; + for (var _i = 1; _i < arguments.length; _i++) { + allDiagnostics[_i - 1] = arguments[_i]; + } + var flatDiagnostics = ts.flatten(allDiagnostics); + if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) { + return flatDiagnostics; + } + var _b = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics), diagnostics = _b.diagnostics, directives = _b.directives; + for (var _c = 0, _d = directives.getUnusedExpectations(); _c < _d.length; _c++) { + var errorExpectation = _d[_c]; + diagnostics.push(ts.createDiagnosticForRange(sourceFile, errorExpectation.range, ts.Diagnostics.Unused_ts_expect_error_directive)); + } + return diagnostics; + } + /** + * Creates a map of comment directives along with the diagnostics immediately preceded by one of them. + * Comments that match to any of those diagnostics are marked as used. + */ + function getDiagnosticsWithPrecedingDirectives(sourceFile, commentDirectives, flatDiagnostics) { + // Diagnostics are only reported if there is no comment directive preceding them + // This will modify the directives map by marking "used" ones with a corresponding diagnostic + var directives = ts.createCommentDirectivesMap(sourceFile, commentDirectives); + var diagnostics = flatDiagnostics.filter(function (diagnostic) { return markPrecedingCommentDirectiveLine(diagnostic, directives) === -1; }); + return { diagnostics: diagnostics, directives: directives }; + } function getSuggestionDiagnostics(sourceFile, cancellationToken) { return runWithCancellationToken(function () { return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken); }); } /** - * Skip errors if previous line start with '// @ts-ignore' comment, not counting non-empty non-comment lines + * @returns The line index marked as preceding the diagnostic, or -1 if none was. */ - function shouldReportDiagnostic(diagnostic) { + function markPrecedingCommentDirectiveLine(diagnostic, directives) { var file = diagnostic.file, start = diagnostic.start; - if (file) { - var lineStarts = ts.getLineStarts(file); - var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; // TODO: GH#18217 - while (line > 0) { - var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]); - var result = ignoreDiagnosticCommentRegEx.exec(previousLineText); - if (!result) { - // non-empty line - return true; - } - if (result[3]) { - // @ts-ignore - return false; - } - line--; - } + if (!file) { + return -1; } - return true; + // Start out with the line just before the text + var lineStarts = ts.getLineStarts(file); + var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line - 1; // TODO: GH#18217 + while (line >= 0) { + // As soon as that line is known to have a comment directive, use that + if (directives.markUsed(line)) { + return line; + } + // Stop searching if the line is not empty and not a comment + var lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim(); + if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) { + return -1; + } + line--; + } + return -1; } function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; - var parent = sourceFile; - walk(sourceFile); + walk(sourceFile, sourceFile); + ts.forEachChildRecursively(sourceFile, walk, walkArray); return diagnostics; - function walk(node) { + function walk(node, parent) { // Return directly from the case if the given node doesnt want to visit each child // Otherwise break to visit each child switch (parent.kind) { @@ -98711,7 +100989,7 @@ var ts; case 161 /* MethodDeclaration */: if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?")); - return; + return "skip"; } // falls through case 160 /* MethodSignature */: @@ -98725,70 +101003,66 @@ var ts; // type annotation if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files)); - return; + return "skip"; } } switch (node.kind) { case 255 /* ImportClause */: if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(node.parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type")); - return; + return "skip"; } break; case 260 /* ExportDeclaration */: if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type")); - return; + return "skip"; } break; case 253 /* ImportEqualsDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files)); - return; + return "skip"; case 259 /* ExportAssignment */: if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files)); - return; + return "skip"; } break; case 279 /* HeritageClause */: var heritageClause = node; if (heritageClause.token === 113 /* ImplementsKeyword */) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files)); - return; + return "skip"; } break; case 246 /* InterfaceDeclaration */: var interfaceKeyword = ts.tokenToString(114 /* InterfaceKeyword */); - ts.Debug.assertDefined(interfaceKeyword); + ts.Debug.assertIsDefined(interfaceKeyword); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword)); - return; + return "skip"; case 249 /* ModuleDeclaration */: var moduleKeyword = node.flags & 16 /* Namespace */ ? ts.tokenToString(136 /* NamespaceKeyword */) : ts.tokenToString(135 /* ModuleKeyword */); - ts.Debug.assertDefined(moduleKeyword); + ts.Debug.assertIsDefined(moduleKeyword); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword)); - return; + return "skip"; case 247 /* TypeAliasDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files)); - return; + return "skip"; case 248 /* EnumDeclaration */: - var enumKeyword = ts.Debug.assertDefined(ts.tokenToString(88 /* EnumKeyword */)); + var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(88 /* EnumKeyword */)); diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword)); - return; + return "skip"; case 218 /* NonNullExpression */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files)); - return; + return "skip"; case 217 /* AsExpression */: diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files)); - return; + return "skip"; case 199 /* TypeAssertionExpression */: ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } - var prevParent = parent; - parent = node; - ts.forEachChild(node, walk, walkArray); - parent = prevParent; } - function walkArray(nodes) { + function walkArray(nodes, parent) { if (parent.decorators === nodes && !options.experimentalDecorators) { diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning)); } @@ -98805,13 +101079,14 @@ var ts; // Check type parameters if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files)); - return; + return "skip"; } // falls through case 225 /* VariableStatement */: // Check modifiers if (nodes === parent.modifiers) { - return checkModifiers(parent.modifiers, parent.kind === 225 /* VariableStatement */); + checkModifiers(parent.modifiers, parent.kind === 225 /* VariableStatement */); + return "skip"; } break; case 159 /* PropertyDeclaration */: @@ -98823,14 +101098,14 @@ var ts; diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind))); } } - return; + return "skip"; } break; case 156 /* Parameter */: // Check modifiers of parameter declaration if (nodes === parent.modifiers) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); - return; + return "skip"; } break; case 196 /* CallExpression */: @@ -98842,14 +101117,10 @@ var ts; // Check type arguments if (nodes === parent.typeArguments) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files)); - return; + return "skip"; } break; } - for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { - var node = nodes_6[_b]; - walk(node); - } } function checkModifiers(modifiers, isConstValid) { for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { @@ -99112,7 +101383,7 @@ var ts; } var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); if (fail && !sourceFileWithAddedExtension) - fail(ts.Diagnostics.File_0_not_found, fileName + ".ts" /* Ts */); + fail(ts.Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + supportedExtensions.join("', '") + "'"); return sourceFileWithAddedExtension; } } @@ -99644,7 +101915,7 @@ var ts; projectReferenceRedirects.set(sourceFilePath, false); return undefined; } - sourceFile = ts.Debug.assertDefined(commandLine.options.configFile); + sourceFile = ts.Debug.checkDefined(commandLine.options.configFile); ts.Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath); addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined); } @@ -99908,7 +102179,7 @@ var ts; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } - var refFile = ts.Debug.assertDefined(getSourceFileByPath(refPathToReportErrorOn.file)); + var refFile = ts.Debug.checkDefined(getSourceFileByPath(refPathToReportErrorOn.file)); var kind = refPathToReportErrorOn.kind, index = refPathToReportErrorOn.index; var pos, end; switch (kind) { @@ -100107,6 +102378,156 @@ var ts; } } ts.createProgram = createProgram; + function updateHostForUseSourceOfProjectReferenceRedirect(host) { + var mapOfDeclarationDirectories; + var symlinkedDirectories; + var symlinkedFiles; + var originalFileExists = host.compilerHost.fileExists; + var originalDirectoryExists = host.compilerHost.directoryExists; + var originalGetDirectories = host.compilerHost.getDirectories; + var originalRealpath = host.compilerHost.realpath; + if (!host.useSourceOfProjectReferenceRedirect) + return { onProgramCreateComplete: ts.noop, fileExists: fileExists }; + host.compilerHost.fileExists = fileExists; + if (originalDirectoryExists) { + // This implementation of directoryExists checks if the directory being requested is + // directory of .d.ts file for the referenced Project. + // If it is it returns true irrespective of whether that directory exists on host + host.compilerHost.directoryExists = function (path) { + if (originalDirectoryExists.call(host.compilerHost, path)) { + handleDirectoryCouldBeSymlink(path); + return true; + } + if (!host.getResolvedProjectReferences()) + return false; + if (!mapOfDeclarationDirectories) { + mapOfDeclarationDirectories = ts.createMap(); + host.forEachResolvedProjectReference(function (ref) { + if (!ref) + return; + var out = ref.commandLine.options.outFile || ref.commandLine.options.out; + if (out) { + mapOfDeclarationDirectories.set(ts.getDirectoryPath(host.toPath(out)), true); + } + else { + // Set declaration's in different locations only, if they are next to source the directory present doesnt change + var declarationDir = ref.commandLine.options.declarationDir || ref.commandLine.options.outDir; + if (declarationDir) { + mapOfDeclarationDirectories.set(host.toPath(declarationDir), true); + } + } + }); + } + return fileOrDirectoryExistsUsingSource(path, /*isFile*/ false); + }; + } + if (originalGetDirectories) { + // Call getDirectories only if directory actually present on the host + // This is needed to ensure that we arent getting directories that we fake about presence for + host.compilerHost.getDirectories = function (path) { + return !host.getResolvedProjectReferences() || (originalDirectoryExists && originalDirectoryExists.call(host.compilerHost, path)) ? + originalGetDirectories.call(host.compilerHost, path) : + []; + }; + } + // This is something we keep for life time of the host + if (originalRealpath) { + host.compilerHost.realpath = function (s) { + return (symlinkedFiles === null || symlinkedFiles === void 0 ? void 0 : symlinkedFiles.get(host.toPath(s))) || + originalRealpath.call(host.compilerHost, s); + }; + } + return { onProgramCreateComplete: onProgramCreateComplete, fileExists: fileExists }; + function onProgramCreateComplete() { + host.compilerHost.fileExists = originalFileExists; + host.compilerHost.directoryExists = originalDirectoryExists; + host.compilerHost.getDirectories = originalGetDirectories; + // DO not revert realpath as it could be used later + } + // This implementation of fileExists checks if the file being requested is + // .d.ts file for the referenced Project. + // If it is it returns true irrespective of whether that file exists on host + function fileExists(file) { + if (originalFileExists.call(host.compilerHost, file)) + return true; + if (!host.getResolvedProjectReferences()) + return false; + if (!ts.isDeclarationFileName(file)) + return false; + // Project references go to source file instead of .d.ts file + return fileOrDirectoryExistsUsingSource(file, /*isFile*/ true); + } + function fileExistsIfProjectReferenceDts(file) { + var source = host.getSourceOfProjectReferenceRedirect(file); + return source !== undefined ? + ts.isString(source) ? originalFileExists.call(host.compilerHost, source) : true : + undefined; + } + function directoryExistsIfProjectReferenceDeclDir(dir) { + var dirPath = host.toPath(dir); + var dirPathWithTrailingDirectorySeparator = "" + dirPath + ts.directorySeparator; + return ts.forEachKey(mapOfDeclarationDirectories, function (declDirPath) { return dirPath === declDirPath || + // Any parent directory of declaration dir + ts.startsWith(declDirPath, dirPathWithTrailingDirectorySeparator) || + // Any directory inside declaration dir + ts.startsWith(dirPath, declDirPath + "/"); }); + } + function handleDirectoryCouldBeSymlink(directory) { + if (!host.getResolvedProjectReferences()) + return; + // Because we already watch node_modules, handle symlinks in there + if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart)) + return; + if (!symlinkedDirectories) + symlinkedDirectories = ts.createMap(); + var directoryPath = ts.ensureTrailingDirectorySeparator(host.toPath(directory)); + if (symlinkedDirectories.has(directoryPath)) + return; + var real = ts.normalizePath(originalRealpath.call(host.compilerHost, directory)); + var realPath; + if (real === directory || + (realPath = ts.ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath) { + // not symlinked + symlinkedDirectories.set(directoryPath, false); + return; + } + symlinkedDirectories.set(directoryPath, { + real: ts.ensureTrailingDirectorySeparator(real), + realPath: realPath + }); + } + function fileOrDirectoryExistsUsingSource(fileOrDirectory, isFile) { + var fileOrDirectoryExistsUsingSource = isFile ? + function (file) { return fileExistsIfProjectReferenceDts(file); } : + function (dir) { return directoryExistsIfProjectReferenceDeclDir(dir); }; + // Check current directory or file + var result = fileOrDirectoryExistsUsingSource(fileOrDirectory); + if (result !== undefined) + return result; + if (!symlinkedDirectories) + return false; + var fileOrDirectoryPath = host.toPath(fileOrDirectory); + if (!ts.stringContains(fileOrDirectoryPath, ts.nodeModulesPathPart)) + return false; + if (isFile && symlinkedFiles && symlinkedFiles.has(fileOrDirectoryPath)) + return true; + // If it contains node_modules check if its one of the symlinked path we know of + return ts.firstDefinedIterator(symlinkedDirectories.entries(), function (_a) { + var directoryPath = _a[0], symlinkedDirectory = _a[1]; + if (!symlinkedDirectory || !ts.startsWith(fileOrDirectoryPath, directoryPath)) + return undefined; + var result = fileOrDirectoryExistsUsingSource(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath)); + if (isFile && result) { + if (!symlinkedFiles) + symlinkedFiles = ts.createMap(); + // Store the real path for the file' + var absolutePath = ts.getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory()); + symlinkedFiles.set(fileOrDirectoryPath, "" + symlinkedDirectory.real + absolutePath.replace(new RegExp(directoryPath, "i"), "")); + } + return result; + }) || false; + } + } /*@internal*/ function handleNoEmitOptions(program, sourceFile, cancellationToken) { var options = program.getCompilerOptions(); @@ -100133,7 +102554,7 @@ var ts; return { fileExists: function (f) { return directoryStructureHost.fileExists(f); }, readDirectory: function (root, extensions, excludes, includes, depth) { - ts.Debug.assertDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + ts.Debug.assertIsDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth); }, readFile: function (f) { return directoryStructureHost.readFile(f); }, @@ -100221,8 +102642,8 @@ var ts; (function (ts) { function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) { var outputFiles = []; - var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped, exportedModulesFromDeclarationEmit: emitResult.exportedModulesFromDeclarationEmit }; + var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit; + return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit }; function writeFile(fileName, text, writeByteOrderMark) { outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); } @@ -100351,7 +102772,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 = ts.Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set"); + var version_1 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set"); var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); @@ -100366,7 +102787,7 @@ var ts; } } } - fileInfos.set(sourceFile.resolvedPath, { version: version_1, signature: oldInfo && oldInfo.signature }); + fileInfos.set(sourceFile.resolvedPath, { version: version_1, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) }); } return { fileInfos: fileInfos, @@ -100430,12 +102851,14 @@ var ts; * This should be called whenever it is safe to commit the state of the builder */ function updateSignaturesFromCache(state, signatureCache) { - signatureCache.forEach(function (signature, path) { - state.fileInfos.get(path).signature = signature; - state.hasCalledUpdateShapeSignature.set(path, true); - }); + signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); }); } BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + function updateSignatureOfFile(state, signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + } + BuilderState.updateSignatureOfFile = updateSignatureOfFile; /** * Returns if the shape of the signature has changed since last emit */ @@ -100614,7 +103037,8 @@ var ts; return state.allFilesExcludingDefaultLibraryFile; } var result; - addSourceFile(firstSourceFile); + if (firstSourceFile) + addSourceFile(firstSourceFile); for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; if (sourceFile !== firstSourceFile) { @@ -100629,6 +103053,7 @@ var ts; } } } + BuilderState.getAllFilesExcludingDefaultLibraryFile = getAllFilesExcludingDefaultLibraryFile; /** * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed */ @@ -100727,6 +103152,7 @@ var ts; state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice(); state.affectedFilesPendingEmitKind = ts.cloneMapOrUndefined(oldState.affectedFilesPendingEmitKind); state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex; + state.seenAffectedFiles = ts.createMap(); } } // Update changed files and copy semantic diagnostics if we can @@ -100769,11 +103195,16 @@ var ts; } } }); - if (oldCompilerOptions && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) { + // If the global file is removed, add all files as changed + if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) { + ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined) + .forEach(function (file) { return state.changedFilesSet.set(file.resolvedPath, true); }); + } + else if (oldCompilerOptions && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) { // Add all files to affectedFilesPendingEmit since emit changed newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* Full */); }); - ts.Debug.assert(state.seenAffectedFiles === undefined); - state.seenAffectedFiles = ts.createMap(); + ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size); + state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); } state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit; return state; @@ -100878,7 +103309,7 @@ var ts; } // With --out or --outFile all outputs go into single file // so operations are performed directly on program, return program - var program = ts.Debug.assertDefined(state.program); + var program = ts.Debug.checkDefined(state.program); var compilerOptions = program.getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { ts.Debug.assert(!state.semanticDiagnosticsPerFile); @@ -100903,10 +103334,10 @@ var ts; if (affectedFilesPendingEmit) { var seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap()); for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) { - var affectedFile = ts.Debug.assertDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]); + var affectedFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]); if (affectedFile) { var seenKind = seenEmittedFiles.get(affectedFile.resolvedPath); - var emitKind = ts.Debug.assertDefined(ts.Debug.assertDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath)); + var emitKind = ts.Debug.checkDefined(ts.Debug.checkDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath)); if (seenKind === undefined || seenKind < emitKind) { // emit this file state.affectedFilesPendingEmitIndex = i; @@ -100930,7 +103361,7 @@ var ts; if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) { if (!state.cleanedDiagnosticsOfLibFiles) { state.cleanedDiagnosticsOfLibFiles = true; - var program_1 = ts.Debug.assertDefined(state.program); + var program_1 = ts.Debug.checkDefined(state.program); var options_2 = program_1.getCompilerOptions(); ts.forEach(program_1.getSourceFiles(), function (f) { return program_1.isSourceFileDefaultLibrary(f) && @@ -100951,14 +103382,14 @@ var ts; function handleDtsMayChangeOf(state, path, cancellationToken, computeHash) { removeSemanticDiagnosticsOf(state, path); if (!state.changedFilesSet.has(path)) { - var program = ts.Debug.assertDefined(state.program); + var program = ts.Debug.checkDefined(state.program); var sourceFile = program.getSourceFileByPath(path); if (sourceFile) { // Even though the js emit doesnt change and we are already handling dts emit and semantic diagnostics // we need to update the signature to reflect correctness of the signature(which is output d.ts emit) of this file // This ensures that we dont later during incremental builds considering wrong signature. // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build - ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.assertDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap); + ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap); // If not dts emit, nothing more to do if (ts.getEmitDeclarations(state.compilerOptions)) { addToAffectedFilesPendingEmit(state, path, 0 /* DtsOnly */); @@ -100980,8 +103411,8 @@ var ts; return !state.semanticDiagnosticsFromOldState.size; } function isChangedSignagure(state, path) { - var newSignature = ts.Debug.assertDefined(state.currentAffectedFilesSignatures).get(path); - var oldSignagure = ts.Debug.assertDefined(state.fileInfos.get(path)).signature; + var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path); + var oldSignagure = ts.Debug.checkDefined(state.fileInfos.get(path)).signature; return newSignature !== oldSignagure; } /** @@ -101007,7 +103438,7 @@ var ts; seenFileNamesMap.set(currentPath, true); var result = fn(state, currentPath); if (result && isChangedSignagure(state, currentPath)) { - var currentSourceFile = ts.Debug.assertDefined(state.program).getSourceFileByPath(currentPath); + var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath); queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath)); } } @@ -101120,7 +103551,7 @@ var ts; * bindAndCheckDiagnostics (from cache) and program diagnostics */ function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { - return ts.concatenate(getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken), ts.Debug.assertDefined(state.program).getProgramDiagnostics(sourceFile)); + return ts.concatenate(getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken), ts.Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile)); } /** * Gets the binder and checker diagnostics either from cache if present, or otherwise from program and caches it @@ -101136,7 +103567,7 @@ var ts; } } // Diagnostics werent cached, get them from program, and cache the result - var diagnostics = ts.Debug.assertDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken); + var diagnostics = ts.Debug.checkDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken); if (state.semanticDiagnosticsPerFile) { state.semanticDiagnosticsPerFile.set(path, diagnostics); } @@ -101148,49 +103579,54 @@ var ts; function getProgramBuildInfo(state, getCanonicalFileName) { if (state.compilerOptions.outFile || state.compilerOptions.out) return undefined; - var currentDirectory = ts.Debug.assertDefined(state.program).getCurrentDirectory(); + var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory(); var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); var fileInfos = {}; state.fileInfos.forEach(function (value, key) { var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key); - fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature }; + fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope }; }); var result = { fileInfos: fileInfos, options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath) }; if (state.referencedMap) { - var referencedMap_1 = {}; - state.referencedMap.forEach(function (value, key) { - referencedMap_1[relativeToBuildInfo(key)] = ts.arrayFrom(value.keys(), relativeToBuildInfo); - }); - result.referencedMap = referencedMap_1; + var referencedMap = {}; + for (var _i = 0, _a = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) { + var key = _a[_i]; + referencedMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.referencedMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); + } + result.referencedMap = referencedMap; } if (state.exportedModulesMap) { - var exportedModulesMap_1 = {}; - state.exportedModulesMap.forEach(function (value, key) { + var exportedModulesMap = {}; + for (var _b = 0, _c = ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) { + var key = _c[_b]; var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key); // Not in temporary cache, use existing value if (newValue === undefined) - exportedModulesMap_1[relativeToBuildInfo(key)] = ts.arrayFrom(value.keys(), relativeToBuildInfo); + exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.exportedModulesMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); // Value in cache and has updated value map, use that else if (newValue) - exportedModulesMap_1[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo); - }); - result.exportedModulesMap = exportedModulesMap_1; + exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive); + } + result.exportedModulesMap = exportedModulesMap; } 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 ? - [ - relativeToBuildInfo(key), - state.hasReusableDiagnostic ? - value : - convertToReusableDiagnostics(value, relativeToBuildInfo) - ] : - relativeToBuildInfo(key)); }); - result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile_1; + var semanticDiagnosticsPerFile = []; + for (var _d = 0, _e = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) { + var key = _e[_d]; + var value = state.semanticDiagnosticsPerFile.get(key); + semanticDiagnosticsPerFile.push(value.length ? + [ + relativeToBuildInfo(key), + state.hasReusableDiagnostic ? + value : + convertToReusableDiagnostics(value, relativeToBuildInfo) + ] : + relativeToBuildInfo(key)); + } + result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile; } return result; function relativeToBuildInfoEnsuringAbsolutePath(path) { @@ -101314,10 +103750,10 @@ var ts; backupState = cloneBuilderProgramState(state); }; builderProgram.restoreState = function () { - state = ts.Debug.assertDefined(backupState); + state = ts.Debug.checkDefined(backupState); backupState = undefined; }; - builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.assertDefined(state.program), sourceFile); }; + builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); }; builderProgram.getSemanticDiagnostics = getSemanticDiagnostics; builderProgram.emit = emit; builderProgram.releaseProgram = function () { @@ -101351,7 +103787,7 @@ var ts; if (state.emittedBuildInfo) { return undefined; } - var affected_1 = ts.Debug.assertDefined(state.program); + var affected_1 = ts.Debug.checkDefined(state.program); return toAffectedFileEmitResult(state, // When whole program is affected, do emit only once (eg when --out or --outFile is specified) // Otherwise just affected file @@ -101363,7 +103799,7 @@ var ts; isPendingEmitFile = true; } else { - var program = ts.Debug.assertDefined(state.program); + var program = ts.Debug.checkDefined(state.program); if (state.programEmitComplete) return undefined; affected = program; @@ -101372,7 +103808,7 @@ var ts; return toAffectedFileEmitResult(state, // When whole program is affected, do emit only once (eg when --out or --outFile is specified) // Otherwise just affected file - ts.Debug.assertDefined(state.program).emit(affected === state.program ? undefined : affected, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles || emitKind === 0 /* DtsOnly */, customTransformers), affected, emitKind, isPendingEmitFile); + ts.Debug.checkDefined(state.program).emit(affected === state.program ? undefined : affected, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles || emitKind === 0 /* DtsOnly */, customTransformers), affected, emitKind, isPendingEmitFile); } /** * Emits the JavaScript and declaration files. @@ -101412,7 +103848,7 @@ var ts; }; } } - return ts.Debug.assertDefined(state.program).emit(targetSourceFile, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers); + return ts.Debug.checkDefined(state.program).emit(targetSourceFile, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers); } /** * Return the semantic diagnostics for the next affected file or undefined if iteration is complete @@ -101452,11 +103888,11 @@ var ts; */ function getSemanticDiagnostics(sourceFile, cancellationToken) { assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); - var compilerOptions = ts.Debug.assertDefined(state.program).getCompilerOptions(); + var compilerOptions = ts.Debug.checkDefined(state.program).getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { ts.Debug.assert(!state.semanticDiagnosticsPerFile); // We dont need to cache the diagnostics just return them from program - return ts.Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken); + return ts.Debug.checkDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken); } if (sourceFile) { return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); @@ -101467,7 +103903,7 @@ var ts; while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) { } var diagnostics; - for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) { + for (var _i = 0, _a = ts.Debug.checkDefined(state.program).getSourceFiles(); _i < _a.length; _i++) { var sourceFile_1 = _a[_i]; diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken)); } @@ -101575,7 +104011,7 @@ var ts; close: ts.noop, }; function getProgram() { - return ts.Debug.assertDefined(state.program); + return ts.Debug.checkDefined(state.program); } } ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram; @@ -101653,13 +104089,13 @@ var ts; return true; } ts.canWatchDirectory = canWatchDirectory; - ts.maxNumberOfFilesToIterateForInvalidation = 256; function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; var filesWithInvalidatedNonRelativeUnresolvedImports; - var allFilesHaveInvalidatedResolution = false; var nonRelativeExternalModuleResolutions = ts.createMultiMap(); + var resolutionsWithFailedLookups = []; + var resolvedFileToResolution = ts.createMultiMap(); var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. @@ -101723,7 +104159,8 @@ var ts; closeTypeRootsWatch(); resolvedModuleNames.clear(); resolvedTypeReferenceDirectives.clear(); - allFilesHaveInvalidatedResolution = false; + resolvedFileToResolution.clear(); + resolutionsWithFailedLookups.length = 0; // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) clearPerDirectoryResolutions(); @@ -101745,7 +104182,7 @@ var ts; return !!value && !!value.length; } function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { - if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { + if (forceAllFilesAsInvalidated) { // Any file asked would have invalidated resolution filesWithInvalidatedResolutions = undefined; return ts.returnTrue; @@ -101763,7 +104200,6 @@ var ts; nonRelativeExternalModuleResolutions.clear(); } function finishCachingPerDirectoryResolution() { - allFilesHaveInvalidatedResolution = false; filesWithInvalidatedNonRelativeUnresolvedImports = undefined; clearPerDirectoryResolutions(); directoryWatchesOfFailedLookups.forEach(function (watcher, path) { @@ -101774,6 +104210,7 @@ var ts; }); } function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) { + var _a; var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference); // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts if (!resolutionHost.getGlobalCache) { @@ -101784,15 +104221,20 @@ var ts; if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results - var _a = ts.loadModuleFromGlobalCache(ts.Debug.assertDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations; if (resolvedModule) { - return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) }; + // Modify existing resolution so its saved in the directory cache as well + primaryResult.resolvedModule = resolvedModule; + (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations); + return primaryResult; } } // Default return the result from the first pass return primaryResult; } - function resolveNamesWithLocalCache(names, containingFile, redirectedReference, cache, perDirectoryCacheWithRedirects, loader, getResolutionWithResolvedFileName, shouldRetryResolution, reusedNames, logChanges) { + function resolveNamesWithLocalCache(_a) { + var _b; + var names = _a.names, containingFile = _a.containingFile, redirectedReference = _a.redirectedReference, cache = _a.cache, perDirectoryCacheWithRedirects = _a.perDirectoryCacheWithRedirects, loader = _a.loader, getResolutionWithResolvedFileName = _a.getResolutionWithResolvedFileName, shouldRetryResolution = _a.shouldRetryResolution, reusedNames = _a.reusedNames, logChanges = _a.logChanges; var path = resolutionHost.toPath(containingFile); var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); var dirPath = ts.getDirectoryPath(path); @@ -101817,7 +104259,7 @@ var ts; var resolution = resolutionsInFile.get(name); // Resolution is valid if it is present and not invalidated if (!seenNamesInFile.has(name) && - allFilesHaveInvalidatedResolution || unmatchedRedirects || !resolution || resolution.isInvalidated || + unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) { var existingResolution = resolution; @@ -101826,13 +104268,13 @@ var ts; resolution = resolutionInDirectory; } else { - resolution = loader(name, containingFile, compilerOptions, resolutionHost, redirectedReference); + resolution = loader(name, containingFile, compilerOptions, ((_b = resolutionHost.getCompilerHost) === null || _b === void 0 ? void 0 : _b.call(resolutionHost)) || resolutionHost, redirectedReference); perDirectoryResolution.set(name, resolution); } resolutionsInFile.set(name, resolution); - watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName); if (existingResolution) { - stopWatchFailedLookupLocationOfResolution(existingResolution); + stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName); } if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { filesWithChangedSetOfUnresolvedImports.push(path); @@ -101847,7 +104289,7 @@ var ts; // Stop watching and remove the unused name resolutionsInFile.forEach(function (resolution, name) { if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) { - stopWatchFailedLookupLocationOfResolution(resolution); + stopWatchFailedLookupLocationOfResolution(resolution, path, getResolutionWithResolvedFileName); resolutionsInFile.delete(name); } }); @@ -101871,21 +104313,35 @@ var ts; } } function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) { - return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, redirectedReference, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, - /*shouldRetryResolution*/ function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, - /*reusedNames*/ undefined, /*logChanges*/ false); + return resolveNamesWithLocalCache({ + names: typeDirectiveNames, + containingFile: containingFile, + redirectedReference: redirectedReference, + cache: resolvedTypeReferenceDirectives, + perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives, + loader: ts.resolveTypeReferenceDirective, + getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective, + shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; }, + }); } function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) { - return resolveNamesWithLocalCache(moduleNames, containingFile, redirectedReference, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, - /*shouldRetryResolution*/ function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); }, reusedNames, logChangesWhenResolvingModule); + return resolveNamesWithLocalCache({ + names: moduleNames, + containingFile: containingFile, + redirectedReference: redirectedReference, + cache: resolvedModuleNames, + perDirectoryCacheWithRedirects: perDirectoryResolvedModuleNames, + loader: resolveModuleName, + getResolutionWithResolvedFileName: getResolvedModule, + shouldRetryResolution: function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); }, + reusedNames: reusedNames, + logChanges: logChangesWhenResolvingModule + }); } function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); return cache && cache.get(moduleName); } - function isNodeModulesDirectory(dirPath) { - return ts.endsWith(dirPath, "/node_modules"); - } function isNodeModulesAtTypesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules/@types"); } @@ -101921,7 +104377,7 @@ var ts; dirPath = ts.getDirectoryPath(dirPath); } // If the directory is node_modules use it to watch, always watch it recursively - if (isNodeModulesDirectory(dirPath)) { + if (ts.isNodeModulesDirectory(dirPath)) { return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined; } var nonRecursive = true; @@ -101945,26 +104401,33 @@ var ts; function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); } - function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution) { - // No need to set the resolution refCount - if (resolution.failedLookupLocations && resolution.failedLookupLocations.length) { - if (resolution.refCount) { - resolution.refCount++; + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) { + if (resolution.refCount) { + resolution.refCount++; + ts.Debug.assertDefined(resolution.files); + } + else { + resolution.refCount = 1; + ts.Debug.assert(resolution.files === undefined); + if (ts.isExternalModuleNameRelative(name)) { + watchFailedLookupLocationOfResolution(resolution); } else { - resolution.refCount = 1; - if (ts.isExternalModuleNameRelative(name)) { - watchFailedLookupLocationOfResolution(resolution); - } - else { - nonRelativeExternalModuleResolutions.add(name, resolution); - } + nonRelativeExternalModuleResolutions.add(name, resolution); + } + var resolved = getResolutionWithResolvedFileName(resolution); + if (resolved && resolved.resolvedFileName) { + resolvedFileToResolution.add(resolutionHost.toPath(resolved.resolvedFileName), resolution); } } + (resolution.files || (resolution.files = [])).push(filePath); } function watchFailedLookupLocationOfResolution(resolution) { ts.Debug.assert(!!resolution.refCount); var failedLookupLocations = resolution.failedLookupLocations; + if (!failedLookupLocations.length) + return; + resolutionsWithFailedLookups.push(resolution); var setAtRoot = false; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; @@ -101992,14 +104455,11 @@ var ts; setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217 } } - function setRefCountToUndefined(resolution) { - resolution.refCount = undefined; - } function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { var program = resolutionHost.getCurrentProgram(); - var updateResolution = program && program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name) ? - setRefCountToUndefined : watchFailedLookupLocationOfResolution; - resolutions.forEach(updateResolution); + if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) { + resolutions.forEach(watchFailedLookupLocationOfResolution); + } } function setDirectoryWatcher(dir, dirPath, nonRecursive) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); @@ -102011,14 +104471,20 @@ var ts; directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive }); } } - function stopWatchFailedLookupLocationOfResolution(resolution) { - if (!resolution.refCount) { - return; - } + function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) { + ts.unorderedRemoveItem(ts.Debug.assertDefined(resolution.files), filePath); resolution.refCount--; if (resolution.refCount) { return; } + var resolved = getResolutionWithResolvedFileName(resolution); + if (resolved && resolved.resolvedFileName) { + resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution); + } + if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) { + // If not watching failed lookups, it wont be there in resolutionsWithFailedLookups + return; + } var failedLookupLocations = resolution.failedLookupLocations; var removeAtRoot = false; for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) { @@ -102061,16 +104527,16 @@ var ts; // Since the file existence changed, update the sourceFiles cache cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } - if (!allFilesHaveInvalidatedResolution && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { resolutionHost.onInvalidatedResolution(); } }, nonRecursive ? 0 /* None */ : 1 /* Recursive */); } - function removeResolutionsOfFileFromCache(cache, filePath) { + function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName) { // Deleted file, stop watching failed lookups for all the resolutions in the file var resolutions = cache.get(filePath); if (resolutions) { - resolutions.forEach(stopWatchFailedLookupLocationOfResolution); + resolutions.forEach(function (resolution) { return stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName); }); cache.delete(filePath); } } @@ -102091,57 +104557,26 @@ var ts; resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); }); } function removeResolutionsOfFile(filePath) { - removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); - removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); + removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModule); + removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirective); } - function invalidateResolutionCache(cache, isInvalidatedResolution, getResolutionWithResolvedFileName) { - var seen = ts.createMap(); - cache.forEach(function (resolutions, containingFilePath) { - var dirPath = ts.getDirectoryPath(containingFilePath); - var seenInDir = seen.get(dirPath); - if (!seenInDir) { - seenInDir = ts.createMap(); - seen.set(dirPath, seenInDir); - } - resolutions.forEach(function (resolution, name) { - if (seenInDir.has(name)) { - return; - } - seenInDir.set(name, true); - if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) { - // Mark the file as needing re-evaluation of module resolution instead of using it blindly. - resolution.isInvalidated = true; - (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true); - // When its a file with inferred types resolution, invalidate type reference directive resolution - if (containingFilePath.endsWith(ts.inferredTypesContainingFile)) { - resolutionHost.onChangedAutomaticTypeDirectiveNames(); - } - } - }); - }); - } - function hasReachedResolutionIterationLimit() { - var maxSize = resolutionHost.maxNumberOfFilesToIterateForInvalidation || ts.maxNumberOfFilesToIterateForInvalidation; - return resolvedModuleNames.size > maxSize || resolvedTypeReferenceDirectives.size > maxSize; - } - function invalidateResolutions(isInvalidatedResolution) { - // If more than maxNumberOfFilesToIterateForInvalidation present, - // just invalidated all files and recalculate the resolutions for files instead - if (hasReachedResolutionIterationLimit()) { - allFilesHaveInvalidatedResolution = true; - return; + function invalidateResolution(resolution) { + resolution.isInvalidated = true; + var changedInAutoTypeReferenced = false; + for (var _i = 0, _a = ts.Debug.assertDefined(resolution.files); _i < _a.length; _i++) { + var containingFilePath = _a[_i]; + (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true); + // When its a file with inferred types resolution, invalidate type reference directive resolution + changedInAutoTypeReferenced = changedInAutoTypeReferenced || containingFilePath.endsWith(ts.inferredTypesContainingFile); + } + if (changedInAutoTypeReferenced) { + resolutionHost.onChangedAutomaticTypeDirectiveNames(); } - invalidateResolutionCache(resolvedModuleNames, isInvalidatedResolution, getResolvedModule); - invalidateResolutionCache(resolvedTypeReferenceDirectives, isInvalidatedResolution, getResolvedTypeReferenceDirective); } function invalidateResolutionOfFile(filePath) { removeResolutionsOfFile(filePath); - invalidateResolutions( // Resolution is invalidated if the resulting file name is same as the deleted file path - function (resolution, getResolutionWithResolvedFileName) { - var result = getResolutionWithResolvedFileName(resolution); - return !!result && resolutionHost.toPath(result.resolvedFileName) === filePath; // TODO: GH#18217 - }); + ts.forEach(resolvedFileToResolution.get(filePath), invalidateResolution); } function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) { ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined); @@ -102167,8 +104602,8 @@ var ts; // 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 var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); - if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || isNodeModulesDirectory(fileOrDirectoryPath) || - isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { + if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) || + isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) { // Invalidate any resolution from this directory isChangedFailedLookupLocation = function (location) { var locationPath = resolutionHost.toPath(location); @@ -102187,20 +104622,21 @@ var ts; isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; } } - var hasChangedFailedLookupLocation = function (resolution) { return ts.some(resolution.failedLookupLocations, isChangedFailedLookupLocation); }; - var invalidatedFilesCount = filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size; - invalidateResolutions( + var invalidated = false; // Resolution is invalidated if the resulting file name is same as the deleted file path - hasChangedFailedLookupLocation); - return allFilesHaveInvalidatedResolution || filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size !== invalidatedFilesCount; + for (var _i = 0, resolutionsWithFailedLookups_1 = resolutionsWithFailedLookups; _i < resolutionsWithFailedLookups_1.length; _i++) { + var resolution = resolutionsWithFailedLookups_1[_i]; + if (resolution.failedLookupLocations.some(isChangedFailedLookupLocation)) { + invalidateResolution(resolution); + invalidated = true; + } + } + return invalidated; } function closeTypeRootsWatch() { ts.clearMap(typeRootsWatches, ts.closeFileWatcher); } function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) { - if (allFilesHaveInvalidatedResolution) { - return undefined; - } if (isInDirectoryPath(rootPath, typeRootPath)) { return rootPath; } @@ -102308,39 +104744,39 @@ var ts; ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */, }; } - function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, oldImportSpecifier) { - var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); + function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier)); if (res === oldImportSpecifier) return undefined; return res; } moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier; // Note: importingSourceFile is just for usesJsExtensionOnImports - function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences, redirectTargetsMap) { + function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, preferences) { if (preferences === void 0) { preferences = {}; } - return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, getPreferences(preferences, compilerOptions, importingSourceFile)); + return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferences(preferences, compilerOptions, importingSourceFile)); } moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; - function getNodeModulesPackageName(compilerOptions, importingSourceFileName, nodeModulesFileName, host, files, redirectTargetsMap) { + function getNodeModulesPackageName(compilerOptions, importingSourceFileName, nodeModulesFileName, host) { var info = getInfo(importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, nodeModulesFileName, info.getCanonicalFileName, host, redirectTargetsMap); + var modulePaths = getAllModulePaths(importingSourceFileName, nodeModulesFileName, host); return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions, /*packageNameOnly*/ true); }); } moduleSpecifiers.getNodeModulesPackageName = getNodeModulesPackageName; - function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, files, redirectTargetsMap, preferences) { + function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, preferences) { var info = getInfo(importingSourceFileName, host); - var modulePaths = getAllModulePaths(files, importingSourceFileName, toFileName, info.getCanonicalFileName, host, redirectTargetsMap); + var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host); return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) || getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences); } /** Returns an import for each symlink and for the realpath. */ - function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, userPreferences, redirectTargetsMap) { + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, userPreferences) { var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); if (ambient) return [ambient]; var info = getInfo(importingSourceFile.path, host); var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol)); - var modulePaths = getAllModulePaths(files, importingSourceFile.path, moduleSourceFile.originalFileName, info.getCanonicalFileName, host, redirectTargetsMap); + var modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host); var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile); var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }); return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); }); @@ -102399,45 +104835,67 @@ var ts; function comparePathsByNumberOfDirectorySeparators(a, b) { return ts.compareValues(numberOfDirectorySeparators(a), numberOfDirectorySeparators(b)); } + function forEachFileNameOfModule(importingFileName, importedFileName, host, preferSymlinks, cb) { + var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + var cwd = host.getCurrentDirectory(); + var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined; + var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray; + var importedFileNames = __spreadArrays((referenceRedirect ? [referenceRedirect] : ts.emptyArray), [importedFileName], redirects); + var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); + if (!preferSymlinks) { + var result_12 = ts.forEach(targets, cb); + if (result_12) + return result_12; + } + var links = host.getProbableSymlinks + ? host.getProbableSymlinks(host.getSourceFiles()) + : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd); + var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; + var result = ts.forEachEntry(links, function (resolved, path) { + if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { + return undefined; // Don't want to a package to globally import from itself + } + var target = ts.find(targets, function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); + if (target === undefined) + return undefined; + var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); + var option = ts.resolvePath(path, relative); + if (!host.fileExists || host.fileExists(option)) { + var result_13 = cb(option); + if (result_13) + return result_13; + } + }); + return result || + (preferSymlinks ? ts.forEach(targets, cb) : undefined); + } + moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule; /** * Looks for existing imports that use symlinks to this module. * Symlinks will be returned first so they are preferred over the real path. */ - function getAllModulePaths(files, importingFileName, importedFileName, getCanonicalFileName, host, redirectTargetsMap) { - var redirects = redirectTargetsMap.get(importedFileName); - var importedFileNames = redirects ? __spreadArrays(redirects, [importedFileName]) : [importedFileName]; - var cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; - var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); }); - var links = host.getProbableSymlinks - ? host.getProbableSymlinks(files) - : ts.discoverProbableSymlinks(files, getCanonicalFileName, cwd); - var result = []; - var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; - links.forEach(function (resolved, path) { - if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { - return; // Don't want to a package to globally import from itself - } - var target = ts.find(targets, function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); - if (target === undefined) - return; - var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); - var option = ts.resolvePath(path, relative); - if (!host.fileExists || host.fileExists(option)) { - result.push(option); - } + function getAllModulePaths(importingFileName, importedFileName, host) { + var cwd = host.getCurrentDirectory(); + var getCanonicalFileName = ts.hostGetCanonicalFileName(host); + var allFileNames = ts.createMap(); + var importedFileFromNodeModules = false; + forEachFileNameOfModule(importingFileName, importedFileName, host, + /*preferSymlinks*/ true, function (path) { + // dont return value, so we collect everything + allFileNames.set(path, getCanonicalFileName(path)); + importedFileFromNodeModules = importedFileFromNodeModules || ts.pathContainsNodeModules(path); }); - result.push.apply(result, targets); - if (result.length < 2) - return result; // Sort by paths closest to importing file Name directory - var allFileNames = ts.arrayToMap(result, ts.identity, getCanonicalFileName); var sortedPaths = []; - var _loop_18 = function (directory) { + var _loop_20 = function (directory) { var directoryStart = ts.ensureTrailingDirectorySeparator(directory); var pathsInDirectory; allFileNames.forEach(function (canonicalFileName, fileName) { if (ts.startsWith(canonicalFileName, directoryStart)) { - (pathsInDirectory || (pathsInDirectory = [])).push(fileName); + // If the importedFile is from node modules, use only paths in node_modules folder as option + if (!importedFileFromNodeModules || ts.pathContainsNodeModules(fileName)) { + (pathsInDirectory || (pathsInDirectory = [])).push(fileName); + } allFileNames.delete(fileName); } }); @@ -102455,9 +104913,9 @@ var ts; }; var out_directory_1; for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) { - var state_7 = _loop_18(directory); + var state_8 = _loop_20(directory); directory = out_directory_1; - if (state_7 === "break") + if (state_8 === "break") break; } if (allFileNames.size) { @@ -102517,27 +104975,28 @@ var ts; if (!parts) { return undefined; } - var packageJsonContent; - var packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + // Simplify the full file path to something that can be resolved by Node. + var moduleSpecifier = moduleFileName; if (!packageNameOnly) { - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - packageJsonContent = host.fileExists(packageJsonPath) - ? JSON.parse(host.readFile(packageJsonPath)) - : undefined; - var versionPaths = packageJsonContent && packageJsonContent.typesVersions - ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) - : undefined; - if (versionPaths) { - var subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); - if (fromPaths !== undefined) { - moduleFileName = ts.combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + var packageRootIndex = parts.packageRootIndex; + var moduleFileNameForExtensionless = void 0; + while (true) { + // If the module could be imported by a directory name, use that directory's name + var _b = tryDirectoryWithPackageJson(packageRootIndex), moduleFileToTry = _b.moduleFileToTry, packageRootPath = _b.packageRootPath; + if (packageRootPath) { + moduleSpecifier = packageRootPath; + break; + } + if (!moduleFileNameForExtensionless) + moduleFileNameForExtensionless = moduleFileToTry; + // try with next level of directory + packageRootIndex = moduleFileName.indexOf(ts.directorySeparator, packageRootIndex + 1); + if (packageRootIndex === -1) { + moduleSpecifier = getExtensionlessFileName(moduleFileNameForExtensionless); + break; } } } - // Simplify the full file path to something that can be resolved by Node. - // If the module could be imported by a directory name, use that directory's name - var moduleSpecifier = packageNameOnly ? moduleFileName : getDirectoryOrExtensionlessFileName(moduleFileName); var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); // Get a path that's relative to node_modules or the importing file's path // if node_modules folder is in this folder or any of its parent folders, no need to keep it. @@ -102550,17 +105009,34 @@ var ts; var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); // For classic resolution, only allow importing from node_modules/@types, not other node_modules return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; - function getDirectoryOrExtensionlessFileName(path) { - // If the file is the main module, it can be imported by the package name - if (packageJsonContent) { + function tryDirectoryWithPackageJson(packageRootIndex) { + var packageRootPath = moduleFileName.substring(0, packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + var moduleFileToTry = moduleFileName; + if (host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + var versionPaths = packageJsonContent.typesVersions + ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + var subModuleName = moduleFileName.slice(packageRootPath.length + 1); + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths); + if (fromPaths !== undefined) { + moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths); + } + } + // If the file is the main module, it can be imported by the package name var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; if (ts.isString(mainFileRelative)) { var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) { + return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry }; } } } + return { moduleFileToTry: moduleFileToTry }; + } + function getExtensionlessFileName(path) { // We still have a file name - remove the extension var fullModulePathWithoutExtension = ts.removeFileExtension(path); // If the file is /index, it can be imported by its directory name @@ -102965,10 +105441,6 @@ var ts; */ function createProgramHost(system, createProgram) { var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); }); - var host = system; - // TODO: `host` is unused! - // eslint-disable-next-line no-unused-expressions - host; return { useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getNewLine: function () { return system.newLine; }, @@ -102985,7 +105457,6 @@ var ts; trace: function (s) { return system.write(s + system.newLine); }, createDirectory: function (path) { return system.createDirectory(path); }, 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 || ts.createEmitAndSemanticDiagnosticsBuilderProgram }; @@ -103016,20 +105487,23 @@ var ts; /** * Creates the watch compiler host from system for config file in watch mode */ - function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, watchOptionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + function createWatchCompilerHostOfConfigFile(_a) { + var configFileName = _a.configFileName, optionsToExtend = _a.optionsToExtend, watchOptionsToExtend = _a.watchOptionsToExtend, extraFileExtensions = _a.extraFileExtensions, system = _a.system, createProgram = _a.createProgram, reportDiagnostic = _a.reportDiagnostic, reportWatchStatus = _a.reportWatchStatus; var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; host.configFileName = configFileName; host.optionsToExtend = optionsToExtend; host.watchOptionsToExtend = watchOptionsToExtend; + host.extraFileExtensions = extraFileExtensions; return host; } ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, watchOptions, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { + function createWatchCompilerHostOfFilesAndCompilerOptions(_a) { + var rootFiles = _a.rootFiles, options = _a.options, watchOptions = _a.watchOptions, projectReferences = _a.projectReferences, system = _a.system, createProgram = _a.createProgram, reportDiagnostic = _a.reportDiagnostic, reportWatchStatus = _a.reportWatchStatus; var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); host.rootFiles = rootFiles; host.options = options; @@ -103085,12 +105559,30 @@ var ts; return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); } ts.createIncrementalProgram = createIncrementalProgram; - function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptions) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, watchOptions, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend); // TODO: GH#18217 + return ts.createWatchCompilerHostOfFilesAndCompilerOptions({ + rootFiles: rootFilesOrConfigFileName, + options: options, + watchOptions: watchOptionsOrExtraFileExtensions, + projectReferences: projectReferencesOrWatchOptionsToExtend, + system: system, + createProgram: createProgram, + reportDiagnostic: reportDiagnostic, + reportWatchStatus: reportWatchStatus, + }); } else { - return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, projectReferencesOrWatchOptionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus); + return ts.createWatchCompilerHostOfConfigFile({ + configFileName: rootFilesOrConfigFileName, + optionsToExtend: options, + watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend, + extraFileExtensions: watchOptionsOrExtraFileExtensions, + system: system, + createProgram: createProgram, + reportDiagnostic: reportDiagnostic, + reportWatchStatus: reportWatchStatus, + }); } } ts.createWatchCompilerHost = createWatchCompilerHost; @@ -103106,16 +105598,13 @@ var ts; var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); var currentDirectory = host.getCurrentDirectory(); - var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, createProgram = host.createProgram; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram; var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences; var configFileSpecs; var configFileParsingDiagnostics; var canConfigFileJsonReportNoInputFiles = false; var hasChangedConfigFileParsingErrors = false; var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); - if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { - host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); - } var directoryStructureHost = cachedDirectoryStructureHost || host; var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost); // From tsc we want to get already parsed result and hence check for rootFileNames @@ -103156,6 +105645,7 @@ var ts; // Members for ResolutionCacheHost compilerHost.toPath = toPath; compilerHost.getCompilationSettings = function () { return compilerOptions; }; + compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect); compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); }; compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); }; compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; }; @@ -103165,7 +105655,6 @@ var ts; scheduleProgramUpdate(); }; compilerHost.fileIsOpen = ts.returnFalse; - compilerHost.maxNumberOfFilesToIterateForInvalidation = host.maxNumberOfFilesToIterateForInvalidation; compilerHost.getCurrentProgram = getCurrentProgram; compilerHost.writeLog = writeLog; // Cache for the module resolution @@ -103198,8 +105687,8 @@ var ts; // Update the wild card directory watch watchConfigFileWildCardDirectories(); return configFileName ? - { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close: close } : - { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames, close: close }; + { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close }; function close() { resolutionCache.clear(); ts.clearMap(sourceFilesCache, function (value) { @@ -103247,7 +105736,7 @@ var ts; else { createNewProgram(hasInvalidatedResolution); } - if (host.afterProgramCreate) { + if (host.afterProgramCreate && program !== builderProgram) { host.afterProgramCreate(builderProgram); } return builderProgram; @@ -103263,6 +105752,7 @@ var ts; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + hasChangedAutomaticTypeDirectiveNames = false; builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches @@ -103307,7 +105797,7 @@ var ts; // If file is missing on host from cache, we can definitely say file doesnt exist // otherwise we need to ensure from the disk if (isFileMissingOnHost(sourceFilesCache.get(path))) { - return true; + return false; } return directoryStructureHost.fileExists(fileName); } @@ -103404,16 +105894,19 @@ var ts; host.clearTimeout(timerToUpdateProgram); } writeLog("Scheduling update"); - timerToUpdateProgram = host.setTimeout(updateProgram, 250); + timerToUpdateProgram = host.setTimeout(updateProgramWithWatchStatus, 250); } function scheduleProgramReload() { ts.Debug.assert(!!configFileName); reloadLevel = ts.ConfigFileProgramReloadLevel.Full; scheduleProgramUpdate(); } - function updateProgram() { + function updateProgramWithWatchStatus() { timerToUpdateProgram = undefined; reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + updateProgram(); + } + function updateProgram() { switch (reloadLevel) { case ts.ConfigFileProgramReloadLevel.Partial: ts.perfLogger.logStartUpdateProgram("PartialConfigReload"); @@ -103429,6 +105922,7 @@ var ts; break; } ts.perfLogger.logStopUpdateProgram("Done"); + return getCurrentBuilderProgram(); } function reloadFileNamesFromConfigFile() { writeLog("Reloading new file names and options"); @@ -103453,7 +105947,7 @@ var ts; watchConfigFileWildCardDirectories(); } function parseConfigFile() { - setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend)); // TODO: GH#18217 + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217 } function setConfigFileParsingResult(configFileParseResult) { rootFileNames = configFileParseResult.fileNames; @@ -103693,7 +106187,7 @@ var ts; if (!compilerHost.resolveModuleNames) { var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; }; compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) { - return ts.loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, redirectedReference, loader_3); + return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3); }; } var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; @@ -104103,14 +106597,14 @@ var ts; } } function getSyntaxDiagnostics(cancellationToken) { - ts.Debug.assertDefined(program); + ts.Debug.assertIsDefined(program); handleDiagnostics(__spreadArrays(program.getConfigFileParsingDiagnostics(), program.getOptionsDiagnostics(cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken)), BuildResultFlags.SyntaxErrors, "Syntactic"); } function getSemanticDiagnostics(cancellationToken) { - handleDiagnostics(ts.Debug.assertDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken), BuildResultFlags.TypeErrors, "Semantic"); + handleDiagnostics(ts.Debug.checkDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken), BuildResultFlags.TypeErrors, "Semantic"); } function emit(writeFileCallback, cancellationToken, customTransformers) { - ts.Debug.assertDefined(program); + ts.Debug.assertIsDefined(program); ts.Debug.assert(step === Step.Emit); // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly program.backupState(); @@ -104244,11 +106738,11 @@ var ts; emitBundle(writeFile, customTransformers); break; case Step.BuildInvalidatedProjectOfBundle: - ts.Debug.assertDefined(invalidatedProjectOfBundle).done(cancellationToken); + ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken); step = Step.Done; break; case Step.QueueReferencingProjects: - queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, ts.Debug.assertDefined(buildResult)); + queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, ts.Debug.checkDefined(buildResult)); step++; break; // Should never be done @@ -105503,6 +107997,7 @@ var ts; placeOpenBraceOnNewLineForFunctions: false, placeOpenBraceOnNewLineForControlBlocks: false, semicolons: SemicolonPreference.Ignore, + trimTrailingWhitespace: true }; } ts.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; @@ -105757,7 +108252,7 @@ var ts; case 247 /* TypeAliasDeclaration */: case 173 /* TypeLiteral */: return 2 /* Type */; - case 321 /* JSDocTypedefTag */: + case 322 /* 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 284 /* EnumMember */: @@ -105793,7 +108288,11 @@ var ts; if (node.kind === 290 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 259 /* ExportAssignment */ || node.parent.kind === 265 /* ExternalModuleReference */) { + else if (node.parent.kind === 259 /* ExportAssignment */ + || node.parent.kind === 265 /* ExternalModuleReference */ + || node.parent.kind === 258 /* ImportSpecifier */ + || node.parent.kind === 255 /* ImportClause */ + || ts.isImportEqualsDeclaration(node.parent) && node === node.parent.name) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -106074,8 +108573,8 @@ var ts; return "class" /* classElement */; case 246 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; case 247 /* TypeAliasDeclaration */: - case 314 /* JSDocCallbackTag */: - case 321 /* JSDocTypedefTag */: + case 315 /* JSDocCallbackTag */: + case 322 /* JSDocTypedefTag */: return "type" /* typeElement */; case 248 /* EnumDeclaration */: return "enum" /* enumElement */; case 242 /* VariableDeclaration */: @@ -106989,7 +109488,7 @@ var ts; function getPossibleGenericSignatures(called, typeArgumentCount, checker) { var type = checker.getTypeAtLocation(called); if (ts.isOptionalChain(called.parent)) { - type = removeOptionality(type, !!called.parent.questionDotToken, /*isOptionalChain*/ true); + type = removeOptionality(type, ts.isOptionalChainRoot(called.parent), /*isOptionalChain*/ true); } var signatures = ts.isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); return signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount; }); @@ -107212,10 +109711,28 @@ var ts; var range = isInComment(sourceFile, position, /*tokenAtPosition*/ undefined); return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end)); } + function getReplacementSpanForContextToken(contextToken) { + if (!contextToken) + return undefined; + switch (contextToken.kind) { + case 10 /* StringLiteral */: + case 14 /* NoSubstitutionTemplateLiteral */: + return createTextSpanFromStringLiteralLikeContent(contextToken); + default: + return createTextSpanFromNode(contextToken); + } + } + ts.getReplacementSpanForContextToken = getReplacementSpanForContextToken; function createTextSpanFromNode(node, sourceFile, endNode) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), (endNode || node).getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextSpanFromStringLiteralLikeContent(node) { + if (node.isUnterminated) + return undefined; + return ts.createTextSpanFromBounds(node.getStart() + 1, node.getEnd() - 1); + } + ts.createTextSpanFromStringLiteralLikeContent = createTextSpanFromStringLiteralLikeContent; function createTextRangeFromNode(node, sourceFile) { return ts.createRange(node.getStart(sourceFile), node.end); } @@ -107300,6 +109817,10 @@ var ts; : ts.isPrivateIdentifier(name) ? ts.idText(name) : ts.getTextOfIdentifierOrLiteral(name); } ts.getNameFromPropertyName = getNameFromPropertyName; + function programContainsModules(program) { + return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!(s.externalModuleIndicator || s.commonJsModuleIndicator); }); + } + ts.programContainsModules = programContainsModules; function programContainsEs6Modules(program) { return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; }); } @@ -107308,14 +109829,27 @@ var ts; return !!compilerOptions.module || compilerOptions.target >= 2 /* ES2015 */ || !!compilerOptions.noEmit; } ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules; - function hostUsesCaseSensitiveFileNames(host) { - return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false; + function createModuleSpecifierResolutionHost(program, host) { + // Mix in `getProbableSymlinks` from Program when host doesn't have it + // in order for non-Project hosts to have a symlinks cache. + return { + fileExists: function (fileName) { return program.fileExists(fileName); }, + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + readFile: ts.maybeBind(host, host.readFile), + useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), + getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks) || (function () { return program.getProbableSymlinks(); }), + getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation), + getSourceFiles: function () { return program.getSourceFiles(); }, + redirectTargetsMap: program.redirectTargetsMap, + getProjectReferenceRedirect: function (fileName) { return program.getProjectReferenceRedirect(fileName); }, + isSourceOfProjectReferenceRedirect: function (fileName) { return program.isSourceOfProjectReferenceRedirect(fileName); }, + }; } - ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames; - function hostGetCanonicalFileName(host) { - return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); + ts.createModuleSpecifierResolutionHost = createModuleSpecifierResolutionHost; + function getModuleSpecifierResolverHost(program, host) { + return __assign(__assign({}, createModuleSpecifierResolutionHost(program, host)), { getCommonSourceDirectory: function () { return program.getCommonSourceDirectory(); } }); } - ts.hostGetCanonicalFileName = hostGetCanonicalFileName; + ts.getModuleSpecifierResolverHost = getModuleSpecifierResolverHost; function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, quotePreference) { return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : undefined; } @@ -107436,16 +109970,26 @@ var ts; return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); } ts.findModifier = findModifier; - function insertImport(changes, sourceFile, importDecl, blankLineBetween) { - var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + function insertImports(changes, sourceFile, imports, blankLineBetween) { + var decl = ts.isArray(imports) ? imports[0] : imports; + var importKindPredicate = decl.kind === 225 /* VariableStatement */ ? ts.isRequireVariableDeclarationStatement : ts.isAnyImportSyntax; + var lastImportDeclaration = ts.findLast(sourceFile.statements, function (statement) { return importKindPredicate(statement); }); if (lastImportDeclaration) { - changes.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); + if (ts.isArray(imports)) { + changes.insertNodesAfter(sourceFile, lastImportDeclaration, imports); + } + else { + changes.insertNodeAfter(sourceFile, lastImportDeclaration, imports); + } + } + else if (ts.isArray(imports)) { + changes.insertNodesAtTopOfFile(sourceFile, imports, blankLineBetween); } else { - changes.insertNodeAtTopOfFile(sourceFile, importDecl, blankLineBetween); + changes.insertNodeAtTopOfFile(sourceFile, imports, blankLineBetween); } } - ts.insertImport = insertImport; + ts.insertImports = insertImports; function getTypeKeywordOfTypeOnlyImport(importClause, sourceFile) { ts.Debug.assert(importClause.isTypeOnly); return ts.cast(importClause.getChildAt(0, sourceFile), isTypeKeywordToken); @@ -107661,8 +110205,8 @@ var ts; * The default is CRLF. */ function getNewLineOrDefaultFromHost(host, formatSettings) { - return (formatSettings && formatSettings.newLineCharacter) || - (host.getNewLine && host.getNewLine()) || + var _a; + return (formatSettings === null || formatSettings === void 0 ? void 0 : formatSettings.newLineCharacter) || ((_a = host.getNewLine) === null || _a === void 0 ? void 0 : _a.call(host)) || carriageReturnLineFeed; } ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; @@ -107779,14 +110323,14 @@ var ts; var symbol = checker.getSymbolAtLocation(node.name); var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); if (renameInfo && renameInfo.text !== (node.name || node.propertyName).getText()) { - clone = ts.createBindingElement(node.dotDotDotToken, node.propertyName || node.name, renameInfo, node.initializer); + clone = ts.setOriginalNode(ts.createBindingElement(node.dotDotDotToken, node.propertyName || node.name, renameInfo, node.initializer), node); } } else if (renameMap && checker && ts.isIdentifier(node)) { var symbol = checker.getSymbolAtLocation(node); var renameInfo = symbol && renameMap.get(String(ts.getSymbolId(symbol))); if (renameInfo) { - clone = ts.createIdentifier(renameInfo.text); + clone = ts.setOriginalNode(ts.createIdentifier(renameInfo.text), node); } } if (!clone) { @@ -107850,6 +110394,27 @@ var ts; addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); } ts.suppressTrailingTrivia = suppressTrailingTrivia; + function copyComments(sourceNode, targetNode) { + var sourceFile = sourceNode.getSourceFile(); + var text = sourceFile.text; + if (hasLeadingLineBreak(sourceNode, text)) { + copyLeadingComments(sourceNode, targetNode, sourceFile); + } + else { + copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile); + } + copyTrailingComments(sourceNode, targetNode, sourceFile); + } + ts.copyComments = copyComments; + 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 addEmitFlagsRecursively(node, flag, getChild) { ts.addEmitFlags(node, flag); var child = getChild(node); @@ -107943,6 +110508,11 @@ var ts; idx = change.indexOf('"' + name); return idx === -1 ? -1 : idx + 1; } + /* @internal */ + function needsParentheses(expression) { + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + } + ts.needsParentheses = needsParentheses; function getContextualTypeFromParent(node, checker) { var parent = node.parent; switch (parent.kind) { @@ -107962,9 +110532,6 @@ var ts; } ts.getContextualTypeFromParent = getContextualTypeFromParent; function quote(text, preferences) { - if (/^\d+$/.test(text)) { - return text; - } // Editors can pass in undefined or empty string - we want to infer the preference in those cases. var quotePreference = preferences.quotePreference || "auto"; var quoted = JSON.stringify(text); @@ -108012,6 +110579,7 @@ var ts; return checker.getTypeAtLocation(caseClause.parent.parent.expression); } ts.getSwitchedType = getSwitchedType; + ts.ANONYMOUS = "anonymous function"; function getTypeNodeIfAccessible(type, enclosingScope, program, host) { var checker = program.getTypeChecker(); var typeIsAccessible = true; @@ -108023,14 +110591,7 @@ var ts; 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, - } + moduleResolverHost: getModuleSpecifierResolverHost(program, host) }); return typeIsAccessible ? res : undefined; } @@ -108351,6 +110912,63 @@ var ts; return ts.isArray(valueOrArray) ? ts.first(valueOrArray) : valueOrArray; } ts.firstOrOnly = firstOrOnly; + function getNameForExportedSymbol(symbol, scriptTarget) { + if (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */) { + // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. + return ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) + || ts.codefix.moduleSymbolToValidIdentifier(ts.Debug.checkDefined(symbol.parent), scriptTarget); + } + return symbol.name; + } + ts.getNameForExportedSymbol = getNameForExportedSymbol; + /** + * Useful to check whether a string contains another string at a specific index + * without allocating another string or traversing the entire contents of the outer string. + * + * This function is useful in place of either of the following: + * + * ```ts + * // Allocates + * haystack.substr(startIndex, needle.length) === needle + * + * // Full traversal + * haystack.indexOf(needle, startIndex) === startIndex + * ``` + * + * @param haystack The string that potentially contains `needle`. + * @param needle The string whose content might sit within `haystack`. + * @param startIndex The index within `haystack` to start searching for `needle`. + */ + function stringContainsAt(haystack, needle, startIndex) { + var needleLength = needle.length; + if (needleLength + startIndex > haystack.length) { + return false; + } + for (var i = 0; i < needleLength; i++) { + if (needle.charCodeAt(i) !== haystack.charCodeAt(i + startIndex)) + return false; + } + return true; + } + ts.stringContainsAt = stringContainsAt; + function startsWithUnderscore(name) { + return name.charCodeAt(0) === 95 /* _ */; + } + ts.startsWithUnderscore = startsWithUnderscore; + function isGlobalDeclaration(declaration) { + return !isNonGlobalDeclaration(declaration); + } + ts.isGlobalDeclaration = isGlobalDeclaration; + function isNonGlobalDeclaration(declaration) { + var sourceFile = declaration.getSourceFile(); + // If the file is not a module, the declaration is global + if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) { + return false; + } + // If the file is a module written in TypeScript, it still might be in a `declare global` augmentation + return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation); + } + ts.isNonGlobalDeclaration = isNonGlobalDeclaration; // #endregion })(ts || (ts = {})); var ts; @@ -108481,7 +111099,7 @@ var ts; if (templateStack.length > 0) { var lastTemplateStackToken = ts.lastOrUndefined(templateStack); if (lastTemplateStackToken === 15 /* TemplateHead */) { - token = scanner.reScanTemplateToken(); + token = scanner.reScanTemplateToken(/* isTaggedTemplate */ false); // Only pop on a TemplateTail; a TemplateMiddle indicates there is more for us. if (token === 17 /* TemplateTail */) { templateStack.pop(); @@ -109012,18 +111630,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 316 /* JSDocParameterTag */: + case 317 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 320 /* JSDocTemplateTag */: + case 321 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); pos = tag.end; break; - case 319 /* JSDocTypeTag */: + case 320 /* JSDocTypeTag */: processElement(tag.typeExpression); pos = tag.end; break; - case 317 /* JSDocReturnTag */: + case 318 /* JSDocReturnTag */: processElement(tag.typeExpression); pos = tag.end; break; @@ -109327,11 +111945,11 @@ var ts; if (!contextToken || !ts.isStringLiteralLike(contextToken)) return undefined; var entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host); - return convertStringLiteralCompletions(entries, sourceFile, checker, log, preferences); + return convertStringLiteralCompletions(entries, contextToken, sourceFile, checker, log, preferences); } } StringCompletions.getStringLiteralCompletions = getStringLiteralCompletions; - function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { + function convertStringLiteralCompletions(completion, contextToken, sourceFile, checker, log, preferences) { if (completion === undefined) { return undefined; } @@ -109340,11 +111958,17 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 99 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, sourceFile, sourceFile, checker, 99 /* 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 */: { - var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); + var entries = completion.types.map(function (type) { return ({ + name: type.value, + kindModifiers: "" /* none */, + kind: "string" /* string */, + sortText: "0", + replacementSpan: ts.getReplacementSpanForContextToken(contextToken) + }); }); return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; } default: @@ -109511,7 +112135,9 @@ var ts; function stringLiteralCompletionsFromProperties(type) { return type && { kind: 1 /* Properties */, - symbols: type.getApparentProperties().filter(function (prop) { return !ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration); }), + symbols: type.getApparentProperties().filter(function (prop) { + return !ts.isPrivateIdentifierPropertyDeclaration(ts.isTransientSymbol(prop) && prop.syntheticOrigin ? prop.syntheticOrigin.valueDeclaration : prop.valueDeclaration); + }), hasIndexSignature: ts.hasIndexSignature(type) }; } @@ -109943,6 +112569,22 @@ var ts; SortText["AutoImportSuggestions"] = "5"; SortText["JavascriptIdentifiers"] = "6"; })(SortText = Completions.SortText || (Completions.SortText = {})); + /** + * Special values for `CompletionInfo['source']` used to disambiguate + * completion items with the same `name`. (Each completion item must + * have a unique name/source combination, because those two fields + * comprise `CompletionEntryIdentifier` in `getCompletionEntryDetails`. + * + * When the completion item is an auto-import suggestion, the source + * is the module specifier of the suggestion. To avoid collisions, + * the values here should not be a module specifier we would ever + * generate for an auto-import. + */ + var CompletionSource; + (function (CompletionSource) { + /** Completions that require `this.` insertion text */ + CompletionSource["ThisProperty"] = "ThisProperty/"; + })(CompletionSource = Completions.CompletionSource || (Completions.CompletionSource = {})); var SymbolOriginInfoKind; (function (SymbolOriginInfoKind) { SymbolOriginInfoKind[SymbolOriginInfoKind["ThisType"] = 1] = "ThisType"; @@ -109960,7 +112602,7 @@ var ts; return !!(origin.kind & 2 /* SymbolMember */); } function originIsExport(origin) { - return !!(origin.kind & 4 /* Export */); + return !!(origin && origin.kind & 4 /* Export */); } function originIsPromise(origin) { return !!(origin.kind & 8 /* Promise */); @@ -110090,14 +112732,16 @@ var ts; } var entries = []; if (isUncheckedFile(sourceFile, compilerOptions)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, + /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); + getCompletionEntriesFromSymbols(symbols, entries, + /* contextToken */ undefined, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, completionData.isJsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap); } if (keywordFilters !== 0 /* None */) { var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); @@ -110110,7 +112754,7 @@ var ts; } for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { var literal = literals_1[_b]; - entries.push(createCompletionEntryForLiteral(literal)); + entries.push(createCompletionEntryForLiteral(literal, preferences)); } return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } @@ -110134,7 +112778,8 @@ var ts; return; } var realName = ts.unescapeLeadingUnderscores(name); - if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target)) { + if (!uniqueNames.has(realName) && ts.isIdentifierText(realName, target)) { + uniqueNames.add(realName); entries.push({ name: realName, kind: "warning" /* warning */, @@ -110145,26 +112790,27 @@ var ts; } }); } - var completionNameForLiteral = function (literal) { - return typeof literal === "object" ? ts.pseudoBigIntToString(literal) + "n" : JSON.stringify(literal); - }; - function createCompletionEntryForLiteral(literal) { - return { name: completionNameForLiteral(literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority }; + function completionNameForLiteral(literal, preferences) { + return typeof literal === "object" ? ts.pseudoBigIntToString(literal) + "n" : + ts.isString(literal) ? ts.quote(literal, preferences) : JSON.stringify(literal); } - function createCompletionEntry(symbol, sortText, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { + function createCompletionEntryForLiteral(literal, preferences) { + return { name: completionNameForLiteral(literal, preferences), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority }; + } + function createCompletionEntry(symbol, sortText, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { var insertText; - var replacementSpan; + var replacementSpan = ts.getReplacementSpanForContextToken(contextToken); var insertQuestionDot = origin && originIsNullableMember(origin); var useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; if (origin && originIsThisType(origin)) { insertText = needsConvertPropertyAccess - ? "this" + (insertQuestionDot ? "?." : "") + "[" + ts.quote(name, preferences) + "]" + ? "this" + (insertQuestionDot ? "?." : "") + "[" + quotePropertyName(name, preferences) + "]" : "this" + (insertQuestionDot ? "?." : ".") + name; } // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790. // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro. else if ((useBraces || insertQuestionDot) && propertyAccessToConvert) { - insertText = useBraces ? needsConvertPropertyAccess ? "[" + ts.quote(name, preferences) + "]" : "[" + name + "]" : name; + insertText = useBraces ? needsConvertPropertyAccess ? "[" + quotePropertyName(name, preferences) + "]" : "[" + name + "]" : name; if (insertQuestionDot || propertyAccessToConvert.questionDotToken) { insertText = "?." + insertText; } @@ -110219,43 +112865,59 @@ var ts; replacementSpan: replacementSpan, }; } + function quotePropertyName(name, preferences) { + if (/^\d+$/.test(name)) { + return name; + } + return ts.quote(name, preferences); + } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { return localSymbol === recommendedCompletion || !!(localSymbol.flags & 1048576 /* ExportValue */) && checker.getExportSymbolOfSymbol(localSymbol) === recommendedCompletion; } function getSourceFromOrigin(origin) { - return origin && originIsExport(origin) ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; + if (originIsExport(origin)) { + return ts.stripQuotes(origin.moduleSymbol.name); + } + if ((origin === null || origin === void 0 ? void 0 : origin.kind) === 1 /* ThisType */) { + return CompletionSource.ThisProperty; + } } - function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) { + function getCompletionEntriesFromSymbols(symbols, entries, contextToken, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap) { var start = ts.timestamp(); // Tracks unique names. - // We don't set this for global variables or completions from external module exports, because we can have multiple of those. - // Based on the order we add things we will always see locals first, then globals, then module exports. + // Value is set to false for global variables or completions from external module exports, because we can have multiple of those; + // true otherwise. 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_1 = symbols; _i < symbols_1.length; _i++) { var symbol = symbols_1[_i]; var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; - var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); + var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, !!jsxIdentifierExpected); if (!info) { continue; } var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; - if (uniques.has(name)) { + if (uniques.get(name)) { continue; } - var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); + var entry = createCompletionEntry(symbol, symbolToSortTextMap && symbolToSortTextMap[ts.getSymbolId(symbol)] || SortText.LocationPriority, contextToken, location, sourceFile, typeChecker, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); if (!entry) { continue; } - // Latter case tests whether this is a global variable. - if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { // TODO: GH#18217 - uniques.set(name, true); - } + /** True for locals; false for globals, module exports from other files, `this.` completions. */ + var shouldShadowLaterSymbols = !origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); })); + uniques.set(name, shouldShadowLaterSymbols); entries.push(entry); } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); - return uniques; + // Prevent consumers of this map from having to worry about + // the boolean value. Externally, it should be seen as the + // set of all names. + return { + has: function (name) { return uniques.has(name); }, + add: function (name) { return uniques.set(name, true); }, + }; } Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; function getLabelCompletionAtPosition(node) { @@ -110288,7 +112950,7 @@ var ts; } return entries; } - function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host) { + function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences) { var compilerOptions = program.getCompilerOptions(); var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId, host); if (!completionData) { @@ -110298,7 +112960,7 @@ var ts; return { type: "request", request: completionData }; } var symbols = completionData.symbols, literals = completionData.literals, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation; - var literal = ts.find(literals, function (l) { return completionNameForLiteral(l) === entryId.name; }); + var literal = ts.find(literals, function (l) { return completionNameForLiteral(l, preferences) === entryId.name; }); if (literal !== undefined) return { type: "literal", literal: literal }; // Find the symbol with the matching entry name. @@ -110307,20 +112969,12 @@ var ts; // completion entry. return ts.firstDefined(symbols, function (symbol) { var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); + var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind, completionData.isJsxIdentifierExpected); return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer, isTypeOnlyLocation: isTypeOnlyLocation } : undefined; }) || { type: "none" }; } - function getSymbolName(symbol, origin, target) { - return origin && originIsExport(origin) && ((origin.isDefaultExport && symbol.escapedName === "default" /* Default */) || - (symbol.escapedName === "export=" /* ExportEquals */)) - // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. - ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) - || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) - : symbol.name; - } function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) { var typeChecker = program.getTypeChecker(); var compilerOptions = program.getCompilerOptions(); @@ -110330,7 +112984,7 @@ var ts; return Completions.StringCompletions.getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, typeChecker, compilerOptions, host, cancellationToken); } // Compute all the completion symbols again. - var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host); + var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences); switch (symbolCompletion.type) { case "request": { var request = symbolCompletion.request; @@ -110352,7 +113006,7 @@ var ts; } case "literal": { var literal = symbolCompletion.literal; - return createSimpleDetails(completionNameForLiteral(literal), "string" /* string */, typeof literal === "string" ? ts.SymbolDisplayPartKind.stringLiteral : ts.SymbolDisplayPartKind.numericLiteral); + return createSimpleDetails(completionNameForLiteral(literal, preferences), "string" /* string */, typeof literal === "string" ? ts.SymbolDisplayPartKind.stringLiteral : ts.SymbolDisplayPartKind.numericLiteral); } case "none": // Didn't find a symbol with this name. See if we can find a keyword instead. @@ -110383,11 +113037,11 @@ var ts; } var moduleSymbol = symbolOriginInfo.moduleSymbol; var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); - var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; + var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, compilerOptions.target), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } - function getCompletionEntrySymbol(program, log, sourceFile, position, entryId, host) { - var completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host); + function getCompletionEntrySymbol(program, log, sourceFile, position, entryId, host, preferences) { + var completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId, host, preferences); return completion.type === "symbol" ? completion.symbol : undefined; } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; @@ -110512,7 +113166,7 @@ var ts; currentToken = ts.getTokenAtPosition(sourceFile, position); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 322 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 323 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -110552,6 +113206,7 @@ var ts; var isRightOfOpenTag = false; var isStartingCloseTag = false; var isJsxInitializer = false; + var isJsxIdentifierExpected = false; var location = ts.getTouchingPropertyName(sourceFile, position); if (contextToken) { // Bail out if this is a known invalid completion location @@ -110630,6 +113285,7 @@ var ts; case 267 /* JsxSelfClosingElement */: case 266 /* JsxElement */: case 268 /* JsxOpeningElement */: + isJsxIdentifierExpected = true; if (contextToken.kind === 29 /* LessThanToken */) { isRightOfOpenTag = true; location = contextToken; @@ -110641,6 +113297,7 @@ var ts; isJsxInitializer = true; break; case 75 /* Identifier */: + isJsxIdentifierExpected = true; // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. if (parent !== previousToken.parent && @@ -110667,7 +113324,8 @@ var ts; getTypeScriptMemberSymbols(); } else if (isRightOfOpenTag) { - var tagSymbols = ts.Debug.assertEachDefined(typeChecker.getJsxIntrinsicTagNamesAt(location), "getJsxIntrinsicTagNames() should all be defined"); + var tagSymbols = typeChecker.getJsxIntrinsicTagNamesAt(location); + ts.Debug.assertEachIsDefined(tagSymbols, "getJsxIntrinsicTagNames() should all be defined"); tryGetGlobalSymbols(); symbols = tagSymbols.concat(symbols); completionKind = 3 /* MemberLike */; @@ -110710,15 +113368,16 @@ var ts; isJsxInitializer: isJsxInitializer, insideJsDocTagTypeExpression: insideJsDocTagTypeExpression, symbolToSortTextMap: symbolToSortTextMap, - isTypeOnlyLocation: isTypeOnly + isTypeOnlyLocation: isTypeOnly, + isJsxIdentifierExpected: isJsxIdentifierExpected, }; function isTagWithTypeExpression(tag) { switch (tag.kind) { - case 316 /* JSDocParameterTag */: - case 322 /* JSDocPropertyTag */: - case 317 /* JSDocReturnTag */: - case 319 /* JSDocTypeTag */: - case 321 /* JSDocTypedefTag */: + case 317 /* JSDocParameterTag */: + case 323 /* JSDocPropertyTag */: + case 318 /* JSDocReturnTag */: + case 320 /* JSDocTypeTag */: + case 322 /* JSDocTypedefTag */: return true; default: return false; @@ -110743,7 +113402,8 @@ var ts; symbol = ts.skipAlias(symbol, typeChecker); if (symbol.flags & (1536 /* Module */ | 384 /* Enum */)) { // Extract module or enum members - var exportedSymbols = ts.Debug.assertEachDefined(typeChecker.getExportsOfModule(symbol), "getExportsOfModule() should all be defined"); + var exportedSymbols = typeChecker.getExportsOfModule(symbol); + ts.Debug.assertEachIsDefined(exportedSymbols, "getExportsOfModule() should all be defined"); var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess(isImportType ? node : (node.parent), symbol.name); }; var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; var isValidAccess = isNamespaceName @@ -110886,6 +113546,7 @@ var ts; function tryGetGlobalSymbols() { var result = tryGetObjectLikeCompletionSymbols() || tryGetImportOrExportClauseCompletionSymbols() + || tryGetLocalNamedExportCompletionSymbols() || tryGetConstructorCompletion() || tryGetClassLikeCompletionSymbols() || tryGetJsxCompletionSymbols() @@ -110955,7 +113616,8 @@ var ts; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); var symbolMeanings = (isTypeOnly ? 0 /* None */ : 111551 /* Value */) | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */; - symbols = ts.Debug.assertEachDefined(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings), "getSymbolsInScope() should all be defined"); + symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + ts.Debug.assertEachIsDefined(symbols, "getSymbolsInScope() should all be defined"); for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { var symbol = symbols_2[_i]; if (!typeChecker.isArgumentsSymbol(symbol) && @@ -110966,7 +113628,7 @@ var ts; // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 290 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); - if (thisType) { + if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { for (var _a = 0, _b = getPropertiesForCompletion(thisType, typeChecker); _a < _b.length; _a++) { var symbol = _b[_a]; symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { kind: 1 /* ThisType */ }; @@ -111000,20 +113662,17 @@ var ts; filterGlobalCompletion(symbols); } function shouldOfferImportCompletions() { - // If not already a module, must have modules enabled and not currently be in a commonjs module. (TODO: import completions for commonjs) + // If not already a module, must have modules enabled. if (!preferences.includeCompletionsForModuleExports) return false; // If already using ES6 modules, OK to continue using them. - if (sourceFile.externalModuleIndicator) + if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator) return true; - // If already using commonjs, don't introduce ES6. - if (sourceFile.commonJsModuleIndicator) - return false; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) return true; // If some file is using ES6 modules, assume that it's OK to add more. - return ts.programContainsEs6Modules(program); + return ts.programContainsModules(program); } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { @@ -111156,6 +113815,7 @@ var ts; var startTime = ts.timestamp(); log("getSymbolsFromOtherSourceFileExports: Recomputing list" + (detailsEntryId ? " for details entry" : "")); var seenResolvedModules = ts.createMap(); + var seenExports = ts.createMap(); /** Bucket B */ var aliasesToAlreadyIncludedSymbols = ts.createMap(); /** Bucket C */ @@ -111176,17 +113836,20 @@ var ts; } // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. - if (resolvedModuleSymbol !== moduleSymbol && - ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator && !ts.findAncestor(d, ts.isGlobalScopeAugmentation); })) { + if (resolvedModuleSymbol !== moduleSymbol && ts.every(resolvedModuleSymbol.declarations, ts.isNonGlobalDeclaration)) { pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true); } - for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + for (var _i = 0, _a = typeChecker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; + var symbolId = ts.getSymbolId(symbol).toString(); + // `getExportsAndPropertiesOfModule` can include duplicates + if (!ts.addToSeen(seenExports, symbolId)) { + continue; + } // If this is `export { _break as break };` (a keyword) -- skip this and prefer the keyword completion. if (ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.propertyName && ts.isIdentifierANonContextualKeyword(d.name); })) { continue; } - var symbolId = ts.getSymbolId(symbol).toString(); // If `symbol.parent !== moduleSymbol`, this is an `export * from "foo"` re-export. Those don't create new symbols. var isExportStarFromReExport = typeChecker.getMergedSymbol(symbol.parent) !== resolvedModuleSymbol; // If `!!d.parent.parent.moduleSpecifier`, this is `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). @@ -111236,7 +113899,7 @@ var ts; var origin = { kind: 4 /* Export */, moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; results.push({ symbol: symbol, - symbolName: getSymbolName(symbol, origin, target), + symbolName: ts.getNameForExportedSymbol(symbol, target), origin: origin, skipFilter: skipFilter, }); @@ -111425,7 +114088,7 @@ var ts; } if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list - symbols = filterObjectMembersList(typeMembers, ts.Debug.assertDefined(existingMembers)); + symbols = filterObjectMembersList(typeMembers, ts.Debug.checkDefined(existingMembers)); } setSortTextToOptionalMember(); return 1 /* Success */; @@ -111442,8 +114105,6 @@ var ts; * export { | }; * * Relevant symbols are stored in the captured 'symbols' variable. - * - * @returns true if 'symbols' was successfully populated; false otherwise. */ function tryGetImportOrExportClauseCompletionSymbols() { // `import { |` or `import { a as 0, | }` @@ -111451,9 +114112,10 @@ var ts; ? ts.tryCast(contextToken.parent, ts.isNamedImportsOrExports) : undefined; if (!namedImportsOrExports) return 0 /* Continue */; - // cursor is in an import clause - // try to show exported member for imported module + // try to show exported member for imported/re-exported module var moduleSpecifier = (namedImportsOrExports.kind === 257 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent).moduleSpecifier; + if (!moduleSpecifier) + return namedImportsOrExports.kind === 257 /* NamedImports */ ? 2 /* Fail */ : 0 /* Continue */; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); // TODO: GH#18217 if (!moduleSpecifierSymbol) return 2 /* Fail */; @@ -111464,6 +114126,35 @@ var ts; symbols = exports.filter(function (e) { return e.escapedName !== "default" /* Default */ && !existing.get(e.escapedName); }); return 1 /* Success */; } + /** + * Adds local declarations for completions in named exports: + * + * export { | }; + * + * Does not check for the absence of a module specifier (`export {} from "./other"`) + * because `tryGetImportOrExportClauseCompletionSymbols` runs first and handles that, + * preventing this function from running. + */ + function tryGetLocalNamedExportCompletionSymbols() { + var _a; + var namedExports = contextToken && (contextToken.kind === 18 /* OpenBraceToken */ || contextToken.kind === 27 /* CommaToken */) + ? ts.tryCast(contextToken.parent, ts.isNamedExports) + : undefined; + if (!namedExports) { + return 0 /* Continue */; + } + var localsContainer = ts.findAncestor(namedExports, ts.or(ts.isSourceFile, ts.isModuleDeclaration)); + completionKind = 5 /* None */; + isNewIdentifierLocation = false; + (_a = localsContainer.locals) === null || _a === void 0 ? void 0 : _a.forEach(function (symbol, name) { + var _a, _b; + symbols.push(symbol); + if ((_b = (_a = localsContainer.symbol) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has(name)) { + symbolToSortTextMap[ts.getSymbolId(symbol)] = SortText.OptionalMember; + } + }); + return 1 /* Success */; + } /** * Aggregates relevant symbols for completion in class declaration * Relevant symbols are stored in the captured 'symbols' variable. @@ -111692,7 +114383,6 @@ var ts; case 96 /* ImportKeyword */: case 115 /* LetKeyword */: case 81 /* ConstKeyword */: - case 121 /* YieldKeyword */: case 145 /* TypeKeyword */: // type htm| return true; case 41 /* AsteriskToken */: @@ -111729,7 +114419,6 @@ var ts; case 119 /* PublicKeyword */: case 120 /* StaticKeyword */: case 109 /* VarKeyword */: - case 121 /* YieldKeyword */: return true; case 126 /* AsyncKeyword */: return ts.isPropertyDeclaration(contextToken.parent); @@ -111816,7 +114505,7 @@ var ts; }); } } - // Set SortText to OptionalMember if it is an optinoal member + // Set SortText to OptionalMember if it is an optional member function setSortTextToOptionalMember() { symbols.forEach(function (m) { if (m.flags & 16777216 /* Optional */) { @@ -111872,7 +114561,8 @@ var ts; return baseSymbols.filter(function (propertySymbol) { return !existingMemberNames.has(propertySymbol.escapedName) && !!propertySymbol.declarations && - !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */); + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */) && + !ts.isPrivateIdentifierPropertyDeclaration(propertySymbol.valueDeclaration); }); } /** @@ -111905,8 +114595,8 @@ var ts; return node.getStart(sourceFile) <= position && position <= node.getEnd(); } } - function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { - var name = getSymbolName(symbol, origin, target); + function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, jsxIdentifierExpected) { + var name = originIsExport(origin) ? ts.getNameForExportedSymbol(symbol, target) : symbol.name; if (name === undefined // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) @@ -111916,7 +114606,7 @@ var ts; return undefined; } var validNameResult = { name: name, needsConvertPropertyAccess: false }; - if (ts.isIdentifierText(name, target) || symbol.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) { + if (ts.isIdentifierText(name, target, jsxIdentifierExpected ? 1 /* JSX */ : 0 /* Standard */) || symbol.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) { return validNameResult; } switch (kind) { @@ -112081,8 +114771,8 @@ var ts; */ function getPropertiesForCompletion(type, checker) { return type.isUnion() - ? ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined") - : ts.Debug.assertEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined"); + ? ts.Debug.checkEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined") + : ts.Debug.checkEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined"); } /** * Returns the immediate owning class declaration of a context token, @@ -112091,7 +114781,7 @@ var ts; function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position) { // class c { method() { } | method2() { } } switch (location.kind) { - case 323 /* SyntaxList */: + case 324 /* 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); @@ -112099,10 +114789,16 @@ var ts; return cls; } break; - case 75 /* Identifier */: // class c extends React.Component { a: () => 1\n compon| } + case 75 /* Identifier */: { + // class c { public prop = c| } + if (ts.isPropertyDeclaration(location.parent) && location.parent.initializer === location) { + return undefined; + } + // class c extends React.Component { a: () => 1\n compon| } if (isFromObjectTypeDeclaration(location)) { return ts.findAncestor(location, ts.isObjectTypeDeclaration); } + } } if (!contextToken) return undefined; @@ -112170,6 +114866,24 @@ var ts; } } } + /** Determines if a type is exactly the same type resolved by the global 'self', 'global', or 'globalThis'. */ + function isProbablyGlobalType(type, sourceFile, checker) { + // The type of `self` and `window` is the same in lib.dom.d.ts, but `window` does not exist in + // lib.webworker.d.ts, so checking against `self` is also a check against `window` when it exists. + var selfSymbol = checker.resolveName("self", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false); + if (selfSymbol && checker.getTypeOfSymbolAtLocation(selfSymbol, sourceFile) === type) { + return true; + } + var globalSymbol = checker.resolveName("global", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false); + if (globalSymbol && checker.getTypeOfSymbolAtLocation(globalSymbol, sourceFile) === type) { + return true; + } + var globalThisSymbol = checker.resolveName("globalThis", /*location*/ undefined, 111551 /* Value */, /*excludeGlobals*/ false); + if (globalThisSymbol && checker.getTypeOfSymbolAtLocation(globalThisSymbol, sourceFile) === type) { + return true; + } + return false; + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); var ts; @@ -112710,7 +115424,7 @@ var ts; return releaseDocumentWithKey(path, key); } function releaseDocumentWithKey(path, key) { - var bucket = ts.Debug.assertDefined(buckets.get(key)); + var bucket = ts.Debug.checkDefined(buckets.get(key)); var entry = bucket.get(path); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); @@ -113176,7 +115890,7 @@ var ts; } function getExportAssignmentExport(ex) { // Get the symbol for the `export =` node; its parent is the module it's the export of. - var exportingModuleSymbol = ts.Debug.assertDefined(ex.symbol.parent, "Expected export symbol to have a parent"); + var exportingModuleSymbol = ts.Debug.checkDefined(ex.symbol.parent, "Expected export symbol to have a parent"); var exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */; return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } }; } @@ -113192,11 +115906,7 @@ var ts; default: return undefined; } - var sym = useLhsSymbol ? checker.getSymbolAtLocation(ts.cast(node.left, ts.isPropertyAccessExpression).name) : symbol; - // Better detection for GH#20803 - if (sym && !(checker.getMergedSymbol(sym.parent).flags & 1536 /* Module */)) { - ts.Debug.fail("Special property assignment kind does not have a module as its parent. Assignment is " + ts.Debug.formatSymbol(sym) + ", parent is " + ts.Debug.formatSymbol(sym.parent)); - } + var sym = useLhsSymbol ? checker.getSymbolAtLocation(ts.getNameOfAccessExpression(ts.cast(node.left, ts.isAccessExpression))) : symbol; return sym && exportInfo(sym, kind); } } @@ -113234,17 +115944,17 @@ var ts; FindAllReferences.getImportOrExportSymbol = getImportOrExportSymbol; function getExportEqualsLocalSymbol(importedSymbol, checker) { if (importedSymbol.flags & 2097152 /* Alias */) { - return ts.Debug.assertDefined(checker.getImmediateAliasedSymbol(importedSymbol)); + return ts.Debug.checkDefined(checker.getImmediateAliasedSymbol(importedSymbol)); } var decl = importedSymbol.valueDeclaration; if (ts.isExportAssignment(decl)) { // `export = class {}` - return ts.Debug.assertDefined(decl.expression.symbol); + return ts.Debug.checkDefined(decl.expression.symbol); } else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}` - return ts.Debug.assertDefined(decl.right.symbol); + return ts.Debug.checkDefined(decl.right.symbol); } else if (ts.isSourceFile(decl)) { // json module - return ts.Debug.assertDefined(decl.symbol); + return ts.Debug.checkDefined(decl.symbol); } return ts.Debug.fail(); } @@ -113501,7 +116211,29 @@ var ts; FindAllReferences.findReferencedSymbols = findReferencedSymbols; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position); - var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); + var referenceEntries; + var entries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); + if (node.parent.kind === 194 /* PropertyAccessExpression */ + || node.parent.kind === 191 /* BindingElement */ + || node.parent.kind === 195 /* ElementAccessExpression */ + || node.kind === 102 /* SuperKeyword */) { + referenceEntries = entries && __spreadArrays(entries); + } + else { + var queue = entries && __spreadArrays(entries); + var seenNodes = ts.createMap(); + while (queue && queue.length) { + var entry = queue.shift(); + if (!ts.addToSeen(seenNodes, ts.getNodeId(entry.node))) { + continue; + } + referenceEntries = ts.append(referenceEntries, entry); + var entries_1 = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, entry.node, entry.node.pos); + if (entries_1) { + queue.push.apply(queue, entries_1); + } + } + } var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } @@ -113742,8 +116474,8 @@ var ts; case 253 /* ImportEqualsDeclaration */: case 258 /* ImportSpecifier */: case 246 /* InterfaceDeclaration */: - case 314 /* JSDocCallbackTag */: - case 321 /* JSDocTypedefTag */: + case 315 /* JSDocCallbackTag */: + case 322 /* JSDocTypedefTag */: case 273 /* JsxAttribute */: case 249 /* ModuleDeclaration */: case 252 /* NamespaceExportDeclaration */: @@ -113769,8 +116501,8 @@ var ts; return !!decl.initializer || ts.isCatchClause(decl.parent); case 160 /* MethodSignature */: case 158 /* PropertySignature */: - case 322 /* JSDocPropertyTag */: - case 316 /* JSDocParameterTag */: + case 323 /* JSDocPropertyTag */: + case 317 /* JSDocParameterTag */: return false; default: return ts.Debug.failBadSyntaxKind(decl); @@ -113927,20 +116659,22 @@ var ts; }; } }); - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - switch (decl.kind) { - case 290 /* 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 249 /* ModuleDeclaration */: - if (sourceFilesSet.has(decl.getSourceFile().fileName)) { - references.push(nodeEntry(decl.name)); - } - break; - default: - // This may be merged with something. - ts.Debug.assert(!!(symbol.flags & 33554432 /* Transient */), "Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + if (symbol.declarations) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + switch (decl.kind) { + case 290 /* 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 249 /* ModuleDeclaration */: + if (sourceFilesSet.has(decl.getSourceFile().fileName)) { + references.push(nodeEntry(decl.name)); + } + break; + default: + // This may be merged with something. + ts.Debug.assert(!!(symbol.flags & 33554432 /* Transient */), "Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); + } } } var exported = symbol.exports.get("export=" /* ExportEquals */); @@ -113951,7 +116685,7 @@ var ts; if (sourceFilesSet.has(sourceFile.fileName)) { // At `module.exports = ...`, reference node is `module` var node = ts.isBinaryExpression(decl) && ts.isPropertyAccessExpression(decl.left) ? decl.left.expression : - ts.isExportAssignment(decl) ? ts.Debug.assertDefined(ts.findChildOfKind(decl, 89 /* ExportKeyword */, sourceFile)) : + ts.isExportAssignment(decl) ? ts.Debug.checkDefined(ts.findChildOfKind(decl, 89 /* ExportKeyword */, sourceFile)) : ts.getNameOfDeclaration(decl) || decl; references.push(nodeEntry(node)); } @@ -114014,7 +116748,7 @@ var ts; } else if (node && node.kind === 84 /* DefaultKeyword */) { addReference(node, symbol, state); - searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); + searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.checkDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, options.use === 2 /* Rename */, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); @@ -114248,6 +116982,8 @@ var ts; } // Go to the symbol we imported from and find references for it. function searchForImportedSymbol(symbol, state) { + if (!symbol.declarations) + return; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var exportingFile = declaration.getSourceFile(); @@ -114333,17 +117069,19 @@ var ts; return exposedByParent ? scope.getSourceFile() : scope; // TODO: GH#18217 } /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */ - function isSymbolReferencedInFile(definition, checker, sourceFile) { - return eachSymbolReferenceInFile(definition, checker, sourceFile, function () { return true; }) || false; + function isSymbolReferencedInFile(definition, checker, sourceFile, searchContainer) { + if (searchContainer === void 0) { searchContainer = sourceFile; } + return eachSymbolReferenceInFile(definition, checker, sourceFile, function () { return true; }, searchContainer) || false; } Core.isSymbolReferencedInFile = isSymbolReferencedInFile; - function eachSymbolReferenceInFile(definition, checker, sourceFile, cb) { + function eachSymbolReferenceInFile(definition, checker, sourceFile, cb, searchContainer) { + if (searchContainer === void 0) { searchContainer = sourceFile; } var symbol = ts.isParameterPropertyDeclaration(definition.parent, definition.parent.parent) ? ts.first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text)) : checker.getSymbolAtLocation(definition); if (!symbol) return undefined; - for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _i < _a.length; _i++) { + for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name, searchContainer); _i < _a.length; _i++) { var token = _a[_i]; if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) continue; @@ -114361,7 +117099,7 @@ var ts; function eachSignatureCall(signature, sourceFiles, checker, cb) { if (!signature.name || !ts.isIdentifier(signature.name)) return; - var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); + var symbol = ts.Debug.checkDefined(checker.getSymbolAtLocation(signature.name)); 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++) { @@ -114548,7 +117286,7 @@ var ts; addRef(); } if (addReferencesHere && state.options.use !== 2 /* Rename */ && state.markSeenReExportRHS(name)) { - addReference(name, ts.Debug.assertDefined(exportSpecifier.symbol), state); + addReference(name, ts.Debug.checkDefined(exportSpecifier.symbol), state); } } else { @@ -114561,7 +117299,7 @@ var ts; var isDefaultExport = referenceLocation.originalKeywordKind === 84 /* DefaultKeyword */ || exportSpecifier.name.originalKeywordKind === 84 /* DefaultKeyword */; var exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */; - var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); + var exportSymbol = ts.Debug.checkDefined(exportSpecifier.symbol); var exportInfo = FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker); if (exportInfo) { searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); @@ -114683,7 +117421,7 @@ var ts; */ function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { var constructorSymbol = getClassConstructorSymbol(classSymbol); - if (constructorSymbol) { + if (constructorSymbol && constructorSymbol.declarations) { for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; var ctrKeyword = ts.findChildOfKind(decl, 129 /* ConstructorKeyword */, sourceFile); @@ -114713,7 +117451,7 @@ var ts; /** Find references to `super` in the constructor of an extending class. */ function findSuperConstructorAccesses(classDeclaration, addNode) { var constructor = getClassConstructorSymbol(classDeclaration.symbol); - if (!constructor) { + if (!(constructor && constructor.declarations)) { return; } for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) { @@ -114838,7 +117576,7 @@ var ts; } // Set the key so that we don't infinitely recurse cachedResults.set(key, false); - var inherits = symbol.declarations.some(function (declaration) { + var inherits = !!symbol.declarations && symbol.declarations.some(function (declaration) { return ts.getAllSuperTypeNodes(declaration).some(function (typeReference) { var type = checker.getTypeAtLocation(typeReference); return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent, cachedResults, checker); @@ -115223,7 +117961,7 @@ var ts; return node.name; if (isConstNamedExpression(node)) return node.parent.name; - return ts.Debug.assertDefined(node.modifiers && ts.find(node.modifiers, isDefaultModifier)); + return ts.Debug.checkDefined(node.modifiers && ts.find(node.modifiers, isDefaultModifier)); } function isDefaultModifier(node) { return node.kind === 84 /* DefaultKeyword */; @@ -115245,7 +117983,7 @@ var ts; } } var declName = isConstNamedExpression(node) ? node.parent.name : - ts.Debug.assertDefined(ts.getNameOfDeclaration(node), "Expected call hierarchy item to have a name"); + ts.Debug.checkDefined(ts.getNameOfDeclaration(node), "Expected call hierarchy item to have a name"); var text = ts.isIdentifier(declName) ? ts.idText(declName) : ts.isStringOrNumericLiteralLike(declName) ? declName.text : ts.isComputedPropertyName(declName) ? @@ -115652,8 +118390,8 @@ var ts; var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; }); var matchers = ts.getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory); // If there isn't some include for this, add a new one. - if (ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && - !ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + if (ts.getRegexFromPattern(ts.Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(oldFileOrDirPath) && + !ts.getRegexFromPattern(ts.Debug.checkDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath))); } } @@ -115732,7 +118470,7 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, ts.createModuleSpecifierResolutionHost(program, host), importLiteral.text) : undefined; }); }; @@ -116057,7 +118795,7 @@ var ts; function getConstructSignatureDefinition() { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class - if (symbol.flags & 32 /* Class */ && !(symbol.flags & 16 /* Function */) && (ts.isNewExpressionTarget(node) || node.kind === 129 /* ConstructorKeyword */)) { + if (symbol.flags & 32 /* Class */ && !(symbol.flags & (16 /* Function */ | 3 /* Variable */)) && (ts.isNewExpressionTarget(node) || node.kind === 129 /* ConstructorKeyword */)) { var cls = ts.find(filteredDeclarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration"); return getSignatureDefinition(cls.members, /*selectConstructors*/ true); } @@ -116250,11 +118988,11 @@ var ts; JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 316 /* JSDocParameterTag */: - case 322 /* JSDocPropertyTag */: + case 317 /* JSDocParameterTag */: + case 323 /* JSDocPropertyTag */: return [declaration]; - case 314 /* JSDocCallbackTag */: - case 321 /* JSDocTypedefTag */: + case 315 /* JSDocCallbackTag */: + case 322 /* JSDocTypedefTag */: return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); @@ -116275,16 +119013,18 @@ var ts; function getCommentText(tag) { var comment = tag.comment; switch (tag.kind) { + case 308 /* JSDocImplementsTag */: + return withNode(tag.class); case 307 /* JSDocAugmentsTag */: return withNode(tag.class); - case 320 /* JSDocTemplateTag */: + case 321 /* JSDocTemplateTag */: return withList(tag.typeParameters); - case 319 /* JSDocTypeTag */: + case 320 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 321 /* JSDocTypedefTag */: - case 314 /* JSDocCallbackTag */: - case 322 /* JSDocPropertyTag */: - case 316 /* JSDocParameterTag */: + case 322 /* JSDocTypedefTag */: + case 315 /* JSDocCallbackTag */: + case 323 /* JSDocPropertyTag */: + case 317 /* JSDocParameterTag */: var name = tag.name; return name ? withNode(name) : comment; default: @@ -116484,6 +119224,8 @@ var ts; // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. return commentOwner.parent.kind === 249 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 226 /* ExpressionStatement */: + return getCommentOwnerInfoWorker(commentOwner.expression); case 209 /* BinaryExpression */: { var be = commentOwner; if (ts.getAssignmentDeclarationKind(be) === 0 /* None */) { @@ -116492,6 +119234,11 @@ var ts; var parameters_2 = ts.isFunctionLike(be.right) ? be.right.parameters : ts.emptyArray; return { commentOwner: commentOwner, parameters: parameters_2 }; } + case 159 /* PropertyDeclaration */: + var init = commentOwner.initializer; + if (init && (ts.isFunctionExpression(init) || ts.isArrowFunction(init))) { + return { commentOwner: commentOwner, parameters: init.parameters }; + } } } /** @@ -117315,8 +120062,8 @@ var ts; case 249 /* ModuleDeclaration */: case 290 /* SourceFile */: case 247 /* TypeAliasDeclaration */: - case 321 /* JSDocTypedefTag */: - case 314 /* JSDocCallbackTag */: + case 322 /* JSDocTypedefTag */: + case 315 /* JSDocCallbackTag */: return true; case 202 /* ArrowFunction */: case 244 /* FunctionDeclaration */: @@ -117553,7 +120300,7 @@ var ts; } // Delete any subsequent imports. for (var i = 1; i < oldImportDecls.length; i++) { - changeTracker.delete(sourceFile, oldImportDecls[i]); + changeTracker.deleteNode(sourceFile, oldImportDecls[i]); } } } @@ -117689,7 +120436,9 @@ var ts; : namedImports.length === 0 ? ts.createNamedImports(sortedImportSpecifiers) : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); // TODO: GH#18217 - // Type-only imports are not allowed to combine + // Type-only imports are not allowed to mix default, namespace, and named imports in any combination. + // We could rewrite a default import as a named import (`import { default as name }`), but we currently + // choose not to as a stylistic preference. if (isTypeOnly && newDefaultImport && newNamedImports) { coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, /*namedBindings*/ undefined)); coalescedImports.push(updateImportDeclarationAndClause((_a = namedImports[0]) !== null && _a !== void 0 ? _a : importDecl, /*name*/ undefined, newNamedImports)); @@ -117837,7 +120586,8 @@ var ts; function addNodeOutliningSpans(sourceFile, cancellationToken, out) { var depthRemaining = 40; var current = 0; - var statements = sourceFile.statements; + // Includes the EOF Token so that comments which aren't attached to statements are included + var statements = __spreadArrays(sourceFile.statements, [sourceFile.endOfFileToken]); var n = statements.length; while (current < n) { while (current < n && !ts.isAnyImportSyntax(statements[current])) { @@ -117861,7 +120611,7 @@ var ts; if (depthRemaining === 0) return; cancellationToken.throwIfCancellationRequested(); - if (ts.isDeclaration(n)) { + if (ts.isDeclaration(n) || n.kind === 1 /* EndOfFileToken */) { addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out); } if (isFunctionExpressionAssignedToVariable(n)) { @@ -118019,7 +120769,11 @@ var ts; case 246 /* InterfaceDeclaration */: case 248 /* EnumDeclaration */: case 251 /* CaseBlock */: + case 173 /* TypeLiteral */: return spanForNode(n); + case 277 /* CaseClause */: + case 278 /* DefaultClause */: + return spanForNodeArray(n.statements); case 193 /* ObjectLiteralExpression */: return spanForObjectOrArrayLiteral(n); case 192 /* ArrayLiteralExpression */: @@ -118074,6 +120828,9 @@ var ts; var closeToken = ts.findChildOfKind(n, close, sourceFile); return openToken && closeToken && spanBetweenTokens(openToken, closeToken, hintSpanNode, sourceFile, autoCollapse, useFullStart); } + function spanForNodeArray(nodeArray) { + return nodeArray.length ? createOutliningSpan(ts.createTextSpanFromRange(nodeArray), "code" /* Code */) : undefined; + } } function functionSpan(node, body, sourceFile) { var openToken = ts.isNodeArrayMultiLine(node.parameters, sourceFile) @@ -118640,7 +121397,7 @@ var ts; token = nextToken(); if (token === 20 /* OpenParenToken */) { token = nextToken(); - if (token === 10 /* StringLiteral */) { + if (token === 10 /* StringLiteral */ || token === 14 /* NoSubstitutionTemplateLiteral */) { // import("mod"); recordModuleName(); return true; @@ -118652,6 +121409,18 @@ var ts; return true; } else { + if (token === 145 /* TypeKeyword */) { + var skipTypeKeyword = ts.scanner.lookAhead(function () { + var token = ts.scanner.scan(); + return token !== 149 /* FromKeyword */ && (token === 41 /* AsteriskToken */ || + token === 18 /* OpenBraceToken */ || + token === 75 /* Identifier */ || + ts.isKeyword(token)); + }); + if (skipTypeKeyword) { + token = nextToken(); + } + } if (token === 75 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); if (token === 149 /* FromKeyword */) { @@ -118722,6 +121491,16 @@ var ts; if (token === 89 /* ExportKeyword */) { markAsExternalModuleIfTopLevel(); token = nextToken(); + if (token === 145 /* TypeKeyword */) { + var skipTypeKeyword = ts.scanner.lookAhead(function () { + var token = ts.scanner.scan(); + return token === 41 /* AsteriskToken */ || + token === 18 /* OpenBraceToken */; + }); + if (skipTypeKeyword) { + token = nextToken(); + } + } if (token === 18 /* OpenBraceToken */) { token = nextToken(); // consume "{ a as B, c, d as D}" clauses @@ -118753,6 +121532,16 @@ var ts; } else if (token === 96 /* ImportKeyword */) { token = nextToken(); + if (token === 145 /* TypeKeyword */) { + var skipTypeKeyword = ts.scanner.lookAhead(function () { + var token = ts.scanner.scan(); + return token === 75 /* Identifier */ || + ts.isKeyword(token); + }); + if (skipTypeKeyword) { + token = nextToken(); + } + } if (token === 75 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); if (token === 62 /* EqualsToken */) { @@ -118766,13 +121555,15 @@ var ts; } return false; } - function tryConsumeRequireCall(skipCurrentToken) { + function tryConsumeRequireCall(skipCurrentToken, allowTemplateLiterals) { + if (allowTemplateLiterals === void 0) { allowTemplateLiterals = false; } var token = skipCurrentToken ? nextToken() : ts.scanner.getToken(); if (token === 139 /* RequireKeyword */) { token = nextToken(); if (token === 20 /* OpenParenToken */) { token = nextToken(); - if (token === 10 /* StringLiteral */) { + if (token === 10 /* StringLiteral */ || + allowTemplateLiterals && token === 14 /* NoSubstitutionTemplateLiteral */) { // require("mod"); recordModuleName(); } @@ -118789,7 +121580,7 @@ var ts; return true; } token = nextToken(); - if (token === 10 /* StringLiteral */) { + if (token === 10 /* StringLiteral */ || token === 14 /* NoSubstitutionTemplateLiteral */) { // looks like define ("modname", ... - skip string literal and comma token = nextToken(); if (token === 27 /* CommaToken */) { @@ -118809,7 +121600,7 @@ var ts; // scan until ']' or EOF while (token !== 23 /* CloseBracketToken */ && token !== 1 /* EndOfFileToken */) { // record string literals as module names - if (token === 10 /* StringLiteral */) { + if (token === 10 /* StringLiteral */ || token === 14 /* NoSubstitutionTemplateLiteral */) { recordModuleName(); } token = nextToken(); @@ -118844,7 +121635,8 @@ var ts; if (tryConsumeDeclare() || tryConsumeImport() || tryConsumeExport() || - (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false) || tryConsumeDefine()))) { + (detectJavaScriptImports && (tryConsumeRequireCall(/*skipCurrentToken*/ false, /*allowTemplateLiterals*/ true) || + tryConsumeDefine()))) { continue; } else { @@ -118920,7 +121712,7 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } // Cannot rename `default` as in `import { default as foo } from "./someModule"; - if (ts.isIdentifier(node) && node.originalKeywordKind === 84 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { + if (ts.isIdentifier(node) && node.originalKeywordKind === 84 /* DefaultKeyword */ && symbol.parent && symbol.parent.flags & 1536 /* Module */) { return undefined; } if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { @@ -119134,7 +121926,7 @@ var ts; // few keystrokes. if (ts.isMappedTypeNode(node)) { var _a = node.getChildren(), openBraceToken = _a[0], children = _a.slice(1); - var closeBraceToken = ts.Debug.assertDefined(children.pop()); + var closeBraceToken = ts.Debug.checkDefined(children.pop()); ts.Debug.assertEqual(openBraceToken.kind, 18 /* OpenBraceToken */); ts.Debug.assertEqual(closeBraceToken.kind, 19 /* CloseBraceToken */); // Group `-/+readonly` and `-/+?` @@ -119253,7 +122045,7 @@ var ts; } function createSyntaxList(children) { ts.Debug.assertGreaterThanOrEqual(children.length, 1); - var syntaxList = ts.createNode(323 /* SyntaxList */, children[0].pos, ts.last(children).end); + var syntaxList = ts.createNode(324 /* SyntaxList */, children[0].pos, ts.last(children).end); syntaxList._children = children; return syntaxList; } @@ -119784,7 +122576,7 @@ var ts; var printer = ts.createPrinter({ removeComments: true }); var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { - var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration); })); + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return checker.typeParameterToDeclaration(p, enclosingDeclaration, signatureHelpNodeBuilderFlags); })); printer.writeList(53776 /* TypeParameters */, args, sourceFile, writer); } }); @@ -119801,7 +122593,7 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter, checker, enclosingDeclaration, sourceFile, printer) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + var param = checker.typeParameterToDeclaration(typeParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts: displayParts, isOptional: false }; @@ -119996,23 +122788,8 @@ var ts; return diags.sort(function (d1, d2) { return d1.start - d2.start; }); function check(node) { if (isJsFile) { - switch (node.kind) { - case 201 /* FunctionExpression */: - var decl = ts.getDeclarationOfExpando(node); - if (decl) { - 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; - } - } - // falls through if no diagnostic was created - case 244 /* FunctionDeclaration */: - var symbol = node.symbol; - if (symbol.members && (symbol.members.size > 0)) { - 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; + if (canBeConvertedToClass(node)) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); } } else { @@ -120119,7 +122896,18 @@ var ts; } ts.isFixablePromiseHandler = isFixablePromiseHandler; function isPromiseHandler(node) { - return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") || ts.hasPropertyAccessExpressionWithName(node, "catch")); + return ts.isCallExpression(node) && (ts.hasPropertyAccessExpressionWithName(node, "then") && hasSupportedNumberOfArguments(node) || + ts.hasPropertyAccessExpressionWithName(node, "catch")); + } + function hasSupportedNumberOfArguments(node) { + if (node.arguments.length > 2) + return false; + if (node.arguments.length < 2) + return true; + return ts.some(node.arguments, function (arg) { + return arg.kind === 100 /* NullKeyword */ || + ts.isIdentifier(arg) && arg.text === "undefined"; + }); } // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts function isFixablePromiseArgument(arg) { @@ -120139,12 +122927,28 @@ var ts; function getKeyFromNode(exp) { return exp.pos.toString() + ":" + exp.end.toString(); } + function canBeConvertedToClass(node) { + var _a, _b, _c, _d; + if (node.kind === 201 /* FunctionExpression */) { + if (ts.isVariableDeclaration(node.parent) && ((_a = node.symbol.members) === null || _a === void 0 ? void 0 : _a.size)) { + return true; + } + var decl = ts.getDeclarationOfExpando(node); + var symbol = decl === null || decl === void 0 ? void 0 : decl.symbol; + return !!(symbol && (((_b = symbol.exports) === null || _b === void 0 ? void 0 : _b.size) || ((_c = symbol.members) === null || _c === void 0 ? void 0 : _c.size))); + } + if (node.kind === 244 /* FunctionDeclaration */) { + return !!((_d = node.symbol.members) === null || _d === void 0 ? void 0 : _d.size); + } + return false; + } })(ts || (ts = {})); /* @internal */ var ts; (function (ts) { var SymbolDisplay; (function (SymbolDisplay) { + var symbolDisplayNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 70221824 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; // TODO(drosen): use contextual SemanticMeaning. function getSymbolKind(typeChecker, symbol, location) { var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); @@ -120589,7 +123393,7 @@ var ts; // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration); + var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration, symbolDisplayNodeBuilderFlags); getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); @@ -120731,7 +123535,7 @@ var ts; } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); + var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration, symbolDisplayNodeBuilderFlags); getPrinter().writeList(53776 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); @@ -120905,11 +123709,11 @@ var ts; this.options = options; } FormattingContext.prototype.updateContext = function (currentRange, currentTokenParent, nextRange, nextTokenParent, commonParent) { - this.currentTokenSpan = ts.Debug.assertDefined(currentRange); - this.currentTokenParent = ts.Debug.assertDefined(currentTokenParent); - this.nextTokenSpan = ts.Debug.assertDefined(nextRange); - this.nextTokenParent = ts.Debug.assertDefined(nextTokenParent); - this.contextNode = ts.Debug.assertDefined(commonParent); + this.currentTokenSpan = ts.Debug.checkDefined(currentRange); + this.currentTokenParent = ts.Debug.checkDefined(currentTokenParent); + this.nextTokenSpan = ts.Debug.checkDefined(nextRange); + this.nextTokenParent = ts.Debug.checkDefined(nextTokenParent); + this.contextNode = ts.Debug.checkDefined(commonParent); // drop cached results this.contextNodeAllOnSameLine = undefined; this.nextNodeAllOnSameLine = undefined; @@ -121160,7 +123964,7 @@ var ts; case 3 /* RescanTemplateToken */: if (token === 19 /* CloseBraceToken */) { lastScanAction = 3 /* RescanTemplateToken */; - return scanner.reScanTemplateToken(); + return scanner.reScanTemplateToken(/* isTaggedTemplate */ false); } break; case 4 /* RescanJsxIdentifier */: @@ -121352,7 +124156,7 @@ var ts; rule("SpaceAfterVoidOperator", 110 /* VoidKeyword */, anyToken, [isNonJsxSameLineTokenContext, isVoidOpContext], 4 /* InsertSpace */), // Async-await rule("SpaceBetweenAsyncAndOpenParen", 126 /* AsyncKeyword */, 20 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 4 /* InsertSpace */), - rule("SpaceBetweenAsyncAndFunctionKeyword", 126 /* AsyncKeyword */, 94 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), + rule("SpaceBetweenAsyncAndFunctionKeyword", 126 /* AsyncKeyword */, [94 /* FunctionKeyword */, 75 /* Identifier */], [isNonJsxSameLineTokenContext], 4 /* InsertSpace */), // Template string rule("NoSpaceBetweenTagAndTemplateString", [75 /* Identifier */, 21 /* CloseParenToken */], [14 /* NoSubstitutionTemplateLiteral */, 15 /* TemplateHead */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), // JSX opening elements @@ -121435,7 +124239,7 @@ var ts; // Treat constructor as an identifier in a function declaration, and remove spaces between constructor and following left parentheses rule("SpaceAfterConstructor", 129 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */), rule("NoSpaceAfterConstructor", 129 /* ConstructorKeyword */, 20 /* OpenParenToken */, [isOptionDisabledOrUndefined("insertSpaceAfterConstructor"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("SpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket], 4 /* InsertSpace */), + rule("SpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionEnabled("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext, isNextTokenNotCloseBracket, isNextTokenNotCloseParen], 4 /* InsertSpace */), rule("NoSpaceAfterComma", 27 /* CommaToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterCommaDelimiter"), isNonJsxSameLineTokenContext, isNonJsxElementOrFragmentContext], 16 /* DeleteSpace */), // Insert space after function keyword for anonymous functions rule("SpaceAfterAnonymousFunctionKeyword", [94 /* FunctionKeyword */, 41 /* AsteriskToken */], 20 /* OpenParenToken */, [isOptionEnabled("insertSpaceAfterFunctionKeywordForAnonymousFunctions"), isFunctionDeclContext], 4 /* InsertSpace */), @@ -121462,6 +124266,9 @@ var ts; rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isNonJsxSameLineTokenContext, isObjectContext], 16 /* DeleteSpace */), rule("NoSpaceAfterOpenBrace", 18 /* OpenBraceToken */, anyToken, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceBeforeCloseBrace", anyToken, 19 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + // Insert a space after opening and before closing empty brace brackets + rule("SpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces")], 4 /* InsertSpace */), + rule("NoSpaceBetweenEmptyBraceBrackets", 18 /* OpenBraceToken */, 19 /* CloseBraceToken */, [isOptionDisabled("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces"), isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), // Insert space after opening and before closing template string braces rule("SpaceAfterTemplateHeadAndMiddle", [15 /* TemplateHead */, 16 /* TemplateMiddle */], anyToken, [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */), rule("SpaceBeforeTemplateMiddleAndTail", anyToken, [16 /* TemplateMiddle */, 17 /* TemplateTail */], [isOptionEnabled("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces"), isNonJsxSameLineTokenContext], 4 /* InsertSpace */), @@ -121784,6 +124591,9 @@ var ts; function isNextTokenNotCloseBracket(context) { return context.nextTokenSpan.kind !== 23 /* CloseBracketToken */; } + function isNextTokenNotCloseParen(context) { + return context.nextTokenSpan.kind !== 21 /* CloseParenToken */; + } function isArrowFunctionContext(context) { return context.contextNode.kind === 202 /* ArrowFunction */; } @@ -121960,8 +124770,8 @@ var ts; (function (ts) { var formatting; (function (formatting) { - function getFormatContext(options) { - return { options: options, getRules: getRulesMap() }; + function getFormatContext(options, host) { + return { options: options, getRules: getRulesMap(), host: host }; } formatting.getFormatContext = getFormatContext; var rulesMapCache; @@ -122374,7 +125184,7 @@ var ts; return formatting.getFormattingScanner(sourceFile.text, sourceFile.languageVariant, getScanStartPosition(enclosingNode, originalRange, sourceFile), originalRange.end, function (scanner) { return formatSpanWorker(originalRange, enclosingNode, formatting.SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options), getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile), scanner, formatContext, requestKind, prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange), sourceFile); }); } function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delta, formattingScanner, _a, requestKind, rangeContainsError, sourceFile) { - var options = _a.options, getRules = _a.getRules; + var options = _a.options, getRules = _a.getRules, host = _a.host; // formatting context is used by rules provider var formattingContext = new formatting.FormattingContext(sourceFile, requestKind, options); var previousRange; @@ -122396,7 +125206,9 @@ var ts; var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { indentTriviaItems(leadingTrivia, initialIndentation, /*indentNextTokenOrTrivia*/ false, function (item) { return processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); }); - trimTrailingWhitespacesForRemainingRange(); + if (options.trimTrailingWhitespace !== false) { + trimTrailingWhitespacesForRemainingRange(); + } } } return edits; @@ -122513,8 +125325,8 @@ var ts; }, getIndentation: function () { return indentation; }, getDelta: getDelta, - recomputeIndentation: function (lineAdded) { - if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(options, node.parent, node, sourceFile)) { + recomputeIndentation: function (lineAdded, parent) { + if (formatting.SmartIndenter.shouldIndentChildNode(options, parent, node, sourceFile)) { indentation += lineAdded ? options.indentSize : -options.indentSize; delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0; } @@ -122715,8 +125527,11 @@ var ts; if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) { var tokenInfo = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.kind === 27 /* CommaToken */ && ts.isCallLikeExpression(parent)) { - formattingScanner.advance(); - tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; + var commaTokenLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; + if (startLine !== commaTokenLine) { + formattingScanner.advance(); + tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined; + } } // consume the list end token only if it is still belong to the parent // there might be the case when current token matches end token but does not considered as one @@ -122833,7 +125648,7 @@ var ts; function processPair(currentItem, currentStartLine, currentParent, previousItem, previousStartLine, previousParent, contextNode, dynamicIndentation) { formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode); var rules = getRules(formattingContext); - var trimTrailingWhitespaces = false; + var trimTrailingWhitespaces = formattingContext.options.trimTrailingWhitespace !== false; var lineAction = 0 /* None */; if (rules) { // Apply rules in reverse order so that higher priority rules (which are first in the array) @@ -122845,7 +125660,7 @@ var ts; // Handle the case where the next line is moved to be the end of this line. // In this case we don't indent the next line in the next pass. if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false, contextNode); } break; case 1 /* LineAdded */: @@ -122853,18 +125668,18 @@ var ts; // In this case we indent token2 in the next pass but we set // sameLineIndent flag to notify the indenter that the indentation is within the line. if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true, contextNode); } break; default: ts.Debug.assert(lineAction === 0 /* None */); } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line - trimTrailingWhitespaces = !(rule.action & 16 /* DeleteSpace */) && rule.flags !== 1 /* CanDeleteNewLines */; + trimTrailingWhitespaces = trimTrailingWhitespaces && !(rule.action & 16 /* DeleteSpace */) && rule.flags !== 1 /* CanDeleteNewLines */; }); } else { - trimTrailingWhitespaces = currentItem.kind !== 1 /* EndOfFileToken */; + trimTrailingWhitespaces = trimTrailingWhitespaces && currentItem.kind !== 1 /* EndOfFileToken */; } if (currentStartLine !== previousStartLine && trimTrailingWhitespaces) { // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line @@ -123039,7 +125854,7 @@ var ts; // edit should not be applied if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { - recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); + recordReplace(previousRange.end, currentRange.pos - previousRange.end, ts.getNewLineOrDefaultFromHost(host, options)); return onLaterLine ? 0 /* None */ : 1 /* LineAdded */; } break; @@ -123511,7 +126326,7 @@ var ts; case 214 /* ClassExpression */: case 246 /* InterfaceDeclaration */: case 247 /* TypeAliasDeclaration */: - case 320 /* JSDocTemplateTag */: + case 321 /* JSDocTemplateTag */: return getList(node.typeParameters); case 197 /* NewExpression */: case 196 /* CallExpression */: @@ -123773,6 +126588,15 @@ var ts; * include all trivia between the node and the previous token */ LeadingTriviaOption[LeadingTriviaOption["IncludeAll"] = 1] = "IncludeAll"; + /** + * Include attached JSDoc comments + */ + LeadingTriviaOption[LeadingTriviaOption["JSDoc"] = 2] = "JSDoc"; + /** + * Only delete trivia on the same line as getStart(). + * Used to avoid deleting leading comments + */ + LeadingTriviaOption[LeadingTriviaOption["StartLine"] = 3] = "StartLine"; })(LeadingTriviaOption = textChanges_3.LeadingTriviaOption || (textChanges_3.LeadingTriviaOption = {})); var TrailingTriviaOption; (function (TrailingTriviaOption) { @@ -123815,6 +126639,15 @@ var ts; if (leadingTriviaOption === LeadingTriviaOption.Exclude) { return node.getStart(sourceFile); } + if (leadingTriviaOption === LeadingTriviaOption.StartLine) { + return ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile); + } + if (leadingTriviaOption === LeadingTriviaOption.JSDoc) { + var JSDocComments = ts.getJSDocCommentRanges(node, sourceFile.text); + if (JSDocComments === null || JSDocComments === void 0 ? void 0 : JSDocComments.length) { + return ts.getLineStartPositionForPosition(JSDocComments[0].pos, sourceFile); + } + } var fullStart = node.getFullStart(); var start = node.getStart(sourceFile); if (fullStart === start) { @@ -123904,6 +126737,10 @@ var ts; ChangeTracker.prototype.delete = function (sourceFile, node) { this.deletedNodes.push({ sourceFile: sourceFile, node: node }); }; + ChangeTracker.prototype.deleteNode = function (sourceFile, node, options) { + if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } + this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options)); + }; ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); }; @@ -123963,15 +126800,36 @@ var ts; this.replaceRangeWithNodes(sourceFile, ts.createRange(pos), newNodes, options); }; ChangeTracker.prototype.insertNodeAtTopOfFile = function (sourceFile, newNode, blankLineBetween) { + this.insertAtTopOfFile(sourceFile, newNode, blankLineBetween); + }; + ChangeTracker.prototype.insertNodesAtTopOfFile = function (sourceFile, newNodes, blankLineBetween) { + this.insertAtTopOfFile(sourceFile, newNodes, blankLineBetween); + }; + ChangeTracker.prototype.insertAtTopOfFile = function (sourceFile, insert, blankLineBetween) { var pos = getInsertionPositionAtSourceFileTop(sourceFile); - this.insertNodeAt(sourceFile, pos, newNode, { + var options = { prefix: pos === 0 ? undefined : this.newLineCharacter, suffix: (ts.isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""), - }); + }; + if (ts.isArray(insert)) { + this.insertNodesAt(sourceFile, pos, insert, options); + } + else { + this.insertNodeAt(sourceFile, pos, insert, options); + } + }; + ChangeTracker.prototype.insertFirstParameter = function (sourceFile, parameters, newParam) { + var p0 = ts.firstOrUndefined(parameters); + if (p0) { + this.insertNodeBefore(sourceFile, p0, newParam); + } + else { + this.insertNodeAt(sourceFile, parameters.pos, newParam); + } }; ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) { if (blankLineBetween === void 0) { blankLineBetween = false; } - this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); + this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}), newNode, this.getOptionsForInsertNodeBefore(before, newNode, blankLineBetween)); }; ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { var pos = before.getStart(sourceFile); @@ -124021,6 +126879,7 @@ var ts; }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { + var _a; var endNode; if (ts.isFunctionLike(node)) { endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); @@ -124032,7 +126891,7 @@ var ts; } } else { - endNode = node.kind !== 242 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; + endNode = (_a = (node.kind === 242 /* VariableDeclaration */ ? node.exclamationToken : node.questionToken)) !== null && _a !== void 0 ? _a : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); return true; @@ -124047,7 +126906,7 @@ var ts; var start = (ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile) || ts.first(node.parameters)).getStart(sourceFile); this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">" }); }; - ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, doubleNewlines) { + ChangeTracker.prototype.getOptionsForInsertNodeBefore = function (before, inserted, doubleNewlines) { if (ts.isStatement(before) || ts.isClassElement(before)) { return { suffix: doubleNewlines ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter }; } @@ -124055,7 +126914,7 @@ var ts; return { suffix: ", " }; } else if (ts.isParameter(before)) { - return {}; + return ts.isParameter(inserted) ? { suffix: ", " } : {}; } else if (ts.isStringLiteral(before) && ts.isImportDeclaration(before.parent) || ts.isNamedImports(before)) { return { suffix: ", " }; @@ -124437,7 +127296,7 @@ var ts; var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { - return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { + return ts.mapDefined(ts.group(changes, function (c) { return c.sourceFile.path; }), function (changesInFile) { var sourceFile = changesInFile[0].sourceFile; // 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. @@ -124451,10 +127310,16 @@ var ts; for (var i = 0; i < normalized.length - 1; i++) { _loop_10(i); } - var textChanges = normalized.map(function (c) { - return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); + var textChanges = ts.mapDefined(normalized, function (c) { + var span = ts.createTextSpanFromRange(c.range); + var newText = computeNewText(c, sourceFile, newLineCharacter, formatContext, validate); + // Filter out redundant changes. + if (span.length === newText.length && ts.stringContainsAt(sourceFile.text, newText, span.start)) { + return undefined; + } + return ts.createTextChange(span, newText); }); - return { fileName: sourceFile.fileName, textChanges: textChanges }; + return textChanges.length > 0 ? { fileName: sourceFile.fileName, textChanges: textChanges } : undefined; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; @@ -124485,7 +127350,9 @@ var ts; : format(change.node); // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line var noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, ""); - return (options.prefix || "") + noIndent + (options.suffix || ""); + return (options.prefix || "") + noIndent + + ((!options.suffix || ts.endsWith(noIndent, options.suffix)) + ? "" : options.suffix); } function getFormatCodeSettingsForWriting(_a, sourceFile) { var options = _a.options; @@ -124514,7 +127381,7 @@ var ts; function getNonformattedText(node, sourceFile, newLineCharacter) { var writer = createWriter(newLineCharacter); var newLine = newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */; - ts.createPrinter({ newLine: newLine, neverAsciiEscape: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); + ts.createPrinter({ newLine: newLine, neverAsciiEscape: true, preserveSourceNewlines: true }, writer).writeNode(4 /* Unspecified */, node, sourceFile, writer); return { text: writer.getText(), node: assignPositionsToNode(node) }; } changesToText.getNonformattedText = getNonformattedText; @@ -124635,8 +127502,8 @@ var ts; writer.writeSymbol(s, sym); setLastNonTriviaPosition(s, /*force*/ false); } - function writeLine() { - writer.writeLine(); + function writeLine(force) { + writer.writeLine(force); } function increaseIndent() { writer.increaseIndent(); @@ -124813,10 +127680,10 @@ var ts; break; } case 254 /* ImportDeclaration */: - var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isImportDeclaration); - deleteNode(changes, sourceFile, node, - // For first import, leave header comment in place - isFirstImport ? { leadingTriviaOption: LeadingTriviaOption.Exclude } : undefined); + case 253 /* ImportEqualsDeclaration */: + var isFirstImport = sourceFile.imports.length && node === ts.first(sourceFile.imports).parent || node === ts.find(sourceFile.statements, ts.isAnyImportSyntax); + // For first import, leave header comment in place, otherwise only delete JSDoc comments + deleteNode(changes, sourceFile, node, { leadingTriviaOption: isFirstImport ? LeadingTriviaOption.Exclude : ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; case 191 /* BindingElement */: var pattern = node.parent; @@ -124846,15 +127713,25 @@ var ts; case 256 /* NamespaceImport */: deleteImportBinding(changes, sourceFile, node); break; + case 26 /* SemicolonToken */: + deleteNode(changes, sourceFile, node, { trailingTriviaOption: TrailingTriviaOption.Exclude }); + break; + case 94 /* FunctionKeyword */: + deleteNode(changes, sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.Exclude }); + break; + case 245 /* ClassDeclaration */: + case 244 /* FunctionDeclaration */: + deleteNode(changes, sourceFile, node, { leadingTriviaOption: ts.hasJSDocNodes(node) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); + break; default: if (ts.isImportClause(node.parent) && node.parent.name === node) { deleteDefaultImport(changes, sourceFile, node.parent); } - else if (ts.isCallLikeExpression(node.parent)) { + else if (ts.isCallExpression(node.parent) && ts.contains(node.parent.arguments, node)) { deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } else { - deleteNode(changes, sourceFile, node, node.kind === 26 /* SemicolonToken */ ? { trailingTriviaOption: TrailingTriviaOption.Exclude } : undefined); + deleteNode(changes, sourceFile, node); } } } @@ -124883,7 +127760,7 @@ var ts; // Delete named imports while preserving the default import // import d|, * as ns| from './file' // import d|, { a }| from './file' - var previousToken = ts.Debug.assertDefined(ts.getTokenAtPosition(sourceFile, node.pos - 1)); + var previousToken = ts.Debug.checkDefined(ts.getTokenAtPosition(sourceFile, node.pos - 1)); changes.deleteRange(sourceFile, { pos: previousToken.getStart(sourceFile), end: node.end }); } else { @@ -124915,7 +127792,7 @@ var ts; deleteNode(changes, sourceFile, parent); break; case 225 /* VariableStatement */: - deleteNode(changes, sourceFile, gp); + deleteNode(changes, sourceFile, gp, { leadingTriviaOption: ts.hasJSDocNodes(gp) ? LeadingTriviaOption.JSDoc : LeadingTriviaOption.StartLine }); break; default: ts.Debug.assertNever(gp); @@ -124932,7 +127809,7 @@ var ts; } textChanges_3.deleteNode = deleteNode; function deleteNodeInList(changes, deletedNodesInLists, sourceFile, node) { - var containingList = ts.Debug.assertDefined(ts.formatting.SmartIndenter.getContainingList(node, sourceFile)); + var containingList = ts.Debug.checkDefined(ts.formatting.SmartIndenter.getContainingList(node, sourceFile)); var index = ts.indexOfNode(containingList, node); ts.Debug.assert(index !== -1); if (containingList.length === 1) { @@ -125043,7 +127920,7 @@ var ts; codefix.eachDiagnostic = eachDiagnostic; function getDiagnostics(_a) { var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken; - return program.getSemanticDiagnostics(sourceFile, cancellationToken).concat(ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken)); + return __spreadArrays(program.getSemanticDiagnostics(sourceFile, cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -125091,7 +127968,7 @@ var ts; }); function makeChange(changeTracker, sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - var assertion = ts.Debug.assertDefined(ts.findAncestor(token, function (n) { return ts.isAsExpression(n) || ts.isTypeAssertion(n); }), "Expected to find an assertion expression"); + var assertion = ts.Debug.checkDefined(ts.findAncestor(token, function (n) { return ts.isAsExpression(n) || ts.isTypeAssertion(n); }), "Expected to find an assertion expression"); var replacement = ts.isAsExpression(assertion) ? ts.createAsExpression(assertion.expression, ts.createKeywordTypeNode(148 /* UnknownKeyword */)) : ts.createTypeAssertion(ts.createKeywordTypeNode(148 /* UnknownKeyword */), assertion.expression); @@ -125123,6 +128000,87 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addMissingAsync"; + var errorCodes = [ + ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code, + ts.Diagnostics.Type_0_is_not_comparable_to_type_1.code + ]; + codefix.registerCodeFix({ + fixIds: [fixId], + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, errorCode = context.errorCode, cancellationToken = context.cancellationToken, program = context.program, span = context.span; + var diagnostic = ts.find(program.getDiagnosticsProducingTypeChecker().getDiagnostics(sourceFile, cancellationToken), getIsMatchingAsyncError(span, errorCode)); + var directSpan = diagnostic && diagnostic.relatedInformation && ts.find(diagnostic.relatedInformation, function (r) { return r.code === ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async.code; }); + var decl = getFixableErrorSpanDeclaration(sourceFile, directSpan); + if (!decl) { + return; + } + var trackChanges = function (cb) { return ts.textChanges.ChangeTracker.with(context, cb); }; + return [getFix(context, decl, trackChanges)]; + }, + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile; + var fixedDeclarations = ts.createMap(); + return codefix.codeFixAll(context, errorCodes, function (t, diagnostic) { + var span = diagnostic.relatedInformation && ts.find(diagnostic.relatedInformation, function (r) { return r.code === ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async.code; }); + var decl = getFixableErrorSpanDeclaration(sourceFile, span); + if (!decl) { + return; + } + var trackChanges = function (cb) { return (cb(t), []); }; + return getFix(context, decl, trackChanges, fixedDeclarations); + }); + }, + }); + function getFix(context, decl, trackChanges, fixedDeclarations) { + var changes = trackChanges(function (t) { return makeChange(t, context.sourceFile, decl, fixedDeclarations); }); + return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers); + } + function makeChange(changeTracker, sourceFile, insertionSite, fixedDeclarations) { + if (fixedDeclarations) { + if (fixedDeclarations.has(ts.getNodeId(insertionSite).toString())) { + return; + } + } + fixedDeclarations === null || fixedDeclarations === void 0 ? void 0 : fixedDeclarations.set(ts.getNodeId(insertionSite).toString(), true); + var cloneWithModifier = ts.getSynthesizedDeepClone(insertionSite, /*includeTrivia*/ true); + cloneWithModifier.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(ts.getModifierFlags(insertionSite) | 256 /* Async */)); + cloneWithModifier.modifierFlagsCache = 0; + changeTracker.replaceNode(sourceFile, insertionSite, cloneWithModifier); + } + function getFixableErrorSpanDeclaration(sourceFile, span) { + if (!span) + return undefined; + var token = ts.getTokenAtPosition(sourceFile, span.start); + // Checker has already done work to determine that async might be possible, and has attached + // related info to the node, so start by finding the signature that exactly matches up + // with the diagnostic range. + var decl = ts.findAncestor(token, function (node) { + if (node.getStart(sourceFile) < span.start || node.getEnd() > ts.textSpanEnd(span)) { + return "quit"; + } + return (ts.isArrowFunction(node) || ts.isMethodDeclaration(node) || ts.isFunctionExpression(node) || ts.isFunctionDeclaration(node)) && ts.textSpansEqual(span, ts.createTextSpanFromNode(node, sourceFile)); + }); + return decl; + } + function getIsMatchingAsyncError(span, errorCode) { + return function (_a) { + var start = _a.start, length = _a.length, relatedInformation = _a.relatedInformation, code = _a.code; + return ts.isNumber(start) && ts.isNumber(length) && ts.textSpansEqual({ start: start, length: length }, span) && + code === errorCode && + !!relatedInformation && + ts.some(relatedInformation, function (related) { return related.code === ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async.code; }); + }; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -125307,7 +128265,7 @@ var ts; reference; var diagnostic = ts.find(diagnostics, function (diagnostic) { return diagnostic.start === errorNode.getStart(sourceFile) && - diagnostic.start + diagnostic.length === errorNode.getEnd(); + (diagnostic.start + diagnostic.length) === errorNode.getEnd(); }); return diagnostic && ts.contains(errorCodes, diagnostic.code) || // A Promise is usually not correct in a binary expression (it’s not valid @@ -125641,7 +128599,7 @@ var ts; } } else { - var jsdocType = ts.Debug.assertDefined(ts.getJSDocType(decl), "A JSDocType for this declaration should exist"); // If not defined, shouldn't have been an error to fix + var jsdocType = ts.Debug.checkDefined(ts.getJSDocType(decl), "A JSDocType for this declaration should exist"); // If not defined, shouldn't have been an error to fix ts.Debug.assert(!decl.type, "The JSDocType decl should have a type"); // If defined, shouldn't have been an error to fix. changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(jsdocType)); } @@ -125740,989 +128698,6 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; -(function (ts) { - var codefix; - (function (codefix) { - var fixId = "inferFromUsage"; - var errorCodes = [ - // Variable declarations - ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, - // Variable uses - ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, - // Parameter declarations - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, - // Get Accessor declarations - ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, - ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, - // Set Accessor declarations - ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, - // Property declarations - ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, - //// Suggestions - // Variable declarations - ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code, - // Variable uses - ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, - // Parameter declarations - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code, - // Get Accessor declarations - ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code, - ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code, - // Set Accessor declarations - ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code, - // Property declarations - ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, - // Function expressions and declarations - ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code, - ]; - codefix.registerCodeFix({ - errorCodes: errorCodes, - getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences; - var token = ts.getTokenAtPosition(sourceFile, start); - var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host, formatContext, preferences); }); - var name = declaration && ts.getNameOfDeclaration(declaration); - return !name || changes.length === 0 ? undefined - : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; - }, - fixIds: [fixId], - getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences; - var markSeen = ts.nodeSeenTracker(); - return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, formatContext, preferences); - }); - }, - }); - function getDiagnostic(errorCode, token) { - switch (errorCode) { - case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: - return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 - case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: - return ts.Diagnostics.Infer_parameter_types_from_usage; - case ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code: - return ts.Diagnostics.Infer_this_type_of_0_from_usage; - default: - return ts.Diagnostics.Infer_type_of_0_from_usage; - } - } - /** Map suggestion code to error code */ - function mapSuggestionDiagnostic(errorCode) { - switch (errorCode) { - case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code: - return ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code; - case ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: - return ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code; - case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: - return ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code; - case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: - return ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code; - case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code: - return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code; - case ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code: - return ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code; - case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code: - return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code; - case ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: - return ts.Diagnostics.Member_0_implicitly_has_an_1_type.code; - } - return errorCode; - } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, formatContext, preferences) { - if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 75 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 104 /* ThisKeyword */) { - return undefined; - } - var parent = token.parent; - errorCode = mapSuggestionDiagnostic(errorCode); - switch (errorCode) { - // Variable and Property declarations - case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: - case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: - if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken, formatContext, preferences); - return parent; - } - if (ts.isPropertyAccessExpression(parent)) { - var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); - 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*/ ""); - addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]); - } - return parent; - } - return undefined; - case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { - var symbol = program.getTypeChecker().getSymbolAtLocation(token); - if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken, formatContext, preferences); - return symbol.valueDeclaration; - } - return undefined; - } - } - var containingFunction = ts.getContainingFunction(token); - if (containingFunction === undefined) { - return undefined; - } - switch (errorCode) { - // Parameter declarations - case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - if (ts.isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); - return containingFunction; - } - // falls through - case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - if (markSeen(containingFunction)) { - var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken, formatContext, preferences); - return param; - } - return undefined; - // Get Accessor declarations - case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: - case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: - if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host, formatContext, preferences); - return containingFunction; - } - return undefined; - // Set Accessor declarations - case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: - if (ts.isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); - return containingFunction; - } - return undefined; - // Function 'this' - case ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code: - if (ts.textChanges.isThisTypeAnnotatable(containingFunction) && markSeen(containingFunction)) { - annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken); - return containingFunction; - } - return undefined; - default: - return ts.Debug.fail(String(errorCode)); - } - } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken, formatContext, preferences) { - if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host, formatContext, preferences); - } - } - function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken, formatContext, preferences) { - if (!ts.isIdentifier(parameterDeclaration.name)) { - return; - } - var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken); - ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length, "Parameter count and inference count should match"); - if (ts.isInJSFile(containingFunction)) { - annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); - } - else { - var needParens = ts.isArrowFunction(containingFunction) && !ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile); - if (needParens) - changes.insertNodeBefore(sourceFile, ts.first(containingFunction.parameters), ts.createToken(20 /* OpenParenToken */)); - for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { - var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; - if (declaration && !declaration.type && !declaration.initializer) { - annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences); - } - } - if (needParens) - changes.insertNodeAfter(sourceFile, ts.last(containingFunction.parameters), ts.createToken(21 /* CloseParenToken */)); - } - } - function annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken) { - var references = getFunctionReferences(containingFunction, sourceFile, program, cancellationToken); - if (!references || !references.length) { - return; - } - var thisInference = inferTypeFromReferences(program, references, cancellationToken).thisParameter(); - var typeNode = ts.getTypeNodeIfAccessible(thisInference, containingFunction, program, host); - if (!typeNode) { - return; - } - if (ts.isInJSFile(containingFunction)) { - annotateJSDocThis(changes, sourceFile, containingFunction, typeNode); - } - else { - changes.tryInsertThisTypeAnnotation(sourceFile, containingFunction, typeNode); - } - } - function annotateJSDocThis(changes, sourceFile, containingFunction, typeNode) { - addJSDocTags(changes, sourceFile, containingFunction, [ - ts.createJSDocThisTag(ts.createJSDocTypeExpression(typeNode)), - ]); - } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken, formatContext, preferences) { - var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); - if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { - var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); - if (type === program.getTypeChecker().getAnyType()) { - type = inferTypeForVariableFromUsage(param.name, program, cancellationToken); - } - if (ts.isInJSFile(setAccessorDeclaration)) { - annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); - } - else { - annotate(changes, sourceFile, param, type, program, host, formatContext, preferences); - } - } - } - function annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences) { - var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host); - if (typeNode) { - if (ts.isInJSFile(sourceFile) && declaration.kind !== 158 /* PropertySignature */) { - var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration; - if (!parent) { - return; - } - var typeExpression = ts.createJSDocTypeExpression(typeNode); - var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, ""); - addJSDocTags(changes, sourceFile, parent, [typeTag]); - } - else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences)) { - changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); - } - } - } - function tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences) { - var _a; - if (ts.isLiteralImportTypeNode(typeNode) && typeNode.qualifier && type.symbol) { - // Replace 'import("./a").SomeType' with 'SomeType' and an actual import if possible - var moduleSymbol = (_a = ts.find(type.symbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) === null || _a === void 0 ? void 0 : _a.getSourceFile().symbol; - // Symbol for the left-most thing after the dot - if (moduleSymbol) { - var symbol = ts.getFirstIdentifier(typeNode.qualifier).symbol; - var action = codefix.getImportCompletionAction(symbol, moduleSymbol, sourceFile, symbol.name, host, program, formatContext, declaration.pos, preferences); - if (action.codeAction.changes.length && changes.tryInsertTypeAnnotation(sourceFile, declaration, ts.createTypeReferenceNode(typeNode.qualifier, typeNode.typeArguments))) { - for (var _i = 0, _b = action.codeAction.changes; _i < _b.length; _i++) { - var change = _b[_i]; - var file = sourceFile.fileName === change.fileName ? sourceFile : ts.Debug.assertDefined(program.getSourceFile(change.fileName)); - changes.pushRaw(file, change); - } - return true; - } - } - } - return false; - } - function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { - var signature = parameterInferences.length && parameterInferences[0].declaration.parent; - if (!signature) { - return; - } - var paramTags = ts.mapDefined(parameterInferences, function (inference) { - var param = inference.declaration; - // 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 && 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), ""); - }); - addJSDocTags(changes, sourceFile, signature, paramTags); - } - function addJSDocTags(changes, sourceFile, parent, newTags) { - var comments = ts.mapDefined(parent.jsDoc, function (j) { return j.comment; }); - var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }); - var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) { - var merged = tryMergeJsdocTags(tag, newTag); - if (merged) - oldTags[i] = merged; - return !!merged; - }); }); - var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray(__spreadArrays((oldTags || ts.emptyArray), unmergedNewTags))); - var jsDocNode = parent.kind === 202 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent; - jsDocNode.jsDoc = parent.jsDoc; - jsDocNode.jsDocCache = parent.jsDocCache; - changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag); - } - function getJsDocNodeForArrowFunction(signature) { - if (signature.parent.kind === 159 /* PropertyDeclaration */) { - return signature.parent; - } - return signature.parent.parent; - } - function tryMergeJsdocTags(oldTag, newTag) { - if (oldTag.kind !== newTag.kind) { - return undefined; - } - switch (oldTag.kind) { - case 316 /* 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 317 /* JSDocReturnTag */: - return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment); - } - } - 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) { - return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; - }); - } - function inferTypeForVariableFromUsage(token, program, cancellationToken) { - var references = getReferences(token, program, cancellationToken); - return inferTypeFromReferences(program, references, cancellationToken).single(); - } - function inferTypeForParametersFromUsage(func, sourceFile, program, cancellationToken) { - var references = getFunctionReferences(func, sourceFile, program, cancellationToken); - return references && inferTypeFromReferences(program, references, cancellationToken).parameters(func) || - func.parameters.map(function (p) { return ({ - declaration: p, - type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType() - }); }); - } - function getFunctionReferences(containingFunction, sourceFile, program, cancellationToken) { - var searchToken; - switch (containingFunction.kind) { - case 162 /* Constructor */: - searchToken = ts.findChildOfKind(containingFunction, 129 /* ConstructorKeyword */, sourceFile); - break; - case 202 /* ArrowFunction */: - case 201 /* FunctionExpression */: - var parent = containingFunction.parent; - searchToken = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ? - parent.name : - containingFunction.name; - break; - case 244 /* FunctionDeclaration */: - case 161 /* MethodDeclaration */: - searchToken = containingFunction.name; - break; - } - if (!searchToken) { - return undefined; - } - return getReferences(searchToken, program, cancellationToken); - } - function inferTypeFromReferences(program, references, cancellationToken) { - var checker = program.getTypeChecker(); - var builtinConstructors = { - string: function () { return checker.getStringType(); }, - number: function () { return checker.getNumberType(); }, - Array: function (t) { return checker.createArrayType(t); }, - Promise: function (t) { return checker.createPromiseType(t); }, - }; - var builtins = [ - checker.getStringType(), - checker.getNumberType(), - checker.createArrayType(checker.getAnyType()), - checker.createPromiseType(checker.getAnyType()), - ]; - return { - single: single, - parameters: parameters, - thisParameter: thisParameter, - }; - function createEmptyUsage() { - return { - isNumber: undefined, - isString: undefined, - isNumberOrString: undefined, - candidateTypes: undefined, - properties: undefined, - calls: undefined, - constructs: undefined, - numberIndex: undefined, - stringIndex: undefined, - candidateThisTypes: undefined, - inferredTypes: undefined, - }; - } - function combineUsages(usages) { - var combinedProperties = ts.createUnderscoreEscapedMap(); - for (var _i = 0, usages_1 = usages; _i < usages_1.length; _i++) { - var u = usages_1[_i]; - if (u.properties) { - u.properties.forEach(function (p, name) { - if (!combinedProperties.has(name)) { - combinedProperties.set(name, []); - } - combinedProperties.get(name).push(p); - }); - } - } - var properties = ts.createUnderscoreEscapedMap(); - combinedProperties.forEach(function (ps, name) { - properties.set(name, combineUsages(ps)); - }); - return { - isNumber: usages.some(function (u) { return u.isNumber; }), - isString: usages.some(function (u) { return u.isString; }), - isNumberOrString: usages.some(function (u) { return u.isNumberOrString; }), - candidateTypes: ts.flatMap(usages, function (u) { return u.candidateTypes; }), - properties: properties, - calls: ts.flatMap(usages, function (u) { return u.calls; }), - constructs: ts.flatMap(usages, function (u) { return u.constructs; }), - numberIndex: ts.forEach(usages, function (u) { return u.numberIndex; }), - stringIndex: ts.forEach(usages, function (u) { return u.stringIndex; }), - candidateThisTypes: ts.flatMap(usages, function (u) { return u.candidateThisTypes; }), - inferredTypes: undefined, - }; - } - function single() { - return combineTypes(inferTypesFromReferencesSingle(references)); - } - function parameters(declaration) { - if (references.length === 0 || !declaration.parameters) { - return undefined; - } - var usage = createEmptyUsage(); - for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { - var reference = references_2[_i]; - cancellationToken.throwIfCancellationRequested(); - calculateUsageOfNode(reference, usage); - } - var calls = __spreadArrays(usage.constructs || [], usage.calls || []); - return declaration.parameters.map(function (parameter, parameterIndex) { - var types = []; - var isRest = ts.isRestParameter(parameter); - var isOptional = false; - for (var _i = 0, calls_1 = calls; _i < calls_1.length; _i++) { - var call = calls_1[_i]; - if (call.argumentTypes.length <= parameterIndex) { - isOptional = ts.isInJSFile(declaration); - types.push(checker.getUndefinedType()); - } - else if (isRest) { - for (var i = parameterIndex; i < call.argumentTypes.length; i++) { - types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[i])); - } - } - else { - types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[parameterIndex])); - } - } - if (ts.isIdentifier(parameter.name)) { - var inferred = inferTypesFromReferencesSingle(getReferences(parameter.name, program, cancellationToken)); - types.push.apply(types, (isRest ? ts.mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred)); - } - var type = combineTypes(types); - return { - type: isRest ? checker.createArrayType(type) : type, - isOptional: isOptional && !isRest, - declaration: parameter - }; - }); - } - function thisParameter() { - var usage = createEmptyUsage(); - for (var _i = 0, references_3 = references; _i < references_3.length; _i++) { - var reference = references_3[_i]; - cancellationToken.throwIfCancellationRequested(); - calculateUsageOfNode(reference, usage); - } - return combineTypes(usage.candidateThisTypes || ts.emptyArray); - } - function inferTypesFromReferencesSingle(references) { - var usage = createEmptyUsage(); - for (var _i = 0, references_4 = references; _i < references_4.length; _i++) { - var reference = references_4[_i]; - cancellationToken.throwIfCancellationRequested(); - calculateUsageOfNode(reference, usage); - } - return inferTypes(usage); - } - function calculateUsageOfNode(node, usage) { - while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { - node = node.parent; - } - switch (node.parent.kind) { - case 226 /* ExpressionStatement */: - addCandidateType(usage, checker.getVoidType()); - break; - case 208 /* PostfixUnaryExpression */: - usage.isNumber = true; - break; - case 207 /* PrefixUnaryExpression */: - inferTypeFromPrefixUnaryExpression(node.parent, usage); - break; - case 209 /* BinaryExpression */: - inferTypeFromBinaryExpression(node, node.parent, usage); - break; - case 277 /* CaseClause */: - case 278 /* DefaultClause */: - inferTypeFromSwitchStatementLabel(node.parent, usage); - break; - case 196 /* CallExpression */: - case 197 /* NewExpression */: - if (node.parent.expression === node) { - inferTypeFromCallExpression(node.parent, usage); - } - else { - inferTypeFromContextualType(node, usage); - } - break; - case 194 /* PropertyAccessExpression */: - inferTypeFromPropertyAccessExpression(node.parent, usage); - break; - case 195 /* ElementAccessExpression */: - inferTypeFromPropertyElementExpression(node.parent, node, usage); - break; - case 281 /* PropertyAssignment */: - case 282 /* ShorthandPropertyAssignment */: - inferTypeFromPropertyAssignment(node.parent, usage); - break; - case 159 /* PropertyDeclaration */: - inferTypeFromPropertyDeclaration(node.parent, usage); - break; - case 242 /* VariableDeclaration */: { - var _a = node.parent, name = _a.name, initializer = _a.initializer; - if (node === name) { - if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. - addCandidateType(usage, checker.getTypeAtLocation(initializer)); - } - break; - } - } - // falls through - default: - return inferTypeFromContextualType(node, usage); - } - } - function inferTypeFromContextualType(node, usage) { - if (ts.isExpressionNode(node)) { - addCandidateType(usage, checker.getContextualType(node)); - } - } - function inferTypeFromPrefixUnaryExpression(node, usage) { - switch (node.operator) { - case 45 /* PlusPlusToken */: - case 46 /* MinusMinusToken */: - case 40 /* MinusToken */: - case 54 /* TildeToken */: - usage.isNumber = true; - break; - case 39 /* PlusToken */: - usage.isNumberOrString = true; - break; - // case SyntaxKind.ExclamationToken: - // no inferences here; - } - } - function inferTypeFromBinaryExpression(node, parent, usage) { - switch (parent.operatorToken.kind) { - // ExponentiationOperator - case 42 /* AsteriskAsteriskToken */: - // MultiplicativeOperator - // falls through - case 41 /* AsteriskToken */: - case 43 /* SlashToken */: - case 44 /* PercentToken */: - // ShiftOperator - // falls through - case 47 /* LessThanLessThanToken */: - case 48 /* GreaterThanGreaterThanToken */: - case 49 /* GreaterThanGreaterThanGreaterThanToken */: - // BitwiseOperator - // falls through - case 50 /* AmpersandToken */: - case 51 /* BarToken */: - case 52 /* CaretToken */: - // CompoundAssignmentOperator - // falls through - case 64 /* MinusEqualsToken */: - case 66 /* AsteriskAsteriskEqualsToken */: - case 65 /* AsteriskEqualsToken */: - case 67 /* SlashEqualsToken */: - case 68 /* PercentEqualsToken */: - case 72 /* AmpersandEqualsToken */: - case 73 /* BarEqualsToken */: - case 74 /* CaretEqualsToken */: - case 69 /* LessThanLessThanEqualsToken */: - case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 70 /* GreaterThanGreaterThanEqualsToken */: - // AdditiveOperator - // falls through - case 40 /* MinusToken */: - // RelationalOperator - // falls through - case 29 /* LessThanToken */: - case 32 /* LessThanEqualsToken */: - case 31 /* GreaterThanToken */: - case 33 /* GreaterThanEqualsToken */: - var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); - if (operandType.flags & 1056 /* EnumLike */) { - addCandidateType(usage, operandType); - } - else { - usage.isNumber = true; - } - break; - case 63 /* PlusEqualsToken */: - case 39 /* PlusToken */: - var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); - if (otherOperandType.flags & 1056 /* EnumLike */) { - addCandidateType(usage, otherOperandType); - } - else if (otherOperandType.flags & 296 /* NumberLike */) { - usage.isNumber = true; - } - else if (otherOperandType.flags & 132 /* StringLike */) { - usage.isString = true; - } - else if (otherOperandType.flags & 1 /* Any */) { - // do nothing, maybe we'll learn something elsewhere - } - else { - usage.isNumberOrString = true; - } - break; - // AssignmentOperators - case 62 /* EqualsToken */: - case 34 /* EqualsEqualsToken */: - case 36 /* EqualsEqualsEqualsToken */: - case 37 /* ExclamationEqualsEqualsToken */: - case 35 /* ExclamationEqualsToken */: - addCandidateType(usage, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); - break; - case 97 /* InKeyword */: - if (node === parent.left) { - usage.isString = true; - } - break; - // LogicalOperator Or NullishCoalescing - case 56 /* BarBarToken */: - case 60 /* QuestionQuestionToken */: - if (node === parent.left && - (node.parent.parent.kind === 242 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { - // var x = x || {}; - // TODO: use getFalsyflagsOfType - addCandidateType(usage, checker.getTypeAtLocation(parent.right)); - } - break; - case 55 /* AmpersandAmpersandToken */: - case 27 /* CommaToken */: - case 98 /* InstanceOfKeyword */: - // nothing to infer here - break; - } - } - function inferTypeFromSwitchStatementLabel(parent, usage) { - addCandidateType(usage, checker.getTypeAtLocation(parent.parent.parent.expression)); - } - function inferTypeFromCallExpression(parent, usage) { - var call = { - argumentTypes: [], - return_: createEmptyUsage() - }; - if (parent.arguments) { - for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - call.argumentTypes.push(checker.getTypeAtLocation(argument)); - } - } - calculateUsageOfNode(parent, call.return_); - if (parent.kind === 196 /* CallExpression */) { - (usage.calls || (usage.calls = [])).push(call); - } - else { - (usage.constructs || (usage.constructs = [])).push(call); - } - } - function inferTypeFromPropertyAccessExpression(parent, usage) { - var name = ts.escapeLeadingUnderscores(parent.name.text); - if (!usage.properties) { - usage.properties = ts.createUnderscoreEscapedMap(); - } - var propertyUsage = usage.properties.get(name) || createEmptyUsage(); - calculateUsageOfNode(parent, propertyUsage); - usage.properties.set(name, propertyUsage); - } - function inferTypeFromPropertyElementExpression(parent, node, usage) { - if (node === parent.argumentExpression) { - usage.isNumberOrString = true; - return; - } - else { - var indexType = checker.getTypeAtLocation(parent.argumentExpression); - var indexUsage = createEmptyUsage(); - calculateUsageOfNode(parent, indexUsage); - if (indexType.flags & 296 /* NumberLike */) { - usage.numberIndex = indexUsage; - } - else { - usage.stringIndex = indexUsage; - } - } - } - function inferTypeFromPropertyAssignment(assignment, usage) { - var nodeWithRealType = ts.isVariableDeclaration(assignment.parent.parent) ? - assignment.parent.parent : - assignment.parent; - addCandidateThisType(usage, checker.getTypeAtLocation(nodeWithRealType)); - } - function inferTypeFromPropertyDeclaration(declaration, usage) { - addCandidateThisType(usage, checker.getTypeAtLocation(declaration.parent)); - } - function removeLowPriorityInferences(inferences, priorities) { - var toRemove = []; - 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)) { - ts.Debug.assert(!low(i), "Priority can't have both low and high"); - toRemove.push(low); - } - } - } - return inferences.filter(function (i) { return toRemove.every(function (f) { return !f(i); }); }); - } - function combineFromUsage(usage) { - return combineTypes(inferTypes(usage)); - } - function combineTypes(inferences) { - if (!inferences.length) - return checker.getAnyType(); - // 1. string or number individually override string | number - // 2. non-any, non-void overrides any or void - // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types - var stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]); - var priorities = [ - { - high: function (t) { return t === checker.getStringType() || t === checker.getNumberType(); }, - low: function (t) { return t === stringNumber; } - }, - { - high: function (t) { return !(t.flags & (1 /* Any */ | 16384 /* Void */)); }, - low: function (t) { return !!(t.flags & (1 /* Any */ | 16384 /* Void */)); } - }, - { - high: function (t) { return !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(ts.getObjectFlags(t) & 16 /* Anonymous */); }, - low: function (t) { return !!(ts.getObjectFlags(t) & 16 /* Anonymous */); } - } - ]; - var good = removeLowPriorityInferences(inferences, priorities); - var anons = good.filter(function (i) { return ts.getObjectFlags(i) & 16 /* Anonymous */; }); - if (anons.length) { - good = good.filter(function (i) { return !(ts.getObjectFlags(i) & 16 /* Anonymous */); }); - good.push(combineAnonymousTypes(anons)); - } - return checker.getWidenedType(checker.getUnionType(good.map(checker.getBaseTypeOfLiteralType), 2 /* Subtype */)); - } - function combineAnonymousTypes(anons) { - if (anons.length === 1) { - return anons[0]; - } - var calls = []; - var constructs = []; - var stringIndices = []; - var numberIndices = []; - var stringIndexReadonly = false; - var numberIndexReadonly = false; - var props = ts.createMultiMap(); - for (var _i = 0, anons_1 = anons; _i < anons_1.length; _i++) { - var anon = anons_1[_i]; - for (var _a = 0, _b = checker.getPropertiesOfType(anon); _a < _b.length; _a++) { - var p = _b[_a]; - props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration)); - } - calls.push.apply(calls, checker.getSignaturesOfType(anon, 0 /* Call */)); - constructs.push.apply(constructs, checker.getSignaturesOfType(anon, 1 /* Construct */)); - if (anon.stringIndexInfo) { - stringIndices.push(anon.stringIndexInfo.type); - stringIndexReadonly = stringIndexReadonly || anon.stringIndexInfo.isReadonly; - } - if (anon.numberIndexInfo) { - numberIndices.push(anon.numberIndexInfo.type); - numberIndexReadonly = numberIndexReadonly || anon.numberIndexInfo.isReadonly; - } - } - var members = ts.mapEntries(props, function (name, types) { - var isOptional = types.length < anons.length ? 16777216 /* Optional */ : 0; - var s = checker.createSymbol(4 /* Property */ | isOptional, name); - s.type = checker.getUnionType(types); - return [name, s]; - }); - return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, stringIndices.length ? checker.createIndexInfo(checker.getUnionType(stringIndices), stringIndexReadonly) : undefined, numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined); - } - function inferTypes(usage) { - var types = []; - if (usage.isNumber) { - types.push(checker.getNumberType()); - } - if (usage.isString) { - types.push(checker.getStringType()); - } - if (usage.isNumberOrString) { - types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()])); - } - if (usage.numberIndex) { - types.push(checker.createArrayType(combineFromUsage(usage.numberIndex))); - } - if (usage.properties && usage.properties.size - || usage.calls && usage.calls.length - || usage.constructs && usage.constructs.length - || usage.stringIndex) { - types.push(inferStructuralType(usage)); - } - types.push.apply(types, (usage.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); })); - types.push.apply(types, inferNamedTypesFromProperties(usage)); - return types; - } - function inferStructuralType(usage) { - var members = ts.createUnderscoreEscapedMap(); - if (usage.properties) { - usage.properties.forEach(function (u, name) { - var symbol = checker.createSymbol(4 /* Property */, name); - symbol.type = combineFromUsage(u); - members.set(name, symbol); - }); - } - var callSignatures = usage.calls ? [getSignatureFromCalls(usage.calls)] : []; - var constructSignatures = usage.constructs ? [getSignatureFromCalls(usage.constructs)] : []; - var stringIndexInfo = usage.stringIndex && checker.createIndexInfo(combineFromUsage(usage.stringIndex), /*isReadonly*/ false); - return checker.createAnonymousType(/*symbol*/ undefined, members, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217 - } - function inferNamedTypesFromProperties(usage) { - if (!usage.properties || !usage.properties.size) - return []; - var types = builtins.filter(function (t) { return allPropertiesAreAssignableToUsage(t, usage); }); - if (0 < types.length && types.length < 3) { - return types.map(function (t) { return inferInstantiationFromUsage(t, usage); }); - } - return []; - } - function allPropertiesAreAssignableToUsage(type, usage) { - if (!usage.properties) - return false; - return !ts.forEachEntry(usage.properties, function (propUsage, name) { - var source = checker.getTypeOfPropertyOfType(type, name); - if (!source) { - return true; - } - if (propUsage.calls) { - var sigs = checker.getSignaturesOfType(source, 0 /* Call */); - return !sigs.length || !checker.isTypeAssignableTo(source, getFunctionFromCalls(propUsage.calls)); - } - else { - return !checker.isTypeAssignableTo(source, combineFromUsage(propUsage)); - } - }); - } - /** - * inference is limited to - * 1. generic types with a single parameter - * 2. inference to/from calls with a single signature - */ - function inferInstantiationFromUsage(type, usage) { - if (!(ts.getObjectFlags(type) & 4 /* Reference */) || !usage.properties) { - return type; - } - var generic = type.target; - var singleTypeParameter = ts.singleOrUndefined(generic.typeParameters); - if (!singleTypeParameter) - return type; - var types = []; - usage.properties.forEach(function (propUsage, name) { - var genericPropertyType = checker.getTypeOfPropertyOfType(generic, name); - ts.Debug.assert(!!genericPropertyType, "generic should have all the properties of its reference."); - types.push.apply(types, inferTypeParameters(genericPropertyType, combineFromUsage(propUsage), singleTypeParameter)); - }); - return builtinConstructors[type.symbol.escapedName](combineTypes(types)); - } - function inferTypeParameters(genericType, usageType, typeParameter) { - if (genericType === typeParameter) { - return [usageType]; - } - else if (genericType.flags & 3145728 /* UnionOrIntersection */) { - return ts.flatMap(genericType.types, function (t) { return inferTypeParameters(t, usageType, typeParameter); }); - } - else if (ts.getObjectFlags(genericType) & 4 /* Reference */ && ts.getObjectFlags(usageType) & 4 /* Reference */) { - // this is wrong because we need a reference to the targetType to, so we can check that it's also a reference - var genericArgs = checker.getTypeArguments(genericType); - var usageArgs = checker.getTypeArguments(usageType); - var types = []; - if (genericArgs && usageArgs) { - for (var i = 0; i < genericArgs.length; i++) { - if (usageArgs[i]) { - types.push.apply(types, inferTypeParameters(genericArgs[i], usageArgs[i], typeParameter)); - } - } - } - return types; - } - var genericSigs = checker.getSignaturesOfType(genericType, 0 /* Call */); - var usageSigs = checker.getSignaturesOfType(usageType, 0 /* Call */); - if (genericSigs.length === 1 && usageSigs.length === 1) { - return inferFromSignatures(genericSigs[0], usageSigs[0], typeParameter); - } - return []; - } - function inferFromSignatures(genericSig, usageSig, typeParameter) { - var types = []; - for (var i = 0; i < genericSig.parameters.length; i++) { - var genericParam = genericSig.parameters[i]; - var usageParam = usageSig.parameters[i]; - var isRest = genericSig.declaration && ts.isRestParameter(genericSig.declaration.parameters[i]); - if (!usageParam) { - break; - } - var genericParamType = checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration); - var elementType = isRest && checker.getElementTypeOfArrayType(genericParamType); - if (elementType) { - genericParamType = elementType; - } - var targetType = usageParam.type || checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration); - types.push.apply(types, inferTypeParameters(genericParamType, targetType, typeParameter)); - } - var genericReturn = checker.getReturnTypeOfSignature(genericSig); - var usageReturn = checker.getReturnTypeOfSignature(usageSig); - types.push.apply(types, inferTypeParameters(genericReturn, usageReturn, typeParameter)); - return types; - } - function getFunctionFromCalls(calls) { - return checker.createAnonymousType(undefined, ts.createSymbolTable(), [getSignatureFromCalls(calls)], ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - } - function getSignatureFromCalls(calls) { - var parameters = []; - var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; })); - var _loop_12 = function (i) { - var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); - symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); })); - if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) { - symbol.flags |= 16777216 /* Optional */; - } - parameters.push(symbol); - }; - for (var i = 0; i < length; i++) { - _loop_12(i); - } - var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); - // TODO: GH#18217 - return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* None */); - } - function addCandidateType(usage, type) { - if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { - (usage.candidateTypes || (usage.candidateTypes = [])).push(type); - } - } - function addCandidateThisType(usage, type) { - if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { - (usage.candidateThisTypes || (usage.candidateThisTypes = [])).push(type); - } - } - } - })(codefix = ts.codefix || (ts.codefix = {})); -})(ts || (ts = {})); -/* @internal */ -var ts; (function (ts) { var codefix; (function (codefix) { @@ -126767,7 +128742,10 @@ var ts; if (!newClassDeclaration) { return undefined; } - ts.copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile); + // Deleting a declaration only deletes JSDoc style comments, so only copy those to the new node. + if (ts.hasJSDocNodes(ctorDeclaration)) { + 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) { @@ -126928,27 +128906,21 @@ var ts; return; } var synthNamesMap = ts.createMap(); - var originalTypeMap = ts.createMap(); - var allVarNames = []; var isInJavascript = ts.isInJSFile(functionToConvert); var setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); - var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); - var constIdentifiers = getConstIdentifiers(synthNamesMap); + var functionToConvertRenamed = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context.sourceFile); var returnStatements = functionToConvertRenamed.body && ts.isBlock(functionToConvertRenamed.body) ? getReturnStatementsWithPromiseHandlers(functionToConvertRenamed.body) : ts.emptyArray; - var transformer = { checker: checker, synthNamesMap: synthNamesMap, allVarNames: allVarNames, setOfExpressionsToReturn: setOfExpressionsToReturn, constIdentifiers: constIdentifiers, originalTypeMap: originalTypeMap, isInJSFile: isInJavascript }; + var transformer = { checker: checker, synthNamesMap: synthNamesMap, setOfExpressionsToReturn: setOfExpressionsToReturn, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; } // add the async keyword changes.insertLastModifierBefore(sourceFile, 126 /* AsyncKeyword */, functionToConvert); - function startTransformation(node, nodeToReplace) { - var newNodes = transformExpression(node, transformer, node); - changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); - } - var _loop_13 = function (statement) { - ts.forEachChild(statement, function visit(node) { + var _loop_12 = function (returnStatement) { + ts.forEachChild(returnStatement, function visit(node) { if (ts.isCallExpression(node)) { - startTransformation(node, statement); + var newNodes = transformExpression(node, transformer); + changes.replaceNodeWithNodes(sourceFile, returnStatement, newNodes); } else if (!ts.isFunctionLike(node)) { ts.forEachChild(node, visit); @@ -126956,8 +128928,8 @@ var ts; }); }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { - var statement = returnStatements_1[_i]; - _loop_13(statement); + var returnStatement = returnStatements_1[_i]; + _loop_12(returnStatement); } } function getReturnStatementsWithPromiseHandlers(body) { @@ -126968,16 +128940,6 @@ var ts; }); return res; } - // Returns the identifiers that are never reassigned in the refactor - function getConstIdentifiers(synthNamesMap) { - var constIdentifiers = []; - synthNamesMap.forEach(function (val) { - if (val.numberOfAssignmentsOriginal === 0) { - constIdentifiers.push(val.identifier); - } - }); - return constIdentifiers; - } /* Finds all of the expressions of promise type that should not be saved in a variable during the refactor */ @@ -126987,16 +128949,16 @@ var ts; } var setOfExpressionsToReturn = ts.createMap(); ts.forEachChild(func.body, function visit(node) { - if (isPromiseReturningExpression(node, checker, "then")) { + if (isPromiseReturningCallExpression(node, checker, "then")) { setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); ts.forEach(node.arguments, visit); } - else if (isPromiseReturningExpression(node, checker, "catch")) { + else if (isPromiseReturningCallExpression(node, checker, "catch")) { setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); // if .catch() is the last call in the chain, move leftward in the chain until we hit something else that should be returned ts.forEachChild(node, visit); } - else if (isPromiseReturningExpression(node, checker)) { + else if (isPromiseTypedExpression(node, checker)) { setOfExpressionsToReturn.set(ts.getNodeId(node).toString(), true); // don't recurse here, since we won't refactor any children or arguments of the expression } @@ -127006,16 +128968,18 @@ var ts; }); return setOfExpressionsToReturn; } - /* - Returns true if node is a promise returning expression - If name is not undefined, node is a promise returning call of name - */ - function isPromiseReturningExpression(node, checker, name) { - var isNodeExpression = name ? ts.isCallExpression(node) : ts.isExpression(node); - var isExpressionOfName = isNodeExpression && (!name || ts.hasPropertyAccessExpressionWithName(node, name)); + function isPromiseReturningCallExpression(node, checker, name) { + if (!ts.isCallExpression(node)) + return false; + var isExpressionOfName = ts.hasPropertyAccessExpressionWithName(node, name); var nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); } + function isPromiseTypedExpression(node, checker) { + if (!ts.isExpression(node)) + return false; + return !!checker.getPromisedTypeOfPromise(checker.getTypeAtLocation(node)); + } function declaredInFile(symbol, sourceFile) { return symbol.valueDeclaration && symbol.valueDeclaration.getSourceFile() === sourceFile; } @@ -127024,31 +128988,34 @@ var ts; This function collects all existing identifier names and names of identifiers that will be created in the refactor. It then checks for any collisions and renames them through getSynthesizedDeepClone */ - function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, context, setOfAllExpressionsToReturn, originalType, allVarNames) { + function renameCollidingVarNames(nodeToRename, checker, synthNamesMap, sourceFile) { var identsToRenameMap = ts.createMap(); // key is the symbol id - var collidingSymbolMap = ts.createMap(); + var collidingSymbolMap = ts.createMultiMap(); ts.forEachChild(nodeToRename, function visit(node) { if (!ts.isIdentifier(node)) { ts.forEachChild(node, visit); return; } var symbol = checker.getSymbolAtLocation(node); - var isDefinedInFile = symbol && declaredInFile(symbol, context.sourceFile); + var isDefinedInFile = symbol && declaredInFile(symbol, sourceFile); if (symbol && isDefinedInFile) { var type = checker.getTypeAtLocation(node); + // Note - the choice of the last call signature is arbitrary var lastCallSignature = getLastCallSignature(type, checker); var symbolIdString = ts.getSymbolId(symbol).toString(); - // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) - // Note - the choice of the last call signature is arbitrary + // If the identifier refers to a function, we want to add the new synthesized variable for the declaration. Example: + // fetch('...').then(response => { ... }) + // will eventually become + // const response = await fetch('...') + // so we push an entry for 'response'. if (lastCallSignature && !ts.isFunctionLikeDeclaration(node.parent) && !synthNamesMap.has(symbolIdString)) { var firstParameter = ts.firstOrUndefined(lastCallSignature.parameters); var ident = firstParameter && ts.isParameter(firstParameter.valueDeclaration) && ts.tryCast(firstParameter.valueDeclaration.name, ts.isIdentifier) || ts.createOptimisticUniqueName("result"); var synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); - allVarNames.push({ identifier: synthName.identifier, symbol: symbol }); - addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); + collidingSymbolMap.add(ident.text, symbol); } - // we only care about identifiers that are parameters, declarations, or binding elements (don't care about other uses) + // We only care about identifiers that are parameters, variable declarations, or binding elements else if (node.parent && (ts.isParameter(node.parent) || ts.isVariableDeclaration(node.parent) || ts.isBindingElement(node.parent))) { var originalName = node.text; var collidingSymbols = collidingSymbolMap.get(originalName); @@ -127057,96 +129024,60 @@ var ts; var newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); - allVarNames.push({ identifier: newName.identifier, symbol: symbol }); - addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); + collidingSymbolMap.add(originalName, symbol); } else { var identifier = ts.getSynthesizedDeepClone(node); - identsToRenameMap.set(symbolIdString, identifier); - synthNamesMap.set(symbolIdString, createSynthIdentifier(identifier, [], allVarNames.filter(function (elem) { return elem.identifier.text === node.text; }).length /*, numberOfAssignmentsSynthesized: 0*/)); - if ((ts.isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || ts.isVariableDeclaration(node.parent)) { - allVarNames.push({ identifier: identifier, symbol: symbol }); - addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); - } + synthNamesMap.set(symbolIdString, createSynthIdentifier(identifier)); + collidingSymbolMap.add(originalName, symbol); } } } }); - return ts.getSynthesizedDeepCloneWithRenames(nodeToRename, /*includeTrivia*/ true, identsToRenameMap, checker, deepCloneCallback); - function isExpressionOrCallOnTypePromise(child) { - var node = child.parent; - if (ts.isCallExpression(node) || ts.isIdentifier(node) && !setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString())) { - var nodeType = checker.getTypeAtLocation(node); - var isPromise = nodeType && checker.getPromisedTypeOfPromise(nodeType); - return !!isPromise; - } - return false; - } - function deepCloneCallback(node, clone) { - if (ts.isIdentifier(node)) { - var symbol = checker.getSymbolAtLocation(node); - var symboldIdString = symbol && ts.getSymbolId(symbol).toString(); - var renameInfo = symbol && synthNamesMap.get(symboldIdString); - if (renameInfo) { - var type = checker.getTypeAtLocation(node); - originalType.set(ts.getNodeId(clone).toString(), type); - } - } - var val = setOfAllExpressionsToReturn.get(ts.getNodeId(node).toString()); - if (val !== undefined) { - setOfAllExpressionsToReturn.delete(ts.getNodeId(node).toString()); - setOfAllExpressionsToReturn.set(ts.getNodeId(clone).toString(), val); - } - } - } - function addNameToFrequencyMap(renamedVarNameFrequencyMap, originalName, symbol) { - if (renamedVarNameFrequencyMap.has(originalName)) { - renamedVarNameFrequencyMap.get(originalName).push(symbol); - } - else { - renamedVarNameFrequencyMap.set(originalName, [symbol]); - } + return ts.getSynthesizedDeepCloneWithRenames(nodeToRename, /*includeTrivia*/ true, identsToRenameMap, checker); } function getNewNameIfConflict(name, originalNames) { var numVarsSameName = (originalNames.get(name.text) || ts.emptyArray).length; - var numberOfAssignmentsOriginal = 0; var identifier = numVarsSameName === 0 ? name : ts.createIdentifier(name.text + "_" + numVarsSameName); - return createSynthIdentifier(identifier, [], numberOfAssignmentsOriginal); + return createSynthIdentifier(identifier); + } + function silentFail() { + codeActionSucceeded = false; + return ts.emptyArray; } // dispatch function to recursively build the refactoring // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts - function transformExpression(node, transformer, outermostParent, prevArgName) { - if (!node) { - return ts.emptyArray; + function transformExpression(node, transformer, prevArgName) { + if (isPromiseReturningCallExpression(node, transformer.checker, "then")) { + if (node.arguments.length === 0) + return silentFail(); + return transformThen(node, transformer, prevArgName); } - var originalType = ts.isIdentifier(node) && transformer.originalTypeMap.get(ts.getNodeId(node).toString()); - var nodeType = originalType || transformer.checker.getTypeAtLocation(node); - if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "then") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { - return transformThen(node, transformer, outermostParent, prevArgName); - } - else if (ts.isCallExpression(node) && ts.hasPropertyAccessExpressionWithName(node, "catch") && nodeType && !!transformer.checker.getPromisedTypeOfPromise(nodeType)) { + if (isPromiseReturningCallExpression(node, transformer.checker, "catch")) { + if (node.arguments.length === 0) + return silentFail(); return transformCatch(node, transformer, prevArgName); } - else if (ts.isPropertyAccessExpression(node)) { - return transformExpression(node.expression, transformer, outermostParent, prevArgName); + if (ts.isPropertyAccessExpression(node)) { + return transformExpression(node.expression, transformer, prevArgName); } - else if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { - return transformPromiseCall(node, transformer, prevArgName); + var nodeType = transformer.checker.getTypeAtLocation(node); + if (nodeType && transformer.checker.getPromisedTypeOfPromise(nodeType)) { + ts.Debug.assertNode(node.original.parent, ts.isPropertyAccessExpression); + return transformPromiseExpressionOfPropertyAccess(node, transformer, prevArgName); } - codeActionSucceeded = false; - return ts.emptyArray; + return silentFail(); } function transformCatch(node, transformer, prevArgName) { var func = node.arguments[0]; var argName = getArgBindingName(func, transformer); - var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); var possibleNameForVarDecl; /* If there is another call in the chain after the .catch() we are transforming, we will need to save the result of both paths (try block and catch block) To do this, we will need to synthesize a variable that we were not aware of while we were adding identifiers to the synthNamesMap We will use the prevArgName and then update the synthNamesMap with a new variable name for the next transformation step */ - if (prevArgName && !shouldReturn) { + if (prevArgName && !shouldReturn(node, transformer)) { if (isSynthIdentifier(prevArgName)) { possibleNameForVarDecl = prevArgName; transformer.synthNamesMap.forEach(function (val, key) { @@ -127159,13 +129090,12 @@ var ts; else { possibleNameForVarDecl = createSynthIdentifier(ts.createOptimisticUniqueName("result"), prevArgName.types); } - possibleNameForVarDecl.numberOfAssignmentsOriginal = 2; // Try block and catch block - // update the constIdentifiers list - if (transformer.constIdentifiers.some(function (elem) { return elem.text === possibleNameForVarDecl.identifier.text; })) { - transformer.constIdentifiers.push(createUniqueSynthName(possibleNameForVarDecl).identifier); - } + // We are about to write a 'let' variable declaration, but `transformExpression` for both + // the try block and catch block will assign to this name. Setting this flag indicates + // that future assignments should be written as `name = value` instead of `const name = value`. + possibleNameForVarDecl.hasBeenDeclared = true; } - var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, possibleNameForVarDecl)); + var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, possibleNameForVarDecl)); var transformationBody = getTransformationBody(func, possibleNameForVarDecl, argName, node, transformer); var catchArg = argName ? isSynthIdentifier(argName) ? argName.identifier.text : argName.bindingPattern : "e"; var catchVariableDeclaration = ts.createVariableDeclaration(catchArg); @@ -127175,11 +129105,11 @@ var ts; */ var varDeclList; var varDeclIdentifier; - if (possibleNameForVarDecl && !shouldReturn) { + if (possibleNameForVarDecl && !shouldReturn(node, transformer)) { varDeclIdentifier = ts.getSynthesizedDeepClone(possibleNameForVarDecl.identifier); var typeArray = possibleNameForVarDecl.types; var unionType = transformer.checker.getUnionType(typeArray, 2 /* Subtype */); - var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType); + var unionTypeNode = transformer.isInJSFile ? undefined : transformer.checker.typeToTypeNode(unionType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined); var varDecl = [ts.createVariableDeclaration(varDeclIdentifier, unionTypeNode)]; varDeclList = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(varDecl, 1 /* Let */)); } @@ -127188,68 +129118,62 @@ var ts; && ts.createVariableStatement(/* modifiers */ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepCloneWithRenames(prevArgName.bindingPattern), /* type */ undefined, varDeclIdentifier)], 2 /* Const */)); return ts.compact([varDeclList, tryStatement, destructuredResult]); } - function getIdentifierTextsFromBindingName(bindingName) { - if (ts.isIdentifier(bindingName)) - return [bindingName.text]; - return ts.flatMap(bindingName.elements, function (element) { - if (ts.isOmittedExpression(element)) - return []; - return getIdentifierTextsFromBindingName(element.name); - }); - } function createUniqueSynthName(prevArgName) { var renamedPrevArg = ts.createOptimisticUniqueName(prevArgName.identifier.text); return createSynthIdentifier(renamedPrevArg); } - function transformThen(node, transformer, outermostParent, prevArgName) { - var _a = node.arguments, res = _a[0], rej = _a[1]; - if (!res) { - return transformExpression(node.expression, transformer, outermostParent); - } - var argNameRes = getArgBindingName(res, transformer); - var transformationBody = getTransformationBody(res, prevArgName, argNameRes, node, transformer); - if (rej) { - var argNameRej = getArgBindingName(rej, transformer); - var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody)); - var transformationBody2 = getTransformationBody(rej, prevArgName, argNameRej, node, transformer); - var catchArg = argNameRej ? isSynthIdentifier(argNameRej) ? argNameRej.identifier.text : argNameRej.bindingPattern : "e"; + function transformThen(node, transformer, prevArgName) { + var _a = node.arguments, onFulfilled = _a[0], onRejected = _a[1]; + var onFulfilledArgumentName = getArgBindingName(onFulfilled, transformer); + var transformationBody = getTransformationBody(onFulfilled, prevArgName, onFulfilledArgumentName, node, transformer); + if (onRejected) { + var onRejectedArgumentName = getArgBindingName(onRejected, transformer); + var tryBlock = ts.createBlock(transformExpression(node.expression, transformer, onFulfilledArgumentName).concat(transformationBody)); + var transformationBody2 = getTransformationBody(onRejected, prevArgName, onRejectedArgumentName, node, transformer); + var catchArg = onRejectedArgumentName ? isSynthIdentifier(onRejectedArgumentName) ? onRejectedArgumentName.identifier.text : onRejectedArgumentName.bindingPattern : "e"; var catchVariableDeclaration = ts.createVariableDeclaration(catchArg); var catchClause = ts.createCatchClause(catchVariableDeclaration, ts.createBlock(transformationBody2)); return [ts.createTry(tryBlock, catchClause, /* finallyBlock */ undefined)]; } - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); + return transformExpression(node.expression, transformer, onFulfilledArgumentName).concat(transformationBody); } - function getFlagOfBindingName(bindingName, constIdentifiers) { - var identifiers = getIdentifierTextsFromBindingName(getNode(bindingName)); - var inArr = constIdentifiers.some(function (elem) { return ts.contains(identifiers, elem.text); }); - return inArr ? 2 /* Const */ : 1 /* Let */; - } - function transformPromiseCall(node, transformer, prevArgName) { - var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(node).toString()); - // the identifier is empty when the handler (.then()) ignores the argument - In this situation we do not need to save the result of the promise returning call - var originalNodeParent = node.original ? node.original.parent : node.parent; - if (prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { - return createTransformedStatement(prevArgName, ts.createAwait(node), transformer); + /** + * Transforms the 'x' part of `x.then(...)`, or the 'y()' part of `y().catch(...)`, where 'x' and 'y()' are Promises. + */ + function transformPromiseExpressionOfPropertyAccess(node, transformer, prevArgName) { + if (shouldReturn(node, transformer)) { + return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; } - else if (!prevArgName && !shouldReturn && (!originalNodeParent || ts.isPropertyAccessExpression(originalNodeParent))) { - return [ts.createStatement(ts.createAwait(node))]; - } - return [ts.createReturn(ts.getSynthesizedDeepClone(node))]; + return createVariableOrAssignmentOrExpressionStatement(prevArgName, ts.createAwait(node), /*typeAnnotation*/ undefined); } - function createTransformedStatement(prevArgName, rightHandSide, transformer) { - if (!prevArgName || isEmpty(prevArgName)) { + function createVariableOrAssignmentOrExpressionStatement(variableName, rightHandSide, typeAnnotation) { + if (!variableName || isEmptyBindingName(variableName)) { // if there's no argName to assign to, there still might be side effects - return [ts.createStatement(rightHandSide)]; + return [ts.createExpressionStatement(rightHandSide)]; } - if (isSynthIdentifier(prevArgName) && prevArgName.types.length < prevArgName.numberOfAssignmentsOriginal) { + if (isSynthIdentifier(variableName) && variableName.hasBeenDeclared) { // if the variable has already been declared, we don't need "let" or "const" - return [ts.createStatement(ts.createAssignment(ts.getSynthesizedDeepClone(prevArgName.identifier), rightHandSide))]; + return [ts.createExpressionStatement(ts.createAssignment(ts.getSynthesizedDeepClone(variableName.identifier), rightHandSide))]; } - return [ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(ts.getSynthesizedDeepClone(getNode(prevArgName)), /*type*/ undefined, rightHandSide)], getFlagOfBindingName(prevArgName, transformer.constIdentifiers))))]; + return [ + ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getSynthesizedDeepClone(getNode(variableName)), typeAnnotation, rightHandSide) + ], 2 /* Const */)) + ]; + } + function maybeAnnotateAndReturn(expressionToReturn, typeAnnotation) { + if (typeAnnotation && expressionToReturn) { + var name = ts.createOptimisticUniqueName("result"); + return __spreadArrays(createVariableOrAssignmentOrExpressionStatement(createSynthIdentifier(name), expressionToReturn, typeAnnotation), [ + ts.createReturn(name) + ]); + } + return [ts.createReturn(expressionToReturn)]; } // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts function getTransformationBody(func, prevArgName, argName, parent, transformer) { - var shouldReturn = transformer.setOfExpressionsToReturn.get(ts.getNodeId(parent).toString()); + var _a, _b, _c, _d; switch (func.kind) { case 100 /* NullKeyword */: // do not produce a transformed statement for a null argument @@ -127260,18 +129184,17 @@ var ts; break; } var synthCall = ts.createCall(ts.getSynthesizedDeepClone(func), /*typeArguments*/ undefined, isSynthIdentifier(argName) ? [argName.identifier] : []); - if (shouldReturn) { - return [ts.createReturn(synthCall)]; + if (shouldReturn(parent, transformer)) { + return maybeAnnotateAndReturn(synthCall, (_a = parent.typeArguments) === null || _a === void 0 ? void 0 : _a[0]); } - var type = transformer.originalTypeMap.get(ts.getNodeId(func).toString()) || transformer.checker.getTypeAtLocation(func); + var type = transformer.checker.getTypeAtLocation(func); var callSignatures = transformer.checker.getSignaturesOfType(type, 0 /* Call */); if (!callSignatures.length) { // if identifier in handler has no call signatures, it's invalid - codeActionSucceeded = false; - break; + return silentFail(); } var returnType = callSignatures[0].getReturnType(); - var varDeclOrAssignment = createTransformedStatement(prevArgName, ts.createAwait(synthCall), transformer); + var varDeclOrAssignment = createVariableOrAssignmentOrExpressionStatement(prevArgName, ts.createAwait(synthCall), (_b = parent.typeArguments) === null || _b === void 0 ? void 0 : _b[0]); if (prevArgName) { prevArgName.types.push(returnType); } @@ -127283,20 +129206,24 @@ var ts; if (ts.isBlock(funcBody)) { var refactoredStmts = []; var seenReturnStatement = false; - for (var _i = 0, _a = funcBody.statements; _i < _a.length; _i++) { - var statement = _a[_i]; + for (var _i = 0, _e = funcBody.statements; _i < _e.length; _i++) { + var statement = _e[_i]; if (ts.isReturnStatement(statement)) { seenReturnStatement = true; - } - if (ts.isReturnStatementWithFixablePromiseHandler(statement)) { - refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); + if (ts.isReturnStatementWithFixablePromiseHandler(statement)) { + refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); + } + else { + refactoredStmts.push.apply(refactoredStmts, maybeAnnotateAndReturn(statement.expression, (_c = parent.typeArguments) === null || _c === void 0 ? void 0 : _c[0])); + } } else { refactoredStmts.push(statement); } } - return shouldReturn ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) : - removeReturns(refactoredStmts, prevArgName, transformer, seenReturnStatement); + return shouldReturn(parent, transformer) + ? refactoredStmts.map(function (s) { return ts.getSynthesizedDeepClone(s); }) + : removeReturns(refactoredStmts, prevArgName, transformer, seenReturnStatement); } else { var innerRetStmts = ts.isFixablePromiseHandler(funcBody) ? [ts.createReturn(funcBody)] : ts.emptyArray; @@ -127308,22 +129235,21 @@ var ts; 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) { - var transformedStatement = createTransformedStatement(prevArgName, possiblyAwaitedRightHandSide, transformer); + if (!shouldReturn(parent, transformer)) { + var transformedStatement = createVariableOrAssignmentOrExpressionStatement(prevArgName, possiblyAwaitedRightHandSide, /*typeAnnotation*/ undefined); if (prevArgName) { prevArgName.types.push(returnType_1); } return transformedStatement; } else { - return [ts.createReturn(possiblyAwaitedRightHandSide)]; + return maybeAnnotateAndReturn(possiblyAwaitedRightHandSide, (_d = parent.typeArguments) === null || _d === void 0 ? void 0 : _d[0]); } } } default: // If no cases apply, we've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. - codeActionSucceeded = false; - break; + return silentFail(); } return ts.emptyArray; } @@ -127337,12 +129263,12 @@ var ts; var stmt = stmts_1[_i]; if (ts.isReturnStatement(stmt)) { if (stmt.expression) { - var possiblyAwaitedExpression = isPromiseReturningExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; + var possiblyAwaitedExpression = isPromiseTypedExpression(stmt.expression, transformer.checker) ? ts.createAwait(stmt.expression) : stmt.expression; if (prevArgName === undefined) { ret.push(ts.createExpressionStatement(possiblyAwaitedExpression)); } else { - ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(getNode(prevArgName), /*type*/ undefined, possiblyAwaitedExpression)], getFlagOfBindingName(prevArgName, transformer.constIdentifiers))))); + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(getNode(prevArgName), /*type*/ undefined, possiblyAwaitedExpression)], 2 /* Const */)))); } } } @@ -127352,7 +129278,7 @@ var ts; } // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables if (!seenReturnStatement && prevArgName !== undefined) { - ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(getNode(prevArgName), /*type*/ undefined, ts.createIdentifier("undefined"))], getFlagOfBindingName(prevArgName, transformer.constIdentifiers))))); + ret.push(ts.createVariableStatement(/*modifiers*/ undefined, (ts.createVariableDeclarationList([ts.createVariableDeclaration(getNode(prevArgName), /*type*/ undefined, ts.createIdentifier("undefined"))], 2 /* Const */)))); } return ret; } @@ -127362,7 +129288,7 @@ var ts; var stmt = innerRetStmts_1[_i]; ts.forEachChild(stmt, function visit(node) { if (ts.isCallExpression(node)) { - var temp = transformExpression(node, transformer, node, prevArgName); + var temp = transformExpression(node, transformer, prevArgName); innerCbBody = innerCbBody.concat(temp); if (innerCbBody.length > 0) { return; @@ -127376,7 +129302,6 @@ var ts; return innerCbBody; } function getArgBindingName(funcNode, transformer) { - var numberOfAssignmentsOriginal = 0; var types = []; var name; if (ts.isFunctionLikeDeclaration(funcNode)) { @@ -127408,10 +129333,10 @@ var ts; var originalNode = getOriginalNode(identifier); var symbol = getSymbol(originalNode); if (!symbol) { - return createSynthIdentifier(identifier, types, numberOfAssignmentsOriginal); + return createSynthIdentifier(identifier, types); } var mapEntry = transformer.synthNamesMap.get(ts.getSymbolId(symbol).toString()); - return mapEntry || createSynthIdentifier(identifier, types, numberOfAssignmentsOriginal); + return mapEntry || createSynthIdentifier(identifier, types); } function getSymbol(node) { return node.symbol ? node.symbol : transformer.checker.getSymbolAtLocation(node); @@ -127420,22 +129345,21 @@ var ts; return node.original ? node.original : node; } } - function isEmpty(bindingName) { + function isEmptyBindingName(bindingName) { if (!bindingName) { return true; } if (isSynthIdentifier(bindingName)) { return !bindingName.identifier.text; } - return ts.every(bindingName.elements, isEmpty); + return ts.every(bindingName.elements, isEmptyBindingName); } function getNode(bindingName) { return isSynthIdentifier(bindingName) ? bindingName.identifier : bindingName.bindingPattern; } - function createSynthIdentifier(identifier, types, numberOfAssignmentsOriginal) { + function createSynthIdentifier(identifier, types) { if (types === void 0) { types = []; } - if (numberOfAssignmentsOriginal === void 0) { numberOfAssignmentsOriginal = 0; } - return { kind: 0 /* Identifier */, identifier: identifier, types: types, numberOfAssignmentsOriginal: numberOfAssignmentsOriginal }; + return { kind: 0 /* Identifier */, identifier: identifier, types: types, hasBeenDeclared: false }; } function createSynthBindingPattern(bindingPattern, elements, types) { if (elements === void 0) { elements = ts.emptyArray; } @@ -127448,6 +129372,9 @@ var ts; function isSynthBindingPattern(bindingName) { return bindingName.kind === 1 /* BindingPattern */; } + function shouldReturn(expression, transformer) { + return !!expression.original && transformer.setOfExpressionsToReturn.has(ts.getNodeId(expression.original).toString()); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -127982,6 +129909,54 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var errorCodes = [ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error.code]; + var fixId = "convertToTypeOnlyImport"; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + var importDeclaration = getImportDeclarationForDiagnosticSpan(context.span, context.sourceFile); + fixSingleImportDeclaration(t, importDeclaration, context); + }); + if (changes.length) { + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_type_only_import, fixId, ts.Diagnostics.Convert_all_imports_not_used_as_a_value_to_type_only_imports)]; + } + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var importDeclaration = getImportDeclarationForDiagnosticSpan(diag, context.sourceFile); + fixSingleImportDeclaration(changes, importDeclaration, context); + }); + } + }); + function getImportDeclarationForDiagnosticSpan(span, sourceFile) { + return ts.tryCast(ts.getTokenAtPosition(sourceFile, span.start).parent, ts.isImportDeclaration); + } + function fixSingleImportDeclaration(changes, importDeclaration, context) { + if (!(importDeclaration === null || importDeclaration === void 0 ? void 0 : importDeclaration.importClause)) { + return; + } + var importClause = importDeclaration.importClause; + // `changes.insertModifierBefore` produces a range that might overlap further changes + changes.insertText(context.sourceFile, importDeclaration.getStart() + "import".length, " type"); + // `import type foo, { Bar }` is not allowed, so move `foo` to new declaration + if (importClause.name && importClause.namedBindings) { + changes.deleteNodeRangeExcludingEnd(context.sourceFile, importClause.name, importDeclaration.importClause.namedBindings); + changes.insertNodeBefore(context.sourceFile, importDeclaration, ts.updateImportDeclaration(importDeclaration, + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(importClause.name, + /*namedBindings*/ undefined, + /*isTypeOnly*/ true), importDeclaration.moduleSpecifier)); + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -127995,7 +129970,7 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile, span = context.span; var classDeclaration = getClass(sourceFile, span.start); - return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { + return ts.mapDefined(ts.getEffectiveImplementsTypeNodes(classDeclaration), function (implementedTypeNode) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces); }); @@ -128006,7 +129981,7 @@ var ts; return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var classDeclaration = getClass(diag.file, diag.start); if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { - for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { + for (var _i = 0, _a = ts.getEffectiveImplementsTypeNodes(classDeclaration); _i < _a.length; _i++) { var implementedTypeNode = _a[_i]; addMissingDeclarations(context, implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); } @@ -128015,7 +129990,7 @@ var ts; }, }); function getClass(sourceFile, pos) { - return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos)), "There should be a containing class"); + return ts.Debug.checkDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos)), "There should be a containing class"); } function symbolPointsToNonPrivateMember(symbol) { return !symbol.valueDeclaration || !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); @@ -128036,7 +130011,9 @@ var ts; if (!classType.getStringIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 0 /* String */); } - codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, context, preferences, function (member) { return insertInterfaceMemberNode(sourceFile, classDeclaration, member); }); + var importAdder = codefix.createImportAdder(sourceFile, context.program, preferences, context.host); + codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, context, preferences, importAdder, function (member) { return insertInterfaceMemberNode(sourceFile, classDeclaration, member); }); + importAdder.writeFixes(changeTracker); function createMissingIndexSignatureDeclaration(type, kind) { var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); if (indexInfoOfKind) { @@ -128092,90 +130069,120 @@ var ts; }, fixIds: [importFixId], getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, preferences = context.preferences; - // Namespace fixes don't conflict, so just build a list. - var addToNamespace = []; - var importType = []; - // Keys are import clause node IDs. - var addToExisting = ts.createMap(); - var newImports = ts.createMap(); - var lastModuleSpecifier; - codefix.eachDiagnostic(context, errorCodes, function (diag) { - var info = getFixesInfo(context, diag.code, diag.start); - if (!info || !info.fixes.length) - return; - var fixes = info.fixes, symbolName = info.symbolName; - var fix = ts.first(fixes); - switch (fix.kind) { - case 0 /* UseNamespace */: - addToNamespace.push(fix); - break; - case 1 /* ImportType */: - importType.push(fix); - break; - case 2 /* AddToExisting */: { - var importClause = fix.importClause, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport; - var key = String(ts.getNodeId(importClause)); - var entry = addToExisting.get(key); - if (!entry) { - addToExisting.set(key, entry = { importClause: importClause, defaultImport: undefined, namedImports: [], canUseTypeOnlyImport: canUseTypeOnlyImport }); - } - if (importKind === 0 /* Named */) { - ts.pushIfUnique(entry.namedImports, symbolName); - } - else { - ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName, "(Add to Existing) Default import should be missing or match symbolName"); - entry.defaultImport = symbolName; - } - break; - } - case 3 /* AddNew */: { - var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind; - var entry = newImports.get(moduleSpecifier); - if (!entry) { - newImports.set(moduleSpecifier, entry = { defaultImport: undefined, namedImports: [], namespaceLikeImport: undefined }); - lastModuleSpecifier = moduleSpecifier; - } - switch (importKind) { - case 1 /* Default */: - ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName, "(Add new) Default import should be missing or match symbolName"); - entry.defaultImport = symbolName; - break; - case 0 /* Named */: - ts.pushIfUnique(entry.namedImports, symbolName); - break; - case 3 /* Equals */: - case 2 /* Namespace */: - ts.Debug.assert(entry.namespaceLikeImport === undefined || entry.namespaceLikeImport.name === symbolName, "Namespacelike import shoudl be missing or match symbolName"); - entry.namespaceLikeImport = { importKind: importKind, name: symbolName }; - break; - } - break; - } - default: - ts.Debug.assertNever(fix, "fix wasn't never - got kind " + fix.kind); - } - }); - return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { - var quotePreference = ts.getQuotePreference(sourceFile, preferences); - for (var _i = 0, addToNamespace_1 = addToNamespace; _i < addToNamespace_1.length; _i++) { - var fix = addToNamespace_1[_i]; - addNamespaceQualifier(changes, sourceFile, fix); - } - for (var _a = 0, importType_1 = importType; _a < importType_1.length; _a++) { - var fix = importType_1[_a]; - addImportType(changes, sourceFile, fix, quotePreference); - } - addToExisting.forEach(function (_a) { - var importClause = _a.importClause, defaultImport = _a.defaultImport, namedImports = _a.namedImports, canUseTypeOnlyImport = _a.canUseTypeOnlyImport; - doAddExistingFix(changes, sourceFile, importClause, defaultImport, namedImports, canUseTypeOnlyImport); - }); - newImports.forEach(function (imports, moduleSpecifier) { - addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports, /*blankLineBetween*/ lastModuleSpecifier === moduleSpecifier); - }); - })); + var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences, host = context.host; + var importAdder = createImportAdder(sourceFile, program, preferences, host); + codefix.eachDiagnostic(context, errorCodes, function (diag) { return importAdder.addImportFromDiagnostic(diag, context); }); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, importAdder.writeFixes)); }, }); + function createImportAdder(sourceFile, program, preferences, host) { + var compilerOptions = program.getCompilerOptions(); + // Namespace fixes don't conflict, so just build a list. + var addToNamespace = []; + var importType = []; + // Keys are import clause node IDs. + var addToExisting = ts.createMap(); + var newImports = ts.createMap(); + return { addImportFromDiagnostic: addImportFromDiagnostic, addImportFromExportedSymbol: addImportFromExportedSymbol, writeFixes: writeFixes }; + function addImportFromDiagnostic(diagnostic, context) { + var info = getFixesInfo(context, diagnostic.code, diagnostic.start); + if (!info || !info.fixes.length) + return; + addImport(info); + } + function addImportFromExportedSymbol(exportedSymbol, usageIsTypeOnly) { + var moduleSymbol = ts.Debug.checkDefined(exportedSymbol.parent); + var symbolName = ts.getNameForExportedSymbol(exportedSymbol, ts.getEmitScriptTarget(compilerOptions)); + var checker = program.getTypeChecker(); + var symbol = checker.getMergedSymbol(ts.skipAlias(exportedSymbol, checker)); + var exportInfos = getAllReExportingModules(sourceFile, symbol, moduleSymbol, symbolName, sourceFile, compilerOptions, checker, program.getSourceFiles()); + var preferTypeOnlyImport = !!usageIsTypeOnly && compilerOptions.importsNotUsedAsValues === 2 /* Error */; + var useRequire = shouldUseRequire(sourceFile, compilerOptions); + var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, /*position*/ undefined, preferTypeOnlyImport, useRequire, host, preferences); + addImport({ fixes: [fix], symbolName: symbolName }); + } + function addImport(info) { + var fixes = info.fixes, symbolName = info.symbolName; + var fix = ts.first(fixes); + switch (fix.kind) { + case 0 /* UseNamespace */: + addToNamespace.push(fix); + break; + case 1 /* ImportType */: + importType.push(fix); + break; + case 2 /* AddToExisting */: { + var importClauseOrBindingPattern = fix.importClauseOrBindingPattern, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport; + var key = String(ts.getNodeId(importClauseOrBindingPattern)); + var entry = addToExisting.get(key); + if (!entry) { + addToExisting.set(key, entry = { importClauseOrBindingPattern: importClauseOrBindingPattern, defaultImport: undefined, namedImports: [], canUseTypeOnlyImport: canUseTypeOnlyImport }); + } + if (importKind === 0 /* Named */) { + ts.pushIfUnique(entry.namedImports, symbolName); + } + else { + ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName, "(Add to Existing) Default import should be missing or match symbolName"); + entry.defaultImport = symbolName; + } + break; + } + case 3 /* AddNew */: { + var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind, useRequire = fix.useRequire, typeOnly = fix.typeOnly; + var entry = newImports.get(moduleSpecifier); + if (!entry) { + newImports.set(moduleSpecifier, entry = { namedImports: [], namespaceLikeImport: undefined, typeOnly: typeOnly, useRequire: useRequire }); + } + else { + // An import clause can only be type-only if every import fix contributing to it can be type-only. + entry.typeOnly = entry.typeOnly && typeOnly; + } + switch (importKind) { + case 1 /* Default */: + ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName, "(Add new) Default import should be missing or match symbolName"); + entry.defaultImport = symbolName; + break; + case 0 /* Named */: + ts.pushIfUnique(entry.namedImports || (entry.namedImports = []), symbolName); + break; + case 3 /* CommonJS */: + case 2 /* Namespace */: + ts.Debug.assert(entry.namespaceLikeImport === undefined || entry.namespaceLikeImport.name === symbolName, "Namespacelike import shoudl be missing or match symbolName"); + entry.namespaceLikeImport = { importKind: importKind, name: symbolName }; + break; + } + break; + } + default: + ts.Debug.assertNever(fix, "fix wasn't never - got kind " + fix.kind); + } + } + function writeFixes(changeTracker) { + var quotePreference = ts.getQuotePreference(sourceFile, preferences); + for (var _i = 0, addToNamespace_1 = addToNamespace; _i < addToNamespace_1.length; _i++) { + var fix = addToNamespace_1[_i]; + addNamespaceQualifier(changeTracker, sourceFile, fix); + } + for (var _a = 0, importType_1 = importType; _a < importType_1.length; _a++) { + var fix = importType_1[_a]; + addImportType(changeTracker, sourceFile, fix, quotePreference); + } + addToExisting.forEach(function (_a) { + var importClauseOrBindingPattern = _a.importClauseOrBindingPattern, defaultImport = _a.defaultImport, namedImports = _a.namedImports, canUseTypeOnlyImport = _a.canUseTypeOnlyImport; + doAddExistingFix(changeTracker, sourceFile, importClauseOrBindingPattern, defaultImport, namedImports, canUseTypeOnlyImport); + }); + var newDeclarations; + newImports.forEach(function (_a, moduleSpecifier) { + var useRequire = _a.useRequire, imports = __rest(_a, ["useRequire"]); + var getDeclarations = useRequire ? getNewRequires : getNewImports; + newDeclarations = ts.combine(newDeclarations, getDeclarations(moduleSpecifier, quotePreference, imports)); + }); + if (newDeclarations) { + ts.insertImports(changeTracker, sourceFile, newDeclarations, /*blankLineBetween*/ true); + } + } + } + codefix.createImportAdder = createImportAdder; // Sorted with the preferred fix coming first. var ImportFixKind; (function (ImportFixKind) { @@ -128189,18 +130196,23 @@ var ts; ImportKind[ImportKind["Named"] = 0] = "Named"; ImportKind[ImportKind["Default"] = 1] = "Default"; ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; - ImportKind[ImportKind["Equals"] = 3] = "Equals"; - ImportKind[ImportKind["ConstEquals"] = 4] = "ConstEquals"; + ImportKind[ImportKind["CommonJS"] = 3] = "CommonJS"; })(ImportKind || (ImportKind = {})); function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { - var exportInfos = getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, sourceFile, program.getCompilerOptions(), program.getTypeChecker(), program.getSourceFiles()); - ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol"); - // We sort the best codefixes first, so taking `first` is best for completions. - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences)).moduleSpecifier; - var fix = ts.first(getFixForImport(exportInfos, symbolName, position, program, sourceFile, host, preferences)); + var compilerOptions = program.getCompilerOptions(); + var exportInfos = getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, sourceFile, compilerOptions, program.getTypeChecker(), program.getSourceFiles()); + var useRequire = shouldUseRequire(sourceFile, compilerOptions); + var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && !ts.isSourceFileJS(sourceFile) && ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences)).moduleSpecifier; + var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences); return { moduleSpecifier: moduleSpecifier, codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences))) }; } codefix.getImportCompletionAction = getImportCompletionAction; + function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences) { + ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol"); + // We sort the best codefixes first, so taking `first` is best. + return ts.first(getFixForImport(exportInfos, symbolName, position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences)); + } function codeFixActionToCodeAction(_a) { var description = _a.description, changes = _a.changes, commands = _a.commands; return { description: description, changes: changes, commands: commands }; @@ -128216,7 +130228,7 @@ var ts; if (defaultInfo && defaultInfo.name === symbolName && ts.skipAlias(defaultInfo.symbol, checker) === exportedSymbol) { result.push({ moduleSymbol: moduleSymbol, importKind: defaultInfo.kind, exportedSymbolIsTypeOnly: isTypeOnlySymbol(defaultInfo.symbol, checker) }); } - for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { var exported = _a[_i]; if (exported.name === symbolName && ts.skipAlias(exported, checker) === exportedSymbol) { result.push({ moduleSymbol: moduleSymbol, importKind: 0 /* Named */, exportedSymbolIsTypeOnly: isTypeOnlySymbol(exported, checker) }); @@ -128233,13 +130245,13 @@ var ts; } function getFixForImport(exportInfos, symbolName, /** undefined only for missing JSX namespace */ - position, program, sourceFile, host, preferences) { + position, preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences) { var checker = program.getTypeChecker(); var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); var useNamespace = position === undefined ? undefined : tryUseExistingNamespaceImport(existingImports, symbolName, position, checker); var addToExisting = tryAddToExistingImport(existingImports, position !== undefined && isTypeOnlyPosition(sourceFile, position)); // Don't bother providing an action to add a new import if we can add to an existing one. - var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences); + var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences); return __spreadArrays((useNamespace ? [useNamespace] : ts.emptyArray), addImport); } function tryUseExistingNamespaceImport(existingImports, symbolName, position, checker) { @@ -128257,58 +130269,91 @@ var ts; // and it is up to the user to decide which one fits best. return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration; - var namespace = getNamespaceImportName(declaration); - if (namespace) { - var moduleSymbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); + var namespacePrefix = getNamespaceLikeImportText(declaration); + if (namespacePrefix) { + var moduleSymbol = getTargetModuleFromNamespaceLikeImport(declaration, checker); if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { - return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, position: position }; + return { kind: 0 /* UseNamespace */, namespacePrefix: namespacePrefix, position: position }; } } }); } + function getTargetModuleFromNamespaceLikeImport(declaration, checker) { + var _a; + switch (declaration.kind) { + case 242 /* VariableDeclaration */: + return checker.resolveExternalModuleName(declaration.initializer.arguments[0]); + case 253 /* ImportEqualsDeclaration */: + return checker.getAliasedSymbol(declaration.symbol); + case 254 /* ImportDeclaration */: + var namespaceImport = ts.tryCast((_a = declaration.importClause) === null || _a === void 0 ? void 0 : _a.namedBindings, ts.isNamespaceImport); + return namespaceImport && checker.getAliasedSymbol(namespaceImport.symbol); + default: + return ts.Debug.assertNever(declaration); + } + } + function getNamespaceLikeImportText(declaration) { + var _a, _b, _c; + switch (declaration.kind) { + case 242 /* VariableDeclaration */: + return (_a = ts.tryCast(declaration.name, ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text; + case 253 /* ImportEqualsDeclaration */: + return declaration.name.text; + case 254 /* ImportDeclaration */: + return (_c = ts.tryCast((_b = declaration.importClause) === null || _b === void 0 ? void 0 : _b.namedBindings, ts.isNamespaceImport)) === null || _c === void 0 ? void 0 : _c.name.text; + default: + return ts.Debug.assertNever(declaration); + } + } function tryAddToExistingImport(existingImports, canUseTypeOnlyImport) { return ts.firstDefined(existingImports, function (_a) { var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind !== 254 /* ImportDeclaration */) + if (declaration.kind === 253 /* ImportEqualsDeclaration */) return undefined; + if (declaration.kind === 242 /* VariableDeclaration */) { + return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 189 /* ObjectBindingPattern */ + ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: declaration.name, importKind: importKind, moduleSpecifier: declaration.initializer.arguments[0].text, canUseTypeOnlyImport: false } + : undefined; + } var importClause = declaration.importClause; if (!importClause) return undefined; var name = importClause.name, namedBindings = importClause.namedBindings; return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 257 /* NamedImports */) - ? { kind: 2 /* AddToExisting */, importClause: importClause, importKind: importKind, canUseTypeOnlyImport: canUseTypeOnlyImport } + ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind: importKind, moduleSpecifier: declaration.moduleSpecifier.getText(), canUseTypeOnlyImport: canUseTypeOnlyImport } : undefined; }); } - function getNamespaceImportName(declaration) { - if (declaration.kind === 254 /* ImportDeclaration */) { - var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; - return namedBindings && namedBindings.kind === 256 /* NamespaceImport */ ? namedBindings.name : undefined; - } - else { - return declaration.name; - } - } function getExistingImportDeclarations(_a, checker, sourceFile) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; // Can't use an es6 import for a type in JS. return exportedSymbolIsTypeOnly && ts.isSourceFileJS(sourceFile) ? ts.emptyArray : ts.mapDefined(sourceFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); - return (i.kind === 254 /* ImportDeclaration */ || i.kind === 253 /* ImportEqualsDeclaration */) - && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind, exportedSymbolIsTypeOnly: exportedSymbolIsTypeOnly } : undefined; + if (ts.isRequireVariableDeclaration(i.parent, /*requireStringLiteralLikeArgument*/ true)) { + return checker.resolveExternalModuleName(moduleSpecifier) === moduleSymbol ? { declaration: i.parent, importKind: importKind } : undefined; + } + if (i.kind === 254 /* ImportDeclaration */ || i.kind === 253 /* ImportEqualsDeclaration */) { + return checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; + } }); } - function getNewImportInfos(program, sourceFile, position, moduleSymbols, host, preferences) { + function shouldUseRequire(sourceFile, compilerOptions) { + return ts.isSourceFileJS(sourceFile) + && !sourceFile.externalModuleIndicator + && (!!sourceFile.commonJsModuleIndicator || ts.getEmitModuleKind(compilerOptions) < ts.ModuleKind.ES2015); + } + function getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, moduleSymbols, host, preferences) { var isJs = ts.isSourceFileJS(sourceFile); + var compilerOptions = program.getCompilerOptions(); var allowsImportingSpecifier = createAutoImportFilter(sourceFile, program, host).allowsImportingSpecifier; var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind, exportedSymbolIsTypeOnly = _a.exportedSymbolIsTypeOnly; - return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) + return ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, compilerOptions, sourceFile, ts.createModuleSpecifierResolutionHost(program, host), preferences) .map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return exportedSymbolIsTypeOnly && isJs - ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.assertDefined(position, "position should be defined") } - : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }; + ? { kind: 1 /* ImportType */, moduleSpecifier: moduleSpecifier, position: ts.Debug.checkDefined(position, "position should be defined") } + : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind, useRequire: useRequire, typeOnly: preferTypeOnlyImport }; }); }); // Sort by presence in package.json, then shortest paths first @@ -128324,19 +130369,18 @@ var ts; return a.moduleSpecifier.length - b.moduleSpecifier.length; }); } - function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, host, preferences) { - var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); - return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, exportInfos, host, preferences); + function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, position, preferTypeOnlyImport, useRequire, host, preferences) { + var existingDeclaration = ts.firstDefined(existingImports, function (info) { return newImportInfoFromExistingSpecifier(info, preferTypeOnlyImport, useRequire); }); + return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences); } - function newImportInfoFromExistingSpecifier(_a) { + function newImportInfoFromExistingSpecifier(_a, preferTypeOnlyImport, useRequire) { var declaration = _a.declaration, importKind = _a.importKind; - var expression = declaration.kind === 254 /* ImportDeclaration */ - ? declaration.moduleSpecifier - : declaration.moduleReference.kind === 265 /* ExternalModuleReference */ - ? declaration.moduleReference.expression - : undefined; - return expression && ts.isStringLiteral(expression) - ? { kind: 3 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } + var moduleSpecifier = declaration.kind === 254 /* ImportDeclaration */ ? declaration.moduleSpecifier : + declaration.kind === 242 /* VariableDeclaration */ ? declaration.initializer.arguments[0] : + declaration.moduleReference.kind === 265 /* ExternalModuleReference */ ? declaration.moduleReference.expression : + undefined; + return moduleSpecifier && ts.isStringLiteral(moduleSpecifier) + ? { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier.text, importKind: importKind, typeOnly: preferTypeOnlyImport, useRequire: useRequire } : undefined; } function getFixesInfo(context, errorCode, pos) { @@ -128355,7 +130399,8 @@ var ts; var symbol = checker.getAliasedSymbol(umdSymbol); var symbolName = umdSymbol.name; var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(sourceFile, program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }]; - var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, program, sourceFile, host, preferences); + var useRequire = shouldUseRequire(sourceFile, program.getCompilerOptions()); + var fixes = getFixForImport(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, useRequire, program, sourceFile, host, preferences); return { fixes: fixes, symbolName: symbolName }; } function getUmdSymbol(token, checker) { @@ -128381,9 +130426,9 @@ var ts; case ts.ModuleKind.CommonJS: case ts.ModuleKind.UMD: if (ts.isInJSFile(importingFile)) { - return ts.isExternalModule(importingFile) ? 2 /* Namespace */ : 4 /* ConstEquals */; + return ts.isExternalModule(importingFile) ? 2 /* Namespace */ : 3 /* CommonJS */; } - return 3 /* Equals */; + return 3 /* CommonJS */; case ts.ModuleKind.System: case ts.ModuleKind.ES2015: case ts.ModuleKind.ES2020: @@ -128406,10 +130451,13 @@ var ts; : symbolToken.text; // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default" /* Default */, "'default' isn't a legal identifier and couldn't occur here"); + var compilerOptions = program.getCompilerOptions(); + var preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === 2 /* Error */ && ts.isValidTypeOnlyAliasUseSite(symbolToken); + var useRequire = shouldUseRequire(sourceFile, compilerOptions); var exportInfos = getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program, host); var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfos.entries(), function (_a) { var _ = _a[0], exportInfos = _a[1]; - return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), program, sourceFile, host, preferences); + return getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences); })); return { fixes: fixes, symbolName: symbolName }; } @@ -128460,7 +130508,7 @@ var ts; // 2. 'import =' will not work in JavaScript, so the decision is between a default // and const/require. if (ts.isInJSFile(importingFile)) { - return ts.isExternalModule(importingFile) ? 1 /* Default */ : 4 /* ConstEquals */; + return ts.isExternalModule(importingFile) ? 1 /* Default */ : 3 /* CommonJS */; } // 3. At this point the most correct choice is probably 'import =', but people // really hate that, so look to see if the importing file has any precedent @@ -128468,12 +130516,12 @@ var ts; for (var _i = 0, _a = importingFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (ts.isImportEqualsDeclaration(statement)) { - return 3 /* Equals */; + return 3 /* CommonJS */; } } // 4. We have no precedent to go on, so just use a default import if // allowSyntheticDefaultImports/esModuleInterop is enabled. - return allowSyntheticDefaults ? 1 /* Default */ : 3 /* Equals */; + return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */; } function getDefaultExportInfoWorker(defaultExport, moduleSymbol, checker, compilerOptions) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); @@ -128484,7 +130532,7 @@ var ts; return { symbolForMeaning: defaultExport, name: name }; if (defaultExport.flags & 2097152 /* Alias */) { var aliased = checker.getImmediateAliasedSymbol(defaultExport); - return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.assertDefined(aliased.parent, "Alias targets of default exports must have a parent"), checker, compilerOptions); + return aliased && getDefaultExportInfoWorker(aliased, ts.Debug.checkDefined(aliased.parent, "Alias targets of default exports must have a parent"), checker, compilerOptions); } if (defaultExport.escapedName !== "default" /* Default */ && defaultExport.escapedName !== "export=" /* ExportEquals */) { @@ -128521,16 +130569,18 @@ var ts; addImportType(changes, sourceFile, fix, quotePreference); return [ts.Diagnostics.Change_0_to_1, symbolName, getImportTypePrefix(fix.moduleSpecifier, quotePreference) + symbolName]; case 2 /* AddToExisting */: { - var importClause = fix.importClause, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport; - doAddExistingFix(changes, sourceFile, importClause, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray, canUseTypeOnlyImport); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(importClause.parent.moduleSpecifier.getText()); + var importClauseOrBindingPattern = fix.importClauseOrBindingPattern, importKind = fix.importKind, canUseTypeOnlyImport = fix.canUseTypeOnlyImport, moduleSpecifier = fix.moduleSpecifier; + doAddExistingFix(changes, sourceFile, importClauseOrBindingPattern, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray, canUseTypeOnlyImport); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); return [importKind === 1 /* Default */ ? ts.Diagnostics.Add_default_import_0_to_existing_import_declaration_from_1 : ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; // you too! } case 3 /* AddNew */: { - var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier; - addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, importKind === 1 /* Default */ ? { defaultImport: symbolName, namedImports: ts.emptyArray, namespaceLikeImport: undefined } - : importKind === 0 /* Named */ ? { defaultImport: undefined, namedImports: [symbolName], namespaceLikeImport: undefined } - : { defaultImport: undefined, namedImports: ts.emptyArray, namespaceLikeImport: { importKind: importKind, name: symbolName } }, /*blankLineBetween*/ true); + var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier, typeOnly = fix.typeOnly, useRequire = fix.useRequire; + var getDeclarations = useRequire ? getNewRequires : getNewImports; + var importsCollection = importKind === 1 /* Default */ ? { defaultImport: symbolName, typeOnly: typeOnly } : + importKind === 0 /* Named */ ? { namedImports: [symbolName], typeOnly: typeOnly } : + { namespaceLikeImport: { importKind: importKind, name: symbolName }, typeOnly: typeOnly }; + ts.insertImports(changes, sourceFile, getDeclarations(moduleSpecifier, quotePreference, importsCollection), /*blankLineBetween*/ true); return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; } default: @@ -128538,6 +130588,16 @@ var ts; } } function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, canUseTypeOnlyImport) { + if (clause.kind === 189 /* ObjectBindingPattern */) { + if (defaultImport) { + addElementToBindingPattern(clause, defaultImport, "default"); + } + for (var _i = 0, namedImports_1 = namedImports; _i < namedImports_1.length; _i++) { + var specifier = namedImports_1[_i]; + addElementToBindingPattern(clause, specifier, /*propertyName*/ undefined); + } + return; + } var convertTypeOnlyToRegular = !canUseTypeOnlyImport && clause.isTypeOnly; if (defaultImport) { ts.Debug.assert(!clause.name, "Cannot add a default import to an import clause that already has one"); @@ -128546,19 +130606,19 @@ var ts; if (namedImports.length) { var specifiers = namedImports.map(function (name) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); }); if (clause.namedBindings && ts.cast(clause.namedBindings, ts.isNamedImports).elements.length) { - for (var _i = 0, specifiers_1 = specifiers; _i < specifiers_1.length; _i++) { - var spec = specifiers_1[_i]; + for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { + var spec = specifiers_1[_a]; changes.insertNodeInListAfter(sourceFile, ts.last(ts.cast(clause.namedBindings, ts.isNamedImports).elements), spec); } } else { if (specifiers.length) { - var namedImports_1 = ts.createNamedImports(specifiers); + var namedImports_2 = ts.createNamedImports(specifiers); if (clause.namedBindings) { - changes.replaceNode(sourceFile, clause.namedBindings, namedImports_1); + changes.replaceNode(sourceFile, clause.namedBindings, namedImports_2); } else { - changes.insertNodeAfter(sourceFile, ts.Debug.assertDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports_1); + changes.insertNodeAfter(sourceFile, ts.Debug.checkDefined(clause.name, "Import clause must have either named imports or a default import"), namedImports_2); } } } @@ -128566,6 +130626,15 @@ var ts; if (convertTypeOnlyToRegular) { changes.delete(sourceFile, ts.getTypeKeywordOfTypeOnlyImport(clause, sourceFile)); } + function addElementToBindingPattern(bindingPattern, name, propertyName) { + var element = ts.createBindingElement(/*dotDotDotToken*/ undefined, propertyName, name); + if (bindingPattern.elements.length) { + changes.insertNodeInListAfter(sourceFile, ts.last(bindingPattern.elements), element); + } + else { + changes.replaceNode(sourceFile, bindingPattern, ts.createObjectBindingPattern([element])); + } + } } function addNamespaceQualifier(changes, sourceFile, _a) { var namespacePrefix = _a.namespacePrefix, position = _a.position; @@ -128579,21 +130648,51 @@ var ts; var quote = ts.getQuoteFromPreference(quotePreference); return "import(" + quote + moduleSpecifier + quote + ")."; } - function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, _a, blankLineBetween) { - var defaultImport = _a.defaultImport, namedImports = _a.namedImports, namespaceLikeImport = _a.namespaceLikeImport; + function getNewImports(moduleSpecifier, quotePreference, imports) { + var _a, _b; var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); - if (defaultImport !== undefined || namedImports.length) { - ts.insertImport(changes, sourceFile, ts.makeImport(defaultImport === undefined ? undefined : ts.createIdentifier(defaultImport), namedImports.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference), /*blankLineBetween*/ blankLineBetween); + var statements; + if (imports.defaultImport !== undefined || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) { + statements = ts.combine(statements, ts.makeImport(imports.defaultImport === undefined ? undefined : ts.createIdentifier(imports.defaultImport), (_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference, imports.typeOnly)); } + var namespaceLikeImport = imports.namespaceLikeImport, typeOnly = imports.typeOnly; if (namespaceLikeImport) { - ts.insertImport(changes, sourceFile, namespaceLikeImport.importKind === 3 /* Equals */ ? ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier)) : - namespaceLikeImport.importKind === 4 /* ConstEquals */ ? createConstEqualsRequireDeclaration(namespaceLikeImport.name, quotedModuleSpecifier) : - ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier), /*blankLineBetween*/ blankLineBetween); + var declaration = namespaceLikeImport.importKind === 3 /* CommonJS */ + ? ts.createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier)) + : ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause( + /*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name)), typeOnly), quotedModuleSpecifier); + statements = ts.combine(statements, declaration); } + return ts.Debug.checkDefined(statements); + } + function getNewRequires(moduleSpecifier, quotePreference, imports) { + var _a, _b; + var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + var statements; + // const { default: foo, bar, etc } = require('./mod'); + if (imports.defaultImport || ((_a = imports.namedImports) === null || _a === void 0 ? void 0 : _a.length)) { + var bindingElements = ((_b = imports.namedImports) === null || _b === void 0 ? void 0 : _b.map(function (name) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name); })) || []; + if (imports.defaultImport) { + bindingElements.unshift(ts.createBindingElement(/*dotDotDotToken*/ undefined, "default", imports.defaultImport)); + } + var declaration = createConstEqualsRequireDeclaration(ts.createObjectBindingPattern(bindingElements), quotedModuleSpecifier); + statements = ts.combine(statements, declaration); + } + // const foo = require('./mod'); + if (imports.namespaceLikeImport) { + var declaration = createConstEqualsRequireDeclaration(imports.namespaceLikeImport.name, quotedModuleSpecifier); + statements = ts.combine(statements, declaration); + } + return ts.Debug.checkDefined(statements); } function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) { - return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(ts.createIdentifier(name), + return ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(typeof name === "string" ? ts.createIdentifier(name) : name, /*type*/ undefined, ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [quotedModuleSpecifier])) ], 2 /* Const */)); } @@ -128603,12 +130702,11 @@ var ts; } function forEachExternalModuleToImportFrom(program, host, from, filterByPackageJson, cb) { var filteredCount = 0; - var packageJson = filterByPackageJson && createAutoImportFilter(from, program, host); - var allSourceFiles = program.getSourceFiles(); - var globalTypingsCache = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); - forEachExternalModule(program.getTypeChecker(), allSourceFiles, function (module, sourceFile) { + var moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); + var packageJson = filterByPackageJson && createAutoImportFilter(from, program, host, moduleSpecifierResolutionHost); + forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), function (module, sourceFile) { if (sourceFile === undefined) { - if (!packageJson || packageJson.allowsImportingAmbientModule(module, allSourceFiles)) { + if (!packageJson || packageJson.allowsImportingAmbientModule(module)) { cb(module); } else if (packageJson) { @@ -128617,8 +130715,8 @@ var ts; } else if (sourceFile && sourceFile !== from && - isImportablePath(from.fileName, sourceFile.fileName, ts.hostGetCanonicalFileName(host), globalTypingsCache)) { - if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile, allSourceFiles)) { + isImportableFile(program, from, sourceFile, moduleSpecifierResolutionHost)) { + if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile)) { cb(module); } else if (packageJson) { @@ -128643,6 +130741,19 @@ var ts; } } } + function isImportableFile(program, from, to, moduleSpecifierResolutionHost) { + var _a; + var getCanonicalFileName = ts.hostGetCanonicalFileName(moduleSpecifierResolutionHost); + var globalTypingsCache = (_a = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation) === null || _a === void 0 ? void 0 : _a.call(moduleSpecifierResolutionHost); + return !!ts.moduleSpecifiers.forEachFileNameOfModule(from.fileName, to.fileName, moduleSpecifierResolutionHost, + /*preferSymlinks*/ false, function (toPath) { + var toFile = program.getSourceFile(toPath); + // Determine to import using toPath only if toPath is what we were looking at + // or there doesnt exist the file in the program by the symlink + return (toFile === to || !toFile) && + isImportablePath(from.fileName, toPath, getCanonicalFileName, globalTypingsCache); + }); + } /** * Don't include something from a `node_modules` that isn't actually reachable by a global import. * A relative import to node_modules is usually a bad idea. @@ -128686,22 +130797,12 @@ var ts; return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; } codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; - function createAutoImportFilter(fromFile, program, host) { + function createAutoImportFilter(fromFile, program, host, moduleSpecifierResolutionHost) { + if (moduleSpecifierResolutionHost === void 0) { moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); } var packageJsons = host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName) || ts.getPackageJsonsVisibleToFile(fromFile.fileName, host); var dependencyGroups = 1 /* Dependencies */ | 2 /* DevDependencies */ | 8 /* OptionalDependencies */; - // Mix in `getProbablySymlinks` from Program when host doesn't have it - // in order for non-Project hosts to have a symlinks cache. - var moduleSpecifierResolutionHost = { - directoryExists: ts.maybeBind(host, host.directoryExists), - fileExists: ts.maybeBind(host, host.fileExists), - getCurrentDirectory: ts.maybeBind(host, host.getCurrentDirectory), - readFile: ts.maybeBind(host, host.readFile), - useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), - getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks) || program.getProbableSymlinks, - getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation), - }; var usesNodeCoreModules; - return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier }; + return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier, moduleSpecifierResolutionHost: moduleSpecifierResolutionHost }; function moduleSpecifierIsCoveredByPackageJson(specifier) { var packageName = getNodeModuleRootSpecifier(specifier); for (var _i = 0, packageJsons_1 = packageJsons; _i < packageJsons_1.length; _i++) { @@ -128712,12 +130813,12 @@ var ts; } return false; } - function allowsImportingAmbientModule(moduleSymbol, allSourceFiles) { + function allowsImportingAmbientModule(moduleSymbol) { if (!packageJsons.length) { return true; } var declaringSourceFile = moduleSymbol.valueDeclaration.getSourceFile(); - var declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName, allSourceFiles); + var declaringNodeModuleName = getNodeModulesPackageNameFromFileName(declaringSourceFile.fileName); if (typeof declaringNodeModuleName === "undefined") { return true; } @@ -128728,11 +130829,11 @@ var ts; return moduleSpecifierIsCoveredByPackageJson(declaringNodeModuleName) || moduleSpecifierIsCoveredByPackageJson(declaredModuleSpecifier); } - function allowsImportingSourceFile(sourceFile, allSourceFiles) { + function allowsImportingSourceFile(sourceFile) { if (!packageJsons.length) { return true; } - var moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName, allSourceFiles); + var moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName); if (!moduleSpecifier) { return true; } @@ -128767,11 +130868,11 @@ var ts; } return false; } - function getNodeModulesPackageNameFromFileName(importedFileName, allSourceFiles) { + function getNodeModulesPackageNameFromFileName(importedFileName) { if (!ts.stringContains(importedFileName, "node_modules")) { return undefined; } - var specifier = ts.moduleSpecifiers.getNodeModulesPackageName(host.getCompilationSettings(), fromFile.path, importedFileName, moduleSpecifierResolutionHost, allSourceFiles, program.redirectTargetsMap); + var specifier = ts.moduleSpecifiers.getNodeModulesPackageName(host.getCompilationSettings(), fromFile.path, importedFileName, moduleSpecifierResolutionHost); if (!specifier) { return undefined; } @@ -128794,6 +130895,68 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixImplicitThis"; + var errorCodes = [ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, span = context.span; + var diagnostic; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { + diagnostic = doChange(t, sourceFile, span.start, program.getTypeChecker()); + }); + return diagnostic ? [codefix.createCodeFixAction(fixId, changes, diagnostic, fixId, ts.Diagnostics.Fix_all_implicit_this_errors)] : ts.emptyArray; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + doChange(changes, diag.file, diag.start, context.program.getTypeChecker()); + }); }, + }); + function doChange(changes, sourceFile, pos, checker) { + var token = ts.getTokenAtPosition(sourceFile, pos); + ts.Debug.assert(token.kind === 104 /* ThisKeyword */); + var fn = ts.getThisContainer(token, /*includeArrowFunctions*/ false); + if (!ts.isFunctionDeclaration(fn) && !ts.isFunctionExpression(fn)) + return undefined; + if (!ts.isSourceFile(ts.getThisContainer(fn, /*includeArrowFunctions*/ false))) { // 'this' is defined outside, convert to arrow function + var fnKeyword = ts.Debug.assertDefined(ts.findChildOfKind(fn, 94 /* FunctionKeyword */, sourceFile)); + var name = fn.name; + var body = ts.Debug.assertDefined(fn.body); // Should be defined because the function contained a 'this' expression + if (ts.isFunctionExpression(fn)) { + if (name && ts.FindAllReferences.Core.isSymbolReferencedInFile(name, checker, sourceFile, body)) { + // Function expression references itself. To fix we would have to extract it to a const. + return undefined; + } + // `function() {}` --> `() => {}` + changes.delete(sourceFile, fnKeyword); + if (name) { + changes.delete(sourceFile, name); + } + changes.insertText(sourceFile, body.pos, " =>"); + return [ts.Diagnostics.Convert_function_expression_0_to_arrow_function, name ? name.text : ts.ANONYMOUS]; + } + else { + // `function f() {}` => `const f = () => {}` + // `name` should be defined because we only do this in inner contexts, and name is only undefined for `export default function() {}`. + changes.replaceNode(sourceFile, fnKeyword, ts.createToken(81 /* ConstKeyword */)); + changes.insertText(sourceFile, name.end, " = "); + changes.insertText(sourceFile, body.pos, " =>"); + return [ts.Diagnostics.Convert_function_declaration_0_to_arrow_function, name.text]; + } + } + // No outer 'this', add a @class tag if in a JS constructor function + else if (ts.isSourceFileJS(sourceFile) && ts.isPropertyAccessExpression(token.parent) && ts.isAssignmentExpression(token.parent.parent)) { + codefix.addJSDocTags(changes, sourceFile, fn, [ts.createJSDocClassTag()]); + return ts.Diagnostics.Add_class_tag; + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -128830,19 +130993,19 @@ var ts; // this.speling = 1; // ^^^^^^^ var node = ts.getTokenAtPosition(sourceFile, pos); + var parent = node.parent; var checker = context.program.getTypeChecker(); var suggestedSymbol; - if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { + if (ts.isPropertyAccessExpression(parent) && parent.name === node) { ts.Debug.assert(ts.isIdentifierOrPrivateIdentifier(node), "Expected an identifier for spelling (property access)"); - var containingType = checker.getTypeAtLocation(node.parent.expression); - if (node.parent.flags & 32 /* OptionalChain */) { + var containingType = checker.getTypeAtLocation(parent.expression); + if (parent.flags & 32 /* OptionalChain */) { containingType = checker.getNonNullableType(containingType); } - var name = node; - suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(name, containingType); + suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(node, containingType); } - else if (ts.isImportSpecifier(node.parent) && node.parent.name === node) { - ts.Debug.assert(node.kind === 75 /* Identifier */, "Expected an identifier for spelling (import)"); + else if (ts.isImportSpecifier(parent) && parent.name === node) { + ts.Debug.assertNode(node, ts.isIdentifier, "Expected an identifier for spelling (import)"); var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); if (resolvedSourceFile && resolvedSourceFile.symbol) { @@ -128897,6 +131060,192 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "returnValueCorrect"; + var fixIdAddReturnStatement = "fixAddReturnStatement"; + var fixIdRemoveBlockBodyBrace = "fixRemoveBlockBodyBrace"; + var fixIdWrapTheBlockWithParen = "fixWrapTheBlockWithParen"; + var errorCodes = [ + ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code, + ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code + ]; + var ProblemKind; + (function (ProblemKind) { + ProblemKind[ProblemKind["MissingReturnStatement"] = 0] = "MissingReturnStatement"; + ProblemKind[ProblemKind["MissingParentheses"] = 1] = "MissingParentheses"; + })(ProblemKind || (ProblemKind = {})); + codefix.registerCodeFix({ + errorCodes: errorCodes, + fixIds: [fixIdAddReturnStatement, fixIdRemoveBlockBodyBrace, fixIdWrapTheBlockWithParen], + getCodeActions: function (context) { + var program = context.program, sourceFile = context.sourceFile, start = context.span.start, errorCode = context.errorCode; + var info = getInfo(program.getTypeChecker(), sourceFile, start, errorCode); + if (!info) + return undefined; + if (info.kind === ProblemKind.MissingReturnStatement) { + return ts.append([getActionForfixAddReturnStatement(context, info.expression, info.statement)], ts.isArrowFunction(info.declaration) ? getActionForfixRemoveBlockBodyBrace(context, info.declaration, info.expression, info.commentSource) : undefined); + } + else { + return [getActionForfixWrapTheBlockWithParen(context, info.declaration, info.expression)]; + } + }, + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(context.program.getTypeChecker(), diag.file, diag.start, diag.code); + if (!info) + return undefined; + switch (context.fixId) { + case fixIdAddReturnStatement: + addReturnStatement(changes, diag.file, info.expression, info.statement); + break; + case fixIdRemoveBlockBodyBrace: + if (!ts.isArrowFunction(info.declaration)) + return undefined; + removeBlockBodyBrace(changes, diag.file, info.declaration, info.expression, info.commentSource, /* withParen */ false); + break; + case fixIdWrapTheBlockWithParen: + if (!ts.isArrowFunction(info.declaration)) + return undefined; + wrapBlockWithParen(changes, diag.file, info.declaration, info.expression); + break; + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); }, + }); + function getFixInfo(checker, declaration, expectType, isFunctionType) { + if (!declaration.body || !ts.isBlock(declaration.body) || ts.length(declaration.body.statements) !== 1) + return undefined; + var firstStatement = ts.first(declaration.body.statements); + if (ts.isExpressionStatement(firstStatement) && checkFixedAssignableTo(checker, declaration, firstStatement.expression, expectType, isFunctionType)) { + return { + declaration: declaration, + kind: ProblemKind.MissingReturnStatement, + expression: firstStatement.expression, + statement: firstStatement, + commentSource: firstStatement.expression + }; + } + else if (ts.isLabeledStatement(firstStatement) && ts.isExpressionStatement(firstStatement.statement)) { + var node = ts.createObjectLiteral([ts.createPropertyAssignment(firstStatement.label, firstStatement.statement.expression)]); + if (checkFixedAssignableTo(checker, declaration, node, expectType, isFunctionType)) { + return ts.isArrowFunction(declaration) ? { + declaration: declaration, + kind: ProblemKind.MissingParentheses, + expression: node, + statement: firstStatement, + commentSource: firstStatement.statement.expression + } : { + declaration: declaration, + kind: ProblemKind.MissingReturnStatement, + expression: node, + statement: firstStatement, + commentSource: firstStatement.statement.expression + }; + } + } + else if (ts.isBlock(firstStatement) && ts.length(firstStatement.statements) === 1) { + var firstBlockStatement = ts.first(firstStatement.statements); + if (ts.isLabeledStatement(firstBlockStatement) && ts.isExpressionStatement(firstBlockStatement.statement)) { + var node = ts.createObjectLiteral([ts.createPropertyAssignment(firstBlockStatement.label, firstBlockStatement.statement.expression)]); + if (checkFixedAssignableTo(checker, declaration, node, expectType, isFunctionType)) { + return { + declaration: declaration, + kind: ProblemKind.MissingReturnStatement, + expression: node, + statement: firstStatement, + commentSource: firstBlockStatement + }; + } + } + } + return undefined; + } + function checkFixedAssignableTo(checker, declaration, expr, type, isFunctionType) { + return checker.isTypeAssignableTo(checker.getTypeAtLocation(isFunctionType ? ts.updateFunctionLikeBody(declaration, ts.createBlock([ts.createReturn(expr)])) : expr), type); + } + function getInfo(checker, sourceFile, position, errorCode) { + var node = ts.getTokenAtPosition(sourceFile, position); + if (!node.parent) + return undefined; + var declaration = ts.findAncestor(node.parent, ts.isFunctionLikeDeclaration); + switch (errorCode) { + case ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value.code: + if (!declaration || !declaration.body || !declaration.type || !ts.rangeContainsRange(declaration.type, node)) + return undefined; + return getFixInfo(checker, declaration, checker.getTypeFromTypeNode(declaration.type), /* isFunctionType */ false); + case ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code: + if (!declaration || !ts.isCallExpression(declaration.parent) || !declaration.body) + return undefined; + var pos = declaration.parent.arguments.indexOf(declaration); + var type = checker.getContextualTypeForArgumentAtIndex(declaration.parent, pos); + if (!type) + return undefined; + return getFixInfo(checker, declaration, type, /* isFunctionType */ true); + case ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code: + if (!ts.isDeclarationName(node) || !ts.isVariableLike(node.parent) && !ts.isJsxAttribute(node.parent)) + return undefined; + var initializer = getVariableLikeInitializer(node.parent); + if (!initializer || !ts.isFunctionLikeDeclaration(initializer) || !initializer.body) + return undefined; + return getFixInfo(checker, initializer, checker.getTypeAtLocation(node.parent), /* isFunctionType */ true); + } + return undefined; + } + function getVariableLikeInitializer(declaration) { + switch (declaration.kind) { + case 242 /* VariableDeclaration */: + case 156 /* Parameter */: + case 191 /* BindingElement */: + case 159 /* PropertyDeclaration */: + case 281 /* PropertyAssignment */: + return declaration.initializer; + case 273 /* JsxAttribute */: + return declaration.initializer && (ts.isJsxExpression(declaration.initializer) ? declaration.initializer.expression : undefined); + case 282 /* ShorthandPropertyAssignment */: + case 158 /* PropertySignature */: + case 284 /* EnumMember */: + case 323 /* JSDocPropertyTag */: + case 317 /* JSDocParameterTag */: + return undefined; + } + } + function addReturnStatement(changes, sourceFile, expression, statement) { + ts.suppressLeadingAndTrailingTrivia(expression); + var probablyNeedSemi = ts.probablyUsesSemicolons(sourceFile); + changes.replaceNode(sourceFile, statement, ts.createReturn(expression), { + leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude, + suffix: probablyNeedSemi ? ";" : undefined + }); + } + function removeBlockBodyBrace(changes, sourceFile, declaration, expression, commentSource, withParen) { + var newBody = (withParen || ts.needsParentheses(expression)) ? ts.createParen(expression) : expression; + ts.suppressLeadingAndTrailingTrivia(commentSource); + ts.copyComments(commentSource, newBody); + changes.replaceNode(sourceFile, declaration.body, newBody); + } + function wrapBlockWithParen(changes, sourceFile, declaration, expression) { + changes.replaceNode(sourceFile, declaration.body, ts.createParen(expression)); + } + function getActionForfixAddReturnStatement(context, expression, statement) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addReturnStatement(t, context.sourceFile, expression, statement); }); + return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_a_return_statement, fixIdAddReturnStatement, ts.Diagnostics.Add_all_missing_return_statement); + } + function getActionForfixRemoveBlockBodyBrace(context, declaration, expression, commentSource) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return removeBlockBodyBrace(t, context.sourceFile, declaration, expression, commentSource, /* withParen */ false); }); + return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_block_body_braces, fixIdRemoveBlockBodyBrace, ts.Diagnostics.Remove_all_incorrect_body_block_braces); + } + function getActionForfixWrapTheBlockWithParen(context, declaration, expression) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return wrapBlockWithParen(t, context.sourceFile, declaration, expression); }); + return codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal, fixIdWrapTheBlockWithParen, ts.Diagnostics.Wrap_all_object_literal_with_parentheses); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -128921,7 +131270,7 @@ var ts; return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)]; } var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; - var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); + var methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs); var addMember = inJs && !ts.isInterfaceDeclaration(parentDeclaration) ? ts.singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); @@ -128929,7 +131278,7 @@ var ts; }, fixIds: [fixId], getAllCodeActions: function (context) { - var program = context.program, preferences = context.preferences; + var program = context.program; var checker = program.getTypeChecker(); var seen = ts.createMap(); var typeDeclToMembers = new ts.NodeMap(); @@ -128952,7 +131301,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = getAllSupers(classDeclaration, checker); - var _loop_14 = function (info) { + var _loop_13 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -128965,7 +131314,7 @@ var ts; var parentDeclaration = info.parentDeclaration, declSourceFile = info.declSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; // Always prefer to add a method declaration if possible. if (call && !ts.isPrivateIdentifier(token)) { - addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences); + addMethodDeclaration(context, changes, declSourceFile, parentDeclaration, token, call, makeStatic, inJs); } else { if (inJs && !ts.isInterfaceDeclaration(parentDeclaration)) { @@ -128973,13 +131322,13 @@ var ts; } else { var typeNode = getTypeNode(program.getTypeChecker(), parentDeclaration, token); - addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, makeStatic); + addPropertyDeclaration(changes, declSourceFile, parentDeclaration, token.text, typeNode, makeStatic ? 32 /* Static */ : 0); } } }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_14(info); + _loop_13(info); } }); })); @@ -129018,18 +131367,18 @@ var ts; var symbol = leftExpressionType.symbol; if (!symbol || !symbol.declarations) return undefined; - var isClass = ts.find(symbol.declarations, ts.isClassLike); + var classDeclaration = ts.find(symbol.declarations, ts.isClassLike); // Don't suggest adding private identifiers to anything other than a class. - if (!isClass && ts.isPrivateIdentifier(token)) { + if (!classDeclaration && ts.isPrivateIdentifier(token)) { return undefined; } // Prefer to change the class instead of the interface if they are merged - var classOrInterface = isClass || ts.find(symbol.declarations, ts.isInterfaceDeclaration); + var classOrInterface = classDeclaration || ts.find(symbol.declarations, ts.isInterfaceDeclaration); if (classOrInterface && !program.isSourceFileFromExternalLibrary(classOrInterface.getSourceFile())) { var makeStatic = (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); - // Static private identifier properties are not supported yet. - if (makeStatic && ts.isPrivateIdentifier(token)) + if (makeStatic && (ts.isPrivateIdentifier(token) || ts.isInterfaceDeclaration(classOrInterface))) { return undefined; + } var declSourceFile = classOrInterface.getSourceFile(); var inJs = ts.isSourceFileJS(declSourceFile); var call = ts.tryCast(parent.parent, ts.isCallExpression); @@ -129089,8 +131438,15 @@ var ts; } function getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, classDeclaration, token, makeStatic) { var typeNode = getTypeNode(context.program.getTypeChecker(), classDeclaration, token); - var addProp = createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, token.text, typeNode); - return makeStatic || ts.isPrivateIdentifier(token) ? [addProp] : [addProp, createAddIndexSignatureAction(context, declSourceFile, classDeclaration, token.text, typeNode)]; + var actions = [createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, token.text, typeNode, makeStatic ? 32 /* Static */ : 0)]; + if (makeStatic || ts.isPrivateIdentifier(token)) { + return actions; + } + if (ts.startsWithUnderscore(token.text)) { + actions.unshift(createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, token.text, typeNode, 8 /* Private */)); + } + actions.push(createAddIndexSignatureAction(context, declSourceFile, classDeclaration, token.text, typeNode)); + return actions; } function getTypeNode(checker, classDeclaration, token) { var typeNode; @@ -129098,22 +131454,25 @@ var ts; var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, classDeclaration); + typeNode = checker.typeToTypeNode(widenedType, classDeclaration, /*flags*/ undefined); } else { var contextualType = checker.getContextualType(token.parent); - typeNode = contextualType ? checker.typeToTypeNode(contextualType) : undefined; + typeNode = contextualType ? checker.typeToTypeNode(contextualType, /*enclosingDeclaration*/ undefined, /*flags*/ undefined) : undefined; } return typeNode || ts.createKeywordTypeNode(125 /* AnyKeyword */); } - function createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); - return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); + function createAddPropertyDeclarationAction(context, declSourceFile, classDeclaration, tokenName, typeNode, modifierFlags) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, declSourceFile, classDeclaration, tokenName, typeNode, modifierFlags); }); + if (modifierFlags & 8 /* Private */) { + return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Declare_private_property_0, tokenName]); + } + return codefix.createCodeFixAction(fixName, changes, [modifierFlags & 32 /* Static */ ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } - function addPropertyDeclaration(changeTracker, declSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { + function addPropertyDeclaration(changeTracker, declSourceFile, classDeclaration, tokenName, typeNode, modifierFlags) { var property = ts.createProperty( /*decorators*/ undefined, - /*modifiers*/ makeStatic ? [ts.createToken(120 /* StaticKeyword */)] : undefined, tokenName, + /*modifiers*/ modifierFlags ? ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags)) : undefined, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined); var lastProp = getNodeToInsertPropertyAfter(classDeclaration); @@ -129151,16 +131510,17 @@ var ts; // No fixId here because code-fix-all currently only works on adding individual named properties. return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } - function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { // Private methods are not implemented yet. if (ts.isPrivateIdentifier(token)) { return undefined; } - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs); }); return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { - var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, typeDecl); + function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs) { + var importAdder = codefix.createImportAdder(declSourceFile, context.program, context.preferences, context.host); + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, typeDecl, importAdder); var containingMethodDeclaration = ts.getAncestor(callExpression, 161 /* MethodDeclaration */); if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); @@ -129168,6 +131528,7 @@ var ts; else { changeTracker.insertNodeAtClassStart(declSourceFile, typeDecl, methodDeclaration); } + importAdder.writeFixes(changeTracker); } function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) { /** @@ -129180,7 +131541,10 @@ var ts; return !!(type && type.flags & 132 /* StringLike */); }); var enumMember = ts.createEnumMember(token, hasStringInitializer ? ts.createStringLiteral(token.text) : undefined); - changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember)))); + changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember))), { + leadingTriviaOption: ts.textChanges.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts.textChanges.TrailingTriviaOption.Exclude + }); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -129225,7 +131589,7 @@ var ts; (function (codefix) { var fixName = "fixCannotFindModule"; var fixIdInstallTypesPackage = "installTypesPackage"; - var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; + var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations.code; var errorCodes = [ errorCodeCannotFindModule, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, @@ -129320,7 +131684,9 @@ var ts; // Note that this is ultimately derived from a map indexed by symbol names, // so duplicates cannot occur. var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); - codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, context, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + var importAdder = codefix.createImportAdder(sourceFile, context.program, preferences, context.host); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, context, preferences, importAdder, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + importAdder.writeFixes(changeTracker); } function symbolPointsToNonPrivateAndAbstractMember(symbol) { // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files @@ -129408,7 +131774,7 @@ var ts; }); function getNode(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - ts.Debug.assert(token.kind === 129 /* ConstructorKeyword */, "token should be at the constructor keyword"); + ts.Debug.assert(ts.isConstructorDeclaration(token.parent), "token should be at the constructor declaration"); return token.parent; } function doChange(changes, sourceFile, ctr) { @@ -129628,6 +131994,51 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdExpression = "fixInvalidJsxCharacters_expression"; + var fixIdHtmlEntity = "fixInvalidJsxCharacters_htmlEntity"; + var errorCodes = [ + ts.Diagnostics.Unexpected_token_Did_you_mean_or_gt.code, + ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace.code + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + fixIds: [fixIdExpression, fixIdHtmlEntity], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, preferences = context.preferences, span = context.span; + var changeToExpression = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, preferences, sourceFile, span.start, /* useHtmlEntity */ false); }); + var changeToHtmlEntity = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, preferences, sourceFile, span.start, /* useHtmlEntity */ true); }); + return [ + codefix.createCodeFixAction(fixIdExpression, changeToExpression, ts.Diagnostics.Wrap_invalid_character_in_an_expression_container, fixIdExpression, ts.Diagnostics.Wrap_all_invalid_characters_in_an_expression_container), + codefix.createCodeFixAction(fixIdHtmlEntity, changeToHtmlEntity, ts.Diagnostics.Convert_invalid_character_to_its_html_entity_code, fixIdHtmlEntity, ts.Diagnostics.Convert_all_invalid_characters_to_HTML_entity_code) + ]; + }, + getAllCodeActions: function (context) { + return codefix.codeFixAll(context, errorCodes, function (changes, diagnostic) { return doChange(changes, context.preferences, diagnostic.file, diagnostic.start, context.fixId === fixIdHtmlEntity); }); + } + }); + var htmlEntity = { + ">": ">", + "}": "}", + }; + function isValidCharacter(character) { + return ts.hasProperty(htmlEntity, character); + } + function doChange(changes, preferences, sourceFile, start, useHtmlEntity) { + var character = sourceFile.getText()[start]; + // sanity check + if (!isValidCharacter(character)) { + return; + } + var replacement = useHtmlEntity ? htmlEntity[character] : "{" + ts.quote(character, preferences) + "}"; + changes.replaceRangeWithText(sourceFile, { pos: start, end: start + 1 }, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -129742,7 +132153,7 @@ var ts; return codefix.createCodeFixAction(fixName, changes, diag, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations); } function deleteTypeParameters(changes, sourceFile, token) { - changes.delete(sourceFile, ts.Debug.assertDefined(ts.cast(token.parent, ts.isDeclarationWithTypeParameterChildren).typeParameters, "The type parameter to delete should exist")); + changes.delete(sourceFile, ts.Debug.checkDefined(ts.cast(token.parent, ts.isDeclarationWithTypeParameterChildren).typeParameters, "The type parameter to delete should exist")); } // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. function tryGetFullImport(token) { @@ -129777,6 +132188,13 @@ var ts; } if (ts.isIdentifier(token) && canPrefix(token)) { changes.replaceNode(sourceFile, token, ts.createIdentifier("_" + token.text)); + if (ts.isParameter(token.parent)) { + ts.getJSDocParameterTags(token.parent).forEach(function (tag) { + if (ts.isIdentifier(tag.name)) { + changes.replaceNode(sourceFile, tag.name, ts.createIdentifier("_" + tag.name.text)); + } + }); + } } } function canPrefix(token) { @@ -129922,7 +132340,7 @@ var ts; } if (ts.isBlock(statement.parent)) { var end_3 = start + length; - var lastStatement = ts.Debug.assertDefined(lastWhere(ts.sliceAfter(statement.parent.statements, statement), function (s) { return s.pos < end_3; }), "Some statement should be last"); + var lastStatement = ts.Debug.checkDefined(lastWhere(ts.sliceAfter(statement.parent.statements, statement), function (s) { return s.pos < end_3; }), "Some statement should be last"); changes.deleteNodeRange(sourceFile, statement, lastStatement); } else { @@ -130014,7 +132432,7 @@ var ts; } }); function doChange(changes, sourceFile, oldTypeNode, newType, checker) { - changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); // TODO: GH#18217 + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode, /*flags*/ undefined)); // TODO: GH#18217 } function getInfo(sourceFile, pos, checker) { var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), isTypeContainer); @@ -130050,6 +132468,51 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixMissingCallParentheses"; + var errorCodes = [ + ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + fixIds: [fixId], + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var callName = getCallName(sourceFile, span.start); + if (!callName) + return; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, callName); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_call_parentheses, fixId, ts.Diagnostics.Add_all_missing_call_parentheses)]; + }, + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var callName = getCallName(diag.file, diag.start); + if (callName) + doChange(changes, diag.file, callName); + }); } + }); + function doChange(changes, sourceFile, name) { + changes.replaceNodeWithText(sourceFile, name, name.text + "()"); + } + function getCallName(sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start); + if (ts.isPropertyAccessExpression(token.parent)) { + var current = token.parent; + while (ts.isPropertyAccessExpression(current.parent)) { + current = current.parent; + } + return current.name; + } + if (ts.isIdentifier(token)) { + return token; + } + return undefined; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -130129,6 +132592,986 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "inferFromUsage"; + var errorCodes = [ + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code, + ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type.code, + //// Suggestions + // Variable declarations + ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code, + // Variable uses + ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + // Parameter declarations + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code, + // Get Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code, + ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code, + // Set Accessor declarations + ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code, + // Property declarations + ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code, + // Function expressions and declarations + ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host, preferences = context.preferences; + var token = ts.getTokenAtPosition(sourceFile, start); + var declaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host, preferences); }); + var name = declaration && ts.getNameOfDeclaration(declaration); + return !name || changes.length === 0 ? undefined + : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host, preferences = context.preferences; + var markSeen = ts.nodeSeenTracker(); + return codefix.codeFixAll(context, errorCodes, function (changes, err) { + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, preferences); + }); + }, + }); + function getDiagnostic(errorCode, token) { + switch (errorCode) { + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.isSetAccessorDeclaration(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Infer_parameter_types_from_usage; + case ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code: + return ts.Diagnostics.Infer_this_type_of_0_from_usage; + default: + return ts.Diagnostics.Infer_type_of_0_from_usage; + } + } + /** Map suggestion code to error code */ + function mapSuggestionDiagnostic(errorCode) { + switch (errorCode) { + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code; + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code; + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code; + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code; + case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_get_accessor_may_be_inferred_from_usage.code: + return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code; + case ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code; + case ts.Diagnostics.Property_0_implicitly_has_type_any_but_a_better_type_for_its_set_accessor_may_be_inferred_from_usage.code: + return ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code; + case ts.Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: + return ts.Diagnostics.Member_0_implicitly_has_an_1_type.code; + } + return errorCode; + } + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, preferences) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 75 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 104 /* ThisKeyword */) { + return undefined; + } + var parent = token.parent; + var importAdder = codefix.createImportAdder(sourceFile, program, preferences, host); + errorCode = mapSuggestionDiagnostic(errorCode); + switch (errorCode) { + // Variable and Property declarations + case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: + case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: + if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location + annotateVariableDeclaration(changes, importAdder, sourceFile, parent, program, host, cancellationToken); + importAdder.writeFixes(changes); + return parent; + } + if (ts.isPropertyAccessExpression(parent)) { + var type = inferTypeForVariableFromUsage(parent.name, program, cancellationToken); + 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*/ ""); + addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]); + } + importAdder.writeFixes(changes); + return parent; + } + return undefined; + case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { + var symbol = program.getTypeChecker().getSymbolAtLocation(token); + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { + annotateVariableDeclaration(changes, importAdder, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + importAdder.writeFixes(changes); + return symbol.valueDeclaration; + } + return undefined; + } + } + var containingFunction = ts.getContainingFunction(token); + if (containingFunction === undefined) { + return undefined; + } + var declaration; + switch (errorCode) { + // Parameter declarations + case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken); + declaration = containingFunction; + break; + } + // falls through + case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: + if (markSeen(containingFunction)) { + var param = ts.cast(parent, ts.isParameter); + annotateParameters(changes, importAdder, sourceFile, param, containingFunction, program, host, cancellationToken); + declaration = param; + } + break; + // Get Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: + case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: + if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { + annotate(changes, importAdder, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + declaration = containingFunction; + } + break; + // Set Accessor declarations + case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: + if (ts.isSetAccessorDeclaration(containingFunction)) { + annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken); + declaration = containingFunction; + } + break; + // Function 'this' + case ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code: + if (ts.textChanges.isThisTypeAnnotatable(containingFunction) && markSeen(containingFunction)) { + annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken); + declaration = containingFunction; + } + break; + default: + return ts.Debug.fail(String(errorCode)); + } + importAdder.writeFixes(changes); + return declaration; + } + function annotateVariableDeclaration(changes, importAdder, sourceFile, declaration, program, host, cancellationToken) { + if (ts.isIdentifier(declaration.name)) { + annotate(changes, importAdder, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + } + } + function annotateParameters(changes, importAdder, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { + if (!ts.isIdentifier(parameterDeclaration.name)) { + return; + } + var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken); + ts.Debug.assert(containingFunction.parameters.length === parameterInferences.length, "Parameter count and inference count should match"); + if (ts.isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); + } + else { + var needParens = ts.isArrowFunction(containingFunction) && !ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile); + if (needParens) + changes.insertNodeBefore(sourceFile, ts.first(containingFunction.parameters), ts.createToken(20 /* OpenParenToken */)); + for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { + var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, importAdder, sourceFile, declaration, type, program, host); + } + } + if (needParens) + changes.insertNodeAfter(sourceFile, ts.last(containingFunction.parameters), ts.createToken(21 /* CloseParenToken */)); + } + } + function annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken) { + var references = getFunctionReferences(containingFunction, sourceFile, program, cancellationToken); + if (!references || !references.length) { + return; + } + var thisInference = inferTypeFromReferences(program, references, cancellationToken).thisParameter(); + var typeNode = ts.getTypeNodeIfAccessible(thisInference, containingFunction, program, host); + if (!typeNode) { + return; + } + if (ts.isInJSFile(containingFunction)) { + annotateJSDocThis(changes, sourceFile, containingFunction, typeNode); + } + else { + changes.tryInsertThisTypeAnnotation(sourceFile, containingFunction, typeNode); + } + } + function annotateJSDocThis(changes, sourceFile, containingFunction, typeNode) { + addJSDocTags(changes, sourceFile, containingFunction, [ + ts.createJSDocThisTag(ts.createJSDocTypeExpression(typeNode)), + ]); + } + function annotateSetAccessor(changes, importAdder, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { + var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); + if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { + var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); + if (type === program.getTypeChecker().getAnyType()) { + type = inferTypeForVariableFromUsage(param.name, program, cancellationToken); + } + if (ts.isInJSFile(setAccessorDeclaration)) { + annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); + } + else { + annotate(changes, importAdder, sourceFile, param, type, program, host); + } + } + } + function annotate(changes, importAdder, sourceFile, declaration, type, program, host) { + var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host); + if (typeNode) { + if (ts.isInJSFile(sourceFile) && declaration.kind !== 158 /* PropertySignature */) { + var parent = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : declaration; + if (!parent) { + return; + } + var typeExpression = ts.createJSDocTypeExpression(typeNode); + var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, ""); + addJSDocTags(changes, sourceFile, parent, [typeTag]); + } + else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, type, sourceFile, changes, importAdder, ts.getEmitScriptTarget(program.getCompilerOptions()))) { + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); + } + } + } + function tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, type, sourceFile, changes, importAdder, scriptTarget) { + var importableReference = codefix.tryGetAutoImportableReferenceFromImportTypeNode(typeNode, type, scriptTarget); + if (importableReference && changes.tryInsertTypeAnnotation(sourceFile, declaration, importableReference.typeReference)) { + ts.forEach(importableReference.symbols, function (s) { return importAdder.addImportFromExportedSymbol(s, /*usageIsTypeOnly*/ true); }); + return true; + } + return false; + } + function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { + var signature = parameterInferences.length && parameterInferences[0].declaration.parent; + if (!signature) { + return; + } + var paramTags = ts.mapDefined(parameterInferences, function (inference) { + var param = inference.declaration; + // 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 && 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), ""); + }); + addJSDocTags(changes, sourceFile, signature, paramTags); + } + function addJSDocTags(changes, sourceFile, parent, newTags) { + var comments = ts.mapDefined(parent.jsDoc, function (j) { return j.comment; }); + var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }); + var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) { + var merged = tryMergeJsdocTags(tag, newTag); + if (merged) + oldTags[i] = merged; + return !!merged; + }); }); + var tag = ts.createJSDocComment(comments.join("\n"), ts.createNodeArray(__spreadArrays((oldTags || ts.emptyArray), unmergedNewTags))); + var jsDocNode = parent.kind === 202 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent; + jsDocNode.jsDoc = parent.jsDoc; + jsDocNode.jsDocCache = parent.jsDocCache; + changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag); + } + codefix.addJSDocTags = addJSDocTags; + function getJsDocNodeForArrowFunction(signature) { + if (signature.parent.kind === 159 /* PropertyDeclaration */) { + return signature.parent; + } + return signature.parent.parent; + } + function tryMergeJsdocTags(oldTag, newTag) { + if (oldTag.kind !== newTag.kind) { + return undefined; + } + switch (oldTag.kind) { + case 317 /* 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 318 /* JSDocReturnTag */: + return ts.createJSDocReturnTag(newTag.typeExpression, oldTag.comment); + } + } + 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) { + return entry.kind !== 0 /* Span */ ? ts.tryCast(entry.node, ts.isIdentifier) : undefined; + }); + } + function inferTypeForVariableFromUsage(token, program, cancellationToken) { + var references = getReferences(token, program, cancellationToken); + return inferTypeFromReferences(program, references, cancellationToken).single(); + } + function inferTypeForParametersFromUsage(func, sourceFile, program, cancellationToken) { + var references = getFunctionReferences(func, sourceFile, program, cancellationToken); + return references && inferTypeFromReferences(program, references, cancellationToken).parameters(func) || + func.parameters.map(function (p) { return ({ + declaration: p, + type: ts.isIdentifier(p.name) ? inferTypeForVariableFromUsage(p.name, program, cancellationToken) : program.getTypeChecker().getAnyType() + }); }); + } + function getFunctionReferences(containingFunction, sourceFile, program, cancellationToken) { + var searchToken; + switch (containingFunction.kind) { + case 162 /* Constructor */: + searchToken = ts.findChildOfKind(containingFunction, 129 /* ConstructorKeyword */, sourceFile); + break; + case 202 /* ArrowFunction */: + case 201 /* FunctionExpression */: + var parent = containingFunction.parent; + searchToken = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ? + parent.name : + containingFunction.name; + break; + case 244 /* FunctionDeclaration */: + case 161 /* MethodDeclaration */: + searchToken = containingFunction.name; + break; + } + if (!searchToken) { + return undefined; + } + return getReferences(searchToken, program, cancellationToken); + } + function inferTypeFromReferences(program, references, cancellationToken) { + var checker = program.getTypeChecker(); + var builtinConstructors = { + string: function () { return checker.getStringType(); }, + number: function () { return checker.getNumberType(); }, + Array: function (t) { return checker.createArrayType(t); }, + Promise: function (t) { return checker.createPromiseType(t); }, + }; + var builtins = [ + checker.getStringType(), + checker.getNumberType(), + checker.createArrayType(checker.getAnyType()), + checker.createPromiseType(checker.getAnyType()), + ]; + return { + single: single, + parameters: parameters, + thisParameter: thisParameter, + }; + function createEmptyUsage() { + return { + isNumber: undefined, + isString: undefined, + isNumberOrString: undefined, + candidateTypes: undefined, + properties: undefined, + calls: undefined, + constructs: undefined, + numberIndex: undefined, + stringIndex: undefined, + candidateThisTypes: undefined, + inferredTypes: undefined, + }; + } + function combineUsages(usages) { + var combinedProperties = ts.createUnderscoreEscapedMap(); + for (var _i = 0, usages_1 = usages; _i < usages_1.length; _i++) { + var u = usages_1[_i]; + if (u.properties) { + u.properties.forEach(function (p, name) { + if (!combinedProperties.has(name)) { + combinedProperties.set(name, []); + } + combinedProperties.get(name).push(p); + }); + } + } + var properties = ts.createUnderscoreEscapedMap(); + combinedProperties.forEach(function (ps, name) { + properties.set(name, combineUsages(ps)); + }); + return { + isNumber: usages.some(function (u) { return u.isNumber; }), + isString: usages.some(function (u) { return u.isString; }), + isNumberOrString: usages.some(function (u) { return u.isNumberOrString; }), + candidateTypes: ts.flatMap(usages, function (u) { return u.candidateTypes; }), + properties: properties, + calls: ts.flatMap(usages, function (u) { return u.calls; }), + constructs: ts.flatMap(usages, function (u) { return u.constructs; }), + numberIndex: ts.forEach(usages, function (u) { return u.numberIndex; }), + stringIndex: ts.forEach(usages, function (u) { return u.stringIndex; }), + candidateThisTypes: ts.flatMap(usages, function (u) { return u.candidateThisTypes; }), + inferredTypes: undefined, + }; + } + function single() { + return combineTypes(inferTypesFromReferencesSingle(references)); + } + function parameters(declaration) { + if (references.length === 0 || !declaration.parameters) { + return undefined; + } + var usage = createEmptyUsage(); + for (var _i = 0, references_2 = references; _i < references_2.length; _i++) { + var reference = references_2[_i]; + cancellationToken.throwIfCancellationRequested(); + calculateUsageOfNode(reference, usage); + } + var calls = __spreadArrays(usage.constructs || [], usage.calls || []); + return declaration.parameters.map(function (parameter, parameterIndex) { + var types = []; + var isRest = ts.isRestParameter(parameter); + var isOptional = false; + for (var _i = 0, calls_1 = calls; _i < calls_1.length; _i++) { + var call = calls_1[_i]; + if (call.argumentTypes.length <= parameterIndex) { + isOptional = ts.isInJSFile(declaration); + types.push(checker.getUndefinedType()); + } + else if (isRest) { + for (var i = parameterIndex; i < call.argumentTypes.length; i++) { + types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[i])); + } + } + else { + types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[parameterIndex])); + } + } + if (ts.isIdentifier(parameter.name)) { + var inferred = inferTypesFromReferencesSingle(getReferences(parameter.name, program, cancellationToken)); + types.push.apply(types, (isRest ? ts.mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred)); + } + var type = combineTypes(types); + return { + type: isRest ? checker.createArrayType(type) : type, + isOptional: isOptional && !isRest, + declaration: parameter + }; + }); + } + function thisParameter() { + var usage = createEmptyUsage(); + for (var _i = 0, references_3 = references; _i < references_3.length; _i++) { + var reference = references_3[_i]; + cancellationToken.throwIfCancellationRequested(); + calculateUsageOfNode(reference, usage); + } + return combineTypes(usage.candidateThisTypes || ts.emptyArray); + } + function inferTypesFromReferencesSingle(references) { + var usage = createEmptyUsage(); + for (var _i = 0, references_4 = references; _i < references_4.length; _i++) { + var reference = references_4[_i]; + cancellationToken.throwIfCancellationRequested(); + calculateUsageOfNode(reference, usage); + } + return inferTypes(usage); + } + function calculateUsageOfNode(node, usage) { + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { + node = node.parent; + } + switch (node.parent.kind) { + case 226 /* ExpressionStatement */: + inferTypeFromExpressionStatement(node, usage); + break; + case 208 /* PostfixUnaryExpression */: + usage.isNumber = true; + break; + case 207 /* PrefixUnaryExpression */: + inferTypeFromPrefixUnaryExpression(node.parent, usage); + break; + case 209 /* BinaryExpression */: + inferTypeFromBinaryExpression(node, node.parent, usage); + break; + case 277 /* CaseClause */: + case 278 /* DefaultClause */: + inferTypeFromSwitchStatementLabel(node.parent, usage); + break; + case 196 /* CallExpression */: + case 197 /* NewExpression */: + if (node.parent.expression === node) { + inferTypeFromCallExpression(node.parent, usage); + } + else { + inferTypeFromContextualType(node, usage); + } + break; + case 194 /* PropertyAccessExpression */: + inferTypeFromPropertyAccessExpression(node.parent, usage); + break; + case 195 /* ElementAccessExpression */: + inferTypeFromPropertyElementExpression(node.parent, node, usage); + break; + case 281 /* PropertyAssignment */: + case 282 /* ShorthandPropertyAssignment */: + inferTypeFromPropertyAssignment(node.parent, usage); + break; + case 159 /* PropertyDeclaration */: + inferTypeFromPropertyDeclaration(node.parent, usage); + break; + case 242 /* VariableDeclaration */: { + var _a = node.parent, name = _a.name, initializer = _a.initializer; + if (node === name) { + if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. + addCandidateType(usage, checker.getTypeAtLocation(initializer)); + } + break; + } + } + // falls through + default: + return inferTypeFromContextualType(node, usage); + } + } + function inferTypeFromContextualType(node, usage) { + if (ts.isExpressionNode(node)) { + addCandidateType(usage, checker.getContextualType(node)); + } + } + function inferTypeFromExpressionStatement(node, usage) { + addCandidateType(usage, ts.isCallExpression(node) ? checker.getVoidType() : checker.getAnyType()); + } + function inferTypeFromPrefixUnaryExpression(node, usage) { + switch (node.operator) { + case 45 /* PlusPlusToken */: + case 46 /* MinusMinusToken */: + case 40 /* MinusToken */: + case 54 /* TildeToken */: + usage.isNumber = true; + break; + case 39 /* PlusToken */: + usage.isNumberOrString = true; + break; + // case SyntaxKind.ExclamationToken: + // no inferences here; + } + } + function inferTypeFromBinaryExpression(node, parent, usage) { + switch (parent.operatorToken.kind) { + // ExponentiationOperator + case 42 /* AsteriskAsteriskToken */: + // MultiplicativeOperator + // falls through + case 41 /* AsteriskToken */: + case 43 /* SlashToken */: + case 44 /* PercentToken */: + // ShiftOperator + // falls through + case 47 /* LessThanLessThanToken */: + case 48 /* GreaterThanGreaterThanToken */: + case 49 /* GreaterThanGreaterThanGreaterThanToken */: + // BitwiseOperator + // falls through + case 50 /* AmpersandToken */: + case 51 /* BarToken */: + case 52 /* CaretToken */: + // CompoundAssignmentOperator + // falls through + case 64 /* MinusEqualsToken */: + case 66 /* AsteriskAsteriskEqualsToken */: + case 65 /* AsteriskEqualsToken */: + case 67 /* SlashEqualsToken */: + case 68 /* PercentEqualsToken */: + case 72 /* AmpersandEqualsToken */: + case 73 /* BarEqualsToken */: + case 74 /* CaretEqualsToken */: + case 69 /* LessThanLessThanEqualsToken */: + case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 70 /* GreaterThanGreaterThanEqualsToken */: + // AdditiveOperator + // falls through + case 40 /* MinusToken */: + // RelationalOperator + // falls through + case 29 /* LessThanToken */: + case 32 /* LessThanEqualsToken */: + case 31 /* GreaterThanToken */: + case 33 /* GreaterThanEqualsToken */: + var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (operandType.flags & 1056 /* EnumLike */) { + addCandidateType(usage, operandType); + } + else { + usage.isNumber = true; + } + break; + case 63 /* PlusEqualsToken */: + case 39 /* PlusToken */: + var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); + if (otherOperandType.flags & 1056 /* EnumLike */) { + addCandidateType(usage, otherOperandType); + } + else if (otherOperandType.flags & 296 /* NumberLike */) { + usage.isNumber = true; + } + else if (otherOperandType.flags & 132 /* StringLike */) { + usage.isString = true; + } + else if (otherOperandType.flags & 1 /* Any */) { + // do nothing, maybe we'll learn something elsewhere + } + else { + usage.isNumberOrString = true; + } + break; + // AssignmentOperators + case 62 /* EqualsToken */: + case 34 /* EqualsEqualsToken */: + case 36 /* EqualsEqualsEqualsToken */: + case 37 /* ExclamationEqualsEqualsToken */: + case 35 /* ExclamationEqualsToken */: + addCandidateType(usage, checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left)); + break; + case 97 /* InKeyword */: + if (node === parent.left) { + usage.isString = true; + } + break; + // LogicalOperator Or NullishCoalescing + case 56 /* BarBarToken */: + case 60 /* QuestionQuestionToken */: + if (node === parent.left && + (node.parent.parent.kind === 242 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + // var x = x || {}; + // TODO: use getFalsyflagsOfType + addCandidateType(usage, checker.getTypeAtLocation(parent.right)); + } + break; + case 55 /* AmpersandAmpersandToken */: + case 27 /* CommaToken */: + case 98 /* InstanceOfKeyword */: + // nothing to infer here + break; + } + } + function inferTypeFromSwitchStatementLabel(parent, usage) { + addCandidateType(usage, checker.getTypeAtLocation(parent.parent.parent.expression)); + } + function inferTypeFromCallExpression(parent, usage) { + var call = { + argumentTypes: [], + return_: createEmptyUsage() + }; + if (parent.arguments) { + for (var _i = 0, _a = parent.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + call.argumentTypes.push(checker.getTypeAtLocation(argument)); + } + } + calculateUsageOfNode(parent, call.return_); + if (parent.kind === 196 /* CallExpression */) { + (usage.calls || (usage.calls = [])).push(call); + } + else { + (usage.constructs || (usage.constructs = [])).push(call); + } + } + function inferTypeFromPropertyAccessExpression(parent, usage) { + var name = ts.escapeLeadingUnderscores(parent.name.text); + if (!usage.properties) { + usage.properties = ts.createUnderscoreEscapedMap(); + } + var propertyUsage = usage.properties.get(name) || createEmptyUsage(); + calculateUsageOfNode(parent, propertyUsage); + usage.properties.set(name, propertyUsage); + } + function inferTypeFromPropertyElementExpression(parent, node, usage) { + if (node === parent.argumentExpression) { + usage.isNumberOrString = true; + return; + } + else { + var indexType = checker.getTypeAtLocation(parent.argumentExpression); + var indexUsage = createEmptyUsage(); + calculateUsageOfNode(parent, indexUsage); + if (indexType.flags & 296 /* NumberLike */) { + usage.numberIndex = indexUsage; + } + else { + usage.stringIndex = indexUsage; + } + } + } + function inferTypeFromPropertyAssignment(assignment, usage) { + var nodeWithRealType = ts.isVariableDeclaration(assignment.parent.parent) ? + assignment.parent.parent : + assignment.parent; + addCandidateThisType(usage, checker.getTypeAtLocation(nodeWithRealType)); + } + function inferTypeFromPropertyDeclaration(declaration, usage) { + addCandidateThisType(usage, checker.getTypeAtLocation(declaration.parent)); + } + function removeLowPriorityInferences(inferences, priorities) { + var toRemove = []; + 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)) { + ts.Debug.assert(!low(i), "Priority can't have both low and high"); + toRemove.push(low); + } + } + } + return inferences.filter(function (i) { return toRemove.every(function (f) { return !f(i); }); }); + } + function combineFromUsage(usage) { + return combineTypes(inferTypes(usage)); + } + function combineTypes(inferences) { + if (!inferences.length) + return checker.getAnyType(); + // 1. string or number individually override string | number + // 2. non-any, non-void overrides any or void + // 3. non-nullable, non-any, non-void, non-anonymous overrides anonymous types + var stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]); + var priorities = [ + { + high: function (t) { return t === checker.getStringType() || t === checker.getNumberType(); }, + low: function (t) { return t === stringNumber; } + }, + { + high: function (t) { return !(t.flags & (1 /* Any */ | 16384 /* Void */)); }, + low: function (t) { return !!(t.flags & (1 /* Any */ | 16384 /* Void */)); } + }, + { + high: function (t) { return !(t.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(ts.getObjectFlags(t) & 16 /* Anonymous */); }, + low: function (t) { return !!(ts.getObjectFlags(t) & 16 /* Anonymous */); } + } + ]; + var good = removeLowPriorityInferences(inferences, priorities); + var anons = good.filter(function (i) { return ts.getObjectFlags(i) & 16 /* Anonymous */; }); + if (anons.length) { + good = good.filter(function (i) { return !(ts.getObjectFlags(i) & 16 /* Anonymous */); }); + good.push(combineAnonymousTypes(anons)); + } + return checker.getWidenedType(checker.getUnionType(good.map(checker.getBaseTypeOfLiteralType), 2 /* Subtype */)); + } + function combineAnonymousTypes(anons) { + if (anons.length === 1) { + return anons[0]; + } + var calls = []; + var constructs = []; + var stringIndices = []; + var numberIndices = []; + var stringIndexReadonly = false; + var numberIndexReadonly = false; + var props = ts.createMultiMap(); + for (var _i = 0, anons_1 = anons; _i < anons_1.length; _i++) { + var anon = anons_1[_i]; + for (var _a = 0, _b = checker.getPropertiesOfType(anon); _a < _b.length; _a++) { + var p = _b[_a]; + props.add(p.name, checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration)); + } + calls.push.apply(calls, checker.getSignaturesOfType(anon, 0 /* Call */)); + constructs.push.apply(constructs, checker.getSignaturesOfType(anon, 1 /* Construct */)); + if (anon.stringIndexInfo) { + stringIndices.push(anon.stringIndexInfo.type); + stringIndexReadonly = stringIndexReadonly || anon.stringIndexInfo.isReadonly; + } + if (anon.numberIndexInfo) { + numberIndices.push(anon.numberIndexInfo.type); + numberIndexReadonly = numberIndexReadonly || anon.numberIndexInfo.isReadonly; + } + } + var members = ts.mapEntries(props, function (name, types) { + var isOptional = types.length < anons.length ? 16777216 /* Optional */ : 0; + var s = checker.createSymbol(4 /* Property */ | isOptional, name); + s.type = checker.getUnionType(types); + return [name, s]; + }); + return checker.createAnonymousType(anons[0].symbol, members, calls, constructs, stringIndices.length ? checker.createIndexInfo(checker.getUnionType(stringIndices), stringIndexReadonly) : undefined, numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined); + } + function inferTypes(usage) { + var _a, _b, _c; + var types = []; + if (usage.isNumber) { + types.push(checker.getNumberType()); + } + if (usage.isString) { + types.push(checker.getStringType()); + } + if (usage.isNumberOrString) { + types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()])); + } + if (usage.numberIndex) { + types.push(checker.createArrayType(combineFromUsage(usage.numberIndex))); + } + if (((_a = usage.properties) === null || _a === void 0 ? void 0 : _a.size) || ((_b = usage.calls) === null || _b === void 0 ? void 0 : _b.length) || ((_c = usage.constructs) === null || _c === void 0 ? void 0 : _c.length) || usage.stringIndex) { + types.push(inferStructuralType(usage)); + } + types.push.apply(types, (usage.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); })); + types.push.apply(types, inferNamedTypesFromProperties(usage)); + return types; + } + function inferStructuralType(usage) { + var members = ts.createUnderscoreEscapedMap(); + if (usage.properties) { + usage.properties.forEach(function (u, name) { + var symbol = checker.createSymbol(4 /* Property */, name); + symbol.type = combineFromUsage(u); + members.set(name, symbol); + }); + } + var callSignatures = usage.calls ? [getSignatureFromCalls(usage.calls)] : []; + var constructSignatures = usage.constructs ? [getSignatureFromCalls(usage.constructs)] : []; + var stringIndexInfo = usage.stringIndex && checker.createIndexInfo(combineFromUsage(usage.stringIndex), /*isReadonly*/ false); + return checker.createAnonymousType(/*symbol*/ undefined, members, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); + } + function inferNamedTypesFromProperties(usage) { + if (!usage.properties || !usage.properties.size) + return []; + var types = builtins.filter(function (t) { return allPropertiesAreAssignableToUsage(t, usage); }); + if (0 < types.length && types.length < 3) { + return types.map(function (t) { return inferInstantiationFromUsage(t, usage); }); + } + return []; + } + function allPropertiesAreAssignableToUsage(type, usage) { + if (!usage.properties) + return false; + return !ts.forEachEntry(usage.properties, function (propUsage, name) { + var source = checker.getTypeOfPropertyOfType(type, name); + if (!source) { + return true; + } + if (propUsage.calls) { + var sigs = checker.getSignaturesOfType(source, 0 /* Call */); + return !sigs.length || !checker.isTypeAssignableTo(source, getFunctionFromCalls(propUsage.calls)); + } + else { + return !checker.isTypeAssignableTo(source, combineFromUsage(propUsage)); + } + }); + } + /** + * inference is limited to + * 1. generic types with a single parameter + * 2. inference to/from calls with a single signature + */ + function inferInstantiationFromUsage(type, usage) { + if (!(ts.getObjectFlags(type) & 4 /* Reference */) || !usage.properties) { + return type; + } + var generic = type.target; + var singleTypeParameter = ts.singleOrUndefined(generic.typeParameters); + if (!singleTypeParameter) + return type; + var types = []; + usage.properties.forEach(function (propUsage, name) { + var genericPropertyType = checker.getTypeOfPropertyOfType(generic, name); + ts.Debug.assert(!!genericPropertyType, "generic should have all the properties of its reference."); + types.push.apply(types, inferTypeParameters(genericPropertyType, combineFromUsage(propUsage), singleTypeParameter)); + }); + return builtinConstructors[type.symbol.escapedName](combineTypes(types)); + } + function inferTypeParameters(genericType, usageType, typeParameter) { + if (genericType === typeParameter) { + return [usageType]; + } + else if (genericType.flags & 3145728 /* UnionOrIntersection */) { + return ts.flatMap(genericType.types, function (t) { return inferTypeParameters(t, usageType, typeParameter); }); + } + else if (ts.getObjectFlags(genericType) & 4 /* Reference */ && ts.getObjectFlags(usageType) & 4 /* Reference */) { + // this is wrong because we need a reference to the targetType to, so we can check that it's also a reference + var genericArgs = checker.getTypeArguments(genericType); + var usageArgs = checker.getTypeArguments(usageType); + var types = []; + if (genericArgs && usageArgs) { + for (var i = 0; i < genericArgs.length; i++) { + if (usageArgs[i]) { + types.push.apply(types, inferTypeParameters(genericArgs[i], usageArgs[i], typeParameter)); + } + } + } + return types; + } + var genericSigs = checker.getSignaturesOfType(genericType, 0 /* Call */); + var usageSigs = checker.getSignaturesOfType(usageType, 0 /* Call */); + if (genericSigs.length === 1 && usageSigs.length === 1) { + return inferFromSignatures(genericSigs[0], usageSigs[0], typeParameter); + } + return []; + } + function inferFromSignatures(genericSig, usageSig, typeParameter) { + var types = []; + for (var i = 0; i < genericSig.parameters.length; i++) { + var genericParam = genericSig.parameters[i]; + var usageParam = usageSig.parameters[i]; + var isRest = genericSig.declaration && ts.isRestParameter(genericSig.declaration.parameters[i]); + if (!usageParam) { + break; + } + var genericParamType = checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration); + var elementType = isRest && checker.getElementTypeOfArrayType(genericParamType); + if (elementType) { + genericParamType = elementType; + } + var targetType = usageParam.type || checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration); + types.push.apply(types, inferTypeParameters(genericParamType, targetType, typeParameter)); + } + var genericReturn = checker.getReturnTypeOfSignature(genericSig); + var usageReturn = checker.getReturnTypeOfSignature(usageSig); + types.push.apply(types, inferTypeParameters(genericReturn, usageReturn, typeParameter)); + return types; + } + function getFunctionFromCalls(calls) { + return checker.createAnonymousType(/*symbol*/ undefined, ts.createSymbolTable(), [getSignatureFromCalls(calls)], ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + } + function getSignatureFromCalls(calls) { + var parameters = []; + var length = Math.max.apply(Math, calls.map(function (c) { return c.argumentTypes.length; })); + var _loop_14 = function (i) { + var symbol = checker.createSymbol(1 /* FunctionScopedVariable */, ts.escapeLeadingUnderscores("arg" + i)); + symbol.type = combineTypes(calls.map(function (call) { return call.argumentTypes[i] || checker.getUndefinedType(); })); + if (calls.some(function (call) { return call.argumentTypes[i] === undefined; })) { + symbol.flags |= 16777216 /* Optional */; + } + parameters.push(symbol); + }; + for (var i = 0; i < length; i++) { + _loop_14(i); + } + var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); + // TODO: GH#18217 + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* None */); + } + function addCandidateType(usage, type) { + if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { + (usage.candidateTypes || (usage.candidateTypes = [])).push(type); + } + } + function addCandidateThisType(usage, type) { + if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { + (usage.candidateThisTypes || (usage.candidateThisTypes = [])).push(type); + } + } + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -130145,12 +133588,13 @@ var ts; if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } + var newLineCharacter = sourceFile.checkJsDirective ? "" : ts.getNewLineOrDefaultFromHost(host, formatContext.options); var fixes = [ // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. codefix.createCodeFixActionWithoutFixAll(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ ts.createTextChange(sourceFile.checkJsDirective ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) - : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), + : ts.createTextSpan(0, 0), "// @ts-nocheck" + newLineCharacter), ])], ts.Diagnostics.Disable_checking_for_this_file), ]; if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) { @@ -130186,45 +133630,36 @@ var ts; * Finds members of the resolved type that are missing in the class pointed to by class decl * and generates source code for the missing members. * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. + * @param importAdder If provided, type annotations will use identifier type references instead of ImportTypeNodes, and the missing imports will be added to the importAdder. * @returns Empty string iff there are no member insertions. */ - function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, context, preferences, out) { + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, context, preferences, importAdder, addClassElement) { var classMembers = classDeclaration.symbol.members; for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { var symbol = possiblyMissingSymbols_1[_i]; if (!classMembers.has(symbol.escapedName)) { - addNewNodeForMemberSymbol(symbol, classDeclaration, context, preferences, out); + addNewNodeForMemberSymbol(symbol, classDeclaration, context, preferences, importAdder, addClassElement); } } } codefix.createMissingMemberNodes = createMissingMemberNodes; - function getModuleSpecifierResolverHost(context) { - return { - directoryExists: context.host.directoryExists ? function (d) { return context.host.directoryExists(d); } : undefined, - fileExists: context.host.fileExists ? function (f) { return context.host.fileExists(f); } : undefined, - getCurrentDirectory: context.host.getCurrentDirectory ? function () { return context.host.getCurrentDirectory(); } : undefined, - readFile: context.host.readFile ? function (f) { return context.host.readFile(f); } : undefined, - useCaseSensitiveFileNames: context.host.useCaseSensitiveFileNames ? function () { return context.host.useCaseSensitiveFileNames(); } : undefined, - getSourceFiles: function () { return context.program.getSourceFiles(); }, - getCommonSourceDirectory: function () { return context.program.getCommonSourceDirectory(); }, - }; - } function getNoopSymbolTrackerWithResolver(context) { return { trackSymbol: ts.noop, - moduleResolverHost: getModuleSpecifierResolverHost(context), + moduleResolverHost: ts.getModuleSpecifierResolverHost(context.program, context.host), }; } codefix.getNoopSymbolTrackerWithResolver = getNoopSymbolTrackerWithResolver; /** * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. */ - function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, context, preferences, out) { + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, context, preferences, importAdder, addClassElement) { var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; } var checker = context.program.getTypeChecker(); + var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions()); var declaration = declarations[0]; var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); @@ -130237,28 +133672,42 @@ var ts; case 159 /* PropertyDeclaration */: var flags = preferences.quotePreference === "single" ? 268435456 /* UseSingleQuotesForStringLiteralType */ : undefined; var typeNode = checker.typeToTypeNode(type, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); - out(ts.createProperty( + if (importAdder) { + var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeNode, type, scriptTarget); + if (importableReference) { + typeNode = importableReference.typeReference; + importSymbols(importAdder, importableReference.symbols); + } + } + addClassElement(ts.createProperty( /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(57 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; case 163 /* GetAccessor */: case 164 /* SetAccessor */: { - var allAccessors = ts.getAllAccessorDeclarations(declarations, declaration); var typeNode_1 = checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); + var allAccessors = ts.getAllAccessorDeclarations(declarations, declaration); var orderedAccessors = allAccessors.secondAccessor ? [allAccessors.firstAccessor, allAccessors.secondAccessor] : [allAccessors.firstAccessor]; + if (importAdder) { + var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeNode_1, type, scriptTarget); + if (importableReference) { + typeNode_1 = importableReference.typeReference; + importSymbols(importAdder, importableReference.symbols); + } + } for (var _i = 0, orderedAccessors_1 = orderedAccessors; _i < orderedAccessors_1.length; _i++) { var accessor = orderedAccessors_1[_i]; if (ts.isGetAccessorDeclaration(accessor)) { - out(ts.createGetAccessor( + addClassElement(ts.createGetAccessor( /*decorators*/ undefined, modifiers, name, ts.emptyArray, typeNode_1, ambient ? undefined : createStubbedMethodBody(preferences))); } else { ts.Debug.assertNode(accessor, ts.isSetAccessorDeclaration, "The counterpart to a getter should be a setter"); var parameter = ts.getSetAccessorValueParameter(accessor); var parameterName = parameter && ts.isIdentifier(parameter.name) ? ts.idText(parameter.name) : undefined; - out(ts.createSetAccessor( + addClassElement(ts.createSetAccessor( /*decorators*/ undefined, modifiers, name, createDummyParameters(1, [parameterName], [typeNode_1], 1, /*inJs*/ false), ambient ? undefined : createStubbedMethodBody(preferences))); } } @@ -130295,23 +133744,61 @@ var ts; } else { ts.Debug.assert(declarations.length === signatures.length, "Declarations and signatures should match count"); - out(createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences)); + addClassElement(createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences)); } } break; } function outputMethod(signature, modifiers, name, body) { - var method = signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body); + var method = signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body, importAdder); if (method) - out(method); + addClassElement(method); } } - function signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body) { + function signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body, importAdder) { var program = context.program; - var signatureDeclaration = program.getTypeChecker().signatureToSignatureDeclaration(signature, 161 /* MethodDeclaration */, enclosingDeclaration, 1 /* NoTruncation */ | 256 /* SuppressAnyReturnType */, getNoopSymbolTrackerWithResolver(context)); + var checker = program.getTypeChecker(); + var scriptTarget = ts.getEmitScriptTarget(program.getCompilerOptions()); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 161 /* MethodDeclaration */, enclosingDeclaration, 1 /* NoTruncation */ | 256 /* SuppressAnyReturnType */, getNoopSymbolTrackerWithResolver(context)); if (!signatureDeclaration) { return undefined; } + if (importAdder) { + if (signatureDeclaration.typeParameters) { + ts.forEach(signatureDeclaration.typeParameters, function (typeParameterDecl, i) { + var typeParameter = signature.typeParameters[i]; + if (typeParameterDecl.constraint) { + var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeParameterDecl.constraint, typeParameter.constraint, scriptTarget); + if (importableReference) { + typeParameterDecl.constraint = importableReference.typeReference; + importSymbols(importAdder, importableReference.symbols); + } + } + if (typeParameterDecl.default) { + var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeParameterDecl.default, typeParameter.default, scriptTarget); + if (importableReference) { + typeParameterDecl.default = importableReference.typeReference; + importSymbols(importAdder, importableReference.symbols); + } + } + }); + } + ts.forEach(signatureDeclaration.parameters, function (parameterDecl, i) { + var parameter = signature.parameters[i]; + var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(parameterDecl.type, checker.getTypeAtLocation(parameter.valueDeclaration), scriptTarget); + if (importableReference) { + parameterDecl.type = importableReference.typeReference; + importSymbols(importAdder, importableReference.symbols); + } + }); + if (signatureDeclaration.type) { + var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(signatureDeclaration.type, signature.resolvedReturnType, scriptTarget); + if (importableReference) { + signatureDeclaration.type = importableReference.typeReference; + importSymbols(importAdder, importableReference.symbols); + } + } + } signatureDeclaration.decorators = undefined; signatureDeclaration.modifiers = modifiers; signatureDeclaration.name = name; @@ -130319,14 +133806,14 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, contextNode) { + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, contextNode, importAdder) { var body = !ts.isInterfaceDeclaration(contextNode); var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; + var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions()); var checker = context.program.getTypeChecker(); var tracker = getNoopSymbolTrackerWithResolver(context); var types = ts.map(args, function (arg) { - // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, /*flags*/ undefined, tracker); + return typeToAutoImportableTypeNode(checker, importAdder, checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, scriptTarget, /*flags*/ undefined, tracker); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) && ts.isIdentifier(arg.name) ? arg.name.text : undefined; @@ -130342,9 +133829,21 @@ var ts; return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), - /*type*/ returnType, body ? createStubbedMethodBody(preferences) : undefined); + /*type*/ returnType, body ? createStubbedMethodBody(context.preferences) : undefined); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; + function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, tracker) { + var typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker); + if (typeNode && ts.isImportTypeNode(typeNode)) { + var importableReference = tryGetAutoImportableReferenceFromImportTypeNode(typeNode, type, scriptTarget); + if (importableReference) { + importSymbols(importAdder, importableReference.symbols); + return importableReference.typeReference; + } + } + return typeNode; + } + codefix.typeToAutoImportableTypeNode = typeToAutoImportableTypeNode; function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { var parameters = []; for (var i = 0; i < argCount; i++) { @@ -130455,6 +133954,50 @@ var ts; return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); } codefix.findJsonProperty = findJsonProperty; + /** + * Given an ImportTypeNode 'import("./a").SomeType>', + * returns an equivalent type reference node with any nested ImportTypeNodes also replaced + * with type references, and a list of symbols that must be imported to use the type reference. + */ + function tryGetAutoImportableReferenceFromImportTypeNode(importTypeNode, type, scriptTarget) { + if (importTypeNode && ts.isLiteralImportTypeNode(importTypeNode) && importTypeNode.qualifier && (!type || type.symbol)) { + // Symbol for the left-most thing after the dot + var firstIdentifier = ts.getFirstIdentifier(importTypeNode.qualifier); + var name = ts.getNameForExportedSymbol(firstIdentifier.symbol, scriptTarget); + var qualifier = name !== firstIdentifier.text + ? replaceFirstIdentifierOfEntityName(importTypeNode.qualifier, ts.createIdentifier(name)) + : importTypeNode.qualifier; + var symbols_4 = [firstIdentifier.symbol]; + var typeArguments_1 = []; + if (importTypeNode.typeArguments) { + importTypeNode.typeArguments.forEach(function (arg) { + var ref = tryGetAutoImportableReferenceFromImportTypeNode(arg, /*undefined*/ type, scriptTarget); + if (ref) { + symbols_4.push.apply(symbols_4, ref.symbols); + typeArguments_1.push(ref.typeReference); + } + else { + typeArguments_1.push(arg); + } + }); + } + return { + symbols: symbols_4, + typeReference: ts.createTypeReferenceNode(qualifier, typeArguments_1) + }; + } + } + codefix.tryGetAutoImportableReferenceFromImportTypeNode = tryGetAutoImportableReferenceFromImportTypeNode; + function replaceFirstIdentifierOfEntityName(name, newIdentifier) { + if (name.kind === 75 /* Identifier */) { + return newIdentifier; + } + return ts.createQualifiedName(replaceFirstIdentifierOfEntityName(name.left, newIdentifier), name.right); + } + function importSymbols(importAdder, symbols) { + symbols.forEach(function (s) { return importAdder.addImportFromExportedSymbol(s, /*usageIsTypeOnly*/ true); }); + } + codefix.importSymbols = importSymbols; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -130918,7 +134461,7 @@ var ts; if (!importDeclaration) { return; } - var importClause = ts.Debug.assertDefined(importDeclaration.importClause); + var importClause = ts.Debug.checkDefined(importDeclaration.importClause); changes.replaceNode(context.sourceFile, importDeclaration, ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importClause, importClause.name, /*namedBindings*/ undefined, importClause.isTypeOnly), importDeclaration.moduleSpecifier)); changes.insertNodeAfter(context.sourceFile, importDeclaration, ts.createImportDeclaration( /*decorators*/ undefined, @@ -130962,6 +134505,46 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixExpectedComma"; + var expectedErrorCode = ts.Diagnostics._0_expected.code; + var errorCodes = [expectedErrorCode]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var info = getInfo(sourceFile, context.span.start, context.errorCode); + if (!info) { + return undefined; + } + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Change_0_to_1, ";", ","], fixId, [ts.Diagnostics.Change_0_to_1, ";", ","])]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start, diag.code); + if (info) + doChange(changes, context.sourceFile, info); + }); }, + }); + function getInfo(sourceFile, pos, _) { + var node = ts.getTokenAtPosition(sourceFile, pos); + return (node.kind === 26 /* SemicolonToken */ && + node.parent && + (ts.isObjectLiteralExpression(node.parent) || + ts.isArrayLiteralExpression(node.parent))) ? { node: node } : undefined; + } + function doChange(changes, sourceFile, _a) { + var node = _a.node; + var newNode = ts.createNode(27 /* CommaToken */); + changes.replaceNode(sourceFile, node, newNode); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var refactor; (function (refactor) { @@ -130979,7 +134562,7 @@ var ts; }, getEditsForAction: function (context, actionName) { ts.Debug.assert(actionName === actionNameDefaultToNamed || actionName === actionNameNamedToDefault, "Unexpected action name"); - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, ts.Debug.assertDefined(getInfo(context), "context must have info"), t, context.cancellationToken); }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, ts.Debug.checkDefined(getInfo(context), "context must have info"), t, context.cancellationToken); }); return { edits: edits, renameFilename: undefined, renameLocation: undefined }; }, }); @@ -131031,10 +134614,10 @@ var ts; function changeExport(exportingSourceFile, _a, changes, checker) { var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; if (wasDefault) { - changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 84 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + changes.delete(exportingSourceFile, ts.Debug.checkDefined(ts.findModifier(exportNode, 84 /* DefaultKeyword */), "Should find a default keyword in modifier list")); } else { - var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 89 /* ExportKeyword */), "Should find an export keyword in modifier list"); + var exportKeyword = ts.Debug.checkDefined(ts.findModifier(exportNode, 89 /* ExportKeyword */), "Should find an export keyword in modifier list"); switch (exportNode.kind) { case 244 /* FunctionDeclaration */: case 245 /* ClassDeclaration */: @@ -131045,7 +134628,7 @@ var ts; // If 'x' isn't used in this file, `export const x = 0;` --> `export default 0;` if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile)) { // We checked in `getInfo` that an initializer exists. - changes.replaceNode(exportingSourceFile, exportNode, ts.createExportDefault(ts.Debug.assertDefined(ts.first(exportNode.declarationList.declarations).initializer, "Initializer was previously known to be present"))); + changes.replaceNode(exportingSourceFile, exportNode, ts.createExportDefault(ts.Debug.checkDefined(ts.first(exportNode.declarationList.declarations).initializer, "Initializer was previously known to be present"))); break; } // falls through @@ -131064,7 +134647,7 @@ var ts; function changeImports(program, _a, changes, cancellationToken) { var wasDefault = _a.wasDefault, exportName = _a.exportName, exportingModuleSymbol = _a.exportingModuleSymbol; var checker = program.getTypeChecker(); - var exportSymbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol"); + var exportSymbol = ts.Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol"); ts.FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, function (ref) { var importingSourceFile = ref.getSourceFile(); if (wasDefault) { @@ -131175,7 +134758,7 @@ var ts; }, getEditsForAction: function (context, actionName) { ts.Debug.assert(actionName === actionNameNamespaceToNamed || actionName === actionNameNamedToNamespace, "Unexpected action name"); - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, t, ts.Debug.assertDefined(getImportToConvert(context), "Context must provide an import to convert")); }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, t, ts.Debug.checkDefined(getImportToConvert(context), "Context must provide an import to convert")); }); return { edits: edits, renameFilename: undefined, renameLocation: undefined }; } }); @@ -131862,7 +135445,7 @@ var ts; case 244 /* FunctionDeclaration */: return scope.name ? "function '" + scope.name.text + "'" - : "anonymous function"; + : ts.ANONYMOUS; case 202 /* ArrowFunction */: return "arrow function"; case 161 /* MethodDeclaration */: @@ -131897,6 +135480,8 @@ var ts; function extractFunctionInScope(node, scope, _a, exposedVariableDeclarations, range, context) { var usagesInScope = _a.usages, typeParameterUsages = _a.typeParameterUsages, substitutions = _a.substitutions; var checker = context.program.getTypeChecker(); + var scriptTarget = ts.getEmitScriptTarget(context.program.getCompilerOptions()); + var importAdder = ts.codefix.createImportAdder(context.file, context.program, context.preferences, context.host); // Make a unique name for the extracted function var file = scope.getSourceFile(); var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); @@ -131912,7 +135497,7 @@ var ts; var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" type = checker.getBaseTypeOfLiteralType(type); - typeNode = checker.typeToTypeNode(type, scope, 1 /* NoTruncation */); + typeNode = ts.codefix.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */); } var paramDecl = ts.createParameter( /*decorators*/ undefined, @@ -131971,6 +135556,7 @@ var ts; else { changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); } + importAdder.writeFixes(changeTracker); var newNodes = []; // replace range with function call var called = getCalledExpression(scope, range, functionNameText); @@ -132433,7 +136019,7 @@ var ts; return curr.parent.parent; } // There must be at least one statement since we started in one. - return ts.Debug.assertDefined(prevStatement, "prevStatement failed to get set"); + return ts.Debug.checkDefined(prevStatement, "prevStatement failed to get set"); } ts.Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); } @@ -132878,7 +136464,7 @@ var ts; }, getEditsForAction: function (context, actionName) { var file = context.file; - var info = ts.Debug.assertDefined(getRangeToExtract(context), "Expected to find a range to extract"); + var info = ts.Debug.checkDefined(getRangeToExtract(context), "Expected to find a range to extract"); var name = ts.getUniqueName("NewType", file); var edits = ts.textChanges.ChangeTracker.with(context, function (changes) { switch (actionName) { @@ -132909,7 +136495,7 @@ var ts; if (!selection || !ts.isTypeNode(selection)) return undefined; var checker = context.program.getTypeChecker(); - var firstStatement = ts.Debug.assertDefined(ts.findAncestor(selection, ts.isStatement), "Should find a statement"); + var firstStatement = ts.Debug.checkDefined(ts.findAncestor(selection, ts.isStatement), "Should find a statement"); var typeParameters = collectTypeParameters(checker, selection, firstStatement, file); if (!typeParameters) return undefined; @@ -132991,7 +136577,7 @@ var ts; var newTypeNode = ts.createTypeAliasDeclaration( /* decorators */ undefined, /* modifiers */ undefined, name, typeParameters.map(function (id) { return ts.updateTypeParameterDeclaration(id, id.name, id.constraint, /* defaultType */ undefined); }), selection); - changes.insertNodeBefore(file, firstStatement, newTypeNode, /* blankLineBetween */ true); + changes.insertNodeBefore(file, firstStatement, ts.ignoreSourceNewlines(newTypeNode), /* blankLineBetween */ true); changes.replaceNode(file, selection, ts.createTypeReferenceNode(name, typeParameters.map(function (id) { return ts.createTypeReferenceNode(id.name, /* typeArguments */ undefined); }))); } function doInterfaceChange(changes, file, name, info) { @@ -133000,12 +136586,12 @@ var ts; /* decorators */ undefined, /* modifiers */ undefined, name, typeParameters, /* heritageClauses */ undefined, typeElements); - changes.insertNodeBefore(file, firstStatement, newTypeNode, /* blankLineBetween */ true); + changes.insertNodeBefore(file, firstStatement, ts.ignoreSourceNewlines(newTypeNode), /* blankLineBetween */ true); changes.replaceNode(file, selection, ts.createTypeReferenceNode(name, typeParameters.map(function (id) { return ts.createTypeReferenceNode(id.name, /* typeArguments */ undefined); }))); } function doTypedefChange(changes, file, name, info) { var firstStatement = info.firstStatement, selection = info.selection, typeParameters = info.typeParameters; - var node = ts.createNode(321 /* JSDocTypedefTag */); + var node = ts.createNode(322 /* JSDocTypedefTag */); node.tagName = ts.createIdentifier("typedef"); // TODO: jsdoc factory https://github.com/Microsoft/TypeScript/pull/29539 node.fullName = ts.createIdentifier(name); node.name = node.fullName; @@ -133013,7 +136599,7 @@ var ts; var templates = []; ts.forEach(typeParameters, function (typeParameter) { var constraint = ts.getEffectiveConstraintOfTypeParameter(typeParameter); - var template = ts.createNode(320 /* JSDocTemplateTag */); + var template = ts.createNode(321 /* JSDocTemplateTag */); template.tagName = ts.createIdentifier("template"); template.constraint = constraint && ts.cast(constraint, ts.isJSDocTypeExpression); var parameter = ts.createNode(155 /* TypeParameter */); @@ -133059,6 +136645,7 @@ var ts; var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; ts.suppressLeadingAndTrailingTrivia(fieldName); + ts.suppressLeadingAndTrailingTrivia(accessorName); ts.suppressLeadingAndTrailingTrivia(declaration); ts.suppressLeadingAndTrailingTrivia(container); var isInClassLike = ts.isClassLike(container); @@ -133110,9 +136697,6 @@ var ts; var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(120 /* StaticKeyword */) : undefined); return modifiers && ts.createNodeArray(modifiers); } - function startsWithUnderscore(name) { - return name.charCodeAt(0) === 95 /* _ */; - } function getConvertibleFieldAtPosition(context) { var file = context.file, startPosition = context.startPosition, endPosition = context.endPosition; var node = ts.getTokenAtPosition(file, startPosition); @@ -133123,7 +136707,7 @@ var ts; || !isConvertibleName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) return undefined; var name = declaration.name.text; - var startWithUnderscore = startsWithUnderscore(name); + var startWithUnderscore = ts.startsWithUnderscore(name); var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file), declaration.name); var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file) : name, declaration.name); return { @@ -133217,7 +136801,7 @@ var ts; }, getEditsForAction: function (context, actionName) { ts.Debug.assert(actionName === refactorName, "Wrong refactor invoked"); - var statements = ts.Debug.assertDefined(getStatementsToMove(context)); + var statements = ts.Debug.checkDefined(getStatementsToMove(context)); var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); }); return { edits: edits, renameFilename: undefined, renameLocation: undefined }; } @@ -133307,7 +136891,7 @@ var ts; var quotePreference = ts.getQuotePreference(oldFile, preferences); var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); if (importsFromNewFile) { - ts.insertImport(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true); + ts.insertImports(changes, oldFile, importsFromNewFile, /*blankLineBetween*/ true); } deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); deleteMovedStatements(oldFile, toMove.ranges, changes); @@ -133474,7 +137058,7 @@ var ts; return ts.flatMap(toMove, function (statement) { if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && - forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) { + forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.checkDefined(d.symbol)); })) { var exports = addExport(statement, useEs6Exports); if (exports) return exports; @@ -133611,7 +137195,7 @@ var ts; for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) { var statement = toMove_1[_i]; forEachTopLevelDeclaration(statement, function (decl) { - movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here")); + movedSymbols.add(ts.Debug.checkDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here")); }); } for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) { @@ -133667,6 +137251,7 @@ var ts; case 253 /* ImportEqualsDeclaration */: case 258 /* ImportSpecifier */: case 255 /* ImportClause */: + case 256 /* NamespaceImport */: return true; case 242 /* VariableDeclaration */: return isVariableDeclarationInImport(decl); @@ -133956,19 +137541,20 @@ var ts; } else if (actionName === removeBracesActionName && returnStatement) { var actualExpression = expression || ts.createVoidZero(); - body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression; + body = ts.needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression; ts.suppressLeadingAndTrailingTrivia(body); + ts.copyTrailingAsLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); ts.copyLeadingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); + ts.copyTrailingComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); } else { ts.Debug.fail("invalid action"); } - var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, func.body, body); }); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { + t.replaceNode(file, func.body, body); + }); return { renameFilename: undefined, renameLocation: undefined, edits: edits }; } - function needsParentheses(expression) { - return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 27 /* CommaToken */ || ts.isObjectLiteralExpression(expression); - } function getConvertibleArrowFunctionAtPosition(file, startPosition) { var node = ts.getTokenAtPosition(file, startPosition); var func = ts.getContainingFunction(node); @@ -134325,7 +137911,7 @@ var ts; ts.suppressLeadingAndTrailingTrivia(property.name); if (ts.isPropertyAssignment(property)) ts.suppressLeadingAndTrailingTrivia(property.initializer); - copyComments(arg, property); + ts.copyComments(arg, property); return property; }); if (hasRestParameter && functionArguments.length >= parameters.length) { @@ -134360,10 +137946,10 @@ var ts; /*dotDotDotToken*/ undefined, thisParameter.name, /*questionToken*/ undefined, thisParameter.type); ts.suppressLeadingAndTrailingTrivia(newThisParameter.name); - copyComments(thisParameter.name, newThisParameter.name); + ts.copyComments(thisParameter.name, newThisParameter.name); if (thisParameter.type) { ts.suppressLeadingAndTrailingTrivia(newThisParameter.type); - copyComments(thisParameter.type, newThisParameter.type); + ts.copyComments(thisParameter.type, newThisParameter.type); } return ts.createNodeArray([newThisParameter, objectParameter]); } @@ -134374,7 +137960,7 @@ var ts; /*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); + ts.copyComments(parameterDeclaration.initializer, element.initializer); } return element; } @@ -134392,9 +137978,9 @@ var ts; /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? ts.createToken(57 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType, /*initializer*/ undefined); ts.suppressLeadingAndTrailingTrivia(propertySignature); - copyComments(parameterDeclaration.name, propertySignature.name); + ts.copyComments(parameterDeclaration.name, propertySignature.name); if (parameterDeclaration.type && propertySignature.type) { - copyComments(parameterDeclaration.type, propertySignature.type); + ts.copyComments(parameterDeclaration.type, propertySignature.type); } return propertySignature; } @@ -134410,26 +137996,6 @@ var ts; 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); } @@ -134441,7 +138007,7 @@ var ts; return [classDeclaration.name]; // If the class declaration doesn't have a name, it should have a default modifier. // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault` - var defaultModifier = ts.Debug.assertDefined(ts.findModifier(classDeclaration, 84 /* DefaultKeyword */), "Nameless class declaration should be a default export"); + var defaultModifier = ts.Debug.checkDefined(ts.findModifier(classDeclaration, 84 /* DefaultKeyword */), "Nameless class declaration should be a default export"); return [defaultModifier]; case 214 /* ClassExpression */: var classExpression = constructorDeclaration.parent; @@ -134459,12 +138025,12 @@ var ts; return [functionDeclaration.name]; // If the function declaration doesn't have a name, it should have a default modifier. // We validated this in `isValidFunctionDeclaration` through `hasNameOrDefault` - var defaultModifier = ts.Debug.assertDefined(ts.findModifier(functionDeclaration, 84 /* DefaultKeyword */), "Nameless function declaration should be a default export"); + var defaultModifier = ts.Debug.checkDefined(ts.findModifier(functionDeclaration, 84 /* DefaultKeyword */), "Nameless function declaration should be a default export"); return [defaultModifier]; case 161 /* MethodDeclaration */: return [functionDeclaration.name]; case 162 /* Constructor */: - var ctrKeyword = ts.Debug.assertDefined(ts.findChildOfKind(functionDeclaration, 129 /* ConstructorKeyword */, functionDeclaration.getSourceFile()), "Constructor declaration should have constructor keyword"); + var ctrKeyword = ts.Debug.checkDefined(ts.findChildOfKind(functionDeclaration, 129 /* ConstructorKeyword */, functionDeclaration.getSourceFile()), "Constructor declaration should have constructor keyword"); if (functionDeclaration.parent.kind === 214 /* ClassExpression */) { var variableDeclaration = functionDeclaration.parent.parent; return [variableDeclaration.name, ctrKeyword]; @@ -134598,7 +138164,6 @@ var ts; indexes.push(index); index++; } - text = ts.escapeString(text); return [index, text, indexes]; } function nodesToTemplate(_a, file) { @@ -134723,7 +138288,7 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 294 /* FirstJSDocNode */ || kid.kind > 322 /* LastJSDocNode */; }); + var child = ts.find(children, function (kid) { return kid.kind < 294 /* FirstJSDocNode */ || kid.kind > 323 /* LastJSDocNode */; }); return child.kind < 153 /* FirstNode */ ? child : child.getFirstToken(sourceFile); @@ -134793,7 +138358,7 @@ var ts; } } function createSyntaxList(nodes, parent) { - var list = createNode(323 /* SyntaxList */, nodes.pos, nodes.end, parent); + var list = createNode(324 /* SyntaxList */, nodes.pos, nodes.end, parent); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { @@ -134877,7 +138442,7 @@ var ts; get: function () { return ts.symbolName(this); }, - enumerable: true, + enumerable: false, configurable: true }); SymbolObject.prototype.getEscapedName = function () { @@ -134924,7 +138489,7 @@ var ts; get: function () { return ts.idText(this); }, - enumerable: true, + enumerable: false, configurable: true }); return IdentifierObject; @@ -134939,7 +138504,7 @@ var ts; get: function () { return ts.idText(this); }, - enumerable: true, + enumerable: false, configurable: true }); return PrivateIdentifierObject; @@ -135032,7 +138597,7 @@ var ts; } return undefined; }, - enumerable: true, + enumerable: false, configurable: true }); return TypeObject; @@ -135406,10 +138971,6 @@ var ts; }); return names; }; - HostCache.prototype.getVersion = function (path) { - var file = this.getHostFileInformation(path); - return (file && file.version); // TODO: GH#18217 - }; HostCache.prototype.getScriptSnapshot = function (path) { var file = this.getHostFileInformation(path); return (file && file.scriptSnapshot); // TODO: GH#18217 @@ -135593,6 +139154,7 @@ var ts; return sourceFile; } function synchronizeHostData() { + var _a; ts.Debug.assert(!syntaxOnly); // perform fast check if host supports it if (host.getProjectVersion) { @@ -135616,7 +139178,7 @@ var ts; var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; var projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (_path, fileName) { return host.getScriptVersion(fileName); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -135646,7 +139208,7 @@ var ts; return host.getDirectories ? host.getDirectories(path) : []; }, readDirectory: function (path, extensions, exclude, include, depth) { - ts.Debug.assertDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + ts.Debug.checkDefined(host.readDirectory, "'LanguageServiceHost.readDirectory' must be implemented to correctly process 'projectReferences'"); return host.readDirectory(path, extensions, exclude, include, depth); }, onReleaseOldSourceFile: onReleaseOldSourceFile, @@ -135674,12 +139236,10 @@ var ts; return host.resolveTypeReferenceDirectives.apply(host, args); }; } - if (host.setResolvedProjectReferenceCallbacks) { - compilerHost.setResolvedProjectReferenceCallbacks = function (callbacks) { return host.setResolvedProjectReferenceCallbacks(callbacks); }; - } if (host.useSourceOfProjectReferenceRedirect) { compilerHost.useSourceOfProjectReferenceRedirect = function () { return host.useSourceOfProjectReferenceRedirect(); }; } + (_a = host.setCompilerHost) === null || _a === void 0 ? void 0 : _a.call(host, compilerHost); var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); var options = { rootNames: rootFileNames, @@ -135765,7 +139325,7 @@ var ts; // We do not support the scenario where a host can modify a registered // file's script kind, i.e. in one project some file is treated as ".ts" // and in another as ".js" - ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind.", path); + ts.Debug.assertEqual(hostFileInformation.scriptKind, oldSourceFile.scriptKind, "Registered script kind should match new script kind."); return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } // We didn't already have the file. Fall through and acquire it from the registry. @@ -135788,8 +139348,10 @@ var ts; } function dispose() { if (program) { + // Use paths to ensure we are using correct key and paths as document registry could bre created with different current directory than host + var key_1 = documentRegistry.getKeyForCompilationSettings(program.getCompilerOptions()); ts.forEach(program.getSourceFiles(), function (f) { - return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); + return documentRegistry.releaseDocumentWithKey(f.resolvedPath, key_1); }); program = undefined; // TODO: GH#18217 } @@ -135835,12 +139397,13 @@ var ts; function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions)), // TODO: GH#18217 + return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions, host)), // TODO: GH#18217 preferences, cancellationToken); } - function getCompletionEntrySymbol(fileName, position, name, source) { + function getCompletionEntrySymbol(fileName, position, name, source, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); - return ts.Completions.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host); + return ts.Completions.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, preferences); } function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); @@ -136106,14 +139669,14 @@ var ts; } function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatSelection(start, end, sourceFile, ts.formatting.getFormatContext(toEditorSettings(options))); + return ts.formatting.formatSelection(start, end, sourceFile, ts.formatting.getFormatContext(toEditorSettings(options), host)); } function getFormattingEditsForDocument(fileName, options) { - return ts.formatting.formatDocument(syntaxTreeCache.getCurrentSourceFile(fileName), ts.formatting.getFormatContext(toEditorSettings(options))); + return ts.formatting.formatDocument(syntaxTreeCache.getCurrentSourceFile(fileName), ts.formatting.getFormatContext(toEditorSettings(options), host)); } function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var formatContext = ts.formatting.getFormatContext(toEditorSettings(options)); + var formatContext = ts.formatting.getFormatContext(toEditorSettings(options), host); if (!ts.isInComment(sourceFile, position)) { switch (key) { case "{": @@ -136133,7 +139696,7 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); - var formatContext = ts.formatting.getFormatContext(formatOptions); + var formatContext = ts.formatting.getFormatContext(formatOptions, host); return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { cancellationToken.throwIfCancellationRequested(); return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); @@ -136144,7 +139707,7 @@ var ts; synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); - var formatContext = ts.formatting.getFormatContext(formatOptions); + var formatContext = ts.formatting.getFormatContext(formatOptions, host); return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } function organizeImports(scope, formatOptions, preferences) { @@ -136152,12 +139715,12 @@ var ts; synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); - var formatContext = ts.formatting.getFormatContext(formatOptions); + var formatContext = ts.formatting.getFormatContext(formatOptions, host); return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); } function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { if (preferences === void 0) { preferences = ts.emptyOptions; } - return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); + return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions, host), preferences, sourceMapper); } function applyCodeActionCommand(fileName, actionOrFormatSettingsOrUndefined) { var action = typeof fileName === "string" ? actionOrFormatSettingsOrUndefined : fileName; @@ -136359,7 +139922,7 @@ var ts; endPosition: endPosition, program: getProgram(), host: host, - formatContext: ts.formatting.getFormatContext(formatOptions), + formatContext: ts.formatting.getFormatContext(formatOptions, host), cancellationToken: cancellationToken, preferences: preferences, }; @@ -136451,6 +140014,7 @@ var ts; getEditsForRefactor: getEditsForRefactor, toLineColumnOffset: sourceMapper.toLineColumnOffset, getSourceMapper: function () { return sourceMapper; }, + clearSourceMapperCache: function () { return sourceMapper.clearCache(); }, prepareCallHierarchy: prepareCallHierarchy, provideCallHierarchyIncomingCalls: provideCallHierarchyIncomingCalls, provideCallHierarchyOutgoingCalls: provideCallHierarchyOutgoingCalls @@ -137777,7 +141341,10 @@ var ts; /// Emit LanguageServiceShimObject.prototype.getEmitOutput = function (fileName) { var _this = this; - return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { return _this.languageService.getEmitOutput(fileName); }); + return this.forwardJSONCall("getEmitOutput('" + fileName + "')", function () { + var _a = _this.languageService.getEmitOutput(fileName), diagnostics = _a.diagnostics, rest = __rest(_a, ["diagnostics"]); + return __assign(__assign({}, rest), { diagnostics: _this.realizeDiagnostics(diagnostics) }); + }); }; LanguageServiceShimObject.prototype.getEmitOutputObject = function (fileName) { var _this = this;